Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
"use client";
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { Route, X, ArrowRight, Search, ChevronDown } from "lucide-react";
import { Spinner } from "../ui/spinner";
import { Button } from "../ui/button";
import { useDebounce } from "../hooks/use-debounce";
import { disambiguateBasenames } from "../lib/format";
import { FilePath } from "../shared/file-path";
import { isFileNodeId } from "./node-id";
import type { GraphPath, NodeSearchResult } from "@repowise-dev/types/graph";
/** The panel's words; the defaults name files, a host searching other nodes (services) names those. */
export interface PathFinderCopy {
title: string;
fromPlaceholder: string;
toPlaceholder: string;
/** Heading over the suggestions shown before anything is typed. */
topHeading: string;
submit: string;
noPath: string;
}
const DEFAULT_COPY: PathFinderCopy = {
title: "Find Path",
fromPlaceholder: "From file...",
toPlaceholder: "To file...",
topHeading: "Top files by importance",
submit: "Find Path",
noPath: "No path found between these nodes.",
};
/** How a suggestion reads: a label and a short detail on the right. */
export type PathFinderOptionDescriber = (r: NodeSearchResult) => { label: string; detail: string };
export interface PathFinderPanelProps {
/** Inject the autocomplete searcher. Returns the top-N nodes for a query. */
searchNodes: (query: string, limit: number) => Promise<NodeSearchResult[]>;
/** Inject the path finder. Returns the engine's `GraphPath` payload. */
findPath: (from: string, to: string) => Promise<GraphPath>;
/** Called with the resolved path's node ids when a path is found. */
onPathFound: (pathNodes: string[]) => void;
/** Clear any prior highlighted path in the parent graph canvas. */
onClear: () => void;
/** Close the panel. */
onClose: () => void;
/** Pre-fill values driven by the parent's context-menu. */
initialFrom?: string;
initialTo?: string;
/** Override any of the panel's words. */
copy?: Partial<PathFinderCopy>;
/** Label suggestions yourself; by default a file path and its language. */
describeOption?: PathFinderOptionDescriber;
}
interface NodeAutocompleteProps {
searchNodes: PathFinderPanelProps["searchNodes"];
value: string;
onChange: (v: string) => void;
placeholder: string;
topHeading: string;
describeOption?: PathFinderOptionDescriber | undefined;
onSubmit?: () => void;
}
function NodeAutocomplete({
searchNodes,
value,
onChange,
placeholder,
topHeading,
describeOption,
onSubmit,
}: NodeAutocompleteProps) {
const [results, setResults] = useState<NodeSearchResult[]>([]);
const [topNodes, setTopNodes] = useState<NodeSearchResult[]>([]);
const [showDropdown, setShowDropdown] = useState(false);
const debounced = useDebounce(value, 250);
const topLoaded = useRef(false);
// Load top nodes by pagerank once for the dropdown
useEffect(() => {
if (topLoaded.current) return;
topLoaded.current = true;
searchNodes("", 20)
.then(setTopNodes)
.catch(() => {});
}, [searchNodes]);
// Search as user types
useEffect(() => {
if (!debounced.trim() || debounced.length < 2) {
setResults([]);
return;
}
searchNodes(debounced, 12)
.then((r) => {
setResults(r);
setShowDropdown(r.length > 0);
})
.catch(() => setResults([]));
}, [debounced, searchNodes]);
const displayResults = results.length > 0 ? results : topNodes;
const handleSelect = useCallback(
(nodeId: string) => {
onChange(nodeId);
setShowDropdown(false);
},
[onChange],
);
return (
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-[var(--color-text-tertiary)]" />
<input
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
onFocus={() => setShowDropdown(true)}
onBlur={() => setTimeout(() => setShowDropdown(false), 150)}
onKeyDown={(e) => {
if (e.key === "Enter") {
setShowDropdown(false);
onSubmit?.();
}
}}
placeholder={placeholder}
className="w-full h-8 pl-8 pr-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-inset)] text-xs font-mono text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] focus:outline-none focus:border-[var(--color-accent-graph)] focus:ring-1 focus:ring-[var(--color-accent-graph)]/30 transition-all"
/>
<ChevronDown className="absolute right-2.5 top-1/2 -translate-y-1/2 w-3 h-3 text-[var(--color-text-tertiary)]" />
{showDropdown && displayResults.length > 0 && (
<div className="absolute top-full left-0 mt-1 w-full max-h-52 overflow-auto z-[var(--z-dropdown)] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] shadow-xl shadow-black/30 py-1">
{results.length === 0 && topNodes.length > 0 && (
<div className="px-3 py-1 text-[10px] text-[var(--color-text-tertiary)] uppercase tracking-wider">
{topHeading}
</div>
)}
{displayResults.map((r) => {
const described = describeOption?.(r);
return (
<button
key={r.node_id}
className="w-full px-3 py-1.5 text-left text-xs hover:bg-[var(--color-bg-elevated)] transition-colors flex items-center gap-2"
onMouseDown={() => handleSelect(r.node_id)}
>
{described ? (
<span className="flex-1 truncate font-mono text-[var(--color-text-primary)]">{described.label}</span>
) : isFileNodeId(r.node_id) ? (
<FilePath path={r.node_id} fold className="flex-1 text-[var(--color-text-primary)]" />
) : (
<span className="flex-1 truncate font-mono text-[var(--color-text-primary)]">{r.node_id}</span>
)}
<span
className={`text-[10px] text-[var(--color-text-tertiary)] shrink-0 tabular-nums ${described ? "" : "capitalize"}`}
>
{described ? described.detail : r.language}
</span>
</button>
);
})}
</div>
)}
</div>
);
}
export function PathFinderPanel({
searchNodes,
findPath,
onPathFound,
onClear,
onClose,
initialFrom = "",
initialTo = "",
copy: copyOverrides,
describeOption,
}: PathFinderPanelProps) {
const copy = { ...DEFAULT_COPY, ...copyOverrides };
const [from, setFrom] = useState(initialFrom);
const [to, setTo] = useState(initialTo);
const [loading, setLoading] = useState(false);
const [result, setResult] = useState<GraphPath | null>(null);
const hopLabels = useMemo(() => disambiguateBasenames(result?.path ?? []), [result]);
const [error, setError] = useState<string | null>(null);
// Sync initial values when they change from context menu
useEffect(() => {
if (initialFrom) setFrom(initialFrom);
}, [initialFrom]);
useEffect(() => {
if (initialTo) setTo(initialTo);
}, [initialTo]);
const handleFind = useCallback(async () => {
if (!from.trim() || !to.trim()) return;
setLoading(true);
setError(null);
setResult(null);
onClear();
try {
const res = await findPath(from.trim(), to.trim());
setResult(res);
if (res.path && res.path.length > 0) {
onPathFound(res.path);
} else {
setError(copy.noPath);
}
} catch {
setError(copy.noPath);
} finally {
setLoading(false);
}
}, [from, to, findPath, onPathFound, onClear, copy.noPath]);
const handleClear = useCallback(() => {
setFrom("");
setTo("");
setResult(null);
setError(null);
onClear();
}, [onClear]);
return (
<div className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)]/90 backdrop-blur-md shadow-xl shadow-black/30 p-3 w-[min(280px,calc(100vw-1.5rem))] space-y-2">
{/* Header */}
<div className="flex items-center gap-2">
<Route className="w-3.5 h-3.5 text-[var(--color-accent-graph)]" />
<span className="text-xs font-semibold text-[var(--color-text-primary)]">
{copy.title}
</span>
<div className="ml-auto flex items-center gap-1">
{(result || error) && (
<Button
size="sm"
variant="ghost"
onClick={handleClear}
className="h-5 w-5 p-0"
aria-label="Clear results"
title="Clear results"
>
<X className="h-3 w-3" />
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={onClose}
className="h-5 w-5 p-0 text-[var(--color-text-tertiary)]"
aria-label="Close"
title="Close"
>
<X className="h-3 w-3" />
</Button>
</div>
</div>
{/* Inputs stacked */}
<div className="space-y-1.5">
<NodeAutocomplete
searchNodes={searchNodes}
value={from}
onChange={setFrom}
placeholder={copy.fromPlaceholder}
topHeading={copy.topHeading}
describeOption={describeOption}
onSubmit={handleFind}
/>
<NodeAutocomplete
searchNodes={searchNodes}
value={to}
onChange={setTo}
placeholder={copy.toPlaceholder}
topHeading={copy.topHeading}
describeOption={describeOption}
onSubmit={handleFind}
/>
</div>
{/* Find button */}
<Button
size="sm"
onClick={handleFind}
disabled={!from.trim() || !to.trim() || loading}
className="w-full h-7 text-xs font-medium gap-1.5"
>
{loading ? (
<Spinner size="sm" />
) : (
<Route className="h-3.5 w-3.5" />
)}
{copy.submit}
</Button>
{/* Result */}
{result && result.path && result.path.length > 0 && (
<div className="rounded-lg bg-[var(--color-bg-inset)] border border-[var(--color-border-default)] p-2 space-y-1">
<p className="text-[10px] font-medium text-[var(--color-accent-graph)] uppercase tracking-wider">
{result.distance} {result.distance === 1 ? "hop" : "hops"}
</p>
<div className="space-y-0.5 max-h-28 overflow-auto">
{result.path.map((nodeName, i) => {
return (
<div key={i} className="flex items-center gap-1">
{i > 0 && (
<ArrowRight className="w-2.5 h-2.5 text-[var(--color-accent-graph)] shrink-0" />
)}
{isFileNodeId(nodeName) ? (
<FilePath
path={nodeName}
mode="distinguishing"
labels={hopLabels}
className="text-[10px] text-[var(--color-text-secondary)]"
/>
) : (
<span
className="truncate font-mono text-[10px] text-[var(--color-text-secondary)]"
title={nodeName}
>
{nodeName}
</span>
)}
</div>
);
})}
</div>
</div>
)}
{error && (
<p className="text-[10px] text-[var(--color-risk-high)]">{error}</p>
)}
</div>
);
}