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.

16.7 KB
Raw Blame
/**
 * Sidebar Home: the face of the extension. The repo's health score and trend,
 * an index-freshness row with a one-click update, and a launcher card per
 * dashboard panel so everything the extension can show is discoverable from the
 * first click on the activity-bar icon. Designed for the sidebar's ~300px
 * width; the dashboards themselves open as editor tabs via `host.openView`.
 *
 * The two statistics group with hairlines and the launchers keep their cards.
 * That split is the rule rather than an inconsistency: a card means "a discrete
 * object you can act on", which every launcher is and neither statistic was.
 * Sizes stay at 11 and 13px here — a ~300px rail is the width argument the
 * compact density exists for, and the full-tab panels do not get the same
 * excuse.
 */

import { useCallback, useEffect, useState, type ComponentType } from "react";
import {
  Activity,
  BookOpen,
  ChevronRight,
  GitBranch,
  Layers,
  Monitor,
  Moon,
  RefreshCw,
  Scale,
  Settings2,
  Share2,
  Sun,
  Wrench,
} from "lucide-react";
import { EmptyState } from "@repowise-dev/ui/shared";
import { scoreTextColor } from "@repowise-dev/ui/health/tokens";
import { formatScore } from "@repowise-dev/types/health";
import type {
  HomeSummary,
  PanelViewId,
  ThemePreference,
} from "../../../../src/shared/webviewMessages";
import type { ViewProps } from "../../runtime/mount";
import type { WebviewHost } from "../../runtime/rpc";
import {
  getThemeKind,
  getThemePreference,
  setThemePreference,
  subscribeTheme,
  type ThemeKind,
} from "../../runtime/theme";
import owlDarkTheme from "../../assets/owl-dark-theme.png";
import owlLightTheme from "../../assets/owl-light-theme.png";

/** The shared band ramp as a text class, so this hero and the health dashboard
 * it launches read a score the same way. */
function scoreTone(score: number | null): string {
  return score == null ? "text-[var(--color-text-tertiary)]" : scoreTextColor(score);
}

/** Compact relative time for the freshness row ("3h ago"). */
function timeAgo(iso: string): string {
  const then = Date.parse(iso);
  if (Number.isNaN(then)) return "";
  const minutes = Math.floor((Date.now() - then) / 60_000);
  if (minutes < 1) return "just now";
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  return days < 30 ? `${days}d ago` : new Date(then).toLocaleDateString();
}

function short(commit: string | null): string | null {
  return commit ? commit.slice(0, 7) : null;
}

interface CardSpec {
  view: PanelViewId;
  title: string;
  icon: ComponentType<{ className?: string }>;
  /** Live micro-stat when the summary carries one, otherwise a static hook. */
  subtitle: (summary: HomeSummary | null, defaultBranch: string | null) => string;
}

const CARDS: CardSpec[] = [
  {
    view: "health",
    title: "Code Health",
    icon: Activity,
    subtitle: (s) =>
      s?.health
        ? `${s.health.openFindings.toLocaleString()} open findings · ${s.health.fileCount.toLocaleString()} files`
        : "The score map, its lenses, and the trend",
  },
  {
    view: "architecture",
    title: "Architecture",
    icon: Layers,
    subtitle: () => "Modules and layers on one canvas",
  },
  {
    view: "graph",
    title: "Knowledge Graph",
    icon: Share2,
    subtitle: () => "Dependencies, communities, execution flows",
  },
  {
    view: "refactoring",
    title: "Refactoring",
    icon: Wrench,
    subtitle: (s) =>
      s?.counts.refactoringPlans != null
        ? `${s.counts.refactoringPlans.toLocaleString()} ranked plans`
        : "Server-ranked refactoring opportunities",
  },
  {
    view: "decisions",
    title: "Decisions",
    icon: Scale,
    subtitle: (s) =>
      s?.counts.decisions != null
        ? `${s.counts.decisions.toLocaleString()} decision records`
        : "Architectural decision records",
  },
  {
    view: "docs",
    title: "Docs",
    icon: BookOpen,
    subtitle: () => "Browse the generated wiki",
  },
  {
    view: "risk",
    title: "Change Risk",
    icon: GitBranch,
    subtitle: (_s, defaultBranch) => `Score this branch against ${defaultBranch ?? "main"}`,
  },
];

