"use client"; import { useEffect, useRef, useState } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { cn } from "@/lib/utils"; type LogLine = { id: number; ts: number; stream: string; line: string }; /** Polls `url?after=` for new lines and keeps the view pinned to the bottom unless scrolled up. */ export function LiveLog({ url, title = "Log", live = true, className }: { url: string; title?: string; live?: boolean; className?: string }) { const [lines, setLines] = useState([]); const box = useRef(null); const stick = useRef(true); useEffect(() => { let last = 0; let stopped = false; const load = async () => { const res = await fetch(`${url}?after=${last}`, { cache: "no-store" }).catch(() => null); if (!res?.ok || stopped) return; const next: LogLine[] = await res.json(); if (next.length === 0) return; last = next[next.length - 1].id; setLines((prev) => [...prev, ...next].slice(-2000)); }; void load(); if (!live) return () => void (stopped = true); const t = setInterval(load, 1_500); return () => { stopped = true; clearInterval(t); }; }, [url, live]); useEffect(() => { if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight; }, [lines]); return ( {title}
{ const el = e.currentTarget; stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40; }} className="h-96 overflow-auto rounded-lg bg-muted/50 px-3 py-2 font-mono text-[11px] leading-relaxed" > {lines.length === 0 ? ( No output yet. ) : ( lines.map((l) => (
{l.line}
)) )}
); }