{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"live-feed","type":"registry:block","title":"Live feed","description":"A live activity feed where events slide in at the top, with relative timestamps, a pulsing live indicator, and pause on hover.","dependencies":["motion","lucide-react"],"registryDependencies":["utils"],"files":[{"path":"registry/prequel/live-feed/live-feed.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n  AnimatePresence,\n  MotionConfig,\n  motion,\n  useInView,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  CreditCard,\n  Pause,\n  Play,\n  RotateCcw,\n  TrendingUp,\n  UserPlus,\n  type LucideIcon,\n} from \"lucide-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 LiveFeedEventType = \"signup\" | \"upgrade\" | \"payment\" | \"refund\";\n\nexport type LiveFeedEvent = {\n  id: string;\n  type: LiveFeedEventType;\n  /** Person or company name. */\n  name: string;\n  /** Short description of what happened, e.g. \"Started the Growth plan\". */\n  detail: string;\n  /** Positive amount in currency units; the sign is implied by the type. */\n  amount?: number;\n};\n\nexport type LiveFeedProps = {\n  className?: string;\n  title?: string;\n  description?: string;\n  /** Seconds between events. Defaults to 3. */\n  interval?: number;\n  /** Maximum number of events kept visible. Defaults to 6. */\n  maxItems?: number;\n  /** Deterministic list of events, cycled in order. */\n  events?: LiveFeedEvent[];\n  formatAmount?: (amount: number) => string;\n};\n\n/* ------------------------------------------------------------------ */\n/* deterministic demo data (no Math.random / Date.now at module load)  */\n/* ------------------------------------------------------------------ */\n\nconst DEFAULT_EVENTS: LiveFeedEvent[] = [\n  { id: \"e01\", type: \"payment\", name: \"Tidewell Health\", detail: \"Paid invoice #3380\", amount: 3380 },\n  { id: \"e02\", type: \"signup\", name: \"Lumio Labs\", detail: \"Started the Growth plan\" },\n  { id: \"e03\", type: \"upgrade\", name: \"Parcel & Pine\", detail: \"Upgraded to Scale\", amount: 240 },\n  { id: \"e04\", type: \"refund\", name: \"Sofia Rossi\", detail: \"Refunded the Starter plan\", amount: 290 },\n  { id: \"e05\", type: \"payment\", name: \"Kestrel Analytics\", detail: \"Paid invoice #2890\", amount: 2890 },\n  { id: \"e06\", type: \"signup\", name: \"Verdant\", detail: \"Started the Starter plan\" },\n  { id: \"e07\", type: \"upgrade\", name: \"Quillfeather\", detail: \"Added 6 seats\", amount: 84 },\n  { id: \"e08\", type: \"payment\", name: \"Brightloom\", detail: \"Paid invoice #4120\", amount: 4120 },\n  { id: \"e09\", type: \"refund\", name: \"Liam O'Connor\", detail: \"Refunded the Growth plan\", amount: 1180 },\n  { id: \"e10\", type: \"signup\", name: \"Coralline\", detail: \"Started the Scale plan\" },\n  { id: \"e11\", type: \"upgrade\", name: \"Fernway\", detail: \"Upgraded to Growth\", amount: 99 },\n  { id: \"e12\", type: \"payment\", name: \"Mosaic HR\", detail: \"Paid invoice #1720\", amount: 1720 },\n];\n\n/* ------------------------------------------------------------------ */\n/* helpers                                                             */\n/* ------------------------------------------------------------------ */\n\nconst TYPE_META: Record<\n  LiveFeedEventType,\n  { icon: LucideIcon; iconClass: string; prefix: string; amountClass: string }\n> = {\n  signup: {\n    icon: UserPlus,\n    iconClass: \"text-muted-foreground\",\n    prefix: \"\",\n    amountClass: \"text-foreground\",\n  },\n  upgrade: {\n    icon: TrendingUp,\n    iconClass: \"text-success\",\n    prefix: \"+\",\n    amountClass: \"text-foreground\",\n  },\n  payment: {\n    icon: CreditCard,\n    iconClass: \"text-foreground\",\n    prefix: \"\",\n    amountClass: \"text-foreground\",\n  },\n  refund: {\n    icon: RotateCcw,\n    iconClass: \"text-destructive\",\n    prefix: \"−\",\n    amountClass: \"text-muted-foreground\",\n  },\n};\n\nfunction defaultFormatAmount(amount: number) {\n  return \"$\" + Math.abs(amount).toLocaleString(\"en-US\");\n}\n\nfunction relativeTime(ageSeconds: number) {\n  const s = Math.max(0, Math.round(ageSeconds));\n  if (s < 5) return \"just now\";\n  if (s < 60) return `${s}s ago`;\n  if (s < 3600) return `${Math.floor(s / 60)}m ago`;\n  if (s < 86400) return `${Math.floor(s / 3600)}h ago`;\n  return `${Math.floor(s / 86400)}d ago`;\n}\n\ntype FeedItem = {\n  key: string;\n  type: LiveFeedEventType;\n  name: string;\n  detail: string;\n  amount?: number;\n  /** Seconds relative to mount (negative for seeded history). */\n  arrivedAt: number;\n};\n\n/** Seeded \"history\" so the feed looks alive before the first live event. */\nconst INITIAL_AGES = [3, 40, 95, 210, 480, 920];\n\nfunction buildInitial(events: LiveFeedEvent[], maxItems: number): FeedItem[] {\n  const items: FeedItem[] = [];\n  const len = events.length;\n  if (len === 0) return items;\n  const n = Math.min(maxItems, INITIAL_AGES.length);\n  for (let i = 0; i < n; i++) {\n    const ev = events[(len - 1 - i + len) % len];\n    items.push({\n      key: `${ev.id}-init-${i}`,\n      type: ev.type,\n      name: ev.name,\n      detail: ev.detail,\n      amount: ev.amount,\n      arrivedAt: -INITIAL_AGES[i],\n    });\n  }\n  return items;\n}\n\n/* ------------------------------------------------------------------ */\n/* block                                                               */\n/* ------------------------------------------------------------------ */\n\nexport function LiveFeed({\n  className,\n  title = \"Live activity\",\n  description = \"Signups, upgrades and payments as they happen.\",\n  interval = 3,\n  maxItems = 6,\n  events = DEFAULT_EVENTS,\n  formatAmount = defaultFormatAmount,\n}: LiveFeedProps) {\n  const ref = useRef<HTMLElement>(null);\n  const inView = useInView(ref, { once: true, margin: \"-10% 0px\" });\n  const reduce = Boolean(useReducedMotion());\n  const show = inView;\n\n  const safeMax = Math.max(1, maxItems);\n\n  const [items, setItems] = useState<FeedItem[]>(() =>\n    buildInitial(events, safeMax)\n  );\n  const [now, setNow] = useState(0);\n  const [hovered, setHovered] = useState(false);\n  const [focused, setFocused] = useState(false);\n  const [userPaused, setUserPaused] = useState(false);\n\n  const nowRef = useRef(0);\n  const cursorRef = useRef(0);\n  const eventsRef = useRef(events);\n  eventsRef.current = events;\n  const maxItemsRef = useRef(safeMax);\n  maxItemsRef.current = safeMax;\n\n  const paused = userPaused || hovered || focused;\n  const running = !paused && !reduce;\n\n  const intervalMs = Math.max(1, interval) * 1000;\n\n  /* clock: keeps relative timestamps ticking (paused on hover/focus). */\n  useEffect(() => {\n    if (!show || paused) return;\n    const id = window.setInterval(() => {\n      nowRef.current += 1;\n      setNow(nowRef.current);\n    }, 1000);\n    return () => window.clearInterval(id);\n  }, [show, paused]);\n\n  /* feed: a new event lands at the top every `interval` seconds. */\n  useEffect(() => {\n    if (!show || paused) return;\n    const id = window.setInterval(() => {\n      const list = eventsRef.current;\n      if (list.length === 0) return;\n      const ev = list[cursorRef.current % list.length];\n      cursorRef.current += 1;\n      const key = `${ev.id}-${cursorRef.current}`;\n      setItems((prev) => {\n        const item: FeedItem = {\n          key,\n          type: ev.type,\n          name: ev.name,\n          detail: ev.detail,\n          amount: ev.amount,\n          arrivedAt: nowRef.current,\n        };\n        return [item, ...prev].slice(0, maxItemsRef.current);\n      });\n    }, intervalMs);\n    return () => window.clearInterval(id);\n  }, [show, paused, intervalMs]);\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <motion.section\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        onPointerEnter={() => setHovered(true)}\n        onPointerLeave={() => setHovered(false)}\n        onFocus={(e) => {\n          if (e.currentTarget.contains(e.target as Node)) setFocused(true);\n        }}\n        onBlur={(e) => {\n          if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {\n            setFocused(false);\n          }\n        }}\n        className={cn(\n          \"rounded-xl border border-border bg-card text-card-foreground shadow-sm\",\n          className\n        )}\n      >\n        {/* header */}\n        <div className=\"flex items-start justify-between gap-3 px-5 py-4 sm:px-6\">\n          <div className=\"min-w-0\">\n            <div className=\"flex items-center gap-2\">\n              <h2 className=\"text-[15px] font-semibold tracking-tight\">\n                {title}\n              </h2>\n              <span className=\"inline-flex items-center gap-1.5 rounded-full border border-border px-2 py-0.5 text-[11px] font-medium text-muted-foreground\">\n                <span className=\"relative flex h-1.5 w-1.5\" aria-hidden=\"true\">\n                  {running ? (\n                    <motion.span\n                      className=\"absolute inset-0 rounded-full bg-success\"\n                      animate={{ scale: [1, 2.2], opacity: [0.5, 0] }}\n                      transition={{\n                        duration: 2.2,\n                        repeat: Infinity,\n                        ease: \"easeOut\",\n                      }}\n                    />\n                  ) : null}\n                  <span\n                    className={cn(\n                      \"relative h-1.5 w-1.5 rounded-full\",\n                      paused ? \"bg-muted-foreground\" : \"bg-success\"\n                    )}\n                  />\n                </span>\n                Live\n              </span>\n            </div>\n            <p className=\"mt-0.5 text-[13px] text-muted-foreground\">\n              {description}\n            </p>\n          </div>\n\n          <button\n            type=\"button\"\n            onClick={() => setUserPaused((p) => !p)}\n            aria-label={userPaused ? \"Resume live feed\" : \"Pause live feed\"}\n            aria-pressed={userPaused}\n            className=\"grid h-8 w-8 shrink-0 place-items-center rounded-lg border border-border bg-muted text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n          >\n            {userPaused ? (\n              <Play className=\"h-3.5 w-3.5\" />\n            ) : (\n              <Pause className=\"h-3.5 w-3.5\" />\n            )}\n          </button>\n        </div>\n\n        {/* feed */}\n        <ul aria-live=\"polite\" className=\"border-t border-border\">\n          <AnimatePresence initial={false}>\n            {items.map((item) => {\n              const meta = TYPE_META[item.type];\n              const Icon = meta.icon;\n              const age = now - item.arrivedAt;\n              return (\n                <motion.li\n                  key={item.key}\n                  layout\n                  initial={reduce ? { opacity: 0 } : { opacity: 0, y: -14 }}\n                  animate={{ opacity: 1, y: 0 }}\n                  exit={reduce ? { opacity: 0 } : { opacity: 0, y: 8 }}\n                  transition={\n                    reduce\n                      ? { duration: 0 }\n                      : {\n                          layout: { duration: 0.4, ease: EASE },\n                          opacity: { duration: 0.3, ease: EASE },\n                          y: { duration: 0.4, ease: EASE },\n                        }\n                  }\n                  className=\"flex items-center gap-3 border-b border-border px-5 py-3 last:border-b-0 sm:px-6\"\n                >\n                  <span className=\"grid h-8 w-8 shrink-0 place-items-center rounded-lg border border-border bg-muted\">\n                    <Icon className={cn(\"h-4 w-4\", meta.iconClass)} />\n                  </span>\n                  <div className=\"min-w-0 flex-1\">\n                    <div className=\"truncate text-sm font-medium\">\n                      {item.name}\n                    </div>\n                    <div className=\"truncate text-xs text-muted-foreground\">\n                      {item.detail}\n                    </div>\n                  </div>\n                  <div className=\"flex shrink-0 flex-col items-end justify-center gap-0.5 pl-2\">\n                    {item.amount != null ? (\n                      <span\n                        className={cn(\n                          \"text-sm font-medium tabular-nums\",\n                          meta.amountClass\n                        )}\n                      >\n                        {meta.prefix}\n                        {formatAmount(item.amount)}\n                      </span>\n                    ) : null}\n                    <span className=\"text-[11px] tabular-nums text-muted-foreground\">\n                      {relativeTime(age)}\n                    </span>\n                  </div>\n                </motion.li>\n              );\n            })}\n          </AnimatePresence>\n        </ul>\n      </motion.section>\n    </MotionConfig>\n  );\n}\n\nexport default LiveFeed;\n"}]}