Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

6.7 KB
Raw Blame
import { Flame } from "lucide-react";
import { Badge } from "../ui/badge";
import { fileEntityPath, symbolEntityPath } from "../shared/entity/routes";
import { EntityHeader } from "../shared/entity";
import { FilePath } from "../shared/file-path";
import type { BreadcrumbSegment } from "../shared/breadcrumb";
import type {
  SymbolDetailData,
  SymbolDetailResponse,
} from "@repowise-dev/types/symbols";
import { FixHistoryBadge, SYMBOL_FIX_TITLE } from "../git/fix-history-badge";
import { AskAboutThis } from "../chat/ask-about-this";
import { SymbolDetailBody } from "./symbol-detail-body";
import { toSymbolBodyCall, toSymbolBodyRelations } from "./normalize-calls";

export interface SymbolPageProps {
  data: SymbolDetailResponse;
  repoId: string;
  linkPrefix?: string;
  breadcrumb?: BreadcrumbSegment[];
  LinkComponent?: React.ElementType<{
    href: string;
    className?: string;
    children: React.ReactNode;
  }>;
  onOpenBlastRadius?: () => void;
}

/**
 * Pure mapping of the route's `SymbolDetailResponse` onto the unified
 * `SymbolDetailData`. The drawer surface normalizes its `CodeSymbol` + graph
 * APIs into the same shape (in its web wrapper), so both render one body.
 *
 * The route populates every field its endpoint actually returns — symbol,
 * graph (callers/callees + degrees), function-blame, governing decisions, and
 * file_context. It deliberately leaves file-level git intelligence (git,
 * co_changes, dead_code) and the graph-percentile / entry-point / heritage
 * feeds undefined: `SymbolDetailResponse` does not carry them, so the body's
 * presence-guards hide those blocks rather than the mapping fabricating data.
 * Governing decisions are passed through and rendered inside `SymbolDetailBody`
 * (not the header) so they appear exactly once on both surfaces.
 */
export function normalizeSymbolDetailResponse(
  data: SymbolDetailResponse,
): SymbolDetailData {
  const s = data.symbol;
  return {
    identity: {
      name: s.name,
      qualified_name: s.qualified_name,
      kind: s.kind,
      visibility: s.visibility,
      language: s.language,
      is_async: s.is_async,
      file_path: s.file_path,
      start_line: s.start_line,
      parent_name: s.parent_name,
      file_is_hotspot: s.file_is_hotspot ?? null,
    },
    signature: s.signature,
    docstring: s.docstring,
    importance_score: s.importance_score ?? null,
    complexity_estimate: s.complexity_estimate,
    blame_mod_count: s.blame_mod_count ?? null,
    blame_recent_mod_count: s.blame_recent_mod_count ?? null,
    blame_median_author_time: s.blame_median_author_time ?? null,
    blame_owner_name: s.blame_owner_name ?? null,
    blame_owner_line_pct: s.blame_owner_line_pct ?? null,
    fix_count: data.fix_count ?? null,
    fix_last_at: data.fix_last_at ?? null,
    graph: {
      in_degree: data.graph.in_degree,
      out_degree: data.graph.out_degree,
      callers: data.graph.callers.map(toSymbolBodyCall),
      callees: data.graph.callees.map(toSymbolBodyCall),
      caller_total: data.graph.caller_total ?? data.graph.callers.length,
      callee_total: data.graph.callee_total ?? data.graph.callees.length,
      ...(data.graph.relations
        ? { relations: toSymbolBodyRelations(data.graph.relations) ?? [] }
        : {}),
    },
    governing_decisions: data.governing_decisions,
    file_context: {
      health_score: data.file_context.health_score,
      language: data.file_context.language,
    },
  };
}

/**
 * The canonical routed symbol page: a standardized entity header (eyebrow,
 * breadcrumb, identity, one-line summary, primary signal) over the shared
 * `SymbolDetailBody`.
 */
export function SymbolPage({
  data,
  repoId,
  linkPrefix,
  breadcrumb,
  LinkComponent,
  onOpenBlastRadius,
}: SymbolPageProps) {
  const prefix = linkPrefix ?? `/repos/${repoId}`;
  const s = data.symbol;
  const normalized = normalizeSymbolDetailResponse(data);

  return (
    <div className="space-y-4">
      <EntityHeader
        eyebrow="SYMBOL"
        breadcrumb={breadcrumb ?? []}
        identity={
          <span className="font-mono break-all" title={s.qualified_name || s.name}>
            {s.name}
          </span>
        }
        summary={symbolSummary(data)}
        metaBadges={
          <>
            <Badge variant="outline" className="h-5 text-[10px]">
              {s.kind}
            </Badge>
            {s.is_async && (
              <Badge variant="outline" className="h-5 text-[10px]">
                async
              </Badge>
            )}
            <Badge variant="outline" className="h-5 text-[10px] capitalize">
              {s.visibility}
            </Badge>
            {s.file_is_hotspot && (
              <Badge
                variant="outline"
                className="h-5 text-[10px] text-[var(--color-error)] border-[var(--color-error)]/30"
              >
                <Flame className="h-2.5 w-2.5" /> hot file
              </Badge>
            )}
            <FixHistoryBadge
              count={data.fix_count ?? null}
              lastFixAt={data.fix_last_at ?? null}
              title={SYMBOL_FIX_TITLE}
              className="h-5 text-[10px]"
            />
            <a
              href={fileEntityPath(prefix, s.file_path)}
              className="max-w-full text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] hover:underline"
            >
              <FilePath path={s.file_path} line={s.start_line} mode="full" />
            </a>
            <AskAboutThis
              context={{
                kind: "symbol",
                label: s.qualified_name || s.name,
                target: s.symbol_id,
                targetKind: "symbol",
              }}
              question={`What does ${s.qualified_name || s.name} do, who calls it, and what should tests protect?`}
              label={`Ask about ${s.name}`}
              className="h-6 w-6"
            />
          </>
        }
        {...(LinkComponent ? { LinkComponent } : {})}
      />

      <SymbolDetailBody
        data={normalized}
        symbolHref={(symId) => symbolEntityPath(prefix, symId)}
        fileHref={(p) => fileEntityPath(prefix, p)}
        {...(onOpenBlastRadius ? { onOpenBlastRadius } : {})}
      />
    </div>
  );
}

/** Synthesised "what is this" one-liner for a symbol — the missing summary. */
function symbolSummary(data: SymbolDetailResponse): string {
  const s = data.symbol;
  if (s.docstring) {
    const firstLine = s.docstring.split("\n").find((l) => l.trim()) ?? "";
    if (firstLine.trim()) return firstLine.trim();
  }
  const kind = s.kind || "symbol";
  const article = /^[aeiou]/i.test(kind) ? "An" : "A";
  const where = s.file_path.split("/").pop() ?? s.file_path;
  return `${article} undocumented ${kind} in ${where}.`;
}