{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"uptime-status","type":"registry:block","title":"Uptime status","description":"A status page with three services, each shown as 90 daily bars that rise in with a wave, hover/focus tooltips with date and status, an overall uptime count-up, and a legend.","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"registry/prequel/uptime-status/uptime-status.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n  AnimatePresence,\n  MotionConfig,\n  animate,\n  motion,\n  useInView,\n  useReducedMotion,\n} from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\n\n/* ------------------------------------------------------------------ */\n/* types                                                               */\n/* ------------------------------------------------------------------ */\n\nexport type UptimeStatus = \"operational\" | \"degraded\" | \"down\";\n\nexport type UptimeService = {\n  id: string;\n  name: string;\n  /** Short sub-caption, e.g. the hostname. */\n  url?: string;\n  /** One status per day, oldest first. */\n  days: UptimeStatus[];\n};\n\nexport type UptimeStatusProps = {\n  className?: string;\n  title?: string;\n  description?: string;\n  services?: UptimeService[];\n  /** Number of days shown per service. Defaults to 90. */\n  dayCount?: number;\n  /** Formats an uptime percentage (0–100). Defaults to two decimals. */\n  formatUptime?: (percent: number) => string;\n};\n\n/* ------------------------------------------------------------------ */\n/* constants + status metadata                                          */\n/* ------------------------------------------------------------------ */\n\nconst DEFAULT_DAY_COUNT = 90;\n\nconst BAR_HEIGHT = 34;\nconst BAR_TOP = 8;\n\nconst WEEKDAYS = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\nconst MONTHS = [\n  \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n  \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\",\n];\n\n/* Most recent day, fixed in UTC so server and client render identically. */\nconst ANCHOR_MS = Date.UTC(2026, 10, 9);\nconst DAY_MS = 86_400_000;\n\nconst STATUS_META: Record<\n  UptimeStatus,\n  { label: string; tooltipLabel: string; color: string }\n> = {\n  operational: {\n    label: \"Operational\",\n    tooltipLabel: \"Operational\",\n    color: \"var(--success)\",\n  },\n  degraded: {\n    label: \"Degraded\",\n    tooltipLabel: \"Degraded performance\",\n    color: \"var(--chart-2)\",\n  },\n  down: {\n    label: \"Down\",\n    tooltipLabel: \"Major outage\",\n    color: \"var(--destructive)\",\n  },\n};\n\n/* ------------------------------------------------------------------ */\n/* deterministic demo data (seeded PRNG — no Math.random / Date.now)    */\n/* ------------------------------------------------------------------ */\n\nfunction mulberry32(seed: number) {\n  let a = seed >>> 0;\n  return function () {\n    a |= 0;\n    a = (a + 0x6d2b79f5) | 0;\n    let t = Math.imul(a ^ (a >>> 15), 1 | a);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\n/* Build a deterministic list of `total` statuses with exactly `down` outages\n   and `degraded` degraded days, scattered by a seeded shuffle. Events are\n   placed only within the first `total - 6` slots so the trailing days stay\n   operational — the page reads \"All systems operational\" right now. */\nfunction generateDays(\n  seed: number,\n  down: number,\n  degraded: number,\n  total: number\n): UptimeStatus[] {\n  const rand = mulberry32(seed);\n  const days: UptimeStatus[] = new Array<UptimeStatus>(total).fill(\n    \"operational\"\n  );\n  const span = Math.max(0, total - 6);\n\n  const order: number[] = [];\n  for (let i = 0; i < span; i++) order.push(i);\n  for (let i = order.length - 1; i > 0; i--) {\n    const j = Math.floor(rand() * (i + 1));\n    const tmp = order[i];\n    order[i] = order[j];\n    order[j] = tmp;\n  }\n\n  for (let i = 0; i < Math.min(down, span); i++) days[order[i]] = \"down\";\n  for (let i = down; i < Math.min(down + degraded, span); i++) {\n    days[order[i]] = \"degraded\";\n  }\n  return days;\n}\n\nconst DEFAULT_SERVICES: UptimeService[] = [\n  {\n    id: \"api\",\n    name: \"API\",\n    url: \"api.northwindlabs.com\",\n    days: generateDays(0x1234abcd, 1, 3, DEFAULT_DAY_COUNT),\n  },\n  {\n    id: \"dashboard\",\n    name: \"Dashboard\",\n    url: \"app.northwindlabs.com\",\n    days: generateDays(0x9e3779b9, 0, 2, DEFAULT_DAY_COUNT),\n  },\n  {\n    id: \"payments\",\n    name: \"Payments\",\n    url: \"pay.northwindlabs.com\",\n    days: generateDays(0xdeadbeef, 1, 2, DEFAULT_DAY_COUNT),\n  },\n];\n\n/* ------------------------------------------------------------------ */\n/* helpers                                                             */\n/* ------------------------------------------------------------------ */\n\nfunction clamp(v: number, min: number, max: number) {\n  return Math.min(max, Math.max(min, v));\n}\n\nfunction dateForIndex(index: number, total: number): Date {\n  const offset = index - (total - 1);\n  return new Date(ANCHOR_MS + offset * DAY_MS);\n}\n\nfunction formatDate(date: Date): string {\n  return `${WEEKDAYS[date.getUTCDay()]}, ${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}`;\n}\n\n/* Uptime = share of days that were not a full outage (degraded still counts\n   as reachable). This is the convention status pages use. */\nfunction uptimePercent(days: UptimeStatus[]): number {\n  if (days.length === 0) return 100;\n  const down = days.filter((d) => d === \"down\").length;\n  return ((days.length - down) / days.length) * 100;\n}\n\nfunction defaultFormatUptime(percent: number) {\n  return `${percent.toFixed(2)}%`;\n}\n\nfunction countBy(days: UptimeStatus[], status: UptimeStatus): number {\n  return days.filter((d) => d === status).length;\n}\n\nfunction plural(n: number, word: string) {\n  return `${n} ${word}${n === 1 ? \"\" : \"s\"}`;\n}\n\ntype BarsGeometry = {\n  width: number;\n  height: number;\n  barW: number;\n  xFor: (index: number) => number;\n};\n\nfunction buildBars(width: number, n: number): BarsGeometry {\n  const step = width / n;\n  const gap = clamp(step * 0.32, 0.5, 1.5);\n  const barW = Math.max(0.5, step - gap);\n  return {\n    width,\n    height: BAR_HEIGHT,\n    barW,\n    xFor: (index) => index * step,\n  };\n}\n\n/* ------------------------------------------------------------------ */\n/* count-up for the overall uptime number                              */\n/* ------------------------------------------------------------------ */\n\nfunction useAnimatedNumber(\n  target: number,\n  opts: { inView: boolean; reduce: boolean }\n) {\n  const [value, setValue] = useState(target);\n  const valueRef = useRef(target);\n  const animRef = useRef<ReturnType<typeof animate> | null>(null);\n  const firstRef = useRef(true);\n\n  useEffect(() => {\n    if (!opts.inView) return;\n    if (opts.reduce) {\n      valueRef.current = target;\n      setValue(target);\n      return;\n    }\n    const from = firstRef.current ? 0 : valueRef.current;\n    firstRef.current = false;\n    animRef.current?.stop();\n    animRef.current = animate(from, target, {\n      duration: 0.9,\n      ease: EASE,\n      onUpdate: (v) => {\n        valueRef.current = v;\n        setValue(v);\n      },\n      onComplete: () => {\n        valueRef.current = target;\n        setValue(target);\n      },\n    });\n    return () => animRef.current?.stop();\n  }, [target, opts.inView, opts.reduce]);\n\n  return value;\n}\n\n/* ------------------------------------------------------------------ */\n/* one service row: name, daily bars, uptime %                          */\n/* ------------------------------------------------------------------ */\n\ntype ServiceRowProps = {\n  service: UptimeService;\n  total: number;\n  index: number;\n  show: boolean;\n  reduce: boolean;\n  formatUptime: (percent: number) => string;\n};\n\nfunction ServiceRow({\n  service,\n  total,\n  index,\n  show,\n  reduce,\n  formatUptime,\n}: ServiceRowProps) {\n  const barsRef = useRef<HTMLDivElement>(null);\n  const [width, setWidth] = useState(0);\n  const [active, setActive] = useState<number | null>(null);\n\n  /* measure the strip so the SVG matches its pixel width */\n  useEffect(() => {\n    const el = barsRef.current;\n    if (!el) return;\n    const update = () => {\n      const w = el.getBoundingClientRect().width;\n      setWidth((prev) => (prev === w ? prev : w));\n    };\n    update();\n    const observer = new ResizeObserver(update);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  const days = useMemo(() => {\n    const d = service.days.slice(-total);\n    while (d.length < total) d.unshift(\"operational\");\n    return d;\n  }, [service.days, total]);\n\n  const uptime = useMemo(() => uptimePercent(days), [days]);\n\n  const geometry = useMemo(\n    () => (width > 0 ? buildBars(width, total) : null),\n    [width, total]\n  );\n\n  const down = countBy(days, \"down\");\n  const degraded = countBy(days, \"degraded\");\n\n  const activeDate = active != null ? dateForIndex(active, total) : null;\n  const activeStatus = active != null ? days[active] : null;\n\n  let tipLeft = 4;\n  if (geometry && active != null) {\n    const cx = geometry.xFor(active) + geometry.barW / 2;\n    tipLeft = clamp(cx - 64, 4, geometry.width - 136);\n  }\n\n  const ariaLabel = `${service.name}: ${formatUptime(uptime)} uptime over the last ${total} days${\n    down ? `, ${plural(down, \"outage\")}` : \"\"\n  }${degraded ? `, ${plural(degraded, \"degraded day\")}` : \"\"}.`;\n\n  return (\n    <motion.div\n      initial={{ opacity: 0, y: reduce ? 0 : 12 }}\n      animate={{ opacity: show ? 1 : 0, y: 0 }}\n      transition={{\n        duration: reduce ? 0 : 0.5,\n        delay: reduce ? 0 : 0.1 + index * 0.07,\n        ease: EASE,\n      }}\n      className=\"grid grid-cols-[1fr_auto] items-baseline gap-x-4 gap-y-1.5 sm:grid-cols-[150px_minmax(0,1fr)_78px] sm:items-center sm:gap-6\"\n    >\n      {/* name */}\n      <div className=\"min-w-0\">\n        <div className=\"truncate text-[13px] font-medium text-foreground\">\n          {service.name}\n        </div>\n        {service.url ? (\n          <div className=\"truncate text-[11.5px] text-muted-foreground\">\n            {service.url}\n          </div>\n        ) : null}\n      </div>\n\n      {/* uptime (right on mobile, last column on desktop) */}\n      <div className=\"text-right text-[13px] font-semibold tabular-nums text-foreground sm:order-3\">\n        {formatUptime(uptime)}\n      </div>\n\n      {/* daily bars */}\n      <div\n        ref={barsRef}\n        className=\"relative col-span-2 h-[34px] min-w-0 sm:order-2 sm:col-span-1\"\n      >\n        {geometry && (\n          <svg\n            viewBox={`0 0 ${geometry.width} ${geometry.height}`}\n            role=\"img\"\n            aria-label={ariaLabel}\n            tabIndex={0}\n            onFocus={() => setActive((a) => a ?? total - 1)}\n            onBlur={() => setActive(null)}\n            onKeyDown={(e) => {\n              if (e.key === \"ArrowRight\" || e.key === \"ArrowLeft\") {\n                e.preventDefault();\n                const dir = e.key === \"ArrowRight\" ? 1 : -1;\n                setActive((a) =>\n                  a == null\n                    ? dir === 1\n                      ? 0\n                      : total - 1\n                    : clamp(a + dir, 0, total - 1)\n                );\n              } else if (e.key === \"Home\") {\n                e.preventDefault();\n                setActive(0);\n              } else if (e.key === \"End\") {\n                e.preventDefault();\n                setActive(total - 1);\n              }\n            }}\n            className=\"block h-full w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n          >\n            {/* bars rise in as a left-to-right wave */}\n            {days.map((status, i) => {\n              const x = geometry.xFor(i);\n              const delay = reduce ? 0 : 0.05 + i * 0.006;\n              return (\n                <motion.rect\n                  key={i}\n                  x={x}\n                  y={BAR_TOP}\n                  width={geometry.barW}\n                  height={geometry.height - BAR_TOP}\n                  rx={Math.min(1, geometry.barW / 2)}\n                  fill={STATUS_META[status].color}\n                  initial={reduce ? { scaleY: 1 } : { scaleY: 0 }}\n                  animate={show ? { scaleY: 1 } : { scaleY: 0 }}\n                  transition={\n                    reduce\n                      ? { duration: 0 }\n                      : { duration: 0.45, delay, ease: EASE }\n                  }\n                  style={{\n                    transformOrigin: `${x + geometry.barW / 2}px ${geometry.height}px`,\n                  }}\n                />\n              );\n            })}\n\n            {/* active bar: a brightened overlay + the lens glint dot */}\n            {active != null && (\n              <motion.g\n                initial={{ opacity: 0 }}\n                animate={{ opacity: 1 }}\n                transition={{ duration: 0.15 }}\n              >\n                <rect\n                  x={geometry.xFor(active)}\n                  y={BAR_TOP}\n                  width={geometry.barW}\n                  height={geometry.height - BAR_TOP}\n                  rx={Math.min(1, geometry.barW / 2)}\n                  fill=\"var(--foreground)\"\n                  opacity={0.22}\n                />\n                <circle\n                  cx={geometry.xFor(active) + geometry.barW / 2}\n                  cy={BAR_TOP - 4}\n                  r={4.5}\n                  fill=\"none\"\n                  stroke=\"var(--foreground)\"\n                  strokeOpacity={0.25}\n                  strokeWidth={1}\n                />\n                <circle\n                  cx={geometry.xFor(active) + geometry.barW / 2}\n                  cy={BAR_TOP - 4}\n                  r={2}\n                  fill=\"var(--foreground)\"\n                />\n              </motion.g>\n            )}\n\n            {/* pointer hit area */}\n            <rect\n              x={0}\n              y={0}\n              width={geometry.width}\n              height={geometry.height}\n              fill=\"transparent\"\n              style={{ cursor: \"crosshair\" }}\n              onPointerMove={(e) => {\n                const el = barsRef.current;\n                if (!el) return;\n                const px = e.clientX - el.getBoundingClientRect().left;\n                const idx = Math.floor((px / geometry.width) * total);\n                setActive(clamp(idx, 0, total - 1));\n              }}\n              onPointerLeave={() => setActive(null)}\n            />\n          </svg>\n        )}\n\n        <AnimatePresence>\n          {active != null && activeDate && activeStatus && (\n            <motion.div\n              key=\"tooltip\"\n              initial={{ opacity: 0, scale: 0.96, y: 4 }}\n              animate={{ opacity: 1, scale: 1, y: 0 }}\n              exit={{ opacity: 0, scale: 0.96, y: 4 }}\n              transition={{ duration: 0.16, ease: \"easeOut\" }}\n              className=\"pointer-events-none absolute z-10 min-w-[136px] rounded-lg border border-border bg-card px-3 py-2 shadow-lg\"\n              style={{ left: tipLeft, top: BAR_HEIGHT + 6 }}\n            >\n              <div className=\"text-[11.5px] text-muted-foreground\">\n                {formatDate(activeDate)}\n              </div>\n              <div className=\"mt-1 flex items-center gap-1.5\">\n                <span\n                  aria-hidden=\"true\"\n                  className=\"h-2 w-2 shrink-0 rounded-full\"\n                  style={{ background: STATUS_META[activeStatus].color }}\n                />\n                <span className=\"text-[12.5px] font-medium text-foreground\">\n                  {STATUS_META[activeStatus].tooltipLabel}\n                </span>\n              </div>\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n    </motion.div>\n  );\n}\n\n/* ------------------------------------------------------------------ */\n/* block                                                               */\n/* ------------------------------------------------------------------ */\n\nexport function UptimeStatus({\n  className,\n  title = \"System status\",\n  description = \"Uptime over the last 90 days, per service.\",\n  services = DEFAULT_SERVICES,\n  dayCount = DEFAULT_DAY_COUNT,\n  formatUptime = defaultFormatUptime,\n}: UptimeStatusProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const inView = useInView(ref, { once: true, margin: \"-10% 0px\" });\n  const reduce = Boolean(useReducedMotion());\n  const show = inView;\n\n  const total = Math.max(1, dayCount);\n\n  /* normalise every service to exactly `total` days (pad front, slice end) */\n  const normalized = useMemo(\n    () =>\n      services.map((s) => {\n        const d = s.days.slice(-total);\n        while (d.length < total) d.unshift(\"operational\");\n        return { ...s, days: d };\n      }),\n    [services, total]\n  );\n\n  const overall = useMemo(() => {\n    if (normalized.length === 0) return 100;\n    const sum = normalized.reduce((acc, s) => acc + uptimePercent(s.days), 0);\n    return sum / normalized.length;\n  }, [normalized]);\n\n  const displayUptime = useAnimatedNumber(overall, { inView, reduce });\n\n  /* current status: read the most recent day of every service */\n  const current = useMemo(() => {\n    const latest = normalized.map((s) => s.days[s.days.length - 1]);\n    if (latest.includes(\"down\"))\n      return { status: \"down\" as UptimeStatus, text: \"Major outage\" };\n    if (latest.includes(\"degraded\"))\n      return {\n        status: \"degraded\" as UptimeStatus,\n        text: \"Some systems degraded\",\n      };\n    return { status: \"operational\" as UptimeStatus, text: \"All systems operational\" };\n  }, [normalized]);\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <motion.div\n        ref={ref}\n        initial={{ opacity: 0, y: 20 }}\n        animate={show ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}\n        transition={{ duration: reduce ? 0 : 0.6, ease: EASE }}\n        className={cn(\n          \"rounded-xl border border-border bg-card text-card-foreground shadow-sm\",\n          className\n        )}\n      >\n        <div className=\"p-5 sm:p-6\">\n          {/* header */}\n          <div className=\"flex flex-wrap items-start justify-between gap-4\">\n            <div>\n              <h2 className=\"text-[15px] font-semibold tracking-tight\">\n                {title}\n              </h2>\n              <p className=\"mt-0.5 text-[13px] text-muted-foreground\">\n                {description}\n              </p>\n            </div>\n\n            {/* overall uptime */}\n            <div className=\"flex items-center gap-3 rounded-lg border border-border bg-muted/40 px-3.5 py-2\">\n              <div className=\"text-right\">\n                <div className=\"text-[22px] font-semibold leading-none tracking-tight tabular-nums\">\n                  {formatUptime(displayUptime)}\n                </div>\n                <div className=\"mt-1 text-[11px] text-muted-foreground\">\n                  Overall uptime · {total}d\n                </div>\n              </div>\n              <span\n                aria-hidden=\"true\"\n                className=\"h-2.5 w-2.5 shrink-0 rounded-full\"\n                style={{ background: STATUS_META[current.status].color }}\n              />\n            </div>\n          </div>\n\n          {/* current status line */}\n          <div className=\"mt-4 flex items-center gap-2 text-[12.5px] text-muted-foreground\">\n            <span\n              aria-hidden=\"true\"\n              className=\"h-2 w-2 shrink-0 rounded-full\"\n              style={{ background: STATUS_META[current.status].color }}\n            />\n            <span className=\"font-medium text-foreground\">{current.text}</span>\n            <span aria-hidden=\"true\">·</span>\n            <span>last {total} days</span>\n          </div>\n\n          {/* services */}\n          <div className=\"mt-5 space-y-4\">\n            {normalized.map((service, index) => (\n              <ServiceRow\n                key={service.id}\n                service={service}\n                total={total}\n                index={index}\n                show={show}\n                reduce={reduce}\n                formatUptime={formatUptime}\n              />\n            ))}\n          </div>\n\n          {/* legend */}\n          <div className=\"mt-6 flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4\">\n            <div\n              role=\"img\"\n              aria-label=\"Legend: operational, degraded and down statuses\"\n              className=\"flex flex-wrap items-center gap-x-4 gap-y-1.5\"\n            >\n              {(Object.keys(STATUS_META) as UptimeStatus[]).map((status) => (\n                <span\n                  key={status}\n                  className=\"inline-flex items-center gap-1.5 text-[11.5px] text-muted-foreground\"\n                >\n                  <span\n                    aria-hidden=\"true\"\n                    className=\"h-2 w-2 shrink-0 rounded-full\"\n                    style={{ background: STATUS_META[status].color }}\n                  />\n                  {STATUS_META[status].label}\n                </span>\n              ))}\n            </div>\n            <span className=\"text-[11.5px] tabular-nums text-muted-foreground\">\n              {formatDate(dateForIndex(0, total))} –{\" \"}\n              {formatDate(dateForIndex(total - 1, total))}\n            </span>\n          </div>\n        </div>\n      </motion.div>\n    </MotionConfig>\n  );\n}\n\nexport default UptimeStatus;\n"}]}