export function App({ host, repo, refreshToken }: ViewProps<"home">) {
  const [summary, setSummary] = useState<HomeSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [updating, setUpdating] = useState(false);

  const load = useCallback(() => {
    setLoading(true);
    host.api
      .homeSummary()
      .then((s) => {
        setSummary(s);
        setLoading(false);
      })
      .catch(() => {
        // The launcher stays useful without stats; sections degrade to their
        // static subtitles and the hero shows its empty state.
        setSummary(null);
        setLoading(false);
      });
  }, [host]);

  useEffect(() => {
    load();
  }, [load, refreshToken]);

  // The host acks update completion whether it succeeded or failed; a success
  // also lands as a refresh, so this reload mostly re-reads the fresh cache.
  useEffect(
    () =>
      host.onUpdateDone(() => {
        setUpdating(false);
        load();
      }),
    [host, load],
  );

  const runUpdate = () => {
    if (updating) return;
    setUpdating(true);
    host.updateIndex();
  };

  return (
    <div className="min-h-screen space-y-3 bg-[var(--color-bg-root)] p-3">
      <Hero
        repoName={repo.name}
        branch={summary?.freshness.branch ?? null}
        health={summary?.health ?? null}
        loading={loading && !summary}
      />
      <Freshness
        freshness={summary?.freshness ?? null}
        updating={updating}
        onUpdate={runUpdate}
      />
      <nav
        aria-label="Dashboards"
        className="border-t border-[var(--color-border-default)] pt-3"
      >
        <p className="px-1 pb-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
          Explore
        </p>
        {CARDS.map((card) => (
          <LauncherRow
            key={card.view}
            icon={card.icon}
            title={card.title}
            subtitle={card.subtitle(summary, repo.defaultBranch)}
            onOpen={() => host.openView(card.view)}
          />
        ))}
        <LauncherRow
          icon={Settings2}
          title="Settings"
          subtitle="Toggle editor signals, server, and more"
          muted
          onOpen={() => host.openView("settings")}
        />
      </nav>
      <Footer host={host} />
    </div>
  );
}

/** Brand mark plus the theme switcher. The preference applies to every
 *  Repowise webview and persists via the host; "auto" follows the editor. */
function Footer({ host }: { host: WebviewHost }) {
  const [pref, setPref] = useState<ThemePreference>(getThemePreference());
  const [kind, setKind] = useState<ThemeKind>(getThemeKind());
  useEffect(() => subscribeTheme(setKind), []);

  const choose = (next: ThemePreference) => {
    setPref(next);
    // Applied locally for instant feedback; the host persists it and pushes
    // theme-changed to every other open Repowise view.
    setThemePreference(next);
    host.setTheme(next);
  };

  const options: { value: ThemePreference; icon: ComponentType<{ className?: string }>; label: string }[] = [
    { value: "auto", icon: Monitor, label: "Follow editor theme" },
    { value: "light", icon: Sun, label: "Light theme" },
    { value: "dark", icon: Moon, label: "Dark theme" },
  ];

  return (
    <footer className="flex items-center justify-between px-1 pb-1 pt-2">
      <span className="flex items-center gap-1.5">
        <img
          src={kind === "dark" ? owlDarkTheme : owlLightTheme}
          alt=""
          className="h-4 w-4"
        />
        <span className="text-xs font-semibold tracking-wide text-[var(--color-text-tertiary)]">
          Repowise
        </span>
      </span>
      <div
        role="group"
        aria-label="Theme"
        className="inline-flex rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-0.5"
      >
        {options.map(({ value, icon: Icon, label }) => (
          <button
            key={value}
            type="button"
            onClick={() => choose(value)}
            aria-pressed={pref === value}
            title={label}
            aria-label={label}
            className={
              pref === value
                ? "rounded-md bg-[var(--color-bg-selected)] p-1 text-[var(--color-text-primary)]"
                : "rounded-md p-1 text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"
            }
          >
            <Icon className="h-3 w-3" />
          </button>
        ))}
      </div>
    </footer>
  );
}

