'use client'; /** * Renders a compact code reference block (file path + line range). * Clicking navigates to the file in the repository browser. */ import { useState } from 'react'; import { FileCode2, ChevronDown, ChevronRight } from 'lucide-react'; import { cn } from '@/lib/utils'; import type { CodeRef } from '@/lib/code-ref-parser'; interface CodeReferenceProps { ref: CodeRef; /** API to fetch line content (optional — shows skeleton if not provided) */ getLineContent?: (filePath: string, startLine: number, endLine: number) => Promise; /** Called when the reference is clicked — navigate to file browser */ onClick?: (ref: CodeRef) => void; /** Base URL for the repository file browser (e.g. /repository/ns/repo) */ repoBaseUrl?: string; /** Branch name to use in the link */ branch?: string; className?: string; } export function CodeReference({ ref, getLineContent, onClick, repoBaseUrl, branch = 'main', className, }: CodeReferenceProps) { const [expanded, setExpanded] = useState(false); const [lines, setLines] = useState(null); const [loading, setLoading] = useState(false); const handleClick = () => { if (onClick) { onClick(ref); return; } if (repoBaseUrl) { // Navigate to file browser with line highlighted window.location.href = `${repoBaseUrl}/blob/${branch}/${ref.filePath}#L${ref.startLine}`; } }; const loadLines = async () => { if (!getLineContent || lines !== null) return; setLoading(true); try { const content = await getLineContent(ref.filePath, ref.startLine, ref.endLine); setLines(content); } catch { setLines([]); } finally { setLoading(false); } }; const toggleExpand = () => { setExpanded((prev) => { if (!prev) loadLines(); return !prev; }); }; const lineLabel = ref.endLine === ref.startLine ? `L${ref.startLine}` : `L${ref.startLine}–L${ref.endLine}`; return (
{/* Header bar */} {/* Code preview (optional) */} {getLineContent && ( <> {expanded && (
{loading ? (
{Array.from({ length: Math.min(ref.endLine - ref.startLine + 1, 5) }).map((_, i) => (
))}
) : lines && lines.length > 0 ? (
{lines.map((line, i) => { const lineNum = ref.startLine + i; return (
{lineNum} {line || ' '}
); })}
) : (
No content available
)}
)} )}
); }