{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "log-stream",
  "type": "registry:component",
  "title": "Log stream",
  "description": "Follow a live event stream with level filters, search, and a tail that pauses when someone scrolls up to read.",
  "categories": [
    "operations"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/log-stream.tsx",
      "type": "registry:component",
      "target": "components/overtrue/log-stream.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconArrowDown as ArrowDown,\n  IconPlayerPause as Pause,\n  IconPlayerPlay as Play,\n  IconSearch as Search,\n  IconTextWrap as TextWrap,\n  IconTrash as Trash,\n  IconX as X,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LogEntry {\n  id: string;\n  time: Date | number | string;\n  level: LogLevel;\n  /** Service, job or component that emitted the line. */\n  source?: string;\n  message: string;\n}\n\nexport interface LogStreamProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"children\" | \"title\"\n> {\n  /** Events, oldest first. Append new entries to the end. */\n  entries: LogEntry[];\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Height of the scrolling log in pixels. */\n  height?: number;\n  /** Render at most this many of the newest matching rows. */\n  maxEntries?: number;\n  /** Follow the tail. Pass with `onFollowChange` to control it. */\n  follow?: boolean;\n  defaultFollow?: boolean;\n  onFollowChange?: (follow: boolean) => void;\n  /** Called by the clear action. Without it, clearing hides the current entries locally. */\n  onClear?: () => void;\n  /** A live source shows a Live/Paused badge, a follow control, and a cursor. Set false for archived logs. */\n  live?: boolean;\n  /** Levels shown initially. */\n  defaultLevels?: LogLevel[];\n  /** Initial text filter, matched against messages and sources. */\n  defaultQuery?: string;\n  /** Wrap long messages instead of truncating them. Rows can still be expanded one at a time. */\n  defaultWrap?: boolean;\n  /** Format timestamps in local time or UTC. */\n  timeZone?: \"local\" | \"utc\";\n}\n\nconst LEVELS: LogLevel[] = [\"debug\", \"info\", \"warn\", \"error\"];\n\nconst levelStyle: Record<LogLevel, { label: string; pill: string; dot: string }> = {\n  debug: {\n    label: \"Debug\",\n    pill: \"bg-muted text-muted-foreground\",\n    dot: \"bg-muted-foreground/50\",\n  },\n  info: {\n    label: \"Info\",\n    pill: \"bg-sky-500/10 text-sky-700 dark:text-sky-300\",\n    dot: \"bg-sky-500\",\n  },\n  warn: {\n    label: \"Warn\",\n    pill: \"bg-amber-500/12 text-amber-700 dark:text-amber-400\",\n    dot: \"bg-amber-500\",\n  },\n  error: {\n    label: \"Error\",\n    pill: \"bg-destructive/12 text-rose-700 dark:text-rose-400\",\n    dot: \"bg-destructive\",\n  },\n};\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-1 focus-visible:ring-offset-card\";\n\nfunction lastIndexOfId(entries: LogEntry[], id: string) {\n  for (let i = entries.length - 1; i >= 0; i--) if (entries[i].id === id) return i;\n  return -1;\n}\n\nconst pad = (value: number, size = 2) => String(value).padStart(size, \"0\");\n\nfunction formatTime(time: LogEntry[\"time\"], zone: \"local\" | \"utc\") {\n  const date = time instanceof Date ? time : new Date(time);\n  if (Number.isNaN(date.getTime())) return [\"--:--:--\", \".---\", undefined] as const;\n  const utc = zone === \"utc\";\n  const hms = `${pad(utc ? date.getUTCHours() : date.getHours())}:${pad(utc ? date.getUTCMinutes() : date.getMinutes())}:${pad(utc ? date.getUTCSeconds() : date.getSeconds())}`;\n  return [hms, `.${pad(utc ? date.getUTCMilliseconds() : date.getMilliseconds(), 3)}`, date.toISOString()] as const;\n}\n\nfunction highlight(text: string, query: string) {\n  if (!query) return text;\n  const lower = text.toLowerCase();\n  const parts: React.ReactNode[] = [];\n  let from = 0;\n  let at = lower.indexOf(query, from);\n  while (at !== -1) {\n    if (at > from) parts.push(text.slice(from, at));\n    parts.push(\n      <mark key={at} className=\"rounded-[2px] bg-amber-300/50 text-inherit dark:bg-amber-400/30\">\n        {text.slice(at, at + query.length)}\n      </mark>,\n    );\n    from = at + query.length;\n    at = lower.indexOf(query, from);\n  }\n  if (from < text.length) parts.push(text.slice(from));\n  return parts;\n}\n\ninterface RowProps {\n  entry: LogEntry;\n  query: string;\n  wrap: boolean;\n  expanded: boolean;\n  enter: boolean;\n  zone: \"local\" | \"utc\";\n  onToggle: (id: string) => void;\n}\n\nconst LogRow = React.memo(function LogRow({\n  entry,\n  query,\n  wrap,\n  expanded,\n  enter,\n  zone,\n  onToggle,\n}: RowProps) {\n  const [hms, ms, iso] = formatTime(entry.time, zone);\n  const open = wrap || expanded;\n  const level = levelStyle[entry.level] ?? levelStyle.info;\n  return (\n    <div\n      data-level={entry.level}\n      data-expanded={expanded || undefined}\n      onClick={wrap ? undefined : () => onToggle(entry.id)}\n      className={cn(\n        \"relative flex items-start gap-3 px-4 py-[5px] leading-[18px]\",\n        entry.level === \"error\"\n          ? \"bg-destructive/[0.06] hover:bg-destructive/10 dark:bg-destructive/10 dark:hover:bg-destructive/15\"\n          : \"hover:bg-muted/60\",\n        enter &&\n          \"transition-[opacity,translate] duration-300 ease-out starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none\",\n      )}\n    >\n      {entry.level === \"error\" && (\n        <span aria-hidden=\"true\" className=\"absolute inset-y-0 left-0 w-0.5 bg-destructive\" />\n      )}\n      <time\n        dateTime={iso}\n        className=\"w-[84px] shrink-0 text-muted-foreground tabular-nums\"\n      >\n        {hms}\n        <span className=\"opacity-55\">{ms}</span>\n      </time>\n      <span\n        className={cn(\n          \"mt-px inline-flex h-4 w-12 shrink-0 items-center justify-center rounded-[4px] text-[10.5px] leading-none font-semibold tracking-wide uppercase\",\n          level.pill,\n        )}\n      >\n        {entry.level}\n      </span>\n      {entry.source !== undefined && (\n        <span className=\"hidden w-16 shrink-0 truncate text-muted-foreground @md/log:block\" title={entry.source}>\n          {entry.source}\n        </span>\n      )}\n      <span\n        className={cn(\n          \"min-w-0 flex-1 text-foreground\",\n          open ? \"break-words whitespace-pre-wrap\" : \"truncate\",\n          entry.level === \"debug\" && \"text-muted-foreground\",\n        )}\n        title={open ? undefined : entry.message}\n      >\n        {entry.source !== undefined && (\n          <span className=\"text-muted-foreground @md/log:hidden\">{entry.source} · </span>\n        )}\n        {highlight(entry.message, query)}\n      </span>\n    </div>\n  );\n});\n\n/** A live, terminal-style event stream that follows the tail until someone scrolls up to read. */\nexport function LogStream({\n  entries,\n  title = \"Events\",\n  description,\n  height = 320,\n  maxEntries = 500,\n  follow: followProp,\n  defaultFollow = true,\n  onFollowChange,\n  onClear,\n  live = true,\n  defaultLevels = LEVELS,\n  defaultQuery = \"\",\n  defaultWrap = false,\n  timeZone = \"local\",\n  className,\n  onKeyDown,\n  ...props\n}: LogStreamProps) {\n  const id = React.useId();\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const searchRef = React.useRef<HTMLInputElement>(null);\n  const pausedBy = React.useRef<\"scroll\" | \"user\" | null>(null);\n\n  const [followState, setFollowState] = React.useState(defaultFollow);\n  const following = followProp ?? followState;\n  const [frozen, setFrozen] = React.useState<LogEntry[] | null>(null);\n  const [levels, setLevels] = React.useState<ReadonlySet<LogLevel>>(() => new Set(defaultLevels));\n  const [search, setSearch] = React.useState(defaultQuery);\n  const [wrap, setWrap] = React.useState(defaultWrap);\n  const [expanded, setExpanded] = React.useState<ReadonlySet<string>>(() => new Set());\n  const [clearedAfter, setClearedAfter] = React.useState<string | null>(null);\n  const [mounted, setMounted] = React.useState(false);\n  React.useEffect(() => setMounted(true), []);\n\n  const setFollowing = React.useCallback(\n    (next: boolean, reason: \"scroll\" | \"user\" = \"user\") => {\n      pausedBy.current = next ? null : reason;\n      // Freeze what is on screen so reading is never interrupted by the stream.\n      setFrozen(next ? null : entries);\n      if (followProp === undefined) setFollowState(next);\n      onFollowChange?.(next);\n    },\n    [entries, followProp, onFollowChange],\n  );\n\n  // Keep a controlled `follow={false}` frozen too.\n  React.useLayoutEffect(() => {\n    if (!following && !frozen) setFrozen(entries);\n    if (following && frozen) setFrozen(null);\n  }, [following, frozen, entries]);\n\n  const visibleSource = React.useMemo(() => {\n    const source = frozen ?? entries;\n    if (clearedAfter === null) return source;\n    const index = lastIndexOfId(source, clearedAfter);\n    return index === -1 ? source : source.slice(index + 1);\n  }, [frozen, entries, clearedAfter]);\n\n  const query = search.trim().toLowerCase();\n  const { rows, counts, matching } = React.useMemo(() => {\n    const counts: Record<LogLevel, number> = { debug: 0, info: 0, warn: 0, error: 0 };\n    const rows: LogEntry[] = [];\n    for (const entry of visibleSource) {\n      if (\n        query &&\n        !entry.message.toLowerCase().includes(query) &&\n        !entry.source?.toLowerCase().includes(query)\n      )\n        continue;\n      counts[entry.level] = (counts[entry.level] ?? 0) + 1;\n      if (levels.has(entry.level)) rows.push(entry);\n    }\n    const matching = rows.length;\n    return { rows: rows.length > maxEntries ? rows.slice(-maxEntries) : rows, counts, matching };\n  }, [visibleSource, query, levels, maxEntries]);\n\n  const pending = React.useMemo(() => {\n    if (following || !frozen) return 0;\n    const last = frozen[frozen.length - 1];\n    const index = last ? lastIndexOfId(entries, last.id) : -1;\n    let count = 0;\n    for (let i = index + 1; i < entries.length; i++) if (levels.has(entries[i].level)) count++;\n    return count;\n  }, [following, frozen, entries, levels]);\n\n  // Stay pinned to the newest row while following.\n  React.useLayoutEffect(() => {\n    const element = scrollRef.current;\n    if (following && element) element.scrollTop = element.scrollHeight;\n  }, [following, rows]);\n\n  const handleScroll = () => {\n    const element = scrollRef.current;\n    if (!element) return;\n    const distance = element.scrollHeight - element.scrollTop - element.clientHeight;\n    if (following && distance > 24) setFollowing(false, \"scroll\");\n    else if (!following && pausedBy.current === \"scroll\" && distance < 2) setFollowing(true);\n  };\n\n  const toggleRow = React.useCallback((rowId: string) => {\n    if (window.getSelection()?.toString()) return;\n    setExpanded((current) => {\n      const next = new Set(current);\n      if (!next.delete(rowId)) next.add(rowId);\n      return next;\n    });\n  }, []);\n\n  const toggleLevel = (level: LogLevel) =>\n    setLevels((current) => {\n      const next = new Set(current);\n      if (!next.delete(level)) next.add(level);\n      return next;\n    });\n\n  const clear = () => {\n    setExpanded(new Set());\n    if (onClear) onClear();\n    else setClearedAfter(entries[entries.length - 1]?.id ?? null);\n    if (!following) setFollowing(true);\n  };\n\n  const resetFilters = () => {\n    setSearch(\"\");\n    setLevels(new Set(LEVELS));\n  };\n\n  const total = visibleSource.length;\n  const filtered = query !== \"\" || levels.size < LEVELS.length;\n\n  return (\n    <div\n      data-slot=\"log-stream\"\n      data-following={following || undefined}\n      className={cn(\n        \"@container/log flex min-w-0 flex-col overflow-hidden rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        const target = event.target as HTMLElement;\n        if (\n          event.key === \"/\" &&\n          !event.defaultPrevented &&\n          !(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement)\n        ) {\n          event.preventDefault();\n          searchRef.current?.focus();\n        }\n      }}\n      {...props}\n    >\n      <div className=\"flex items-start gap-3 px-4 pt-3.5 pb-3\">\n        <div className=\"min-w-0 flex-1\">\n          <div className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1\">\n            <p id={`${id}-title`} className=\"min-w-0 text-sm leading-6 font-semibold tracking-tight break-words\">\n              {title}\n            </p>\n            {live && (\n              <span\n                className={cn(\n                  \"inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2 py-px text-[11px] leading-4 font-medium\",\n                  following ? \"text-emerald-700 dark:text-emerald-400\" : \"text-amber-700 dark:text-amber-400\",\n                )}\n              >\n                <span className=\"relative flex size-1.5\" aria-hidden=\"true\">\n                  {following && (\n                    <span className=\"absolute inline-flex size-full animate-ping rounded-full bg-emerald-500 opacity-70 motion-reduce:hidden\" />\n                  )}\n                  <span\n                    className={cn(\n                      \"relative inline-flex size-1.5 rounded-full\",\n                      following ? \"bg-emerald-500\" : \"bg-amber-500\",\n                    )}\n                  />\n                </span>\n                {following ? \"Live\" : \"Paused\"}\n              </span>\n            )}\n          </div>\n          {description && <p className=\"truncate text-xs text-muted-foreground\">{description}</p>}\n        </div>\n        <div className=\"flex shrink-0 items-center gap-1\">\n          <button\n            type=\"button\"\n            aria-pressed={wrap}\n            title=\"Wrap long lines\"\n            onClick={() => setWrap((value) => !value)}\n            className={cn(\n              \"inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground aria-pressed:bg-muted aria-pressed:text-foreground motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <TextWrap className=\"size-4\" aria-hidden=\"true\" />\n            <span className=\"sr-only\">Wrap long lines</span>\n          </button>\n          <button\n            type=\"button\"\n            title=\"Clear\"\n            onClick={clear}\n            className={cn(\n              \"inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <Trash className=\"size-4\" aria-hidden=\"true\" />\n            <span className=\"sr-only\">Clear events</span>\n          </button>\n          {live && (\n            <button\n              type=\"button\"\n              title={following ? \"Pause the tail\" : \"Resume following\"}\n              aria-label={following ? \"Pause following\" : \"Resume following\"}\n              onClick={() => setFollowing(!following)}\n              className={cn(\n                \"ml-1 inline-flex h-7 items-center gap-1.5 rounded-md border bg-card px-2 text-xs font-medium shadow-xs transition-colors hover:bg-muted motion-reduce:transition-none @md/log:px-2.5\",\n                focusRing,\n              )}\n            >\n              {following ? (\n                <Pause className=\"size-3.5\" aria-hidden=\"true\" />\n              ) : (\n                <Play className=\"size-3.5\" aria-hidden=\"true\" />\n              )}\n              <span className=\"sr-only @md/log:not-sr-only\">{following ? \"Pause\" : \"Resume\"}</span>\n            </button>\n          )}\n        </div>\n      </div>\n\n      <div className=\"flex flex-wrap items-center gap-2 border-y bg-muted/30 px-4 py-2\">\n        <div role=\"group\" aria-label=\"Levels\" className=\"flex flex-wrap items-center gap-1\">\n          {LEVELS.map((level) => {\n            const active = levels.has(level);\n            return (\n              <button\n                key={level}\n                type=\"button\"\n                aria-pressed={active}\n                onClick={() => toggleLevel(level)}\n                className={cn(\n                  \"inline-flex h-6 items-center gap-1 rounded-md border px-1.5 text-xs transition-colors motion-reduce:transition-none @md/log:gap-1.5 @md/log:px-2\",\n                  active\n                    ? \"border-border bg-card text-foreground shadow-xs\"\n                    : \"border-transparent text-muted-foreground hover:text-foreground\",\n                  focusRing,\n                )}\n              >\n                <span\n                  aria-hidden=\"true\"\n                  className={cn(\n                    \"size-1.5 rounded-full\",\n                    active ? levelStyle[level].dot : \"bg-transparent ring-1 ring-muted-foreground/50 ring-inset\",\n                  )}\n                />\n                {levelStyle[level].label}\n                <span className=\"font-mono text-[11px] text-muted-foreground tabular-nums\">{counts[level]}</span>\n              </button>\n            );\n          })}\n        </div>\n        <div className=\"relative ml-auto min-w-36 flex-1 @lg/log:max-w-60\">\n          <Search\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground\"\n          />\n          <input\n            ref={searchRef}\n            type=\"text\"\n            value={search}\n            onChange={(event) => setSearch(event.target.value)}\n            onKeyDown={(event) => {\n              if (event.key === \"Escape\" && search) {\n                event.stopPropagation();\n                setSearch(\"\");\n              }\n            }}\n            placeholder=\"Filter…\"\n            aria-label=\"Filter messages\"\n            spellCheck={false}\n            className=\"h-7 w-full rounded-md border border-input bg-card pr-7 pl-7 text-xs text-foreground shadow-xs transition-[border-color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 motion-reduce:transition-none\"\n          />\n          {search ? (\n            <button\n              type=\"button\"\n              onClick={() => {\n                setSearch(\"\");\n                searchRef.current?.focus();\n              }}\n              className={cn(\n                \"absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:text-foreground\",\n                focusRing,\n              )}\n            >\n              <X className=\"size-3\" aria-hidden=\"true\" />\n              <span className=\"sr-only\">Clear filter</span>\n            </button>\n          ) : (\n            <kbd className=\"pointer-events-none absolute top-1/2 right-1.5 hidden -translate-y-1/2 rounded border bg-muted px-1 font-mono text-[10px] leading-4 text-muted-foreground @md/log:block\">\n              /\n            </kbd>\n          )}\n        </div>\n      </div>\n\n      <div className=\"relative\">\n        <div\n          ref={scrollRef}\n          role=\"log\"\n          aria-live=\"polite\"\n          aria-relevant=\"additions\"\n          aria-labelledby={`${id}-title`}\n          tabIndex={0}\n          onScroll={handleScroll}\n          className=\"overflow-y-auto overscroll-contain py-1.5 font-mono text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset\"\n          style={{ height }}\n        >\n          {rows.map((entry) => (\n            <LogRow\n              key={entry.id}\n              entry={entry}\n              query={query}\n              wrap={wrap}\n              expanded={expanded.has(entry.id)}\n              enter={mounted}\n              zone={timeZone}\n              onToggle={toggleRow}\n            />\n          ))}\n          {rows.length === 0 && (\n            <div className=\"flex h-full flex-col items-center justify-center gap-2 px-4 text-center font-sans\">\n              {total === 0 ? (\n                <p className=\"text-xs text-muted-foreground\">\n                  {live ? \"Waiting for events…\" : \"No events yet.\"}\n                </p>\n              ) : (\n                <>\n                  <p className=\"text-xs text-muted-foreground\">No events match these filters.</p>\n                  <button\n                    type=\"button\"\n                    onClick={resetFilters}\n                    className={cn(\"rounded-md px-2 py-1 text-xs font-medium text-primary hover:bg-muted\", focusRing)}\n                  >\n                    Show all events\n                  </button>\n                </>\n              )}\n            </div>\n          )}\n          {rows.length > 0 && live && following && (\n            <div aria-hidden=\"true\" className=\"px-4 py-[5px] leading-[18px]\">\n              <span className=\"inline-block h-3.5 w-[7px] translate-y-[3px] animate-pulse bg-foreground/35 motion-reduce:animate-none\" />\n            </div>\n          )}\n        </div>\n        <div\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-x-0 top-0 h-4 bg-linear-to-b from-card to-transparent\"\n        />\n        {!following && (\n          <button\n            type=\"button\"\n            onClick={() => setFollowing(true)}\n            className={cn(\n              \"absolute bottom-3 left-1/2 inline-flex h-7 -translate-x-1/2 items-center gap-1.5 rounded-full bg-foreground px-3 text-xs font-medium text-background shadow-lg transition-[opacity,translate] duration-200 starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <ArrowDown className=\"size-3.5\" aria-hidden=\"true\" />\n            Jump to latest\n            {pending > 0 && (\n              <span className=\"rounded-full bg-background/20 px-1.5 font-mono text-[11px] tabular-nums\">\n                {pending > 999 ? \"999+\" : pending} new\n              </span>\n            )}\n          </button>\n        )}\n      </div>\n\n      <div className=\"flex items-center justify-between gap-3 border-t px-4 py-1.5 font-mono text-[11px] text-muted-foreground tabular-nums\">\n        <span>\n          {filtered ? `${matching.toLocaleString(\"en-US\")} of ${total.toLocaleString(\"en-US\")}` : total.toLocaleString(\"en-US\")}{\" \"}\n          {total === 1 ? \"event\" : \"events\"}\n          {rows.length < matching && ` · showing last ${rows.length.toLocaleString(\"en-US\")}`}\n        </span>\n        <span>{timeZone === \"utc\" ? \"UTC\" : \"Local time\"}</span>\n      </div>\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/log-stream. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
