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
feat(docs): add Present mode (slide deck + guided walkthrough) (#914)
Raghav Chamadiya2e7e42fcc7bd
diff --git a/packages/ui/__tests__/present/build-present-model.test.ts b/packages/ui/__tests__/present/build-present-model.test.tsnew file mode 100644index 000000000..4f26ab84a--- /dev/null+++ b/packages/ui/__tests__/present/build-present-model.test.ts@@ -0,0 +1,157 @@+import { describe, it, expect } from "vitest";+import { buildPresentModel, canPresent } from "../../src/present/build-present-model.js";+import {+ splitOnH2,+ extractMermaidBlocks,+ stripLeadingH1,+ countWords,+ clampProse,+} from "../../src/present/split-markdown.js";+import type { DocPage } from "@repowise-dev/types/docs";++function makePage(overrides: Partial<DocPage> = {}): DocPage {+ return {+ id: "p1",+ repository_id: "r1",+ page_type: "file_page",+ title: "Page",+ content: "",+ target_path: "src/foo.ts",+ source_hash: "h",+ model_name: "m",+ provider_name: "p",+ input_tokens: 0,+ output_tokens: 0,+ cached_tokens: 0,+ generation_level: 0,+ version: 1,+ confidence: 1,+ freshness_status: "fresh",+ metadata: {},+ human_notes: null,+ created_at: "",+ updated_at: "",+ ...overrides,+ };+}++describe("split-markdown", () => {+ it("splits on H2 and keeps the lead", () => {+ const { lead, sections } = splitOnH2("Intro line.\n\n## First\nbody a\n\n## Second\nbody b");+ expect(lead).toBe("Intro line.");+ expect(sections.map((s) => s.heading)).toEqual(["First", "Second"]);+ expect(sections[0]!.body).toContain("body a");+ });++ it("ignores ## inside a code fence", () => {+ const { sections } = splitOnH2("lead\n\n```\n## not a heading\n```\n\n## Real\nx");+ expect(sections.map((s) => s.heading)).toEqual(["Real"]);+ });++ it("strips a single leading H1", () => {+ expect(stripLeadingH1("# Title\n\nbody")).toBe("body");+ expect(stripLeadingH1("no heading")).toBe("no heading");+ });++ it("extracts mermaid blocks", () => {+ const blocks = extractMermaidBlocks("text\n\n```mermaid\ngraph TD\nA-->B\n```\n\nmore");+ expect(blocks).toEqual(["graph TD\nA-->B"]);+ });++ it("counts words ignoring fences and markdown punctuation", () => {+ expect(countWords("## Heading\n\none two three\n\n```\nignored code here\n```")).toBe(4);+ });++ it("clamps prose on paragraph boundaries but always returns the first", () => {+ const long = "a".repeat(600);+ expect(clampProse(`${long}\n\nsecond`, 300)).toBe(long);+ });+});++describe("canPresent", () => {+ it("requires a repo_overview page", () => {+ expect(canPresent([makePage({ page_type: "file_page" })])).toBe(false);+ expect(canPresent([makePage({ page_type: "repo_overview" })])).toBe(true);+ });+});++describe("buildPresentModel", () => {+ const overview = makePage({+ id: "ov",+ page_type: "repo_overview",+ title: "Acme Overview",+ target_path: "repo",+ content: "# Acme\n\nA build tool.\n\n## Details\nmore",+ metadata: {+ layer_order: ["API", "Core"],+ guided_tour: [+ { order: 1, title: "main.py", target_path: "src/main.py", reason: "entry point" },+ { order: 2, title: "core.py", target_path: "src/core.py", reason: "the engine" },+ ],+ },+ });+ const arch = makePage({+ id: "arch",+ page_type: "architecture_diagram",+ title: "System architecture",+ content: "Intro\n\n```mermaid\ngraph TD\nA-->B\n```",+ });+ const layerCore = makePage({+ id: "lc",+ page_type: "layer_page",+ title: "Core layer",+ content: "# Core\n\nThe core does the work and holds the pipeline together nicely.",+ metadata: { layer_name: "Core" },+ });+ const layerApi = makePage({+ id: "la",+ page_type: "layer_page",+ title: "API layer",+ content: "# API\n\nThe API exposes endpoints to callers over HTTP with care.",+ metadata: { layer_name: "API" },+ });+ const mainFile = makePage({ id: "mf", target_path: "src/main.py", title: "main.py", content: "# main\n\nStarts the program and wires everything up on boot." });++ it("derives a clean repo name from a 'Repository Overview: name' title", () => {+ const colonOverview = makePage({+ page_type: "repo_overview",+ title: "Repository Overview: repowise",+ content: "## Project Summary\n\nRepowise is a codebase documentation engine.",+ metadata: {},+ });+ const model = buildPresentModel([colonOverview]);+ expect(model.repoName).toBe("repowise");+ // Title tagline is the real summary sentence, not the "Project Summary" heading.+ expect(model.deck[0]!.bodyMarkdown).toContain("codebase documentation engine");+ expect(model.deck[0]!.bodyMarkdown).not.toContain("Project Summary");+ });++ it("builds a title slide, diagram slide, ordered layers, and a closing", () => {+ const model = buildPresentModel([overview, arch, layerCore, layerApi, mainFile]);+ expect(model.repoName).toBe("Acme");+ expect(model.deck[0]!.kind).toBe("title");+ expect(model.deck.some((s) => s.kind === "diagram" && s.mermaid?.includes("graph TD"))).toBe(true);+ // Layers ordered by layer_order: API before Core.+ const layerTitles = model.deck.filter((s) => s.eyebrow === "Layer").map((s) => s.title);+ expect(layerTitles).toEqual(["API layer", "Core layer"]);+ expect(model.deck[model.deck.length - 1]!.kind).toBe("closing");+ });++ it("builds a walkthrough from the guided tour with time estimates", () => {+ const model = buildPresentModel([overview, mainFile]);+ expect(model.walkthrough).toHaveLength(2);+ expect(model.walkthrough[0]!.title).toBe("main.py");+ expect(model.walkthrough[0]!.reason).toBe("entry point");+ expect(model.walkthrough[0]!.sourcePageId).toBe("mf");+ expect(model.walkthrough[0]!.estMinutes).toBeGreaterThanOrEqual(2);+ expect(model.totalMinutes).toBe(+ model.walkthrough.reduce((s, w) => s + w.estMinutes, 0),+ );+ });++ it("falls back to deck sections when there is no guided tour", () => {+ const bareOverview = makePage({ id: "ov2", page_type: "repo_overview", title: "Bare", content: "# Bare\n\nx", metadata: {} });+ const model = buildPresentModel([bareOverview, layerCore]);+ expect(model.walkthrough.length).toBeGreaterThan(0);+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex dda56d478..0ccecaa08 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -84,6 +84,8 @@"./security/*": "./src/security/*.tsx","./onboarding": "./src/onboarding/index.ts","./onboarding/*": "./src/onboarding/*.tsx",+ "./present": "./src/present/index.ts",+ "./present/*": "./src/present/*.tsx","./settings": "./src/settings/index.ts","./settings/*": "./src/settings/*.tsx","./shared": "./src/shared/index.ts",diff --git a/packages/ui/src/present/build-present-model.ts b/packages/ui/src/present/build-present-model.tsnew file mode 100644index 000000000..02c6f1c30--- /dev/null+++ b/packages/ui/src/present/build-present-model.ts@@ -0,0 +1,256 @@+// Build a Present model (slide deck + guided walkthrough) from already-loaded+// wiki pages. Pure and synchronous: no LLM, no network, no DB. Every section is+// guarded so missing page types (e.g. no architecture diagram, index-only repos)+// degrade to a shorter deck instead of erroring.++import type { DocPage } from "@repowise-dev/types/docs";+import { filterMarkdownByPersona } from "../docs/reader-persona";+import {+ splitOnH2,+ stripLeadingH1,+ extractMermaidBlocks,+ clampProse,+ countWords,+} from "./split-markdown";+import type { PresentModel, PresentSlide, PresentStep } from "./types";++// Curation caps keep the deck tight and premium on large repos.+const MAX_LAYER_SLIDES = 5;+const MAX_MODULE_SLIDES = 5;+const MAX_TOUR_STOPS = 8;+const DECK_BODY_CHARS = 520;+const STEP_BODY_CHARS = 1100;++interface TourStop {+ order?: number | undefined;+ title?: string | undefined;+ target_path?: string | undefined;+ reason?: string | undefined;+ kind?: string | undefined;+}++function readTour(overview: DocPage | undefined): TourStop[] {+ const raw = overview?.metadata?.["guided_tour"];+ if (!Array.isArray(raw)) return [];+ return raw+ .filter((s): s is Record<string, unknown> => !!s && typeof s === "object")+ .map((s) => ({+ order: typeof s["order"] === "number" ? (s["order"] as number) : undefined,+ title: typeof s["title"] === "string" ? (s["title"] as string) : undefined,+ target_path:+ typeof s["target_path"] === "string" ? (s["target_path"] as string) : undefined,+ reason: typeof s["reason"] === "string" ? (s["reason"] as string) : undefined,+ kind: typeof s["kind"] === "string" ? (s["kind"] as string) : undefined,+ }));+}++function readLayerOrder(overview: DocPage | undefined): string[] {+ const raw = overview?.metadata?.["layer_order"];+ return Array.isArray(raw) ? raw.filter((x): x is string => typeof x === "string") : [];+}++function metaString(page: DocPage, key: string): string | undefined {+ const v = page.metadata?.[key];+ return typeof v === "string" ? v : undefined;+}++/**+ * A readable repo name from the overview page title. Titles look like+ * "Repository Overview: repowise" — prefer the part after the colon, then+ * strip stray "repository"/"overview" words, so the title slide reads "repowise"+ * not "This repository".+ */+function deriveRepoName(overview: DocPage | undefined, override?: string): string {+ const fromOverride = override?.trim();+ if (fromOverride) return fromOverride;+ if (!overview) return "This repository";+ const title = overview.title.trim();+ const afterColon = title.includes(":") ? (title.split(":").pop() ?? title).trim() : title;+ const cleaned = afterColon.replace(/\b(repository|repo|overview)\b/gi, "").replace(/\s+/g, " ").trim();+ return cleaned || afterColon || "This repository";+}++/** First real prose paragraph of a page (skips a leading heading). */+function firstProse(page: DocPage, maxChars: number): string {+ const filtered = stripLeadingH1(filterMarkdownByPersona(page.content, "overview"));+ const { lead, sections } = splitOnH2(filtered);+ const leadText = lead.trim();+ const source = leadText.length >= 40 ? leadText : (sections[0]?.body.trim() ?? leadText);+ const firstPara = source.split(/\n{2,}/)[0] ?? "";+ return clampProse(firstPara, maxChars);+}++/** Persona-filtered lead excerpt for a slide (prose + diagrams only). */+function slideBody(page: DocPage, maxChars: number): string {+ const filtered = stripLeadingH1(filterMarkdownByPersona(page.content, "overview"));+ const { lead, sections } = splitOnH2(filtered);+ let text = lead.trim();+ const first = sections[0];+ if (text.length < 60 && first) {+ text = `## ${first.heading}\n\n${first.body}`.trim();+ }+ return clampProse(text, maxChars);+}++function estimateMinutes(markdown: string): number {+ const words = countWords(markdown);+ return Math.min(12, Math.max(2, 2 + Math.ceil(words / 200)));+}++/** True when there is enough generated content to present. */+export function canPresent(pages: DocPage[]): boolean {+ return pages.some((p) => p.page_type === "repo_overview");+}++export function buildPresentModel(+ pages: DocPage[],+ opts: { repoName?: string } = {},+): PresentModel {+ const overview = pages.find((p) => p.page_type === "repo_overview");+ const repoName = deriveRepoName(overview, opts.repoName);++ const deck: PresentSlide[] = [];++ // 1 — Title+ deck.push({+ id: "title",+ kind: "title",+ eyebrow: "Repository",+ title: repoName,+ bodyMarkdown: overview ? firstProse(overview, 280) : undefined,+ sourcePageId: overview?.id,+ sourcePath: overview?.target_path,+ freshness: overview?.freshness_status,+ });++ // 2 — Architecture diagram slides+ const archPage = pages.find((p) => p.page_type === "architecture_diagram");+ if (archPage) {+ const charts = extractMermaidBlocks(archPage.content).slice(0, 2);+ charts.forEach((chart, i) => {+ deck.push({+ id: `arch-${i}`,+ kind: "diagram",+ eyebrow: "Architecture",+ title: charts.length > 1 ? `${archPage.title} (${i + 1})` : archPage.title,+ mermaid: chart,+ sourcePageId: archPage.id,+ sourcePath: archPage.target_path,+ freshness: archPage.freshness_status,+ });+ });+ }++ // 3 — Layers, ordered by the overview's layer_order when resolvable+ const layerOrder = readLayerOrder(overview);+ const rankOf = (name: string | undefined) => {+ if (!name) return Number.MAX_SAFE_INTEGER;+ const idx = layerOrder.indexOf(name);+ return idx === -1 ? Number.MAX_SAFE_INTEGER : idx;+ };+ const layerPages = pages+ .filter((p) => p.page_type === "layer_page")+ .sort((a, b) => rankOf(metaString(a, "layer_name")) - rankOf(metaString(b, "layer_name")))+ .slice(0, MAX_LAYER_SLIDES);+ for (const p of layerPages) {+ deck.push({+ id: `layer-${p.id}`,+ kind: "section",+ eyebrow: "Layer",+ title: p.title,+ bodyMarkdown: slideBody(p, DECK_BODY_CHARS),+ sourcePageId: p.id,+ sourcePath: p.target_path,+ freshness: p.freshness_status,+ });+ }++ // 4 — Modules, richest first (longest content is a decent proxy)+ const modulePages = pages+ .filter((p) => p.page_type === "module_page")+ .sort((a, b) => b.content.length - a.content.length)+ .slice(0, MAX_MODULE_SLIDES);+ for (const p of modulePages) {+ deck.push({+ id: `module-${p.id}`,+ kind: "section",+ eyebrow: "Module",+ title: p.title,+ bodyMarkdown: slideBody(p, DECK_BODY_CHARS),+ sourcePageId: p.id,+ sourcePath: p.target_path,+ freshness: p.freshness_status,+ });+ }++ // 5 — Where to start (guided-tour landmarks as one list slide)+ const tour = readTour(overview);+ if (tour.length > 0) {+ const items = tour+ .slice(0, MAX_TOUR_STOPS)+ .map((s) => {+ const label = s.title || s.target_path || "";+ const reason = s.reason ? ` — ${s.reason}` : "";+ return `- **${label}**${reason}`;+ })+ .join("\n");+ deck.push({+ id: "key-files",+ kind: "section",+ eyebrow: "Where to start",+ title: "Key files to read first",+ bodyMarkdown: items,+ });+ }++ // 6 — Closing+ deck.push({+ id: "closing",+ kind: "closing",+ eyebrow: "Keep exploring",+ title: "That's the tour",+ bodyMarkdown:+ "Open any page in the reader for the full detail, ask the assistant a question, or dive into the knowledge graph.",+ });++ // Walkthrough — one step per guided-tour stop, in order.+ const byPath = new Map(pages.map((p) => [p.target_path, p]));+ let walkthrough: PresentStep[] = tour.map((stop, i) => {+ const page = stop.target_path ? byPath.get(stop.target_path) : undefined;+ const body = page ? slideBody(page, STEP_BODY_CHARS) : "";+ const forEstimate = body || stop.reason || stop.title || "";+ return {+ id: `step-${i}`,+ order: stop.order ?? i + 1,+ title: stop.title || page?.title || stop.target_path || `Step ${i + 1}`,+ reason: stop.reason,+ targetPath: stop.target_path,+ bodyMarkdown: body,+ estMinutes: estimateMinutes(forEstimate),+ sourcePageId: page?.id,+ freshness: page?.freshness_status,+ };+ });++ // Fallback: no tour metadata (older/edge indexes) — walk the deck's section+ // slides so the walkthrough is never empty when a deck exists.+ if (walkthrough.length === 0) {+ walkthrough = deck+ .filter((s) => s.kind === "section" && s.bodyMarkdown)+ .map((s, i) => ({+ id: `step-${i}`,+ order: i + 1,+ title: s.title,+ reason: s.eyebrow,+ targetPath: s.sourcePath,+ bodyMarkdown: s.bodyMarkdown,+ estMinutes: estimateMinutes(s.bodyMarkdown ?? ""),+ sourcePageId: s.sourcePageId,+ freshness: s.freshness,+ }));+ }++ const totalMinutes = walkthrough.reduce((sum, s) => sum + s.estMinutes, 0);++ return { repoName, deck, walkthrough, totalMinutes };+}diff --git a/packages/ui/src/present/deck-view.tsx b/packages/ui/src/present/deck-view.tsxnew file mode 100644index 000000000..b043e6237--- /dev/null+++ b/packages/ui/src/present/deck-view.tsx@@ -0,0 +1,147 @@+"use client";++import { AnimatePresence, motion, useReducedMotion } from "framer-motion";+import { ChevronLeft, ChevronRight, ExternalLink } from "lucide-react";+import { WikiMarkdown } from "../wiki/wiki-markdown";+import { MermaidDiagram } from "../wiki/mermaid-diagram";+import { cn } from "../lib/cn";+import { SlideProgress } from "./slide-progress";+import type { PresentSlide } from "./types";++export interface PresentLinkComponent {+ (props: { href: string; className?: string; children: React.ReactNode }): React.ReactElement;+}++interface DeckViewProps {+ slides: PresentSlide[];+ index: number;+ onIndex: (i: number) => void;+ onOpenPage?: ((pageId: string) => void) | undefined;+}++const FRESHNESS_DOT: Record<string, string> = {+ fresh: "var(--color-confidence-fresh)",+ stale: "var(--color-confidence-stale)",+ outdated: "var(--color-confidence-outdated)",+};++export function DeckView({ slides, index, onIndex, onOpenPage }: DeckViewProps) {+ const reduce = useReducedMotion();+ const slide = slides[index];+ if (!slide) return null;++ const atStart = index === 0;+ const atEnd = index === slides.length - 1;+ const isTitle = slide.kind === "title";+ const isDiagram = slide.kind === "diagram";++ return (+ <div className="relative flex h-full flex-col">+ {/* Slide canvas */}+ <div+ className={cn(+ "relative flex flex-1 items-center justify-center overflow-hidden py-4",+ isDiagram ? "px-4 sm:px-8" : "px-6 sm:px-16",+ )}+ >+ <AnimatePresence mode="wait">+ <motion.div+ key={slide.id}+ initial={reduce ? false : { opacity: 0, y: 12 }}+ animate={{ opacity: 1, y: 0 }}+ exit={reduce ? { opacity: 0 } : { opacity: 0, y: -12 }}+ transition={{ duration: 0.22, ease: "easeOut" }}+ className={cn(+ "w-full",+ isTitle ? "max-w-3xl text-center" : isDiagram ? "max-w-6xl" : "max-w-3xl text-left",+ )}+ >+ {slide.eyebrow && (+ <p className="mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--color-text-tertiary)]">+ {slide.eyebrow}+ </p>+ )}+ <h2+ className={cn(+ "font-serif font-semibold tracking-tight text-[var(--color-text-primary)]",+ isTitle ? "text-5xl sm:text-6xl" : isDiagram ? "text-2xl sm:text-3xl" : "text-3xl sm:text-4xl",+ )}+ >+ {slide.title}+ </h2>++ {slide.mermaid && (+ <div className="mt-4 flex justify-center">+ <div className="w-full">+ <MermaidDiagram chart={slide.mermaid} securityLevel="loose" />+ </div>+ </div>+ )}++ {slide.bodyMarkdown && (+ <div+ className={cn(+ "mt-6 text-[var(--color-text-secondary)]",+ isTitle ? "mx-auto max-w-xl text-lg" : "text-base",+ )}+ >+ <WikiMarkdown content={slide.bodyMarkdown} />+ </div>+ )}++ {slide.sourcePageId && onOpenPage && (+ <button+ type="button"+ onClick={() => onOpenPage(slide.sourcePageId!)}+ className={cn(+ "mt-6 inline-flex items-center gap-1.5 text-xs font-medium text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-accent-primary)]",+ isTitle && "mx-auto",+ )}+ >+ <ExternalLink className="h-3.5 w-3.5" />+ Open{slide.sourcePath ? ` ${slide.sourcePath}` : ""} in reader+ </button>+ )}+ </motion.div>+ </AnimatePresence>++ {/* Prev / next click zones */}+ <button+ type="button"+ onClick={() => onIndex(index - 1)}+ disabled={atStart}+ aria-label="Previous slide"+ className="absolute left-3 top-1/2 -translate-y-1/2 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]/70 p-2 text-[var(--color-text-secondary)] backdrop-blur transition-opacity hover:text-[var(--color-text-primary)] disabled:pointer-events-none disabled:opacity-0"+ >+ <ChevronLeft className="h-5 w-5" />+ </button>+ <button+ type="button"+ onClick={() => onIndex(index + 1)}+ disabled={atEnd}+ aria-label="Next slide"+ className="absolute right-3 top-1/2 -translate-y-1/2 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]/70 p-2 text-[var(--color-text-secondary)] backdrop-blur transition-opacity hover:text-[var(--color-text-primary)] disabled:pointer-events-none disabled:opacity-0"+ >+ <ChevronRight className="h-5 w-5" />+ </button>+ </div>++ {/* Footer: freshness + progress */}+ <div className="flex shrink-0 items-center justify-between px-6 pb-6 pt-2 sm:px-16">+ <div className="flex items-center gap-2">+ {slide.freshness && FRESHNESS_DOT[slide.freshness] && (+ <span+ className="h-1.5 w-1.5 rounded-full"+ style={{ background: FRESHNESS_DOT[slide.freshness] }}+ title={`Source is ${slide.freshness}`}+ />+ )}+ </div>+ <SlideProgress index={index} total={slides.length} onSelect={onIndex} />+ <span className="hidden text-[11px] text-[var(--color-text-tertiary)] sm:block">+ ← → to navigate+ </span>+ </div>+ </div>+ );+}diff --git a/packages/ui/src/present/index.ts b/packages/ui/src/present/index.tsnew file mode 100644index 000000000..c14460b44--- /dev/null+++ b/packages/ui/src/present/index.ts@@ -0,0 +1,9 @@+// Present mode — on-the-fly slide deck + guided walkthrough over already-loaded+// wiki pages. Framework-light and self-contained so the OSS dashboard and a+// future hosted app share one implementation: the host supplies DocPage[] and+// renders <PresentOverlay>.++export { buildPresentModel, canPresent } from "./build-present-model";+export { PresentOverlay, type PresentMode } from "./present-overlay";+export { PresentButton } from "./present-button";+export type { PresentModel, PresentSlide, PresentStep, PresentSlideKind } from "./types";diff --git a/packages/ui/src/present/present-button.tsx b/packages/ui/src/present/present-button.tsxnew file mode 100644index 000000000..aa562c4c0--- /dev/null+++ b/packages/ui/src/present/present-button.tsx@@ -0,0 +1,23 @@+"use client";++import { Presentation } from "lucide-react";++/**+ * Header entry point for Present mode. Styled to match the docs header's+ * secondary actions (Search / Export), so it reads as one of them rather than+ * a primary call to action.+ */+export function PresentButton({ onClick, disabled }: { onClick: () => void; disabled?: boolean }) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ title="Present this repository"+ className="flex items-center gap-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2.5 py-1.5 text-xs text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-secondary)] disabled:pointer-events-none disabled:opacity-40"+ >+ <Presentation className="h-3.5 w-3.5" />+ <span className="hidden sm:inline">Present</span>+ </button>+ );+}diff --git a/packages/ui/src/present/present-overlay.tsx b/packages/ui/src/present/present-overlay.tsxnew file mode 100644index 000000000..2b3bb544c--- /dev/null+++ b/packages/ui/src/present/present-overlay.tsx@@ -0,0 +1,138 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { X, Presentation, Route } from "lucide-react";+import { cn } from "../lib/cn";+import { DeckView } from "./deck-view";+import { WalkthroughView } from "./walkthrough-view";+import { usePresentKeyboard } from "./use-present-keyboard";+import type { PresentModel } from "./types";++export type PresentMode = "deck" | "walkthrough";++interface PresentOverlayProps {+ model: PresentModel;+ initialMode?: PresentMode;+ onClose: () => void;+ onModeChange?: (mode: PresentMode) => void;+ /** Jump to a page in the reader (host closes the overlay + navigates). */+ onOpenPage?: (pageId: string) => void;+}++const MODES: { value: PresentMode; label: string; icon: typeof Presentation }[] = [+ { value: "deck", label: "Deck", icon: Presentation },+ { value: "walkthrough", label: "Walkthrough", icon: Route },+];++/**+ * Full-screen, keyboard-driven presentation surface. Escapes the dashboard+ * chrome entirely (fixed inset-0), locks page scroll, and is theme-aware via+ * CSS tokens only. Holds a separate index per mode so toggling Deck /+ * Walkthrough preserves each one's position.+ */+export function PresentOverlay({ model, initialMode = "deck", onClose, onModeChange, onOpenPage }: PresentOverlayProps) {+ const [mode, setMode] = useState<PresentMode>(initialMode);+ const [deckIndex, setDeckIndex] = useState(0);+ const [stepIndex, setStepIndex] = useState(0);++ const hasWalkthrough = model.walkthrough.length > 0;+ const total = mode === "deck" ? model.deck.length : model.walkthrough.length;+ const index = mode === "deck" ? deckIndex : stepIndex;+ const setIndex = mode === "deck" ? setDeckIndex : setStepIndex;++ const clamp = useCallback((i: number) => Math.min(total - 1, Math.max(0, i)), [total]);+ const goto = useCallback((i: number) => setIndex(clamp(i)), [setIndex, clamp]);++ const switchMode = useCallback(+ (next: PresentMode) => {+ setMode(next);+ onModeChange?.(next);+ },+ [onModeChange],+ );++ usePresentKeyboard({+ onPrev: () => goto(index - 1),+ onNext: () => goto(index + 1),+ onFirst: () => goto(0),+ onLast: () => goto(total - 1),+ onClose,+ });++ // Lock page scroll for the overlay's lifetime.+ useEffect(() => {+ const prev = document.body.style.overflow;+ document.body.style.overflow = "hidden";+ return () => {+ document.body.style.overflow = prev;+ };+ }, []);++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-label="Repository presentation"+ className="fixed inset-0 z-[var(--z-modal)] flex flex-col bg-[var(--color-bg-inset)]"+ >+ {/* Top bar */}+ <header className="flex h-12 shrink-0 items-center justify-between border-b border-[var(--color-border-default)] bg-[var(--color-bg-root)]/80 px-4 backdrop-blur">+ <div className="flex items-center rounded-lg bg-[var(--color-bg-elevated)] p-0.5" role="tablist" aria-label="Presentation mode">+ {MODES.map((m) => {+ const Icon = m.icon;+ const disabled = m.value === "walkthrough" && !hasWalkthrough;+ const active = mode === m.value;+ return (+ <button+ key={m.value}+ type="button"+ role="tab"+ aria-selected={active}+ disabled={disabled}+ onClick={() => switchMode(m.value)}+ className={cn(+ "flex items-center gap-1.5 rounded-md px-3 py-1 text-xs font-medium transition-colors disabled:opacity-40",+ active+ ? "bg-[var(--color-bg-surface)] text-[var(--color-text-primary)] shadow-sm"+ : "text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",+ )}+ >+ <Icon className="h-3.5 w-3.5" />+ {m.label}+ </button>+ );+ })}+ </div>++ <span className="pointer-events-none absolute left-1/2 hidden -translate-x-1/2 text-xs font-medium text-[var(--color-text-tertiary)] sm:block">+ {model.repoName}+ </span>++ <button+ type="button"+ onClick={onClose}+ aria-label="Close presentation (Esc)"+ title="Close (Esc)"+ className="rounded-md p-1.5 text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"+ >+ <X className="h-4 w-4" />+ </button>+ </header>++ {/* Body */}+ <div className="min-h-0 flex-1">+ {mode === "deck" ? (+ <DeckView slides={model.deck} index={deckIndex} onIndex={goto} onOpenPage={onOpenPage} />+ ) : (+ <WalkthroughView+ steps={model.walkthrough}+ index={stepIndex}+ onIndex={goto}+ totalMinutes={model.totalMinutes}+ onOpenPage={onOpenPage}+ />+ )}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/present/slide-progress.tsx b/packages/ui/src/present/slide-progress.tsxnew file mode 100644index 000000000..dcb18bd37--- /dev/null+++ b/packages/ui/src/present/slide-progress.tsx@@ -0,0 +1,53 @@+"use client";++import { cn } from "../lib/cn";++/**+ * Bottom-of-deck progress: clickable dots when the deck is short, a slim bar+ * when it's long, always with a "n / total" counter. Accent marks the current+ * slide; everything else stays neutral (Linear-style restraint).+ */+export function SlideProgress({+ index,+ total,+ onSelect,+}: {+ index: number;+ total: number;+ onSelect: (i: number) => void;+}) {+ const showDots = total <= 16;+ return (+ <div className="flex items-center gap-3">+ {showDots ? (+ <div className="flex items-center gap-1.5">+ {Array.from({ length: total }).map((_, i) => (+ <button+ key={i}+ type="button"+ onClick={() => onSelect(i)}+ aria-label={`Go to slide ${i + 1}`}+ aria-current={i === index ? "true" : undefined}+ className={cn(+ "h-1.5 rounded-full transition-all",+ i === index+ ? "w-5 bg-[var(--color-accent-primary)]"+ : "w-1.5 bg-[var(--color-border-active)] hover:bg-[var(--color-text-tertiary)]",+ )}+ />+ ))}+ </div>+ ) : (+ <div className="h-1.5 w-40 overflow-hidden rounded-full bg-[var(--color-border-active)]">+ <div+ className="h-full rounded-full bg-[var(--color-accent-primary)] transition-all"+ style={{ width: `${((index + 1) / total) * 100}%` }}+ />+ </div>+ )}+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {index + 1} / {total}+ </span>+ </div>+ );+}diff --git a/packages/ui/src/present/split-markdown.ts b/packages/ui/src/present/split-markdown.tsnew file mode 100644index 000000000..199e9d012--- /dev/null+++ b/packages/ui/src/present/split-markdown.ts@@ -0,0 +1,118 @@+// Small, dependency-free markdown helpers for turning a wiki page into slide+// material. All fence-aware so a `## ` or ``` inside a fenced code block is+// never mistaken for a heading or a block boundary (same care as+// reader-persona's filter).++export interface MarkdownSection {+ heading: string;+ body: string;+}++export interface SplitMarkdown {+ /** Content before the first H2 (typically the lead paragraph). */+ lead: string;+ sections: MarkdownSection[];+}++const FENCE = /^\s*```/;+const H1 = /^#\s+(.+?)\s*$/;+const H2 = /^##\s+(.+?)\s*$/;++/** Split markdown on `## ` headings, ignoring headings inside code fences. */+export function splitOnH2(markdown: string): SplitMarkdown {+ const lines = markdown.split("\n");+ const leadLines: string[] = [];+ const sections: MarkdownSection[] = [];+ let current: MarkdownSection | null = null;+ let inFence = false;++ const push = (line: string) => {+ if (current) current.body += (current.body ? "\n" : "") + line;+ else leadLines.push(line);+ };++ for (const line of lines) {+ if (FENCE.test(line)) {+ inFence = !inFence;+ push(line);+ continue;+ }+ const h2 = !inFence ? H2.exec(line) : null;+ if (h2) {+ current = { heading: h2[1] ?? "", body: "" };+ sections.push(current);+ continue;+ }+ push(line);+ }++ return {+ lead: leadLines.join("\n").trim(),+ sections: sections.map((s) => ({ heading: s.heading, body: s.body.trim() })),+ };+}++/** Drop a single leading `# Title` line (the slide shows the title itself). */+export function stripLeadingH1(markdown: string): string {+ const lines = markdown.split("\n");+ let i = 0;+ while (i < lines.length && (lines[i] ?? "").trim() === "") i++;+ if (i < lines.length && H1.test(lines[i] ?? "")) {+ return lines.slice(i + 1).join("\n").trimStart();+ }+ return markdown;+}++/** Extract the source of every ```mermaid fenced block, in order. */+export function extractMermaidBlocks(markdown: string): string[] {+ const blocks: string[] = [];+ const lines = markdown.split("\n");+ let inBlock = false;+ let buf: string[] = [];+ for (const line of lines) {+ if (!inBlock && /^\s*```mermaid\b/.test(line)) {+ inBlock = true;+ buf = [];+ continue;+ }+ if (inBlock && /^\s*```\s*$/.test(line)) {+ inBlock = false;+ const chart = buf.join("\n").trim();+ if (chart) blocks.push(chart);+ continue;+ }+ if (inBlock) buf.push(line);+ }+ return blocks;+}++/** Remove fenced code and mermaid blocks (used only for word counting). */+function stripFences(markdown: string): string {+ return markdown.replace(/```[\s\S]*?```/g, " ");+}++export function countWords(markdown: string): number {+ const text = stripFences(markdown).replace(/[#>*`_\-|]/g, " ");+ const words = text.trim().split(/\s+/).filter(Boolean);+ return words.length;+}++/**+ * Trim prose to a slide-sized excerpt on a paragraph boundary. Keeps whole+ * paragraphs up to `maxChars`, and always returns at least the first paragraph+ * so a slide is never blank when the first block is long.+ */+export function clampProse(markdown: string, maxChars: number): string {+ const trimmed = markdown.trim();+ if (trimmed.length <= maxChars) return trimmed;+ const paras = trimmed.split(/\n{2,}/);+ const out: string[] = [];+ let len = 0;+ for (const p of paras) {+ if (out.length > 0 && len + p.length > maxChars) break;+ out.push(p);+ len += p.length + 2;+ if (len >= maxChars) break;+ }+ return out.join("\n\n").trim();+}diff --git a/packages/ui/src/present/types.ts b/packages/ui/src/present/types.tsnew file mode 100644index 000000000..c7ed926ea--- /dev/null+++ b/packages/ui/src/present/types.ts@@ -0,0 +1,50 @@+// Present mode — the data model for an on-the-fly slide deck + guided+// walkthrough, built entirely from already-generated wiki pages. No new+// generation, no network, no DB: `buildPresentModel` (build-present-model.ts)+// transforms the loaded `DocPage[]` into this shape, and the overlay renders it.+//+// Kept framework-free (plain data) so the same model serves the OSS dashboard+// and a future hosted app without re-implementing any logic.++export type PresentSlideKind = "title" | "section" | "diagram" | "closing";++export interface PresentSlide {+ /** Stable id within the deck (slug), used as a React key. */+ id: string;+ kind: PresentSlideKind;+ /** Small uppercase label above the title (e.g. "Architecture", "Module"). */+ eyebrow?: string | undefined;+ title: string;+ /** Prose body rendered via WikiMarkdown. Omitted on pure-diagram slides. */+ bodyMarkdown?: string | undefined;+ /** Mermaid source for a diagram slide, rendered via MermaidDiagram. */+ mermaid?: string | undefined;+ /** Page this slide was derived from, so "open in reader" can jump there. */+ sourcePageId?: string | undefined;+ sourcePath?: string | undefined;+ /** Freshness of the source page (fresh/stale/outdated), for a subtle dot. */+ freshness?: string | undefined;+}++export interface PresentStep {+ id: string;+ order: number;+ title: string;+ /** One-line "why this matters" pulled from the guided-tour stop. */+ reason?: string | undefined;+ targetPath?: string | undefined;+ /** Reading body for the step, rendered via WikiMarkdown. */+ bodyMarkdown?: string | undefined;+ /** Deterministic reading-time estimate in minutes. */+ estMinutes: number;+ sourcePageId?: string | undefined;+ freshness?: string | undefined;+}++export interface PresentModel {+ repoName: string;+ deck: PresentSlide[];+ walkthrough: PresentStep[];+ /** Sum of every walkthrough step's estMinutes. */+ totalMinutes: number;+}diff --git a/packages/ui/src/present/use-present-keyboard.ts b/packages/ui/src/present/use-present-keyboard.tsnew file mode 100644index 000000000..495887720--- /dev/null+++ b/packages/ui/src/present/use-present-keyboard.ts@@ -0,0 +1,58 @@+"use client";++import { useEffect } from "react";++interface PresentKeys {+ onPrev: () => void;+ onNext: () => void;+ onClose: () => void;+ onFirst?: () => void;+ onLast?: () => void;+}++/**+ * Global keyboard navigation for the Present overlay: ←/PageUp = prev,+ * →/PageDown/Space = next, Home/End = first/last, Escape = close. Ignores key+ * events while a text input/textarea is focused so nothing is hijacked.+ */+export function usePresentKeyboard({ onPrev, onNext, onClose, onFirst, onLast }: PresentKeys) {+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ const target = e.target as HTMLElement | null;+ if (target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)) {+ return;+ }+ switch (e.key) {+ case "ArrowRight":+ case "PageDown":+ case " ":+ e.preventDefault();+ onNext();+ break;+ case "ArrowLeft":+ case "PageUp":+ e.preventDefault();+ onPrev();+ break;+ case "Home":+ if (onFirst) {+ e.preventDefault();+ onFirst();+ }+ break;+ case "End":+ if (onLast) {+ e.preventDefault();+ onLast();+ }+ break;+ case "Escape":+ e.preventDefault();+ onClose();+ break;+ }+ };+ document.addEventListener("keydown", onKey);+ return () => document.removeEventListener("keydown", onKey);+ }, [onPrev, onNext, onClose, onFirst, onLast]);+}diff --git a/packages/ui/src/present/walkthrough-view.tsx b/packages/ui/src/present/walkthrough-view.tsxnew file mode 100644index 000000000..2b2c8cbe4--- /dev/null+++ b/packages/ui/src/present/walkthrough-view.tsx@@ -0,0 +1,138 @@+"use client";++import { Check, Clock, ChevronLeft, ChevronRight, ExternalLink } from "lucide-react";+import { WikiMarkdown } from "../wiki/wiki-markdown";+import { cn } from "../lib/cn";+import type { PresentStep } from "./types";++interface WalkthroughViewProps {+ steps: PresentStep[];+ index: number;+ onIndex: (i: number) => void;+ totalMinutes: number;+ onOpenPage?: ((pageId: string) => void) | undefined;+}++export function WalkthroughView({ steps, index, onIndex, totalMinutes, onOpenPage }: WalkthroughViewProps) {+ const step = steps[index];+ if (!step) return null;++ const pct = ((index + 1) / steps.length) * 100;++ return (+ <div className="flex h-full min-h-0">+ {/* Step rail */}+ <aside className="hidden w-72 shrink-0 flex-col border-r border-[var(--color-border-default)] bg-[var(--color-bg-surface)] md:flex">+ <div className="shrink-0 border-b border-[var(--color-border-default)] px-4 py-3">+ <div className="flex items-center justify-between">+ <span className="text-xs font-semibold uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Walkthrough+ </span>+ <span className="inline-flex items-center gap-1 rounded-full bg-[var(--color-bg-elevated)] px-2 py-0.5 text-[11px] text-[var(--color-text-secondary)]">+ <Clock className="h-3 w-3" />~{totalMinutes} min+ </span>+ </div>+ <div className="mt-2 h-1 w-full overflow-hidden rounded-full bg-[var(--color-border-active)]">+ <div className="h-full rounded-full bg-[var(--color-accent-primary)] transition-all" style={{ width: `${pct}%` }} />+ </div>+ </div>+ <nav className="flex-1 overflow-y-auto p-2">+ {steps.map((s, i) => {+ const done = i < index;+ const current = i === index;+ return (+ <button+ key={s.id}+ type="button"+ onClick={() => onIndex(i)}+ className={cn(+ "flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-sm transition-colors",+ current+ ? "bg-[var(--color-accent-muted)] text-[var(--color-text-primary)]"+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",+ )}+ >+ <span+ className={cn(+ "flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[11px] font-semibold",+ done+ ? "bg-[var(--color-accent-primary)] text-[var(--color-text-on-accent)]"+ : current+ ? "border border-[var(--color-accent-primary)] text-[var(--color-accent-primary)]"+ : "border border-[var(--color-border-active)] text-[var(--color-text-tertiary)]",+ )}+ >+ {done ? <Check className="h-3 w-3" /> : i + 1}+ </span>+ <span className="min-w-0 flex-1 truncate">{s.title}</span>+ </button>+ );+ })}+ </nav>+ </aside>++ {/* Content pane */}+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex-1 overflow-y-auto px-6 py-8 sm:px-12">+ <div className="mx-auto max-w-3xl">+ <p className="mb-2 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--color-text-tertiary)]">+ Step {index + 1} of {steps.length} · ~{step.estMinutes} min+ </p>+ <h2 className="font-serif text-3xl font-semibold tracking-tight text-[var(--color-text-primary)]">+ {step.title}+ </h2>+ {step.reason && (+ <div className="mt-4 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-4 py-3">+ <p className="text-xs font-semibold uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Why this matters+ </p>+ <p className="mt-1 text-sm text-[var(--color-text-secondary)]">{step.reason}</p>+ </div>+ )}+ {step.bodyMarkdown ? (+ <div className="mt-6 text-base text-[var(--color-text-secondary)]">+ <WikiMarkdown content={step.bodyMarkdown} />+ </div>+ ) : (+ <p className="mt-6 text-sm text-[var(--color-text-tertiary)]">+ No generated page for this file yet. Open it in the reader to read the source.+ </p>+ )}+ {step.sourcePageId && onOpenPage && (+ <button+ type="button"+ onClick={() => onOpenPage(step.sourcePageId!)}+ className="mt-6 inline-flex items-center gap-1.5 text-xs font-medium text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-accent-primary)]"+ >+ <ExternalLink className="h-3.5 w-3.5" />+ Open{step.targetPath ? ` ${step.targetPath}` : ""} in reader+ </button>+ )}+ </div>+ </div>++ {/* Footer nav */}+ <div className="flex shrink-0 items-center justify-between border-t border-[var(--color-border-default)] px-6 py-3 sm:px-12">+ <button+ type="button"+ onClick={() => onIndex(index - 1)}+ disabled={index === 0}+ className="inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] disabled:pointer-events-none disabled:opacity-40"+ >+ <ChevronLeft className="h-4 w-4" />+ Prev+ </button>+ <button+ type="button"+ onClick={() => onIndex(index + 1)}+ disabled={index === steps.length - 1}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--color-accent-fill)] px-4 py-1.5 text-sm font-medium text-[var(--color-text-on-accent)] shadow-[var(--shadow-button)] transition-[filter] hover:brightness-[1.06] disabled:pointer-events-none disabled:opacity-40"+ >+ Next stop+ <ChevronRight className="h-4 w-4" />+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/packages/web/src/components/docs/docs-explorer.tsx b/packages/web/src/components/docs/docs-explorer.tsxindex 6d474391b..dfeafe122 100644--- a/packages/web/src/components/docs/docs-explorer.tsx+++ b/packages/web/src/components/docs/docs-explorer.tsx@@ -7,6 +7,13 @@ import { cn } from "@/lib/utils/cn";import { usePages } from "@/lib/hooks/use-pages";import { DocsTree } from "@repowise-dev/ui/docs/docs-tree";import { DocsCommandPalette } from "@repowise-dev/ui/docs/command-palette";+import {+ PresentButton,+ PresentOverlay,+ buildPresentModel,+ canPresent,+ type PresentMode,+} from "@repowise-dev/ui/present";import {DEFAULT_PERSONA,type ReaderPersona,@@ -92,6 +99,40 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {router.replace(`?${params.toString()}`, { scroll: false });}, [searchParams, router]);+ // Present mode — an on-the-fly slide deck + guided walkthrough over the same+ // loaded pages. Open state lives in ?present=deck|walkthrough so a specific+ // mode is shareable. The model is derived, never generated or fetched.+ const presentable = useMemo(+ () => canPresent(pages as unknown as DocPage[]),+ [pages],+ );+ const presentModel = useMemo(+ () => (presentable ? buildPresentModel(pages as unknown as DocPage[]) : null),+ [pages, presentable],+ );+ const presentParam = searchParams.get("present");+ const presentMode: PresentMode | null =+ presentParam === "walkthrough" ? "walkthrough" : presentParam === "deck" ? "deck" : null;+ const setPresent = useCallback(+ (mode: PresentMode | null, pageId?: string) => {+ const params = new URLSearchParams(searchParams.toString());+ if (mode) params.set("present", mode);+ else params.delete("present");+ if (pageId) params.set("page", pageId);+ const qs = params.toString();+ router.replace(qs ? `?${qs}` : "?", { scroll: false });+ },+ [searchParams, router],+ );+ const openInReaderFromPresent = useCallback(+ (pageId: string) => {+ const match = pages.find((p) => p.id === pageId);+ if (match) setSelectedPage(match);+ setPresent(null, pageId);+ },+ [pages, setPresent],+ );+// Server-backed search for the ⌘K palette: hit the semantic/full-text// endpoint, then map results back to the loaded page objects so selection// behaves identically to a client-side hit. Unknown ids (rare) are dropped.@@ -237,6 +278,7 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {page={selectedPage}repoId={repoId}/>+ {presentable && <PresentButton onClick={() => setPresent("deck")} />}{selectedPage && (<SidebarToggleopen={sidebarOpen}@@ -247,6 +289,17 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {<div className="flex-1 min-h-0">{body}</div>+ {/* Present mode overlay — full-screen, escapes the dashboard chrome */}+ {presentMode && presentModel && (+ <PresentOverlay+ model={presentModel}+ initialMode={presentMode}+ onClose={() => setPresent(null)}+ onModeChange={(m) => setPresent(m)}+ onOpenPage={openInReaderFromPresent}+ />+ )}+{/* ⌘K full-text command palette over loaded pages */}<DocsCommandPalettepages={pages as unknown as DocPage[]}