function Hero({
  repoName,
  branch,
  health,
  loading,
}: {
  repoName: string;
  branch: string | null;
  health: HomeSummary["health"];
  loading: boolean;
}) {
  // Average health leads; hotspot health (NLOC-weighted, more volatile) is the
  // secondary read. Quiet or small repos gate hotspot scoring off entirely, in
  // which case only the average shows.
  const hasHotspot = health?.hotspot != null;
  const headline = health?.average ?? health?.hotspot ?? null;
  // A statistic, not an object you can act on, so it groups with rhythm rather
  // than with a border and a raised ground. The launchers below keep theirs:
  // those are navigation buttons.
  return (
    <section aria-label="Repository health" className="px-1 pt-1">
      <div className="flex items-center justify-between gap-2">
        <p className="truncate text-xs font-semibold text-[var(--color-text-primary)]">
          {repoName}
        </p>
        {branch ? (
          <span className="flex min-w-0 shrink items-center gap-1 text-xs text-[var(--color-text-tertiary)]">
            <GitBranch className="h-3 w-3 shrink-0" />
            <span className="truncate font-mono">{branch}</span>
          </span>
        ) : null}
      </div>

      {loading ? (
        <div className="mt-3 space-y-2" role="status" aria-label="Loading health score">
          <div className="h-9 w-24 animate-pulse rounded-md bg-[var(--color-bg-inset)]" />
          <div className="h-3 w-40 animate-pulse rounded bg-[var(--color-bg-inset)]" />
        </div>
      ) : headline != null ? (
        <>
          <div className="mt-3 flex items-end gap-2">
            <span
              className={`text-4xl font-bold leading-none tracking-tight tabular-nums ${scoreTone(headline)}`}
            >
              {formatScore(headline)}
            </span>
            <span className="pb-0.5 text-xs text-[var(--color-text-tertiary)]">/ 10</span>
          </div>
          <p className="mt-1.5 flex flex-wrap items-center gap-x-1.5 text-xs text-[var(--color-text-secondary)]">
            <span>Average health</span>
            {hasHotspot ? (
              <>
                <span aria-hidden className="text-[var(--color-text-tertiary)]">·</span>
                <span>hotspot {health?.hotspot != null ? formatScore(health.hotspot) : undefined}</span>
                <DeltaChip delta={health?.hotspotDelta ?? null} />
              </>
            ) : null}
            <span aria-hidden className="text-[var(--color-text-tertiary)]">·</span>
            <span>{(health?.fileCount ?? 0).toLocaleString()} files</span>
          </p>
          {hasHotspot && (health?.history.length ?? 0) >= 2 ? (
            <Sparkline values={health?.history ?? []} tone={scoreTone(health?.hotspot ?? null)} />
          ) : null}
        </>
      ) : (
        <EmptyState
          size="compact"
          title="No health data yet"
          description="Scores appear after the first full index."
        />
      )}
    </section>
  );
}

/**
 * Hotspot movement since the last snapshot.
 *
 * Not a filled pill and not coloured. Green forty pixels under a green health
 * numeral is the two-marks-one-colour trap: on the numeral green means "band:
 * healthy", here it would mean "direction: improved", and a reader who
 * correctly infers one has been taught a rule that makes them wrong about the
 * other. Health owns green/amber/red on this surface because those carry a
 * band; direction is carried by the arrow, which needs no hue.
 */
function DeltaChip({ delta }: { delta: number | null }) {
  if (delta == null || delta === 0) return null;
  return (
    <span
      className="text-[10px] font-medium tabular-nums text-[var(--color-text-tertiary)]"
      title="Hotspot health change since the previous snapshot"
    >
      {delta > 0 ? "▲" : "▼"} {Math.abs(delta).toFixed(1)}
    </span>
  );
}

/** Tiny inline trend line; the hero already labels it, so it is decorative. */
function Sparkline({ values, tone }: { values: number[]; tone: string }) {
  const width = 100;
  const height = 24;
  const min = Math.min(...values);
  const max = Math.max(...values);
  const span = max - min || 1;
  const step = width / (values.length - 1);
  const points = values
    .map((v, i) => `${(i * step).toFixed(1)},${(height - 3 - ((v - min) / span) * (height - 6)).toFixed(1)}`)
    .join(" ");
  return (
    <svg
      viewBox={`0 0 ${width} ${height}`}
      preserveAspectRatio="none"
      className={`mt-2 h-6 w-full ${tone}`}
      aria-hidden
    >
      <polyline
        points={points}
        fill="none"
        stroke="currentColor"
        strokeWidth="1.5"
        opacity="0.9"
      />
    </svg>
  );
}

function Freshness({
  freshness,
  updating,
  onUpdate,
}: {
  freshness: HomeSummary["freshness"] | null;
  updating: boolean;
  onUpdate: () => void;
}) {
  const stale = freshness?.stale ?? false;
  const indexed = short(freshness?.indexedCommit ?? null);
  const live = short(freshness?.liveCommit ?? null);

  let detail = "";
  if (stale && indexed && live) detail = `${indexed} → ${live}`;
  else if (indexed) {
    const ago = freshness?.lastIndexedAt ? timeAgo(freshness.lastIndexedAt) : "";
    detail = ago ? `${indexed} · indexed ${ago}` : indexed;
  }

  return (
    // A statistic plus its one action, so it groups with a hairline rather than
    // a card. The dot renders only when the index is behind: a marker every
    // state carries says nothing, and a quiet row is a fresh index.
    <section
      aria-label="Index freshness"
      className="flex items-center gap-2.5 border-t border-[var(--color-border-default)] px-1 pt-3"
    >
      {stale ? (
        <span
          className="h-2 w-2 shrink-0 rounded-full bg-[var(--color-warning)]"
          aria-hidden
        />
      ) : null}
      <div className="min-w-0 flex-1">
        <p className="text-xs font-medium text-[var(--color-text-primary)]">
          {updating ? "Updating index…" : stale ? "Index behind checkout" : "Index up to date"}
        </p>
        {detail ? (
          <p className="truncate font-mono text-[10px] text-[var(--color-text-tertiary)]">
            {detail}
          </p>
        ) : null}
      </div>
      <button
        type="button"
        onClick={onUpdate}
        disabled={updating}
        title="Update the index with recent changes"
        className={
          stale && !updating
            ? "flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--color-accent-primary)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-on-accent)] transition-opacity hover:opacity-90"
            : "flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] disabled:cursor-default disabled:opacity-60"
        }
      >
        <RefreshCw className={updating ? "h-3 w-3 animate-spin" : "h-3 w-3"} />
        {updating ? "Updating" : "Update"}
      </button>
    </section>
  );
}

function LauncherRow({
  icon: Icon,
  title,
  subtitle,
  muted,
  onOpen,
}: {
  icon: ComponentType<{ className?: string }>;
  title: string;
  subtitle: string;
  muted?: boolean;
  onOpen: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onOpen}
      className="group flex w-full items-center gap-3 rounded-md border-b border-[var(--color-border-default)] px-2 py-2 text-left transition-colors last:border-b-0 hover:bg-[var(--color-bg-wash-hover)]"
    >
      <Icon
        className={
          "h-4 w-4 shrink-0 " +
          (muted ? "text-[var(--color-text-secondary)]" : "text-[var(--color-accent-primary)]")
        }
      />
      <span className="min-w-0 flex-1">
        <span className="block text-xs font-medium text-[var(--color-text-primary)]">{title}</span>
        <span className="block text-xs leading-snug text-[var(--color-text-tertiary)]">
          {subtitle}
        </span>
      </span>
      <ChevronRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)] opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100" />
    </button>
  );
}