diff --git a/docs/CODE_MAP.md b/docs/CODE_MAP.md index 5dfa2fd4..33fcd680 100644 --- a/docs/CODE_MAP.md +++ b/docs/CODE_MAP.md @@ -32,8 +32,9 @@ Browser | Feature | Where | | --- | --- | -| Landing page, interactive treemap example, shared navigation | `site/src/App.tsx`, `site/src/Landing.tsx`, `site/src/site.css` | -| User guides, search, table of contents | `site/src/App.tsx`, `site/src/docs/` | +| Landing page, product screenshots, shared navigation | `site/src/Landing.tsx`, `site/src/SiteChrome.tsx`, `site/src/site.css`, `site/public/screenshots/` | +| Product tour, design decisions, user guides, search, table of contents | `site/src/App.tsx`, `site/src/docs/` | +| Full-size screenshot viewer and zoom controls | `site/src/ScreenshotViewer.tsx` | | Static HTML, page metadata, sitemap, and GitHub Pages base path | `site/src/server.tsx`, `site/scripts/prerender.mjs`, `site/vite.config.ts` | ### CLI and process lifecycle diff --git a/site/DESIGN.md b/site/DESIGN.md index 149a59f4..671116c8 100644 --- a/site/DESIGN.md +++ b/site/DESIGN.md @@ -1,11 +1,12 @@ # Public site -The public site extends Srcly's light application palette and Draftably's demonstration-first structure. -It serves developers who want to inspect a local codebase or generate a report for an agent. +The public site extends Srcly's light application palette. It serves developers who want to inspect a local codebase or create a report for an agent. -The landing page pairs a direct setup command with an interactive, labeled example. -The example explains tile area, metric color, and file selection before the longer product copy. -Guides use grouped navigation, content search, section links, and previous/next links. +## Surface modes + +- Landing: Persuade. Lead with real Srcly views, then give two paths: see the product or use it. +- Guides: Read. Group navigation by the visitor's task, keep the article easy to scan, and link search results to the matching section. +- Screenshot viewer: Experience. Let the captured application view fill the screen. Keep zoom, reset, close, keyboard focus, and native image-link fallback. ## Tokens @@ -16,5 +17,16 @@ Guides use grouped navigation, content search, section links, and previous/next - Page width: 1160px; hero type: 42–68px; body: 15px. - Controls have visible focus outlines. Motion respects reduced-motion settings. -The treemap and terminal output are illustrations. Keep that labeling visible. -Do not imply the public site scans files or that missing measurements equal zero. +## Product proof + +- Use screenshots captured from the running application. Keep captions specific to the view and the action it supports. +- The hero uses the repository treemap. The gallery uses the treemap, code inspector, and data-flow views. +- The site must not imply that it scans files or that missing measurements equal zero. +- Do not invent metrics or terminal output to fill space. + +## Guides + +- Navigation groups: Discover, Use Srcly, and Automate & configure. +- Keep the page title, short summary, and edit link in one compact heading area. +- Search results show matching text and link to a matching section when one exists. +- Screenshot figures can open at full size. Keep the image link usable without JavaScript. diff --git a/site/README.md b/site/README.md index 87097ceb..bd16bcd5 100644 --- a/site/README.md +++ b/site/README.md @@ -13,9 +13,10 @@ pnpm test Open the printed development URL with `/srcly/` appended. The build writes `site/dist/`. Each guide has a complete HTML page, with page metadata and a canonical URL. -The browser adds the interactive example, guide search, and copy buttons. +The browser adds section-linked guide search, copy buttons, and a full-size screenshot viewer. -Edit user guides in `src/docs/pages/`. Keep command examples in sync with `server/app/run.py`. +Edit the product tour, design notes, and user guides in `src/docs/pages/`. +Keep command examples in sync with `server/app/run.py`. Add new pages to the navigation in `src/App.tsx` when required. The build reads page titles and introductions from Markdown for search metadata. @@ -24,12 +25,14 @@ Pull requests build the site and run its browser checks. See [DEPLOY.md](DEPLOY. ## Reference and design -Draftably's public site supplied the structure: an interactive product example, direct setup actions, and searchable task guides. +Draftably's public site supplied the structure: a product preview, direct setup actions, and searchable task guides. Srcly keeps its light surfaces, blue links, Inter type, and IBM Plex Mono commands. -The treemap uses clearly labeled example data. It does not scan visitor files. +Real app screenshots show Srcly inspecting its public source and checked-in fixtures. +Capture provenance is in `public/screenshots/README.md`. The site does not scan visitor files. +The docs have three groups: Discover, Use Srcly, and Automate & configure. ## Verification `pnpm test` runs a browser against the built site under `/srcly/`. -It checks direct guide links, rendered content, navigation, search, the example controls, and narrow screens. +It checks static guide content, local links, images, search anchors, screenshot zoom, copy feedback, and narrow screens. Keep screenshot evidence under the repository's ignored `tmp/` directory. diff --git a/site/public/screenshots/README.md b/site/public/screenshots/README.md new file mode 100644 index 00000000..b8227850 --- /dev/null +++ b/site/public/screenshots/README.md @@ -0,0 +1,12 @@ +# Screenshot assets + +These app screenshots come from a real local Srcly run at source revision `653037aa` (2026-11-06). The scanned source is the public `client/src` tree. The graph examples use the checked-in `engine/examples/symbol-graph` fixture. No private repository data appears in these images. + +Each JPEG is 1440 × 960 pixels at quality 88. Capture URLs, UI steps, raw PNG paths, and factual captions are recorded in `tmp/10x/docs/app/CAPTURES.md`. + +- `treemap.jpg` — client source tree sized by LOC and colored by maximum complexity. +- `hotspots.jpg` — ranked complexity list beside the treemap. +- `quadrant.jpg` — activity 2×2, with the Hot mess quadrant selected. +- `code-inspector.jpg` — `App.tsx` source and metrics, focused on the `openAt` complexity witness. +- `data-flow.jpg` — route trace with its partial outcome and callback handoff in the inspector. +- `symbols.jpg` — `NotePage` references in the symbol graph. diff --git a/site/public/screenshots/code-inspector.jpg b/site/public/screenshots/code-inspector.jpg new file mode 100644 index 00000000..e4505840 Binary files /dev/null and b/site/public/screenshots/code-inspector.jpg differ diff --git a/site/public/screenshots/data-flow.jpg b/site/public/screenshots/data-flow.jpg new file mode 100644 index 00000000..849b93eb Binary files /dev/null and b/site/public/screenshots/data-flow.jpg differ diff --git a/site/public/screenshots/hotspots.jpg b/site/public/screenshots/hotspots.jpg new file mode 100644 index 00000000..70853665 Binary files /dev/null and b/site/public/screenshots/hotspots.jpg differ diff --git a/site/public/screenshots/quadrant.jpg b/site/public/screenshots/quadrant.jpg new file mode 100644 index 00000000..561d1af3 Binary files /dev/null and b/site/public/screenshots/quadrant.jpg differ diff --git a/site/public/screenshots/symbols.jpg b/site/public/screenshots/symbols.jpg new file mode 100644 index 00000000..cd836781 Binary files /dev/null and b/site/public/screenshots/symbols.jpg differ diff --git a/site/public/screenshots/treemap.jpg b/site/public/screenshots/treemap.jpg new file mode 100644 index 00000000..e1877c30 Binary files /dev/null and b/site/public/screenshots/treemap.jpg differ diff --git a/site/scripts/prerender.mjs b/site/scripts/prerender.mjs index 1556bb21..5a9077a6 100644 --- a/site/scripts/prerender.mjs +++ b/site/scripts/prerender.mjs @@ -22,7 +22,8 @@ for (const filename of (await readdir("src/docs/pages")).filter((name) => name.e const description = markdown.split(/\n\s*\n/).find((block) => !block.startsWith("#")) ?.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/[`*_]/g, "").replace(/\s+/g, " ").slice(0, 200); assert(description, `Missing page introduction: ${filename}`); - pages.push({ route: `docs/${filename.slice(0, -3)}/`, title: `${title} · Srcly docs`, description }); + const slug = filename.slice(0, -3); + pages.push({ route: slug === "overview" ? "docs/" : `docs/${slug}/`, title: `${title} · Srcly docs`, description }); } function html(page) { @@ -35,7 +36,9 @@ function html(page) { ``, ``, ``, - ``, + ``, + ``, + ``, ].join("\n "); assert.equal(template.match(/.*?<\/title>/g)?.length, 1); assert.equal(template.match(/<!-- page-meta -->/g)?.length, 1); @@ -49,13 +52,19 @@ function html(page) { for (const page of pages) { const directory = `dist/${page.route}`; await mkdir(directory, { recursive: true }); - await writeFile(`${directory}/index.html`, html(page)); + const content = html(page); + for (const match of content.matchAll(/<img[^>]+src="(\/srcly\/screenshots\/[^"?#]+)"/g)) { + const asset = await readFile(`dist/${match[1].slice(base.length)}`); + assert(asset.length > 0, `Missing screenshot in ${page.route}: ${match[1]}`); + } + await writeFile(`${directory}/index.html`, content); } -// Keep the docs entry point readable on static hosts, including without JavaScript. -const start = pages.find((page) => page.route === "docs/get-started/"); -assert(start, "The docs need a get-started page"); -await writeFile("dist/docs/index.html", html(start)); +// Keep the overview alias readable on static hosts, including without JavaScript. +const overview = pages.find((page) => page.route === "docs/"); +assert(overview, "The docs need an overview page"); +await mkdir("dist/docs/overview", { recursive: true }); +await writeFile("dist/docs/overview/index.html", html(overview)); await writeFile("dist/404.html", html({ route: "404/", title: "Page not found · Srcly", description: "Find Srcly documentation and setup guides." }).replace('<meta property="og:type"', '<meta name="robots" content="noindex" /><meta property="og:type"')); await writeFile("dist/.nojekyll", ""); await writeFile("dist/robots.txt", `User-agent: *\nAllow: /\nSitemap: ${origin}${base}sitemap.xml\n`); diff --git a/site/src/App.tsx b/site/src/App.tsx index 3e68084f..703f2e21 100644 --- a/site/src/App.tsx +++ b/site/src/App.tsx @@ -1,37 +1,44 @@ import { For, Show, createMemo, createSignal, onCleanup } from 'solid-js'; import { marked } from 'marked'; -import { ArrowRight, BookOpen, ChevronDown, ChevronLeft, ChevronRight, Code2, ExternalLink, Search, X } from 'lucide-solid'; +import { BookOpen, ChevronDown, ChevronLeft, ChevronRight, Code2, ExternalLink, Search, X } from 'lucide-solid'; import { Landing } from './Landing'; +import { Footer, Header } from './SiteChrome'; +import { ScreenshotViewer } from './ScreenshotViewer'; const docs = import.meta.glob('./docs/pages/*.md', { query: '?raw', import: 'default', eager: true }) as Record<string, string>; export const pages = [ + { slug: 'overview', title: 'Overview', description: 'Choose a path through Srcly, from a quick tour to your first local analysis.' }, + { slug: 'tour', title: 'Product tour', description: 'See how the explorer connects repository structure, code, and analysis.' }, + { slug: 'design', title: 'Design decisions', description: 'Learn what Srcly measures, how it presents evidence, and where its limits are.' }, { slug: 'get-started', title: 'Get started', description: 'Install Srcly and analyze your first codebase.' }, { slug: 'explore', title: 'Explore a codebase', description: 'Navigate the treemap, hotspots, explorer, and code view.' }, { slug: 'metrics', title: 'Metrics', description: 'Understand metric values, scope, and coverage.' }, { slug: 'findings', title: 'Findings', description: 'Read checker findings and understand what Srcly measured.' }, - { slug: 'data-flow', title: 'Data flow', description: 'Trace TypeScript and JavaScript values through the codebase.' }, + { slug: 'data-flow', title: 'Data flow', description: 'Trace TypeScript, JavaScript, and Python values through the codebase.' }, { slug: 'reports', title: 'Reports', description: 'Write compact, reviewable analysis artifacts.' }, { slug: 'cli', title: 'Command line', description: 'Use Srcly commands in scripts and agent workflows.' }, { slug: 'configuration', title: 'Configuration', description: 'Set project rules, ignores, and analysis options.' }, ]; const groups = [ - { title: 'Start', slugs: ['get-started', 'explore'] }, - { title: 'Understand', slugs: ['metrics', 'findings', 'data-flow'] }, - { title: 'Automate', slugs: ['reports', 'cli'] }, - { title: 'Configure', slugs: ['configuration'] }, + { title: 'Discover', slugs: ['overview', 'tour', 'design'] }, + { title: 'Use Srcly', slugs: ['get-started', 'explore', 'metrics', 'findings', 'data-flow'] }, + { title: 'Automate & configure', slugs: ['reports', 'cli', 'configuration'] }, ]; const base = import.meta.env.BASE_URL; export default function App(props: { path?: string }) { const pathname = props.path ?? '/'; const localPath = pathname.startsWith(base) ? pathname.slice(base.length) : pathname.replace(/^\//, ''); - const slug = localPath.replace(/^docs\/?/, '').replace(/\/$/, '') || (localPath === 'docs' ? 'get-started' : ''); + const normalizedPath = localPath.replace(/^\/+|\/+$/g, ''); + if (normalizedPath === '' || normalizedPath === 'index.html') return <Landing base={base}/>; + if (normalizedPath === 'docs') return <DocsPage page={pages[0]} base={base}/>; + if (normalizedPath === 'docs/overview') return <DocsPage page={pages[0]} base={base}/>; + const slug = normalizedPath.startsWith('docs/') ? normalizedPath.slice(5) : ''; const page = pages.find(item => item.slug === slug); - if (localPath === '' || localPath === 'index.html') return <Landing base={base} />; - if (page) return <DocsPage page={page} base={base} />; - return <NotFound base={base} />; + if (page) return <DocsPage page={page} base={base}/>; + return <NotFound base={base}/>; } function DocsPage(props: { page: (typeof pages)[number]; base: string }) { @@ -41,25 +48,27 @@ function DocsPage(props: { page: (typeof pages)[number]; base: string }) { const parsed = marked.parse(normalizedSource.replace(/^# .+\n+/, '')) as string; const headings: { title: string; id: string; depth: number }[] = []; const body = parsed.replace(/<h([23])>(.*?)<\/h\1>/g, (_full, level: string, raw: string) => { - const title = raw.replace(/<[^>]+>/g, '').replace(/&/g, '&').replace(/'|'/g, "'").replace(/"/g, '"'); + const title = decodeEntities(raw.replace(/<[^>]+>/g, '')); const id = slugify(title); headings.push({ title, id, depth: Number(level) }); return `<h${level} id="${id}">${raw}</h${level}>`; - }); + }).replace(/<a href="([^"]*\/screenshots\/[^\"]+)"[^>]*>/g, '<a class="shot-link" href="$1">'); const [query, setQuery] = createSignal(''); const [menuOpen, setMenuOpen] = createSignal(false); const [copied, setCopied] = createSignal(''); let copyTimer: ReturnType<typeof setTimeout> | undefined; + let lastCopiedButton: HTMLButtonElement | undefined; onCleanup(() => clearTimeout(copyTimer)); + const searchResults = createMemo(() => { const q = query().trim().toLowerCase(); if (!q) return []; return pages.flatMap(candidate => { - const text = docs[`./docs/pages/${candidate.slug}.md`] ?? ''; + const text = (docs[`./docs/pages/${candidate.slug}.md`] ?? '').replace(/<[^>]*>/g, ''); const at = text.toLowerCase().indexOf(q); - return (candidate.title.toLowerCase().includes(q) || at >= 0) - ? [{ ...candidate, excerpt: at >= 0 ? excerpt(text, at) : candidate.description }] - : []; + if (at < 0 && !candidate.title.toLowerCase().includes(q)) return []; + const heading = matchingHeading(text, at); + return [{ ...candidate, match: at >= 0 ? text.slice(at, at + q.length) : candidate.title, excerpt: at >= 0 ? excerpt(text, at) : candidate.description, anchor: heading ? slugify(heading) : '' }]; }); }); const idx = pages.findIndex(p => p.slug === props.page.slug); @@ -68,62 +77,107 @@ function DocsPage(props: { page: (typeof pages)[number]; base: string }) { const copyCode = async (button: HTMLButtonElement, code: string) => { try { await navigator.clipboard.writeText(code); - setCopied(button.dataset.codeId ?? ''); clearTimeout(copyTimer); - copyTimer = setTimeout(() => setCopied(''), 1200); + if (lastCopiedButton && lastCopiedButton !== button) { + lastCopiedButton.classList.remove('is-copied'); + lastCopiedButton.textContent = 'Copy'; + } + setCopied(button.dataset.codeId ?? ''); + button.classList.add('is-copied'); + button.textContent = 'Copied'; + lastCopiedButton = button; + copyTimer = setTimeout(() => { + setCopied(''); + button.classList.remove('is-copied'); + button.textContent = 'Copy'; + if (lastCopiedButton === button) lastCopiedButton = undefined; + }, 1300); } catch { /* The code stays selectable when clipboard access is unavailable. */ } }; let codeIndex = 0; const contentHtml = body.replace(/<pre><code([^>]*)>([\s\S]*?)<\/code><\/pre>/g, (full: string) => { const id = `code-${codeIndex++}`; - return `<div class="code-wrap" data-code-id="${id}">${full}<button class="code-copy" type="button" data-code-id="${id}" aria-label="Copy code"><span aria-hidden="true">⧉</span><span class="sr-only">Copy code</span></button></div>`; + return `<div class="code-wrap" data-code-id="${id}">${full}<button class="code-copy" type="button" data-code-id="${id}" aria-label="Copy code">Copy</button></div>`; }); - return <div class="site-shell docs-shell"> - <Header base={props.base} active="docs" /> - <a class="skip-link" href="#article">Skip to guide</a> - <div class="docs-topline"><span>Documentation</span><span aria-hidden="true">/</span><span>{props.page.title}</span></div> - <div class="docs-layout"> - <aside class="docs-sidebar" aria-label="Documentation navigation"> - <div class="sidebar-label">Browse guides</div> - <div class="search-box"><Search size={15} aria-hidden="true"/><input data-doc-search aria-label="Search documentation" type="search" placeholder="Search guides" value={query()} onInput={e => setQuery(e.currentTarget.value)} /><Show when={query()}><button type="button" aria-label="Clear search" onClick={() => setQuery('')}><X size={14}/></button></Show></div> - <Show when={query()} fallback={<For each={groups}>{group => <section class="nav-group"><h2>{group.title}</h2><For each={group.slugs}>{s => { const p = pages.find(x => x.slug === s)!; return <a class="side-link" classList={{ current: p.slug === props.page.slug }} href={`${props.base}docs/${p.slug}/`} aria-current={p.slug === props.page.slug ? 'page' : undefined}>{p.title}</a>; }}</For></section>}</For>}> - <div class="search-results" aria-live="polite"> - <Show when={searchResults().length} fallback={<p class="empty-search">No guides match “{query()}”. Try “metric” or “report”.</p>}> - <For each={searchResults()}>{result => <a class="search-result" data-search-result={result.slug} href={`${props.base}docs/${result.slug}/`}><strong>{result.title}</strong><span>{result.excerpt}</span></a>}</For> - </Show> + return <ScreenshotViewer> + <div class="site-shell docs-shell"> + <Header base={props.base} active="docs"/> + <a class="skip-link" href="#article">Skip to guide</a> + <div class="docs-layout"> + <aside class="docs-sidebar" aria-label="Documentation navigation"> + <div class="sidebar-label">Documentation</div> + <SearchBox query={query} setQuery={setQuery} /> + <Show when={query()} fallback={<For each={groups}>{group => <section class="nav-group"><h2>{group.title}</h2><For each={group.slugs}>{s => { const p = pages.find(x => x.slug === s)!; return <a class="side-link" classList={{ current: p.slug === props.page.slug }} href={`${props.base}docs/${p.slug}/`} aria-current={p.slug === props.page.slug ? 'page' : undefined}>{p.title}</a>; }}</For></section>}</For>}> + <SearchContent query={query} results={searchResults}/> + </Show> + <div class="sidebar-bottom"><a href="https://github.com/byronwall/srcly/tree/codex/product-guide/site/src/docs/pages" target="_blank" rel="noreferrer"><Code2 size={14}/> Edit guides <ExternalLink size={12}/></a></div> + </aside> + <main id="article" class="docs-article"> + <div class="mobile-doc-tools"> + <SearchBox query={query} setQuery={setQuery} /> + <Show when={query()}><SearchContent query={query} results={searchResults}/></Show> + <button type="button" class="topics-toggle" data-topics-toggle aria-expanded={menuOpen()} onClick={() => setMenuOpen(!menuOpen())}><BookOpen size={16}/> Topics <ChevronDown size={15} classList={{ rotated: menuOpen() }}/></button> + <Show when={menuOpen()}><div class="mobile-topics" data-mobile-topics><For each={groups}>{group => <section><h2>{group.title}</h2><For each={group.slugs}>{s => { const p = pages.find(x => x.slug === s)!; return <a href={`${props.base}docs/${p.slug}/`} aria-current={p.slug === props.page.slug ? 'page' : undefined}>{p.title}</a>; }}</For></section>}</For></div></Show> </div> - </Show> - <div class="sidebar-bottom"><a href="https://github.com/byronwall/srcly" target="_blank" rel="noreferrer"><Code2 size={14}/> View source <ExternalLink size={12}/></a></div> - </aside> - <main id="article" class="docs-article"> - <button type="button" class="topics-toggle" data-topics-toggle aria-expanded={menuOpen()} onClick={() => setMenuOpen(!menuOpen())}><BookOpen size={16}/> Topics <ChevronDown size={15} classList={{ rotated: menuOpen() }}/></button> - <Show when={menuOpen()}><div class="mobile-topics" data-mobile-topics><For each={pages}>{p => <a href={`${props.base}docs/${p.slug}/`} aria-current={p.slug === props.page.slug ? 'page' : undefined}>{p.title}</a>}</For></div></Show> - <div class="article-head"><div><p class="breadcrumb"><a href={`${props.base}docs/get-started/`}>Docs</a><span>/</span>{props.page.title}</p><h1>{props.page.title}</h1><p class="article-summary">{props.page.description}</p></div><a class="edit-link" href={`https://github.com/byronwall/srcly/tree/main/site/src/docs/pages/${props.page.slug}.md`} target="_blank" rel="noreferrer">Edit this page <ExternalLink size={13}/></a></div> - <div class="article-grid"> - <article class="markdown" innerHTML={contentHtml} ref={el => { - el.addEventListener('click', event => { - const button = (event.target as Element).closest<HTMLButtonElement>('.code-copy'); - if (!button) return; - const pre = button.closest('.code-wrap')?.querySelector('code'); - if (pre) void copyCode(button, pre.textContent ?? ''); - }); - }} /> - <aside class="toc" aria-label="On this page"><h2>On this page</h2><Show when={headings.length} fallback={<p>Sections will appear here.</p>}><For each={headings}>{heading => <a classList={{ indent: heading.depth === 3 }} href={`#${heading.id}`}>{heading.title}</a>}</For></Show></aside> - </div> - <nav class="page-nav" aria-label="Guide pages"><Show when={previous}><a href={`${props.base}docs/${previous!.slug}/`}><ChevronLeft size={15}/><span><small>Previous</small><strong>{previous!.title}</strong></span></a></Show><Show when={next}><a class="next-page" href={`${props.base}docs/${next!.slug}/`}><span><small>Next</small><strong>{next!.title}</strong></span><ChevronRight size={15}/></a></Show></nav> - </main> + <div class="article-head"> + <div><h1>{props.page.title}</h1><p class="article-summary">{props.page.description}</p></div> + <a class="edit-link" href={`https://github.com/byronwall/srcly/blob/codex/product-guide/site/src/docs/pages/${props.page.slug}.md`} target="_blank" rel="noreferrer">Edit page <ExternalLink size={13}/></a> + </div> + <div class="article-grid"> + <article class="markdown" innerHTML={contentHtml} ref={el => { + el.addEventListener('click', event => { + const button = (event.target as Element).closest<HTMLButtonElement>('.code-copy'); + if (!button) return; + const pre = button.closest('.code-wrap')?.querySelector('code'); + if (pre) void copyCode(button, pre.textContent ?? ''); + }); + }} /> + <aside class="toc" aria-label="On this page"><h2>On this page</h2><Show when={headings.length} fallback={<p>Sections will appear here.</p>}><For each={headings}>{heading => <a classList={{ indent: heading.depth === 3 }} href={`#${heading.id}`}>{heading.title}</a>}</For></Show></aside> + </div> + <nav class="page-nav" aria-label="Guide pages"><Show when={previous}><a href={`${props.base}docs/${previous!.slug}/`}><ChevronLeft size={15}/><span><small>Previous</small><strong>{previous!.title}</strong></span></a></Show><Show when={next}><a class="next-page" href={`${props.base}docs/${next!.slug}/`}><span><small>Next</small><strong>{next!.title}</strong></span><ChevronRight size={15}/></a></Show></nav> + </main> + </div> + <Footer base={props.base}/> + <Show when={copied()}><span class="sr-only" aria-live="polite">Code copied</span></Show> </div> - <Footer base={props.base}/> - <Show when={copied()}><span class="sr-only" aria-live="polite">Code copied</span></Show> + </ScreenshotViewer>; +} + +function SearchBox(props: { query: () => string; setQuery: (value: string) => void }) { + return <div class="search-box"><Search size={15} aria-hidden="true"/><input data-doc-search aria-label="Search documentation" type="search" placeholder="Search docs" value={props.query()} onInput={e => props.setQuery(e.currentTarget.value)}/><button class="search-clear" type="button" aria-label="Clear search" disabled={!props.query()} onClick={() => props.setQuery('')}><X size={14}/></button></div>; +} + +function SearchContent(props: { query: () => string; results: () => SearchResult[] }) { + return <div class="search-results" aria-live="polite"> + <Show when={props.results().length} fallback={<p class="empty-search">No guides match “{props.query()}”. Try “metric” or “report”.</p>}> + <For each={props.results()}>{result => <a class="search-result" data-search-result={result.slug} href={`${base}docs/${result.slug}/${result.anchor ? `#${result.anchor}` : ''}`}><strong>{result.title}</strong><span>{highlight(result.excerpt, result.match)}</span></a>}</For> + </Show> </div>; } +type SearchResult = { slug: string; title: string; excerpt: string; match: string; anchor: string }; +function highlight(text: string, match: string) { + const index = text.toLowerCase().indexOf(match.toLowerCase()); + if (index < 0) return text; + return <>{text.slice(0, index)}<mark>{text.slice(index, index + match.length)}</mark>{text.slice(index + match.length)}</>; +} +function matchingHeading(text: string, at: number) { + if (at < 0) return ''; + const headings = [...text.matchAll(/^#{2,3}\s+(.+)$/gm)]; + const lineStart = text.lastIndexOf('\n', at) + 1; + const headingOnLine = headings.find(heading => heading.index === lineStart); + if (headingOnLine) return cleanHeading(headingOnLine[1]); + return cleanHeading([...headings].reverse().find(heading => heading.index! < at)?.[1] ?? ''); +} +function cleanHeading(text: string) { return decodeEntities(text.replace(/`([^`]+)`/g, '$1').replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').replace(/[*_~]/g, '').trim()); } function slugify(text: string) { return text.toLowerCase().replace(/<[^>]*>/g, '').replace(/[^\w\s-]/g, '').trim().replace(/[\s]+/g, '-'); } -function excerpt(text: string, at: number) { return text.slice(Math.max(0, at - 48), at + 90).replace(/[#*`\[\]()>]/g, ' ').replace(/\s+/g, ' ').trim(); } +function excerpt(text: string, at: number) { + const start = Math.max(0, at - 52); + const from = start ? text.lastIndexOf(' ', start) + 1 : 0; + return text.slice(from, at + 105).replace(/\[([^\]]+)\]\([^)]+\)/g, '$1').replace(/[#*`\[\]()>|]/g, ' ').replace(/\s+/g, ' ').trim(); +} +function decodeEntities(text: string) { return text.replace(/&/g, '&').replace(/'|'/g, "'").replace(/"/g, '"'); } -function Header(props: { base: string; active?: string }) { - return <header class="site-header"><a class="brand" href={props.base} aria-label="Srcly home"><Mark/><span>srcly</span></a><nav aria-label="Main navigation"><a href={`${props.base}#explore`} classList={{ active: props.active === 'explore' }}>Explore</a><a href={`${props.base}docs/get-started/`} classList={{ active: props.active === 'docs' }}>Docs</a><a href="https://github.com/byronwall/srcly" target="_blank" rel="noreferrer">GitHub <ExternalLink size={12}/></a></nav></header>; +function NotFound(props: { base: string }) { + return <div class="site-shell"><Header base={props.base}/><main class="not-found"><h1>This page is not here.</h1><p>Choose a guide from the documentation.</p><a class="text-link" href={`${props.base}docs/`}>Open the docs <ChevronRight size={15}/></a></main><Footer base={props.base}/></div>; } -function Mark() { return <svg class="brand-mark" viewBox="0 0 28 28" aria-hidden="true"><path d="M2 2h11v11H2zM15 2h11v6H15zM15 10h11v16H15zM2 15h11v11H2z" fill="currentColor"/><path d="M4.5 4.5h6v6h-6z" fill="#fff"/></svg>; } -function Footer(props: { base: string }) { return <footer class="site-footer"><a class="brand footer-brand" href={props.base}><Mark/><span>srcly</span></a><span>Read the shape of your code.</span><div><a href={`${props.base}docs/get-started/`}>Docs</a><a href="https://github.com/byronwall/srcly" target="_blank" rel="noreferrer">GitHub <ExternalLink size={12}/></a></div></footer>; } -function NotFound(props: { base: string }) { return <div class="site-shell"><Header base={props.base}/><main class="not-found"><h1>This page is not here.</h1><p>Choose a guide from the documentation.</p><a class="text-link" href={`${props.base}docs/get-started/`}>Open the docs <ArrowRight size={15}/></a></main><Footer base={props.base}/></div>; } diff --git a/site/src/Landing.tsx b/site/src/Landing.tsx index c2516c14..b1cc6d84 100644 --- a/site/src/Landing.tsx +++ b/site/src/Landing.tsx @@ -1,72 +1,107 @@ -import { For, createSignal } from 'solid-js'; -import { ArrowDownRight, ArrowRight, Check, CircleHelp, Compass, Code2, FileCode2, Layers3 } from 'lucide-solid'; +import { ArrowRight, ArrowUpRight } from 'lucide-solid'; +import { createSignal, onCleanup } from 'solid-js'; +import { Footer, Header } from './SiteChrome'; +import { ScreenshotViewer } from './ScreenshotViewer'; -type Metric = 'complexity' | 'comment noise'; -type DemoFile = { name: string; loc: number; complexity: number; comments: number; note: string }; -const files: DemoFile[] = [ - { name: 'scan.ts', loc: 346, complexity: 21, comments: 4, note: 'Several paths converge here. Start with the largest branches.' }, - { name: 'report.ts', loc: 228, complexity: 13, comments: 2, note: 'A central report module with a few high-complexity functions.' }, - { name: 'cache.ts', loc: 146, complexity: 5, comments: 7, note: 'More commentary than executable code in this sample.' }, - { name: 'tree.ts', loc: 119, complexity: 8, comments: 1, note: 'Small aggregation helpers. Values shown are sample data.' }, - { name: 'schema.ts', loc: 91, complexity: 3, comments: 3, note: 'Type and schema definitions are compact in this sample.' }, - { name: 'paths.ts', loc: 73, complexity: 4, comments: 1, note: 'A small path utility file.' }, - { name: 'format.ts', loc: 54, complexity: 2, comments: 2, note: 'Low measured complexity in this sample.' }, - { name: 'types.ts', loc: 39, complexity: 1, comments: 1, note: 'A few shared types.' }, +const views = [ + { + image: 'treemap.jpg', + title: 'See the shape of a repository', + detail: 'The treemap sizes each region by code volume and colors it by the selected signal. Move from a folder to the files that need attention.', + guide: 'explore', + guideTitle: 'Explore a codebase', + }, + { + image: 'code-inspector.jpg', + title: 'Inspect code with its context', + detail: 'Open a file or symbol to read source alongside its measurements and findings. Follow the evidence into the code you maintain.', + guide: 'findings', + guideTitle: 'Read findings', + }, + { + image: 'data-flow.jpg', + title: 'Trace values across functions', + detail: 'Follow supported TypeScript, JavaScript, and Python values through calls. Each trace names where it stops or why analysis is unavailable.', + guide: 'data-flow', + guideTitle: 'Understand data flow', + }, ]; export function Landing(props: { base: string }) { - const [metric, setMetric] = createSignal<Metric>('complexity'); - const [selected, setSelected] = createSignal(files[0]); - return <div class="site-shell landing-shell"> - <Header base={props.base}/> + return <ScreenshotViewer><div class="site-shell landing-shell"> + <Header base={props.base} active="tour"/> <a class="skip-link" href="#main">Skip to content</a> <main id="main"> - <section class="hero-frame"> + <section class="hero-frame" aria-labelledby="hero-title"> <div class="hero-copy"> - <h1>See where the code gets hard.</h1> - <p class="hero-deck">Srcly maps a codebase into an explorable view of files, functions, and the signals that matter. Start local. Follow the evidence.</p> - <div class="hero-actions"><CopyCommand text="uvx srcly"/><a class="button button-primary" href={`${props.base}docs/get-started/`}>Get started <ArrowRight size={16}/></a></div> + <h1 id="hero-title">See where the code gets hard.</h1> + <p class="hero-deck">Explore a real codebase through its structure, measurements, and findings. Start with the whole tree, then open the code behind a signal.</p> + <div class="hero-actions"> + <CopyCommand text="uvx srcly"/> + <a class="button button-primary" href={`${props.base}docs/get-started/`}>Use Srcly <ArrowRight size={16}/></a> + </div> <p class="hero-note">Runs on your machine. No account or upload.</p> </div> - <TreemapDemo metric={metric} setMetric={setMetric} selected={selected} setSelected={setSelected}/> + <figure class="hero-product-shot"> + <a class="shot-link" href={`${props.base}screenshots/treemap.jpg`} aria-label="Open full size screenshot of Srcly's repository treemap"> + <img src={`${props.base}screenshots/treemap.jpg`} alt="Srcly repository treemap with file regions sized by lines of code and colored by complexity." fetchpriority="high"/> + </a> + <figcaption><span>Repository overview</span><span>Area shows code volume · color shows the selected metric</span></figcaption> + </figure> </section> - <section class="how-section" id="explore"> - <div class="section-heading"><h2>A map you can follow.</h2><p>Area shows lines of code. Color shows a selected metric. Click a file to see what the sample contains.</p></div> - <div class="explore-row"><div class="flow-step"><span class="step-mark"><Layers3 size={18}/></span><div><h3>Start at the whole tree</h3><p>Folders contain files. Files can contain functions and nested scopes. Zoom in when a region needs a closer look.</p></div></div><ArrowDownRight class="flow-arrow" size={23}/><div class="flow-step"><span class="step-mark"><Compass size={18}/></span><div><h3>Compare useful signals</h3><p>Rank hotspots by complexity, size, structure, or supported language signals. A missing measurement stays named as unavailable.</p></div></div><ArrowDownRight class="flow-arrow" size={23}/><div class="flow-step"><span class="step-mark"><FileCode2 size={18}/></span><div><h3>Open the source</h3><p>Inspect a file or function with its metrics and findings in context. Srcly points to code; you decide what to change.</p></div></div></div> + + <section class="product-tour" id="product-tour" aria-labelledby="tour-title"> + <div class="section-heading"> + <div><h2 id="tour-title">A codebase, from overview to evidence.</h2><p>Three views connect the shape of the project to the source and analysis behind it.</p></div> + <a class="text-link" href={`${props.base}docs/tour/`}>Product tour <ArrowRight size={15}/></a> + </div> + <div class="tour-gallery"> + {views.map((view) => <article class="tour-view"> + <figure class="tour-shot"> + <a class="shot-link" href={`${props.base}screenshots/${view.image}`} aria-label={`Open full size screenshot: ${view.title}`}> + <img src={`${props.base}screenshots/${view.image}`} alt={`${view.title}. Srcly application screenshot.`} loading="lazy"/> + </a> + <figcaption>{view.title}</figcaption> + </figure> + <p>{view.detail}</p> + <a class="text-link" href={`${props.base}docs/${view.guide}/`}>{view.guideTitle} <ArrowUpRight size={14}/></a> + </article>)} + </div> </section> - <section class="workflow-section"><div class="workflow-copy"><h2>From a quick look to a repeatable review.</h2><p>Use the browser to explore a project. Use the CLI to produce evidence that fits into a pull request or an agent's working context.</p><a class="text-link" href={`${props.base}docs/reports/`}>See report output <ArrowRight size={15}/></a></div><div class="workflow-code"><div class="code-title"><span>terminal</span><span>local analysis</span></div><pre><code>{`$ uvx srcly report . --out .srcly -report.md -findings.json -hotspots.json -metrics.schema.json + <section class="use-paths" aria-labelledby="use-title"> + <div><h2 id="use-title">See the product. Then use it on your code.</h2><p>Browse how Srcly works, or install it and open a local project. The same guides explain metrics, reports, the command line, and configuration.</p></div> + <div class="path-links"> + <a href={`${props.base}docs/tour/`}><span><strong>See the product</strong><small>Walk through the explorer and its signals.</small></span><ArrowRight size={17}/></a> + <a href={`${props.base}docs/get-started/`}><span><strong>Use Srcly</strong><small>Install the CLI and analyze a repository.</small></span><ArrowRight size={17}/></a> + </div> + </section> -Analysis: 1,248 files · 6 tools · 42 unavailable`}</code></pre><p class="sample-caption">Illustrative terminal output</p></div></section> - <section class="coverage-section"><h2>Useful signals, with their limits in view.</h2><div class="coverage-copy"><p>Srcly combines broad source metrics with language-aware analysis where available. The supported signals vary by language and tool setup; a metric that does not apply is N/A, never zero.</p><p>Data-flow analysis covers TypeScript, JavaScript, and Python. It runs with Node.js 18 or newer. Without Node, the rest of Srcly still works and data flow shows the reason it was not analyzed.</p><a class="text-link" href={`${props.base}docs/metrics/`}>How to read the metrics <ArrowRight size={15}/></a></div></section> - <section class="docs-cta"><div><h2>Start with your codebase.</h2><p>One command opens the local explorer. The guides cover reports, findings, metrics, and configuration.</p></div><a class="button button-primary" href={`${props.base}docs/get-started/`}>Read the guide <ArrowRight size={16}/></a></section> + <section class="trust-note" aria-label="Analysis limits"> + <h2>Measurements keep their limits in view.</h2> + <p>Supported signals vary by language and tool setup. A metric that does not apply is shown as N/A, never zero. Data-flow results name their outcome and stop reason.</p> + <a class="text-link" href={`${props.base}docs/metrics/`}>How to read the metrics <ArrowRight size={15}/></a> + </section> </main> <Footer base={props.base}/> - </div>; -} - -function TreemapDemo(props: { metric: () => Metric; setMetric: (v: Metric) => void; selected: () => DemoFile; setSelected: (f: DemoFile) => void }) { - const shown = () => props.selected(); - return <section class="demo" aria-label="Interactive illustrative treemap"> - <div class="demo-top"><div><span class="demo-title">srcly / example-project</span><span class="demo-sample">Sample data</span></div><span class="demo-status"><span/>Illustration</span></div> - <div class="demo-toolbar"><div class="demo-crumb"><span>src</span><span>/</span><strong>analyzer</strong></div><div class="metric-control" role="group" aria-label="Color tiles by metric"><span>Color</span><button data-metric="complexity" type="button" classList={{ chosen: props.metric() === 'complexity' }} aria-pressed={props.metric() === 'complexity'} onClick={() => props.setMetric('complexity')}>Complexity</button><button data-metric="comment-noise" type="button" classList={{ chosen: props.metric() === 'comment noise' }} aria-pressed={props.metric() === 'comment noise'} onClick={() => props.setMetric('comment noise')}>Comment noise</button></div></div> - <div class="demo-body"><div class="tile-map" role="group" aria-label="Sample source files. Tile size represents lines of code."> - <For each={files}>{(file, i) => <button data-file={file.name} type="button" class={`map-tile tile-${i()}`} style={{ 'background-color': props.metric() === 'complexity' ? `hsl(200 38% ${91 - file.complexity * 1.4}%)` : `hsl(36 45% ${93 - file.comments * 4}%)` }} classList={{ selected: shown().name === file.name }} aria-pressed={shown().name === file.name} aria-label={`${file.name}, ${file.loc} lines of code, complexity ${file.complexity}, comment flags ${file.comments}`} onClick={() => props.setSelected(file)}><span>{file.name}</span><small>{file.loc} LOC</small></button>}</For> - <span class="tile-label">AREA · LOC</span> - </div><aside class="demo-detail" aria-live="polite"><div class="detail-top"><span>Selected file</span><span class="selected-dot"/></div><strong data-selected-file>{shown().name}</strong><dl><div><dt>Lines of code</dt><dd>{shown().loc}</dd></div><div><dt>Complexity</dt><dd>{shown().complexity}</dd></div><div><dt>Comment flags</dt><dd>{shown().comments}</dd></div></dl><p>{shown().note}</p><span class="metric-swatch" classList={{ warm: props.metric() === 'comment noise' }}><i/>Color: {props.metric()}</span></aside></div> - <div class="demo-legend"><span><i class="legend-low"/>lower</span><span><i class="legend-high"/>higher {props.metric()}</span><span class="demo-footnote"><CircleHelp size={13}/> Example values, not a live scan</span></div> - </section>; + </div></ScreenshotViewer>; } -function Header(props: { base: string }) { return <header class="site-header"><a class="brand" href={props.base} aria-label="Srcly home"><Mark/><span>srcly</span></a><nav aria-label="Main navigation"><a href={`${props.base}#explore`}>Explore</a><a href={`${props.base}docs/get-started/`}>Docs</a><a href="https://github.com/byronwall/srcly" target="_blank" rel="noreferrer">GitHub <Code2 size={13}/></a></nav></header>; } -function Mark() { return <svg class="brand-mark" viewBox="0 0 28 28" aria-hidden="true"><path d="M2 2h11v11H2zM15 2h11v6H15zM15 10h11v16H15zM2 15h11v11H2z" fill="currentColor"/><path d="M4.5 4.5h6v6h-6z" fill="#fff"/></svg>; } -function Footer(props: { base: string }) { return <footer class="site-footer"><a class="brand footer-brand" href={props.base}><Mark/><span>srcly</span></a><span>Read the shape of your code.</span><div><a href={`${props.base}docs/get-started/`}>Docs</a><a href="https://github.com/byronwall/srcly" target="_blank" rel="noreferrer">GitHub <Code2 size={12}/></a></div></footer>; } function CopyCommand(props: { text: string }) { - const [copied, setCopied] = createSignal(false); let timer: ReturnType<typeof setTimeout> | undefined; - const run = async () => { try { await navigator.clipboard.writeText(props.text); setCopied(true); clearTimeout(timer); timer = setTimeout(() => setCopied(false), 1300); } catch { /* Keep the command visible and selectable. */ } }; - return <button class="command-button" type="button" onClick={run} aria-label={`Copy command ${props.text}`}><code><span>$</span> {props.text}</code><span class="command-copy" aria-hidden="true">{copied() ? <Check size={15}/> : 'Copy'}</span><span class="sr-only" aria-live="polite">{copied() ? 'Command copied' : ''}</span></button>; + let timer: ReturnType<typeof setTimeout> | undefined; + const [copied, setCopied] = createSignal(false); + const run = async () => { + try { + await navigator.clipboard.writeText(props.text); + setCopied(true); + clearTimeout(timer); + timer = setTimeout(() => setCopied(false), 1300); + } catch { /* Keep the command visible and selectable. */ } + }; + onCleanup(() => clearTimeout(timer)); + return <button class="command-button" type="button" onClick={run} aria-label={`Copy command ${props.text}`}> + <code><span>$</span> {props.text}</code> + <span class="command-copy" aria-hidden="true">{copied() ? 'Copied' : 'Copy'}</span> + <span class="sr-only" aria-live="polite">{copied() ? 'Command copied' : ''}</span> + </button>; } diff --git a/site/src/ScreenshotViewer.tsx b/site/src/ScreenshotViewer.tsx new file mode 100644 index 00000000..7bd8ee04 --- /dev/null +++ b/site/src/ScreenshotViewer.tsx @@ -0,0 +1,52 @@ +import { Show, createSignal, onCleanup, type JSX } from 'solid-js'; +import { Minus, Plus, RotateCcw, X } from 'lucide-solid'; + +export function ScreenshotViewer(props: { children: JSX.Element }) { + const [source, setSource] = createSignal(''); + const [alt, setAlt] = createSignal(''); + const [scale, setScale] = createSignal(1); + let dialog!: HTMLDialogElement; + let trigger: HTMLElement | undefined; + + const open = (event: MouseEvent) => { + const link = (event.target as Element).closest<HTMLAnchorElement>('.shot-link'); + if (!link) return; + const image = link.querySelector('img'); + if (!image) return; + event.preventDefault(); + trigger = link; + setSource(link.href); + setAlt(image.alt); + setScale(1); + dialog.showModal(); + }; + const close = () => { + if (dialog.open) dialog.close(); + }; + const onClose = () => { + setSource(''); + trigger?.focus(); + trigger = undefined; + }; + onCleanup(() => dialog?.removeEventListener('close', onClose)); + + return <div class="screenshot-surface" onClick={open}> + {props.children} + <dialog class="screenshot-dialog" ref={el => { dialog = el; el.addEventListener('close', onClose); }} onClick={event => { if (event.target === dialog) close(); }} aria-label="Screenshot viewer"> + <div class="viewer-toolbar"> + <span>Screenshot</span> + <div class="viewer-controls"> + <button type="button" aria-label="Zoom out" disabled={scale() <= 0.5} onClick={() => setScale(value => Math.max(0.5, value - 0.25))}><Minus size={16}/></button> + <span>{Math.round(scale() * 100)}%</span> + <button type="button" aria-label="Zoom in" disabled={scale() >= 2.5} onClick={() => setScale(value => Math.min(2.5, value + 0.25))}><Plus size={16}/></button> + <button type="button" aria-label="Reset zoom" onClick={() => setScale(1)}><RotateCcw size={15}/></button> + <button type="button" aria-label="Close screenshot" onClick={close}><X size={17}/></button> + </div> + </div> + <div class="viewer-viewport" tabindex="0"> + <Show when={source()}>{src => <img src={src()} alt={alt()} style={{ width: `${scale() * 100}%` }}/>}</Show> + </div> + <p class="sr-only" aria-live="polite">{source() ? alt() : ''}</p> + </dialog> + </div>; +} diff --git a/site/src/SiteChrome.tsx b/site/src/SiteChrome.tsx new file mode 100644 index 00000000..41cca2cb --- /dev/null +++ b/site/src/SiteChrome.tsx @@ -0,0 +1,27 @@ +import { ExternalLink } from 'lucide-solid'; + +export function Header(props: { base: string; active?: 'tour' | 'docs' }) { + return <header class="site-header"> + <a class="brand" href={props.base} aria-label="Srcly home"><Mark/><span>srcly</span></a> + <nav aria-label="Main navigation"> + <a href={`${props.base}#product-tour`} classList={{ active: props.active === 'tour' }}>Tour</a> + <a href={`${props.base}docs/`} classList={{ active: props.active === 'docs' }}>Docs</a> + <a href="https://github.com/byronwall/srcly" target="_blank" rel="noreferrer">GitHub <ExternalLink size={12}/></a> + </nav> + </header>; +} + +export function Footer(props: { base: string }) { + return <footer class="site-footer"> + <a class="brand footer-brand" href={props.base}><Mark/><span>srcly</span></a> + <span>Read the shape of your code.</span> + <div><a href={`${props.base}docs/`}>Docs</a><a href="https://github.com/byronwall/srcly" target="_blank" rel="noreferrer">GitHub <ExternalLink size={12}/></a></div> + </footer>; +} + +function Mark() { + return <svg class="brand-mark" viewBox="0 0 28 28" aria-hidden="true"> + <path d="M2 2h11v11H2zM15 2h11v6H15zM15 10h11v16H15zM2 15h11v11H2z" fill="currentColor"/> + <path d="M4.5 4.5h6v6h-6z" fill="#fff"/> + </svg>; +} diff --git a/site/src/docs/pages/cli.md b/site/src/docs/pages/cli.md index 28f3b8bc..b205e5d5 100644 --- a/site/src/docs/pages/cli.md +++ b/site/src/docs/pages/cli.md @@ -1,6 +1,6 @@ # Command-line reference -Srcly has an interactive command and headless commands for scripts, agents, and CI. Run `uvx srcly --help` or `uvx srcly <command> --help` for the options available in your installed version. +Srcly has an interactive command and headless commands for scripts, agents, and CI. Run `uvx srcly --help` or `uvx srcly <command> --help` to see options in the version you installed. ## Open the interactive app @@ -9,75 +9,85 @@ uvx srcly uvx srcly /path/to/repository ``` -The server binds to `127.0.0.1` by default and opens the browser. You can set `--port` to choose a port or `--host` to choose an interface. The app reads local repository files through this server. Keep the server on a trusted local interface. +The server binds to `127.0.0.1` by default, selects an available port, and opens the browser. Use `--port` to select a port or `--host` to select another interface. Keep the server on a trusted local interface because the app reads repository files through it. Keep the terminal open while using the app; stop it with `Ctrl+C`. ## Scan and summarize -`scan` writes the raw analysis tree as JSON. The default filename is `codebase_mri.json`. +`scan` writes the raw analysis tree as JSON. Its default filename is `codebase_mri.json`: ```bash uvx srcly scan . --out tree.json ``` -`report` writes the Markdown and JSON artifacts described in [Reports](../reports/). Use `--stdout` for one bundled JSON payload, `--refresh` to rerun analysis and checks, and `--verbose` for progress. +`report` writes a Markdown summary and JSON artifacts. Choose an output directory and profile: ```bash -uvx srcly report . --out .srcly --profile python +uvx srcly report . --out .srcly --profile frontend ``` +Use `--stdout` for a bundled JSON payload, `--refresh` to rescan and rerun checks, and `--verbose` to print per-file progress to stderr. To include the full raw tree, use `--include-tree`; to include TypeScript and TSX imports, use `--include-dependencies`. Select the output format with `--format markdown`, `--format json`, or `--format both`. + +The findings profile and the top-table metric are different settings. Use `--profile` for the weighted findings queue; use `--metric` for top files and functions. For example: + +```bash +uvx srcly report . --profile frontend --metric complexity --limit 30 --out .srcly +``` + +Add `--quadrant activity`, `blast_radius`, `component_weight`, `comment_noise`, or `findings` to add a 2×2 breakdown. Use `--quadrant-cohort file`, `function`, or `component` when the preset supports it. + ## Rank or explain -`hotspots` ranks files or functions by one metric. The default metric is complexity; the default cohort is files. +`hotspots` ranks files or functions by one metric. The default metric is complexity and the default cohort is files: ```bash uvx srcly hotspots . --metric complexity --cohort function --limit 20 --format json ``` -`explain` prints a summary for a repository, folder, file, or symbol. Use `file::symbol` to select a symbol. Paths are relative to the analyzed root; `--at` can also use a line location copied from the report. +`explain` summarizes a repository, folder, file, or symbol. Use a path relative to the analyzed root, `file::symbol`, or a `file::name@line` value when names repeat: ```bash +uvx srcly explain . --at src uvx srcly explain . --at src/app.tsx uvx srcly explain . --at "src/app.tsx::App" ``` +You can also pass a `path:line name` Start at location printed by the report. `explain` reports scan provenance and checker coverage so you can see whether it reused a scan and what remains unmeasured. + ## Compare refs -`compare` compares Git refs. By default, it compares the merge base with the current working tree, including uncommitted edits. You can provide explicit refs or output JSON: +`compare` compares Git refs. By default it compares the merge base with the current working tree, including uncommitted edits. Give two refs to compare explicit revisions, or request JSON: ```bash +uvx srcly compare uvx srcly compare main HEAD --json +uvx srcly compare main pr:42 --json ``` -Unavailable measurements stay null. If a file is measured on only one side, Srcly records a coverage change and does not count that missing measurement as a zero delta. +Unavailable measurements stay null. If a file is measured on one side only, Srcly records a coverage change and does not count the missing value as a zero delta. A file absent from one dependency graph has unknown fan-in and fan-out. ## Fix and check -`fix` prints a diff of supported mechanical fixes. It only applies them with `--write`: +`fix` prints a diff of supported mechanical fixes. It applies changes only with `--write`: ```bash uvx srcly fix . uvx srcly fix . --write ``` -The `unreachable-file` rule can delete files. It runs only when you name it, and only with `--write`; inspect its diff first: +The `unreachable-file` rule can delete a file. Name that rule to run it, and inspect the diff before applying it: ```bash uvx srcly fix . --rule unreachable-file +uvx srcly fix . --rule unreachable-file --write ``` -`check` requires `--ratchet` and an existing budget. First create the budget with `report`: +`check` requires `--ratchet` and an existing size budget. Create that budget with `report`; the default report writes `.srcly/size_budget.json`: ```bash uvx srcly report . --out .srcly uvx srcly check . --ratchet ``` -The budget tracks code files above 5,000 estimated tokens (file bytes divided by four). The check exits 1 when a tracked file grows above its baseline, or a new file crosses that threshold. A missing budget exits 2. - -The budget comes from `.srcly/size_budget.json`. If you use another report directory, pass its budget file with `--budget`: - -```bash -uvx srcly check . --ratchet --budget /tmp/srcly-report/size_budget.json -``` +The budget tracks code files over 5,000 estimated tokens, based on file bytes divided by four. The baseline only goes down. The check exits nonzero when a tracked file grows above its baseline or a new file crosses the threshold. Use `--budget` to pass a budget from another report directory. -See [Configuration](../configuration/) and [Reports](../reports/) for related settings and artifacts. +For supported settings see [Configuration](../configuration/). For the report artifacts and review order, see [Reports](../reports/). diff --git a/site/src/docs/pages/configuration.md b/site/src/docs/pages/configuration.md index 618ea2e3..79a433df 100644 --- a/site/src/docs/pages/configuration.md +++ b/site/src/docs/pages/configuration.md @@ -1,41 +1,61 @@ # Configuration -Most users can start Srcly without a configuration file. This page covers the project settings and environment variables that change scan behavior or optional checks. +Most users can start Srcly without a configuration file. Use this page when you need to choose a scan root, add TypeScript entry points, enable optional rules, or understand why a check is unavailable. ## Choose the scan root -Pass a directory to `srcly` or a headless command to select the root. Without a path, Srcly uses the enclosing Git repository, or the current directory when it is not inside one. Srcly follows Git ignore rules and skips common generated, hidden, dependency, and build directories. +Pass a directory to the interactive command or a headless command: ```bash uvx srcly /path/to/repository uvx srcly report /path/to/repository --out .srcly ``` -The interactive server binds to `127.0.0.1` by default and chooses an available port. `--host` and `--port` select another interface or port. Use the local default for local code browsing. +Without a path, Srcly uses the enclosing Git repository or the current directory when no repository contains it. In a Git repository, discovery includes tracked files and nonignored untracked files. Srcly follows Git ignore rules and skips common generated, hidden, dependency, and build paths. Start at a subdirectory when you want a narrower review. -## Add TypeScript reachability entries +The interactive server binds to `127.0.0.1` by default and chooses an available port. Use `--host` or `--port` when you need to change those settings. The local app reads repository files through this server; keep the default local interface unless you have a specific reason to bind elsewhere. -Srcly detects common TypeScript entry points from routes, package metadata, scripts, and configuration. If your application uses an entry pattern that Srcly does not detect, add globs to `srcly.toml` at the Git root. Patterns are relative to that file. +## Configure TypeScript reachability entries + +Srcly detects common TypeScript entry points from routes, package metadata, scripts, and configuration. If your application uses another entry pattern, add globs to `srcly.toml` at the Git root. Patterns are relative to that file: ```toml [reachability] entries = ["app/scripts/**/*.ts"] ``` -Reachability applies to the TypeScript and JavaScript import graph. Treat an unreachable-file finding as a prompt to check your runtime entry points, dynamic loading, and project structure. +Reachability follows the TypeScript and JavaScript import graph from entries. An unreachable-file signal is a prompt to inspect runtime entry points, dynamic loading, and project structure. It is not proof that a file is unused. After changing entries, refresh the report so the new analysis is used: + +```bash +uvx srcly report . --refresh --out .srcly +``` ## Add ast-grep rules -Put ast-grep YAML rule files in `.srcly/rules/`. Srcly discovers `.yml` and `.yaml` files there and reports their matches with its other findings. Install the ast-grep CLI in the project or on `PATH`, or select it with `SRCLY_AST_GREP`. If it is not available, Srcly reports the check as unavailable. +Put ast-grep YAML rules under `.srcly/rules/` in the project. Srcly discovers `.yml` and `.yaml` files there. Install ast-grep in the project or on `PATH`, or select it with `SRCLY_AST_GREP`. If the binary is unavailable, Srcly reports the check as unavailable rather than reporting zero matches. + +See the [rule-pack examples](https://github.com/byronwall/srcly/tree/main/docs/rule-packs) for syntax and sample rules. Rerun the scan after adding rules or changing the checker environment. + +## Set environment variables + +| Variable | Purpose | +| --- | --- | +| `SRCLY_NODE` | Select the Node executable for data-flow analysis. Defaults to `node` on `PATH`; Node.js 18 or newer is required. | +| `SRCLY_CACHE_DIR` | Select the local analysis cache directory. | +| `SRCLY_FINDINGS_TIMEOUT` | Set the timeout for checker jobs. | +| `SRCLY_DATAFLOW_TIMEOUT` | Override data-flow request timeouts. | +| `SRCLY_AST_GREP` | Select the ast-grep executable and override project and `PATH` discovery. | -See the [rule-pack examples](https://github.com/byronwall/srcly/tree/main/docs/rule-packs) for rule syntax and examples. +Cache data is stored in your user cache directory, not in the analyzed repository. A changed file or checker signature can trigger fresh analysis. Use `--refresh` when a command supports it and you need to rerun the checks without relying on cached results. -## Environment variables +## Troubleshoot a missing result -- `SRCLY_NODE` selects the Node.js executable used by data-flow analysis. The default is `node` on `PATH`; Node.js 18 or newer is required. -- `SRCLY_CACHE_DIR` changes the local cache directory. By default, the cache is in the operating system's user cache location. -- `SRCLY_FINDINGS_TIMEOUT` sets the timeout for checker jobs. -- `SRCLY_DATAFLOW_TIMEOUT` overrides data-flow request timeouts. -- `SRCLY_AST_GREP` selects the ast-grep executable and overrides project and `PATH` discovery. +| Symptom | Check | Next step | +| --- | --- | --- | +| Data flow says not analyzed | Node version and `SRCLY_NODE`; project type detection and supported language | Install or select Node 18+, then rerun. If the code pattern is unsupported, treat it as an evidence limit. | +| Checker coverage is N/A | Report's `Analysis:` line and checker reason | Install/configure the project tool or accept the gap; use `--refresh` after setup changes. | +| Reachability marks an entry file unused | Detected entries and dynamic imports | Add an entry glob in `srcly.toml`, then refresh. Confirm any finding against the runtime. | +| ast-grep has no results or is unavailable | Rule file location, YAML extension, binary discovery | Put files in `.srcly/rules/` and install or select ast-grep. | +| Metrics appear as N/A | Node type, language support, analyzer status, or missing history | Read the reason; N/A means unavailable or not applicable, not zero. | -For the full list of command options, run `uvx srcly --help` or see the [CLI reference](../cli/). Use [Reports](../reports/) to select an output directory without changing cache settings. +For the full command list, use the [CLI reference](../cli/). For N/A interpretation, see [Metrics](../metrics/); for checker behavior, see [Findings](../findings/). diff --git a/site/src/docs/pages/data-flow.md b/site/src/docs/pages/data-flow.md index 1e4f05ab..ce16ff41 100644 --- a/site/src/docs/pages/data-flow.md +++ b/site/src/docs/pages/data-flow.md @@ -1,32 +1,59 @@ # Data-flow analysis -Data flow traces how values move through supported source code. Use it to investigate where a request is handled, what a function does with an input, or where a value is written or returned. It is a separate feature from the TypeScript and TSX import dependency graph. +Data flow traces how values move through supported source code. Use it to investigate where a request is handled, what a function does with an input, or where a value is written or returned. It is separate from the TypeScript and TSX import dependency graph. + +<figure><a href="/srcly/screenshots/data-flow.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/data-flow.jpg" alt="Partial route trace for /notes/[id] in Srcly's included symbol-graph example" width="1440" height="960" loading="lazy" /></a><figcaption>The <code>/notes/[id]</code> route trace in the included symbol-graph example is anchored at <code>NotePage</code>. It is partial: one callback handoff has no call sites to pair its values. Inspect the unproven handoff before relying on the path.</figcaption></figure> ## Open a trace -In the app, switch to **Data flow** from a selected file or function. Choose an anchor, such as a route, exported function, or file. Depending on the anchor and language, Srcly can show a route, a value-flow trace, or function effects. Select a graph item to inspect its source location and relations. +1. Analyze a supported repository in the app. +2. Select a file or function and switch to **Data flow**. +3. Choose an available anchor, such as a route, exported function, or file. +4. Select a graph item to inspect its source location and modeled relations. +5. Read the outcome and any assumptions, stops, or unavailable reason. + +Depending on the anchor and language, Srcly can show a route, value-flow trace, or function effects. A route graph may show where a route's values move; an anchor graph starts from a selected symbol. The exact view depends on available code facts and supported language constructs. -For a repository summary or an agent workflow, use the headless commands first: +For a repository summary or agent workflow, use a report and scoped explanation: ```bash uvx srcly report . --out .srcly uvx srcly explain . --at src/app.tsx ``` -The data-flow graph is currently an interactive app view; the headless examples above provide general scan and scope context. +These commands provide scan and scope context. The interactive Data flow view currently carries the graph exploration. ## Requirements and language support -The bundled engine requires Node.js 18 or newer on `PATH`. Set `SRCLY_NODE` if you need to select a specific Node executable. If Node or the engine is unavailable, Srcly names the reason and keeps the rest of the scan available. +The bundled engine requires Node.js 18 or newer on `PATH`. Set `SRCLY_NODE` to choose another executable. The engine analyzes TypeScript, JavaScript, and Python roots. TypeScript and JavaScript projects are detected from project configuration or source files; loose files can also be analyzed. Python projects are detected from Python project files or `.py` files. -The engine analyzes TypeScript, JavaScript, and Python roots. TypeScript and JavaScript projects are detected from project configuration or source files. Python projects are detected from Python project files or `.py` files. Loose TypeScript or JavaScript files can also be analyzed. Without project type configuration, some guarantees about null values are unavailable. +Python analysis has a different feature set from TypeScript. Python routes can open their handler in anchor mode; the TypeScript route graph does not apply to Python. Without project type configuration, some guarantees about null values are unavailable. Unsupported constructs and incomplete evidence can stop a trace early. -Python analysis has a different feature set from TypeScript. Python routes can open their handler in anchor mode; the TypeScript route graph does not apply to Python. Unsupported constructs or incomplete evidence can stop a trace early. +If Node or the engine is unavailable, Srcly names the reason and leaves the rest of the scan available. An unavailable trace is not an empty proof. See [Configuration](../configuration/) for selecting Node and [Get started](../get-started/) for the base scan. ## Read outcomes honestly -Trace results name their outcome. A result can be complete, partial, stale, or not analyzed, with a reason where applicable. A partial result may include an assumed relationship or an unmodeled handoff. Do not treat an empty graph or a missing edge as proof that a value cannot flow. +Trace outcomes distinguish different evidence states. The app may show no status text for a landed, fully proven (`ok`) result. Other outcomes have visible labels or reasons: + +| Outcome | How to use it | +| --- | --- | +| Proven (`ok`) | No status banner appears. The result landed without an assumed library step or a frontier; it remains limited to modeled language and library facts. | +| Assumed | The app says “Landed · assumes library code.” Read “Assumed library steps” in the inspector. A trace that also has a stop is labeled partial. | +| Partial | The app says “Partial: some paths stop at frontiers.” Inspect the frontier rows and locations before drawing a conclusion. | +| Stale | The app says “Source changed. Refresh.” Rebuild the graph from the current sources before using it. | +| Unsupported | The analysis names why it could not trace the selected anchor, such as “Nothing to trace.” Treat this as an analysis limit. | +| Stopped at budget | The app names the budget limit. The trace stopped before covering the full requested slice. | +| Not analyzed | The app says “Data flow N/A” and gives a reason such as Node.js not found or a timeout. Do not treat it as zero edges. | + +The engine's graph is not a whole-program proof. It models selected language constructs and libraries. An empty graph, a missing edge, or a partial path does not prove that a value cannot flow. Check assumptions and source locations, then verify important conclusions in code and tests. See [Design decisions](../design/) for how Srcly keeps modeled data flow separate from imports. + +## A review sequence -The engine models selected language constructs and libraries; it is not a whole-program proof. Coverage depends on the code, available project configuration, and the models Srcly supports. Review the trace's assumptions and source locations, then verify important conclusions in the code and tests. +1. State the path or symbol you want to investigate. +2. Pick a route or anchor that corresponds to that question. +3. Follow the graph and inspect the source behind each key edge. +4. Read the outcome, assumptions, and terminal or stop locations. +5. Confirm important behavior against source and tests. +6. If the trace is unavailable, decide whether the reason can be fixed through setup or reflects an unsupported case. -See [Explore](../explore/) for the related views and [Configuration](../configuration/) for choosing the Node executable. +This keeps a plausible graph from becoming a stronger claim than its evidence supports. For other views, see [Explore](../explore/). For checker coverage and findings, see [Findings](../findings/). diff --git a/site/src/docs/pages/design.md b/site/src/docs/pages/design.md new file mode 100644 index 00000000..c705aafd --- /dev/null +++ b/site/src/docs/pages/design.md @@ -0,0 +1,53 @@ +# Design decisions + +Srcly combines a visual code map with source-level evidence and repeatable terminal output. Its design follows a simple review path: orient, select a question, inspect the evidence, and decide what to verify. This page explains the choices behind that path and where they set limits. + +## Two evidence trails + +At revision `653037aa`, Srcly scanned its own public `client/src` tree: 236 files and 33,823 LOC. Hot Spots ranks 235 measured files; `viewModel.ts::buildViewModel` leads at CCN 135. The inspector opens `App.tsx::openAt` with source and metrics. Together, these screens support a product choice: move from map to ranked candidate to source witness. They show how the review works, not a measured improvement. The [capture record](/srcly/screenshots/README.md) names the source and revision. + +<figure><a href="/srcly/screenshots/hotspots.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/hotspots.jpg" alt="Complexity-ranked Srcly client files, led by viewModel.ts at CCN 135" width="1440" height="960" loading="lazy" /></a><figcaption>Hot Spots for Srcly's <code>client/src</code> at revision <code>653037aa</code>: 236 files, 33,823 LOC, and a top measured complexity of CCN 135 in <code>viewModel.ts::buildViewModel</code>.</figcaption></figure> + +<figure><a href="/srcly/screenshots/code-inspector.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/code-inspector.jpg" alt="Srcly's code inspector showing App.tsx and the openAt function" width="1440" height="960" loading="lazy" /></a><figcaption>The inspector opens <code>App.tsx::openAt</code> with source and metrics. It demonstrates the next step after a ranked signal: inspect the code and its evidence.</figcaption></figure> + +A separate report on the included `engine/examples/solid-route` fixture at the same revision, `653037aa`, returns five findings with `--limit 5` across 10 code files. The first row points to `src/data/records.ts::isRecordItem` (complexity 8, 24 LOC). Inspect its branches and nearby tests; change it only if a test-backed, behavior-preserving simplification is clear. The [fixture source](https://github.com/byronwall/srcly/blob/main/engine/examples/solid-route/src/data/records.ts) is a different corpus from the client screenshots. Reproduce the report with [Reports](../reports/). + +This case gives the CLI a matching role: create a bounded queue, name its evidence, and leave the final decision with the reviewer. The [agent-reporting plan](https://github.com/byronwall/srcly/blob/main/docs/intent/agent-reporting/implementation-plan.md) describes the emphasis on freshness, provenance, and coverage. + +## Start with a local view of the codebase + +Srcly runs as a local command and opens a browser app served from the local process. It reads the repository you choose, follows Git ignore rules, skips common generated and dependency directories, and caches analysis in the user's cache directory. + +The map provides orientation; the code viewer connects a selected node to its source. The CLI saves a report for terminal or agent review. Both workflows expose evidence and its coverage. + +## Keep the tree granular enough to inspect + +The analysis tree mirrors folders and files, then adds detected functions and nested scopes. Leftover lines inside parent scopes become body fragments, so nested scopes do not double-count area. Folder and file values roll up according to each metric's rule. The [code map](https://github.com/byronwall/srcly/blob/main/docs/CODE_MAP.md) points to the tree builder and aggregation code. + +Granularity creates a navigation trade-off. A repository-wide tile is useful for orientation; a function tile is useful for inspection. Linked views let you move between those scales. See [Explore](../explore/) and [Metrics](../metrics/). + +## Preserve unavailable evidence as unavailable + +An unavailable metric is not zero. A missing, failed, or timed-out checker did not report a clean result. A TypeScript-only metric does not apply to another language. Srcly keeps these cases separate and gives a reason where it has one. Comparisons separate coverage changes from measured deltas. + +This prevents missing analysis from looking like improvement. Rankings can use different evidence for different files, so check coverage before comparing them. Configure a missing checker or accept the gap. See [Metrics](../metrics/), [Findings](../findings/), and the [agent-reporting plan](https://github.com/byronwall/srcly/blob/main/docs/intent/agent-reporting/implementation-plan.md) for freshness and provenance decisions. + +## Use the right relationship for the question + +The TypeScript and TSX dependency graph shows imports. Data flow traces modeled values, function effects, or supported routes. An import edge does not prove value movement; a data-flow edge is not a general runtime trace. The [integration brief](https://github.com/byronwall/srcly/blob/main/docs/intent/tsx-dataflow-integration/intent-brief.md) and [logic visibility brief](https://github.com/byronwall/srcly/blob/main/docs/intent/dataflow-logic-visibility/intent-brief.md) explain the boundary. + +Symbols mode shows which functions, classes, fields, or types reference a symbol. Edges carry a resolution label: exact, typed, or name-based. This gives more detail than imports without claiming value flow. See the [symbol graph brief](https://github.com/byronwall/srcly/blob/main/docs/intent/symbol-graph/intent-brief.md). + +Data flow is optional. It runs through a bundled engine that requires Node.js 18 or newer. The engine's results carry outcomes and provenance, including partial, assumed, stale, and unavailable states. The rest of the scan does not depend on that engine. This keeps the base map usable when the optional analysis cannot run. Read [Data-flow analysis](../data-flow/) before relying on a trace. + +## Keep review signals separate from decisions + +Metrics describe code structure; findings report checker output; Git activity describes history when available. A profile or Hot Spots ranking helps choose where to look, but it does not prove quality, safety, or maintainability. Review the source and confirm what matters for the project. + +The same rule shapes the agent workflow. Reports include structured artifacts, metric definitions, checker coverage, and an analysis provenance line. Scoped `explain` output keeps the next question bounded. The artifacts are evidence for review, not instructions to refactor blindly. + +## What these choices cost + +Local analysis means the user runs the command and keeps the server process open while using the app. Language-specific measurements have different coverage. Data-flow analysis needs Node and may stop at unsupported constructs. The visual map is a navigation aid, not a substitute for tests, type checks, or runtime behavior. Reports can be reused from cache, so the `Analysis:` line matters when deciding whether to refresh. + +Start with [Get started](../get-started/), then use [Reports](../reports/) to check provenance or [Configuration](../configuration/) to address supported setup gaps. diff --git a/site/src/docs/pages/explore.md b/site/src/docs/pages/explore.md index 200aba7e..f318ccf5 100644 --- a/site/src/docs/pages/explore.md +++ b/site/src/docs/pages/explore.md @@ -1,37 +1,60 @@ # Explore a codebase -Srcly offers linked views of one scan: a treemap, a file explorer, Hot Spots, a 2×2 view, a code viewer, and dependency or data-flow graphs where supported. Each view helps you move from a broad signal to the source behind it. +Use Srcly's linked views to move from a broad signal to the source behind it. This guide helps you choose a view, inspect its evidence, and decide whether the result needs follow-up. -## Treemap +<figure><a href="/srcly/screenshots/treemap.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/treemap.jpg" alt="Srcly's treemap view of a scanned repository" width="1440" height="960" loading="lazy" /></a><figcaption>Treemap view of a repository in Srcly. Area represents LOC; color follows the selected metric.</figcaption></figure> -The treemap shows folders, files, functions, and code fragments as nested rectangles. Area represents lines of code (LOC). Choose a metric to color the rectangles and change the legend. A folder or file can be opened to focus the map on that part of the repository. +## Choose the view for your question -Use the path and file-type controls to focus the view. You can also hide selected paths from the current view. These view controls change what you see; they do not rewrite the source files. +| Question | View | What to inspect next | +| --- | --- | --- | +| Where is code concentrated? | Treemap | Open the largest folder or file, then inspect its children. | +| Which files or functions rank highest for one signal? | Hot Spots | Check the metric, cohort, value, and witness. | +| Which items have two signals at once? | 2×2 | Read the axis names and cut-offs; select points to inspect members. | +| What imports this TypeScript or TSX module? | Dependency graph | Follow direct import relationships and their source locations. | +| How does a modeled value move through supported code? | Data flow | Read the outcome, assumptions, and stop points. | -## Explorer and Hot Spots +These views are not interchangeable. The dependency graph describes imports; it does not establish runtime calls or value movement. Data flow traces selected modeled relations and has different language coverage. See [Data-flow analysis](../data-flow/) before interpreting a trace. -The explorer lists the scanned tree with sortable columns. Which columns apply depends on the selected node and metric. Select a row to focus the corresponding node and open its code where available. +### Symbols mode -Hot Spots ranks files or functions against peers of the same type for one metric. Use it to find a high value to inspect, then open the row and check its witness, source lines, and measurement availability. A ranking is a prompt for review, not a diagnosis. +Switch the graph from Imports to **Symbols** to inspect references around one symbol. The focus appears in the middle; referrers appear on the left and referenced symbols on the right, grouped by their source files and classes. Press `/` to search symbols. Select a box to read its reference lines in the inspector. Shift-click a box or press `E` to open its own hop in place. Use the kind chips and Tests control to narrow the graph. The edge's resolution label matters: exact, typed, and name-based matches are different levels of evidence. Follow an edge into source before relying on it. -## The 2×2 view +<figure><a href="/srcly/screenshots/symbols.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/symbols.jpg" alt="Symbols graph for NotePage in the included symbol-graph example" width="1440" height="960" loading="lazy" /></a><figcaption>Symbols mode centers <code>NotePage</code> and shows its references to <code>fetchNote</code> and <code>NoteView</code>. The inspector provides source locations and reference counts.</figcaption></figure> -The 2×2 view places files, functions, or supported components on two metric axes. Srcly includes presets such as activity, blast radius, component weight, comment noise, and findings. The view groups points into quadrants; you can adjust the cut-offs and select a group to inspect its members. +## Read the treemap -Some presets or cohorts do not apply to every project. Srcly omits unavailable points or explains why a view has no usable data. A point's position reflects the selected metrics and cut-offs, not an overall quality grade. +Each rectangle represents a folder, file, function, or code fragment. Area represents lines of code (LOC). Choose a metric to color tiles and read its legend. Open a folder or file to focus the map. Use the path and file-type controls to narrow the visible scope. Hiding a path changes the view; it does not alter source files or the scan. + +A large tile is not automatically a problem. It may reflect a legitimate module or generated content that should be excluded. Use the tile to choose where to inspect, then confirm its classification and contents in the explorer or code viewer. + +## Rank candidates with Hot Spots + +Hot Spots ranks files or functions for one selected metric and cohort. Select a metric, then choose whether to rank files or functions where the control is available. The list orders measured values worst first and presents a witness when the value is an aggregate. N/A results are grouped separately because they cannot be ranked as measured values. + +Open a row to focus the corresponding source. Check the metric definition and cohort before comparing two entries. A file rank compares files; a function rank compares functions. A high value means “inspect this,” not “change this.” The [Metrics guide](../metrics/) explains aggregation and availability. + +## Compare two signals in the 2×2 view + +The 2×2 view places files, functions, or supported components on two metric axes. Presets include activity, blast radius, component weight, comment noise, and findings. Choose the preset and cohort, then read the axis labels. Drag the cut-offs to explore how different thresholds change quadrant membership. Select a group or point to inspect its members. + +<figure><a href="/srcly/screenshots/quadrant.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/quadrant.jpg" alt="Activity 2×2 for Srcly's client source, with the Hot mess quadrant selected" width="1440" height="960" loading="lazy" /></a><figcaption>Activity 2×2 of Srcly's client source: maximum complexity against commits. The selected Hot mess group lists files beyond both cut-offs.</figcaption></figure> + +The cut-offs help you ask a question; they are not universal risk boundaries. A preset can omit unavailable points or show that it has no usable data. Read the selected metrics, cohort, and cut-offs before comparing groups. A point's position is not an overall quality grade. ## Inspect source and relationships -Select a file or function to open the code viewer. Metrics and findings can link to lines that contributed to a result. Use the dependency graph to inspect TypeScript and TSX import relationships. It can include external packages and nearby TypeScript path aliases. +Select a file or function from a tile or row to open the code viewer. Review the source, metric values, checker findings, and line evidence together. For a folder maximum, follow its witness function. For a checker finding, note the rule and tool that produced it. Some file classes, such as tests, docs, fixtures, generated, or vendored files, may be counted but left out of a default findings rank; see [Findings](../findings/). -The separate Data flow view traces modeled routes, values, and function effects. Its supported language and analysis limits differ from the dependency graph. See [Data-flow analysis](../data-flow/). +Use the dependency graph to understand direct TypeScript and TSX imports, including nearby path aliases and external packages when available. Use Data flow for modeled routes, values, or function effects. A missing edge is not proof that no relationship exists. The dependency graph may not cover other languages; data flow can stop at unsupported constructs. See [Configuration](../configuration/) for setup limits. -## A useful review sequence +## A practical review sequence -1. Choose a metric that matches the question you have. -2. Find a folder or file with a high or unexpected value. -3. Open its code and check the metric's definition and witness. -4. Check whether related findings or dependencies add context. -5. Confirm any suspected issue in the source and with your project tools. +1. State the question before choosing a metric. +2. Choose the matching view and check its legend, cohort, or axes. +3. Select a high or unexpected item and open its source. +4. Read the metric definition, witness, checker identity, and coverage status. +5. Confirm a suspected issue with source, tests, or the project's checker. +6. Record the decision and any evidence gap. -This sequence avoids treating file size, complexity, or a static-analysis message as proof of a bug. See [Understand metrics](../metrics/) and [Read findings](../findings/) for how Srcly reports these signals. +This sequence avoids treating size, complexity, or a static-analysis message as proof of a bug. If you need a saved investigation, use `uvx srcly report . --out .srcly`, then narrow it with `uvx srcly explain . --at path/to/file`. The [Reports guide](../reports/) maps artifacts to questions. diff --git a/site/src/docs/pages/findings.md b/site/src/docs/pages/findings.md index b6d77c4f..0b76f9ea 100644 --- a/site/src/docs/pages/findings.md +++ b/site/src/docs/pages/findings.md @@ -1,36 +1,55 @@ # Findings and check coverage -Findings bring selected checker results into Srcly's explorer, code viewer, and reports. Use them to locate code that may need attention, then inspect the source and confirm the issue. A finding is a triage signal, not a confirmed bug. +Findings bring selected checker results into Srcly's explorer, code viewer, and reports. Use them to find code worth reviewing, then confirm the issue with its source and tool. A finding is a triage signal, not a confirmed bug. -## Checks Srcly can run +## Check coverage before reading the queue -Srcly selects checks based on the code and tools it finds: +Srcly selects checks based on the files and tools it finds. Checks run independently and have time limits. Missing tools, failures, and timeouts leave measurements unavailable with a reason. They do not count as zero findings. Read the coverage summary in the report or the checker status in the app before treating the queue as complete. -- For TypeScript projects, it runs the project's TypeScript compiler when `tsc` and a TypeScript configuration are available. -- It runs ESLint when the project has ESLint and its configuration. -- It runs Ruff for Python. Srcly uses the project's Ruff configuration when present; otherwise it uses a small built-in set of bug-finding rules, identified as Srcly defaults. -- For TypeScript files outside project checker coverage, Srcly has rules for selected patterns, including explicit `any`, suppression directives without a reason, and chains of non-null assertions. -- Srcly also checks selected TypeScript patterns, including Solid-specific rules, await-in-loop patterns, and import-graph reachability. -- Optional ast-grep YAML rules under `.srcly/rules/` can add project-specific checks when ast-grep is installed. +| Check | When Srcly runs it | What an unavailable result means | +| --- | --- | --- | +| TypeScript compiler (`tsc --noEmit`) | TypeScript project configuration and compiler are available | The project configuration or compiler was not available, or the run failed or timed out. | +| ESLint | The project has ESLint and its configuration | ESLint was not detected, or its run failed or timed out. | +| Ruff | Python files are present; Srcly ships Ruff | The run failed or timed out. Srcly uses project Ruff settings when present, otherwise labeled Srcly defaults. | +| Srcly TypeScript rules | TS files are outside project checker coverage | A selected built-in pattern matched, or that rule set did not cover the file. | +| Reachability and Solid rules | Supported TypeScript graph and patterns are available | Entry-point detection or language coverage may not match the project. Configure entries when needed. | +| ast-grep rules | `.srcly/rules/` files exist and ast-grep is available | The optional binary or rule run is unavailable. | -Checks run independently and have time limits. If a required tool is missing, fails, or times out, Srcly reports that status and reason. It does not turn a missing check into a clean result or a count of zero. Check the tool coverage line in the report before using findings as a complete review. +The exact checks vary by project. Srcly runs `tsc` per detected TypeScript project, expands solution configurations, runs ESLint when configured, and runs Ruff for Python. Its built-in TS checks include selected patterns such as explicit `any`, suppression directives without a reason, and non-null assertion chains when project tools do not cover those files. It also reports selected reachability, Solid, and await-in-loop signals. Optional ast-grep YAML rules can add project-specific checks. See [Configuration](../configuration/) for setup. -## Understand the findings queue +## Read a finding -The report queue ranks code files using a selected profile. Profiles include `general`, `frontend`, `backend`, `typescript`, `python`, and `docs`. They weight available risk-related metrics to help choose a review order. You can also rank files and functions by one metric with `hotspots`. +When you open a finding, check these fields: -Some paths are classified as tests, documentation, styles, fixtures, generated files, vendored code, configuration, or data. The report explains which classes it left out and why. Use `--include-class` when you want one of those classes ranked too. +| Field | Review question | +| --- | --- | +| Tool and rule | Which checker produced this result, and what pattern does the rule detect? | +| Location | Where should you inspect the source? | +| Message and evidence | What specific code caused the result? | +| Coverage | Which files did this checker analyze, and which did it leave unavailable? | +| Profile or rank | Why did this file appear in the queue, and which metric drove its position? | -When you open a finding, review its location, checker, rule, message, and evidence. Different checkers can have different assumptions and coverage. A finding score does not replace the checker's own output or your review. +The report's findings queue uses a profile such as `general`, `frontend`, `backend`, `typescript`, `python`, or `docs`. A profile weights available risk-related metrics to suggest a review order. It does not replace the checker's diagnostic. Hot Spots ranks one selected metric. A queue score and a checker message are different kinds of evidence. -## Improve coverage +## Files outside the default queue -Install and configure the checkers your project uses, then rerun with `--refresh` to bypass cached results: +The report classifies files as code, tests, docs, styles, fixtures, generated, vendored, config, or data based on their paths. It explains which classes were left out and why. This keeps a README, fixture, or generated file from becoming a refactor target by accident, while preserving the count and reason. Use `--include-class` when you intentionally want to rank one class. + +Example: in the included `solid-route` project at revision `653037aa`, the `frontend` profile reported five ranked findings. Its first row pointed to `src/data/records.ts::isRecordItem` with complexity 8 and 24 LOC. That is an example of a review starting point, not a claim that the function contains a defect. Inspect the named source and tests before deciding what to do. + +## Improve coverage when the answer matters + +If a result is unavailable, use the stated reason to decide whether to install or configure the relevant checker. For TypeScript reachability, Srcly detects common entries from routes, package metadata, scripts, and configuration. If the app has an entry pattern Srcly does not detect, add it to `srcly.toml`: + +```toml +[reachability] +entries = ["app/scripts/**/*.ts"] +``` + +Then rescan so the result reflects the new setup: ```bash uvx srcly report . --refresh --out .srcly ``` -For reachability findings, Srcly detects common entries from routes, package metadata, scripts, and configuration. If your TypeScript entry points are not detected, add them under `[reachability] entries` in `srcly.toml`; see [Configuration](../configuration/). - -See [Metrics](../metrics/) for N/A values and [Reports](../reports/) for checker coverage artifacts. +For a particular report run, check `Analysis:`. It names the scan state, Git HEAD, uncommitted files, checkers and their coverage, code files no checker covers, and files that failed analysis. If you need source-level review, use [Reports](../reports/) to find the relevant artifact, then [Metrics](../metrics/) for N/A and aggregation rules. diff --git a/site/src/docs/pages/get-started.md b/site/src/docs/pages/get-started.md index 774e9149..ea0ab5f1 100644 --- a/site/src/docs/pages/get-started.md +++ b/site/src/docs/pages/get-started.md @@ -1,54 +1,67 @@ # Get started -Srcly turns a local codebase into an interactive map. Use the treemap and file explorer to find areas to inspect, then open code and metrics in context. You can also generate Markdown and JSON reports for scripts and coding agents. +Run Srcly on a repository, choose one review question, and follow its evidence into the source. This guide takes you from installation to a first browser review and a saved terminal report. -## Install and launch +## 1. Launch Srcly -Install [uv](https://docs.astral.sh/uv/) if it is not already available. Then run Srcly with `uvx`; this downloads and runs the tool without a global Srcly install. +Install [uv](https://docs.astral.sh/uv/) if you do not have it. Then run Srcly without a global install: ```bash uvx srcly ``` -Srcly starts a local web server and opens the app in your browser. By default, the server binds to `127.0.0.1` and selects an available port. Keep the terminal open while you use the app. Press `Ctrl+C` there to stop the server. - -The command uses the enclosing Git repository as its initial root. If the current directory is not in a Git repository, it uses that directory. You can pass a path to choose another root: +The command uses the enclosing Git repository as its initial root. Outside a repository, it uses the current directory. Pass a path to select another root: ```bash -uvx srcly . -uvx srcly ../another-project uvx srcly /path/to/repository ``` -The packaged Srcly release requires Python 3.13 or newer. The Python files you analyze do not need to use that Python version. +The packaged release requires Python 3.13 or newer. The code you analyze can use another Python version. Srcly starts a local web server and opens the app in your browser. The default bind address is `127.0.0.1`, and Srcly selects an available port. Keep the terminal open while you use the app. Press `Ctrl+C` in that terminal to stop it. + +<figure><a href="/srcly/screenshots/treemap.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/treemap.jpg" alt="The Srcly app showing a repository treemap" width="1440" height="960" loading="lazy" /></a><figcaption>Repository treemap in the Srcly app. Use the path bar to choose a root, then select Analyze to scan it.</figcaption></figure> + +## 2. Scan a repository + +When the app opens, review the suggested path or enter another directory in the path bar. Select **Analyze**. Srcly shows scan progress while it reads files. In a Git repository, file discovery includes tracked files and nonignored untracked files. Git-ignored and common generated or dependency paths are excluded. If you want a narrower scan, enter a subdirectory as the root. + +The first scan can take longer than a later visit because the local cache can reuse unchanged analysis. The cache is stored in your user cache directory, not in the analyzed repository. A file change invalidates the cached analysis for that root. In a terminal workflow, use `--refresh` on commands that support it when you need to rerun analysis and checks; see [Reports](../reports/). -## Run your first scan +## 3. Complete a first review -When the app opens, enter or paste a path in the path bar, or keep the suggested path. Click **Analyze**. Srcly reads source files under that path and shows scan progress. The first scan can take longer than later visits; unchanged results are cached on your computer. +Start with a question. For example: “Which function has the highest complexity in this folder?” -Start in the treemap. Each rectangle represents a folder, file, function, or code fragment. Area represents lines of code. Choose a color metric from the view controls, then select a folder or file to inspect it. The explorer and Hot Spots list provide sortable and ranked views of the same analysis. +1. Start in the treemap. Area represents lines of code; color represents the selected metric. +2. Choose Complexity in the metric controls. A darker or stronger color indicates more of the selected metric under its legend. +3. Open Hot Spots or sort the explorer by complexity to find a high-ranked function or file. +4. Select the row or tile. Read the value, metric witness, and source lines in the code viewer. +5. Check whether the measurement applies and whether a checker finding or dependency adds useful context. +6. Confirm a suspected problem against the source and your project's own tools. -Use the code viewer to inspect the source behind a metric or finding. Srcly's measurements help you choose where to look; they do not prove that code is wrong or unsafe. See [Explore the views](../explore/) and [Understand metrics](../metrics/) for details. +<figure><a href="/srcly/screenshots/code-inspector.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/code-inspector.jpg" alt="Srcly's source inspector with metrics and findings" width="1440" height="960" loading="lazy" /></a><figcaption>Source inspection in Srcly. A metric directs attention; use its definition and witness to understand the value.</figcaption></figure> -## Generate a report +The measurement helps you choose where to look. It does not say that code is defective or must be changed. A folder complexity value is the maximum among its functions, not the sum. A checker result depends on that tool's rules and coverage. Read [Explore](../explore/) and [Metrics](../metrics/) for more. -For a terminal workflow, create a report without opening the browser: +## 4. Save a report + +For a terminal workflow, create a report: ```bash uvx srcly report . --out .srcly ``` -This writes a Markdown summary and JSON artifacts under `.srcly/`. Review `report.md` first. The report includes measurement coverage and names unavailable results where applicable. See [Reports for agents and CI](../reports/) for output details. +This writes `report.md` and structured JSON files under `.srcly/`. Read `report.md` first. It includes a scan summary, ranked findings, metric hotspots, and coverage information. The `Analysis:` line records whether the scan was reused or fresh, the Git revision and uncommitted state, checker coverage, and analysis failures. Use that information to decide whether the result is current enough for your review. + +To inspect a narrower scope, run: -## What Srcly analyzes +```bash +uvx srcly explain . --at src +uvx srcly explain . --at "src/app.tsx::App" +``` -Srcly uses Lizard for broad source metrics and adds tree-sitter analysis for TypeScript and TSX, CSS and SCSS, Markdown, notebooks, and Python. The metrics differ by language and file type. A metric that does not apply or could not be measured is shown as N/A, not zero. +The first command explains a folder; the second explains a symbol. Use a path relative to the analyzed root. The printed `Start at` location can be copied into `--at` when you need to investigate a particular row. See [Reports](../reports/) for output details and [CLI](../cli/) for the full command list. -The optional data-flow views require Node.js 18 or newer. Without Node.js, the treemap, metrics, and other scan features remain available. Read [Data-flow analysis](../data-flow/) for its language scope and limits. +## 5. Decide what to do next -## Next steps +If a result is unavailable, read its reason. You may need a project checker, a TypeScript reachability entry, Git history, or Node.js for optional data flow. If a result is measured, inspect the code and decide whether it merits a change, a test, or no action. Srcly is a review aid, not an automatic quality verdict. -- [Explore the views](../explore/) -- [Read findings and coverage](../findings/) -- [Use the headless CLI](../cli/) -- [Configure entries and rules](../configuration/) +Metrics that do not apply or could not be measured appear as N/A, never as zero. Data-flow analysis requires Node.js 18 or newer and supports TypeScript, JavaScript, and Python roots. Without Node, the base scan remains available. See [Findings](../findings/) for checker coverage and [Data flow](../data-flow/) for trace outcomes. diff --git a/site/src/docs/pages/metrics.md b/site/src/docs/pages/metrics.md index 3100fae1..839d86ac 100644 --- a/site/src/docs/pages/metrics.md +++ b/site/src/docs/pages/metrics.md @@ -1,30 +1,49 @@ # Understand metrics -Srcly measures source structure and selected language signals. Metrics appear in the treemap, explorer, Hot Spots, reports, and code viewer. Each metric has a defined scope and aggregation rule; interpret it with its label and availability. +Use metrics to decide where to inspect, then check the code that produced the value. This guide explains common measurements, how folder values work, and what to do when a metric is unavailable. -## Common measurements +## Read a metric in context -- **LOC** counts nonblank, noncomment lines of code. Folder and file totals aggregate child values. -- **Complexity** is cyclomatic complexity (CCN). A function has its own value. A file or folder shows the maximum among its functions and names the function that sets it. The average complexity is a separate metric. -- **Cognitive complexity** estimates branching and nesting using Sonar's rules. It is available for TypeScript, JavaScript, and Python. -- **Nesting depth, function length, and parameter count** describe code shape. Their aggregation can differ; the metric catalog and UI identify the measure. -- **Component metrics** describe detected React or Solid components, including component LOC, hooks, effects, JSX depth, props, inline handlers, and conditionals. -- **TypeScript signals** include explicit `any` and TypeScript suppression directives. -- **Comment noise** flags selected patterns such as long comment blocks or commented-out code. It is a heuristic, not a style verdict. -- **Git activity** includes commit count and churn over a selected history window. It depends on available Git history. +A metric has a scope and an aggregation rule. A function may have an exact measurement. A file or folder may sum values from children, take the maximum, or report an average. The UI and generated `metrics.schema.json` identify definitions and interpretation hints. Check those details before you compare two values. -Other measurements include file size, imports, exports, TODOs, Markdown data URLs, and language-specific metrics. Detail metrics provide context; they are not all risk scores. +Common measurements include: -## Why a metric can be N/A +| Metric | What it describes | How to use it | +| --- | --- | --- | +| LOC | Nonblank, noncomment lines of code | Find where code is concentrated; size alone is not a risk verdict. | +| Complexity (CCN) | Branching paths in a function | Inspect the function that sets a file or folder maximum. | +| Cognitive complexity | Branching and nesting effort under Sonar's rules | Compare functions with different nesting shapes. Available for TS, JS, and Python. | +| Function length, nesting, parameters | Code shape | Use as context for a review question, not as quality scores. | +| Component metrics | Detected React or Solid component structure | Inspect component LOC, hooks, effects, JSX depth, props, inline handlers, and conditionals. | +| Comment noise | Selected comment patterns | Check the flagged lines; this heuristic is not a style verdict. | +| Git activity | Commit count and churn in a selected history window | Add history to code structure when repository history is available. | -N/A means a metric does not apply to that node, its analyzer did not measure it, or required data was unavailable. For example, component metrics do not apply to a file with no detected component. Some checks depend on project configuration or tools. Git activity can be unavailable when Git history is missing. +Other metrics include file size, imports, exports, TODOs, type signals, and language-specific measures. Detail metrics can provide context without being ranked as risk. See [Findings](../findings/) for checker results, which are separate evidence. -Srcly preserves N/A as a distinct state. It is never zero. In comparisons, a metric available on only one side is a coverage change and has no delta. This prevents a missing measurement from appearing to be an improvement. +## Example: a maximum with a witness -## Read aggregated values carefully +Suppose three functions in a folder have CCN values 2, 4, and 8. The folder's complexity is 8 because the rule is maximum, not sum. Srcly names the function with CCN 8 as the witness. The value means “this is the most complex measured function in the folder”; it does not mean the folder has total complexity 8 or that the function is defective. -Folder values summarize children according to the metric's rule. Some sum; some use the maximum; others use an average. For complexity, a folder's maximum points to a witness function. Do not read that maximum as the total complexity of all code in the folder. +This example is illustrative. Use the displayed witness and metric definition for your actual scan. The witness gives you a source location to inspect. If the file or folder has no measured function for a metric, the result may be N/A instead of a numeric value. -Metrics help compare similar code and direct attention. They do not measure correctness, security, or maintainability as a single objective score. Validate a signal against the source, tests, and the project's own standards. +## Distinguish zero from N/A -For exact metric definitions and ranking options, see the UI metric details and `metrics.schema.json` generated by [a report](../reports/). For context on checks that add findings, see [Findings and coverage](../findings/). +A measured zero is evidence that the metric applies and its measured value is zero. N/A means the metric does not apply, its analyzer did not measure it, or required data was unavailable. For example, component metrics do not apply to a file with no detected component. Git activity can be unavailable without suitable Git history. A checker metric can be unavailable when a required tool is missing or fails. + +Srcly preserves this difference in the UI, reports, and comparisons. If a value is N/A, look for its reason. Do not turn it into zero when ranking or comparing. If the metric is important to your review, use [Configuration](../configuration/) to address supported setup gaps or accept that the scan cannot answer that question. + +## Interpret comparisons carefully + +Folder values aggregate children by the metric's rule. Complexity is a maximum and names its witness; LOC is a sum; other metrics may use maximum, average, or count. A single file's metric can change because its code changed, because measurement coverage changed, or because the measured population differs. `compare` keeps a metric unavailable on one side as `null` and reports measurement coverage changes separately from numeric deltas. + +This prevents missing coverage from appearing as improvement. It also means two rows with similar values may have different evidence behind them. Read metric definitions, coverage, and witness before you draw a conclusion. + +## Turn a signal into a review + +1. State the question you want to answer. +2. Choose a metric whose definition matches that question. +3. Check the node type and aggregation rule. +4. Open the source or witness that contributed the value. +5. Confirm suspected problems with the source, tests, or the project's tools. + +Metrics help you compare and focus attention. They do not measure correctness, security, or maintainability as one objective score. For per-metric rankings, use [Explore](../explore/); for the report schema and generated evidence, see [Reports](../reports/). diff --git a/site/src/docs/pages/overview.md b/site/src/docs/pages/overview.md new file mode 100644 index 00000000..55d7a17c --- /dev/null +++ b/site/src/docs/pages/overview.md @@ -0,0 +1,55 @@ +# Understand a codebase with Srcly + +Srcly helps you move from a broad view of a repository to the exact code behind a signal. It runs on your machine, maps folders, files, functions, and nested scopes, then links metrics and selected checker results to source. You can explore in the browser or create scoped reports for a terminal, an agent, or CI. + +- **Discover Srcly:** [Product tour](../tour/) and [Design decisions](../design/). +- **Use Srcly:** [Get started](../get-started/) and [Reports](../reports/). + +<figure><a href="/srcly/screenshots/treemap.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/treemap.jpg" alt="Srcly showing a codebase in its treemap view" width="1440" height="960" loading="lazy" /></a><figcaption>Srcly maps a repository into folders, files, and code scopes. The screenshot shows the treemap view; inspect a tile to see its source and evidence.</figcaption></figure> + +## Choose your path + +### If you want to try Srcly + +Start with [Get started](../get-started/). Launch the app, analyze a repository, and complete one short review: choose a metric, inspect a high or unexpected value, and check the source behind it. Then follow [Explore the views](../explore/) to compare the treemap, explorer, Hot Spots, 2×2, and graph views. + +### If you want to understand the product + +Read the [Product tour](../tour/) for the main workflow and the [Design decisions](../design/) for the choices that shape it. Srcly combines a visual map for human navigation with CLI reports for repeatable review. It treats unavailable evidence as unavailable, and keeps import relationships distinct from modeled value flow. + +### If you are reviewing code + +Use [Metrics](../metrics/) to learn what a value measures and how a folder value is aggregated. Use [Findings](../findings/) to check which tools ran and what they reported. Use [Data-flow analysis](../data-flow/) when you need to trace a modeled value through supported code. Rankings and traces help direct review; they do not establish that code is defective or safe. + +### If you are automating a review + +Start with [Reports for agents and CI](../reports/), then use the [Command-line reference](../cli/) for flags. A report includes Markdown and machine-readable artifacts. `explain` lets you investigate a repository, folder, file, or symbol without loading the full tree into your prompt. Read the analysis and coverage information before acting on results. + +## What Srcly does + +Run `uvx srcly` from a repository to open the local app. The treemap gives a spatial overview: area represents lines of code, while color represents the selected metric. The explorer, Hot Spots, and 2×2 views offer other ways to sort or compare the same scan. Select a file or scope to open source and supporting evidence. + +The scan uses Lizard for broad source coverage and language-aware analyzers for richer signals where supported. Metrics vary by language and node. A metric can be zero, or it can be unavailable because it does not apply or could not be measured. Srcly keeps these states separate and reports reasons where available. + +For a repeatable terminal workflow, run: + +```bash +uvx srcly report . --out .srcly +uvx srcly explain . --at src +``` + +The report gives you an overview and artifacts. `explain` narrows the next question to a folder, file, or symbol. Both commands share the analysis cache. See [Reports](../reports/) for artifact meanings and [CLI](../cli/) for supported scopes and options. + +## What Srcly does not claim + +A large file is not automatically a problem. Complexity is not a quality score. A checker finding is not a confirmed defect. An empty or partial data-flow result does not prove that a value cannot reach a destination. Use each signal to decide where to inspect, then verify the claim against source and the tools your project trusts. + +Data-flow analysis is optional and requires Node.js 18 or newer. Without it, the rest of Srcly remains usable and the unavailable result has a reason. Import graphs and data-flow graphs answer different questions; see [Design decisions](../design/) for why they stay distinct. + +## Continue + +- [Get started](../get-started/) — launch Srcly and complete your first review. +- [Product tour](../tour/) — follow one workflow from map to source evidence. +- [Explore](../explore/) — choose a view for a review question. +- [Reports](../reports/) — produce artifacts for agents and CI. +- [Configuration](../configuration/) — set roots, entries, optional checks, and environment variables. diff --git a/site/src/docs/pages/reports.md b/site/src/docs/pages/reports.md index 6d87a0bf..d6dbae3b 100644 --- a/site/src/docs/pages/reports.md +++ b/site/src/docs/pages/reports.md @@ -1,60 +1,81 @@ # Reports for agents and CI -Use `report` to scan a repository and write a compact Markdown summary plus JSON artifacts. The output gives a developer or coding agent a starting point for review. It does not make changes to the analyzed source tree beyond the output directory you choose. +Use `report` to scan a repository and write a Markdown summary plus JSON artifacts. The output gives a developer or coding agent a starting point for review. It does not change the analyzed source tree, except for files you choose in the report output directory. -## Create a report +## Create a report for a review + +From a checkout that has Srcly installed, this command reports on the included `solid-route` example: ```bash -uvx srcly report . --out .srcly +uvx srcly report engine/examples/solid-route --out tmp/solid-route-report --profile frontend --limit 5 ``` -The default output directory is `.srcly`. The report command scans the current repository when you omit the path. Choose a different path when needed: +With the published command, use `uvx srcly report /path/to/repository --out /path/to/report`. Review `report.md` first. It names the selected profile and ranking metric, gives scan and checker coverage, lists ranked findings, and shows a compact folder breakdown. Then use the printed `Start at` location or a folder path with `explain`: ```bash -uvx srcly report /path/to/repository --out /tmp/srcly-report +uvx srcly explain /path/to/repository --at src/data +uvx srcly explain /path/to/repository --at "src/data/records.ts::isRecordItem" ``` -The main files include: +In the included example at revision `653037aa`, the frontend report ranked `src/data/records.ts` with a high complexity signal. It named `isRecordItem` at line 18 as the witness (complexity 8, 24 LOC). The folder explanation for `src/` covers 10 code files. These facts show how to follow a report; they do not establish a defect in that function. Re-run against your checkout to get current evidence. + +## Match each artifact to a question + +The default report writes these artifacts: -- `report.md`: summary, scan and checker coverage, ranked file and function tables, and a compact tree breakdown. -- `findings.json`: machine-readable ranked findings with evidence and suggested prompts. -- `findings.top.json`: a compact top set for an agent to read first. -- `tree.summary.json`: a compressed repository tree. -- `hotspots.json`: file and function rankings for the selected metric. -- `metrics.schema.json`: metric definitions and interpretation hints. -- `agent-skill.md`: guidance for an agent that reads the generated artifacts. -- `size_budget.json`: baseline for the size ratchet used by `check`. +| Artifact | Use it to answer | +| --- | --- | +| `report.md` | What did the scan find, what ranked highest, and what should I inspect first? | +| `manifest.json` | Which revision, scan state, checkers, and coverage details produced this report? | +| `findings.top.json` | What evidence should an agent load first from the findings queue? | +| `action-plan.md` | What review tasks did Srcly derive from the ranked evidence? Inspect the cited source before acting. | +| `tree.summary.json` | Which folders and files make up the compact repository summary? | +| `findings.json` | What are the machine-readable ranked findings up to `--limit`, with their evidence? | +| `hotspots.json` | Which files or functions rank highest for the selected single metric? | +| `metrics.schema.json` | What do metrics mean, and how should an agent interpret them? | +| `agent-skill.md` | What guidance should an agent follow when it consumes the report? | +| `size_budget.json` | Which code files exceed the token-size threshold, and what baseline does the ratchet use? | -Artifact formats can be set with `--format markdown`, `--format json`, or `--format both`. The default is `both`. To include the complete analysis tree, add `--include-tree`. To include the TypeScript and TSX dependency graph, add `--include-dependencies`. +The manifest identifies artifact paths and scan provenance. `report.md` is a practical first read; the JSON files support targeted tools and agent workflows. Use `--include-tree` to include the full raw tree or `--include-dependencies` to include the TypeScript and TSX import graph. -## Choose the ranking +If you add `--quadrant <preset>`, Srcly also writes `quadrants.json` with the full member lists for the selected 2×2. The report's Markdown section gives a compact readable summary. -The findings queue uses a profile. Set one of `general`, `frontend`, `backend`, `typescript`, `python`, or `docs`: +## Choose a profile and ranking metric + +The findings queue uses one profile: `general`, `frontend`, `backend`, `typescript`, `python`, or `docs`. Profiles weight available risk-related metrics to suggest a review order. The top files and functions tables rank by one metric. If you omit `--metric`, Srcly chooses the profile's lead metric. Specify one when you need consistent rankings across runs: ```bash -uvx srcly report . --profile frontend --out .srcly +uvx srcly report . --profile frontend --metric complexity --limit 20 --out .srcly ``` -The top file and function tables use one metric. If you omit `--metric`, Srcly chooses the profile's lead metric. Select one explicitly when you want to focus on it: +The findings profile score and a Hot Spots metric rank answer different questions. Do not compare their scores as if they were the same scale. N/A remains unavailable and is not a zero. A file measured on one side of a comparison only is a coverage change without a metric delta. + +Add a named 2×2 preset when you want to inspect two metric axes: ```bash -uvx srcly report . --metric complexity --limit 30 --out .srcly +uvx srcly report . --quadrant blast_radius --quadrant-cohort file --out .srcly ``` -Add a named 2×2 preset to the report with `--quadrant activity`, `blast_radius`, `component_weight`, `comment_noise`, or `findings`. The `quadrants.json` artifact contains the member lists. Use `--quadrant-cohort file`, `function`, or `component` to choose the point type where the preset supports it. +Presets include `activity`, `blast_radius`, `component_weight`, `comment_noise`, and `findings`. Some presets or cohorts do not apply to every project. -## Use JSON on stdout +## Check freshness and coverage -For a one-shot agent call, emit the bundled report as JSON on standard output: +Srcly reuses cached analysis when the files and checker signatures are unchanged. Use `--refresh` to rescan and rerun checks; use `--verbose` for per-file progress on stderr: ```bash -uvx srcly report . --stdout +uvx srcly report . --refresh --out .srcly --verbose ``` -Machine-readable output is kept on stdout. Version information and progress go to stderr. The static metric schema and agent guide are written with `--out`, not included as generated files when using stdout alone. +Read the `Analysis:` line and manifest before taking action. They report whether the scan was reused or fresh, the Git HEAD, uncommitted files, checker status and file counts, code files no checker covers, and analysis failures. If a checker is missing or fails, its coverage is unavailable with a reason. Do not read that as a clean run. -## Refresh and interpret results +## Use stdout for a one-shot agent call + +`report --stdout` emits a bundled JSON payload to standard output: + +```bash +uvx srcly report . --stdout +``` -Srcly reuses cached results when files and checker signatures are unchanged. Pass `--refresh` to rescan and rerun the checks. `--verbose` prints per-file progress to stderr. +Machine-readable output is kept on stdout; progress and cache warnings go to stderr. The static metric schema and agent guide are written only by `report --out`. Use `--format markdown`, `json`, or `both` when you want a chosen file format in an output directory. -Read the report's analysis and coverage information before acting on a finding. Missing or failed tools can leave coverage N/A with a reason. Metric N/A values remain different from zero. Rankings help prioritize code review; they are not proof of a defect. See [Findings](../findings/) and [Metrics](../metrics/) for interpretation guidance. +Reports help you choose what to inspect. Confirm each claim with its source, checker evidence, and project tests. See [Findings](../findings/) for coverage and [CLI](../cli/) for commands such as `explain`, `hotspots`, and `compare`. diff --git a/site/src/docs/pages/tour.md b/site/src/docs/pages/tour.md new file mode 100644 index 00000000..43c66809 --- /dev/null +++ b/site/src/docs/pages/tour.md @@ -0,0 +1,60 @@ +# Product tour + +Srcly is designed for one practical loop: orient yourself in a codebase, choose a useful signal, inspect the code behind it, and decide what to do next. The browser keeps those steps connected. The CLI makes a similar investigation repeatable for scripts and coding agents. + +<figure><a href="/srcly/screenshots/treemap.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/treemap.jpg" alt="Srcly's treemap with a repository selection" width="1440" height="960" loading="lazy" /></a><figcaption>Treemap view of a repository in Srcly. Area shows lines of code; tile color follows the selected metric.</figcaption></figure> + +## 1. Start with the shape of the repository + +Run Srcly from a repository: + +```bash +uvx srcly +``` + +The app opens in your browser and serves the local repository through a local web server. Keep the terminal open while you work. Use the path bar to choose a repository, then select **Analyze**. The first scan reads files and reports progress. Unchanged analysis can be reused from the local cache on a later visit. + +The treemap provides the broad view. Folders contain files, and files can contain functions and nested scopes. Tile area represents lines of code; color represents the selected metric. Start by asking a specific question, such as “Which files have the highest complexity?” or “Where does this component concentrate its logic?” + +## 2. Choose a signal that matches the question + +Choose a metric in the view controls. Complexity can help locate branching-heavy functions. LOC can show where code is concentrated. Component metrics can help inspect React or Solid component shape. Git activity can add historical context when repository history is available. + +Open Hot Spots when you want a ranked list, or use the 2×2 view to compare two supported metrics. A ranking is relative to its cohort and selected metric. A high value identifies a place to inspect; it does not diagnose a defect. For definitions and aggregation rules, see [Understand metrics](../metrics/). + +## 3. Inspect the source and its witness + +Select a file or function tile, or select its row in the explorer. Srcly opens the source with available metrics, findings, and line evidence. For an aggregated value, check which rule produced it. For maximum complexity, Srcly carries the function that sets the maximum as a witness. For a checker result, read the tool, rule, location, and message. + +<figure><a href="/srcly/screenshots/code-inspector.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/code-inspector.jpg" alt="Srcly's code inspector showing source and analysis evidence" width="1440" height="960" loading="lazy" /></a><figcaption>Code inspector for a selected source item. Use the source location and witness to check why the metric or finding appears.</figcaption></figure> + +Ask what the evidence supports. A complexity value describes branching structure. A checker finding reports what that checker detected under its configuration. Neither says whether a change is needed. Read the relevant code, then confirm a suspected issue with the project's tests or checker. + +## 4. Follow a relationship when the question needs it + +Use the dependency graph to inspect TypeScript and TSX import relationships. It answers which modules import or use other modules. It is not a call graph and does not show where a particular runtime value goes. + +The graph also has **Symbols** mode for symbol-level references. It centers one symbol, shows referrers on the left and referenced symbols on the right, and frames the focus by file and class. Press `/` to find a symbol. Select a box to inspect references and source lines. Shift-click a box or press `E` to open that symbol's hop in place. Kind filters and the Tests control help narrow the view. These are static references; check the displayed resolution and source locations before treating a link as exact. + +<figure><a href="/srcly/screenshots/symbols.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/symbols.jpg" alt="Symbols graph for NotePage in the included symbol-graph example" width="1440" height="960" loading="lazy" /></a><figcaption>Symbols mode centers <code>NotePage</code> and shows its references to <code>fetchNote</code> and <code>NoteView</code>. The inspector provides source locations and reference counts.</figcaption></figure> + +Use Data flow when you have a supported route or symbol and want to follow modeled values, function effects, or route handling. Select a file or function, open Data flow, and choose an anchor available for that code. Inspect graph items and their source locations. For a route or value path, read the outcome and any assumptions or stops before drawing a conclusion. The bundled engine requires Node.js 18 or newer. See [Data-flow analysis](../data-flow/) for language limits and outcome meanings. + +<figure><a href="/srcly/screenshots/data-flow.jpg" target="_blank" rel="noreferrer"><img src="/srcly/screenshots/data-flow.jpg" alt="Partial route trace for /notes/[id] in Srcly's included symbol-graph example" width="1440" height="960" loading="lazy" /></a><figcaption>The <code>/notes/[id]</code> route trace in the included symbol-graph example is anchored at <code>NotePage</code>. It is partial: one callback handoff has no call sites to pair its values. Inspect the unproven handoff before relying on the path.</figcaption></figure> + +## 5. Repeat the investigation in a terminal + +If you need a saved review or want to pass evidence to an agent, run: + +```bash +uvx srcly report . --out .srcly +uvx srcly explain . --at path/to/file.ts +``` + +Read `report.md` first, then follow its suggested scope into `explain`. The generated `Analysis:` line records whether the scan was reused or fresh, the Git revision and working-tree state, checker coverage, and analysis failures. It helps distinguish a measured result from a gap in coverage. See [Reports](../reports/) for artifact-to-question mapping. + +## Make the next decision + +The first review should end with a decision, not just a list of high values. You might verify a finding, add a missing checker, adjust a TypeScript entry glob, or defer a refactor because the evidence is weak. Keep the signal and its coverage with that decision. If a result is unavailable, use its reason to decide whether to configure a tool or accept the gap. + +Start with [Get started](../get-started/) for installation details. Use [Explore](../explore/) to compare the views, or [Findings](../findings/) to understand checker coverage. diff --git a/site/src/site.css b/site/src/site.css index 268e1e4b..f9582032 100644 --- a/site/src/site.css +++ b/site/src/site.css @@ -151,13 +151,16 @@ code, pre { font-family: var(--mono); font-variant-ligatures: none; } .search-box:focus-within { border-color: var(--blue); } .search-box input { min-width: 0; width: 100%; border: 0; padding: 0; background: transparent; color: var(--ink); font-size: 12px; outline: none; } .search-box input::placeholder { color: #647689; opacity: 1; } +.search-box input::-webkit-search-cancel-button { appearance: none; } .search-box button { display: grid; place-items: center; border: 0; background: none; cursor: pointer; padding: 2px; color: #536a7e; } +.search-box .search-clear { flex: 0 0 22px; width: 22px; height: 26px; opacity: 1; } +.search-box .search-clear:disabled { opacity: .42; cursor: default; } .nav-group { margin-top: 25px; } .nav-group h2 { margin: 0 0 7px; color: #768595; font-size: 10px; font-weight: 650; letter-spacing: .08em; text-transform: uppercase; } .side-link { display: block; margin-left: -9px; padding: 5px 8px; border-radius: 3px; color: #455a6e; font-size: 13px; } .side-link:hover { background: #edf2f5; text-decoration: none; } .side-link.current { color: #155e91; background: #e8f1f7; font-weight: 650; } -.sidebar-bottom { position: absolute; bottom: 7px; left: 0; } +.sidebar-bottom { margin-top: 22px; } .sidebar-bottom a { display: flex; align-items: center; gap: 6px; color: #566a7c; font-size: 11px; } .search-results { padding-top: 14px; } .search-result { display: block; padding: 10px 2px; border-bottom: 1px solid var(--line); color: inherit; } @@ -295,3 +298,114 @@ code, pre { font-family: var(--mono); font-variant-ligatures: none; } @media (prefers-reduced-motion: reduce) { *, *::before, *::after { scroll-behavior: auto !important; transition-duration: .01ms !important; animation-duration: .01ms !important; } } + +/* Product proof and guide navigation */ +.hero-frame { width: min(1160px, calc(100% - 64px)); padding-top: 54px; grid-template-columns: minmax(260px, .62fr) minmax(0, 1.38fr); gap: 44px; } +.hero-deck { margin: 18px 0 20px; font-size: 16px; line-height: 1.6; } +.hero-product-shot { min-width: 0; margin: 0; } +.hero-product-shot .shot-link { display: block; border: 1px solid var(--line-strong); background: #edf2f5; } +.hero-product-shot img { display: block; width: 100%; height: auto; } +.hero-product-shot figcaption { display: flex; justify-content: space-between; gap: 16px; padding-top: 9px; color: #526273; font-size: 11px; } +.shot-link { cursor: zoom-in; } +.product-tour, .use-paths, .trust-note { width: min(1160px, calc(100% - 64px)); margin: 0 auto; } +.product-tour { border-top: 1px solid var(--line); padding: 33px 0 42px; scroll-margin-top: 18px; } +.product-tour .section-heading { align-items: end; margin-bottom: 20px; } +.product-tour .section-heading h2 { margin: 0; color: var(--ink); font-size: clamp(25px, 3vw, 34px); line-height: 1.16; letter-spacing: -.04em; } +.product-tour .section-heading p { margin: 7px 0 0; color: var(--muted); font-size: 14px; } +.product-tour .section-heading > .text-link { flex: 0 0 auto; } +.tour-gallery { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 26px; } +.tour-view figure { margin: 0; } +.tour-shot .shot-link { display: block; overflow: hidden; border: 1px solid var(--line-strong); background: #edf2f5; } +.tour-shot img { display: block; width: 100%; aspect-ratio: 1.5; object-fit: cover; object-position: top left; } +.tour-shot figcaption { margin-top: 11px; color: #203247; font-size: 16px; font-weight: 650; letter-spacing: -.015em; } +.tour-view > p { min-height: 66px; margin: 6px 0 7px; color: #526273; font-size: 13px; line-height: 1.55; } +.tour-view .text-link, .trust-note .text-link { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 600; } +.use-paths { border-top: 1px solid var(--line); padding: 35px 0; display: grid; grid-template-columns: 1fr 1fr; gap: 56px; align-items: start; } +.use-paths h2, .trust-note h2 { margin: 0; font-size: clamp(24px, 3vw, 32px); letter-spacing: -.04em; line-height: 1.17; } +.use-paths p, .trust-note p { max-width: 520px; margin: 10px 0 0; color: #526273; font-size: 14px; line-height: 1.65; } +.path-links { border-top: 1px solid var(--line); } +.path-links a { display: flex; justify-content: space-between; align-items: center; gap: 18px; padding: 12px 2px; border-bottom: 1px solid var(--line); color: #29445b; } +.path-links a:hover { text-decoration: none; color: var(--blue-dark); } +.path-links strong, .path-links small { display: block; } +.path-links strong { font-size: 14px; font-weight: 650; } +.path-links small { margin-top: 2px; color: #617284; font-size: 12px; } +.trust-note { border-top: 1px solid var(--line); padding: 30px 0 40px; } +.trust-note h2 { font-size: 21px; } +.trust-note p { margin-top: 7px; } +.trust-note .text-link { margin-top: 9px; } + +.docs-layout { gap: 42px; padding-top: 27px; } +.docs-sidebar { position: sticky; top: 16px; align-self: start; max-height: calc(100vh - 32px); overflow-y: auto; padding-bottom: 16px; } +.nav-group { margin-top: 20px; } +.search-result mark { color: #163d59; background: #dcecf6; } +.article-head { padding-top: 0; padding-bottom: 17px; } +.article-grid { padding-top: 24px; } +.markdown { max-width: none; } +.markdown > :not(figure) { max-width: 74ch; } +.markdown figure { margin: 1.5em 0; } +.markdown figure img { display: block; width: 100%; border: 1px solid var(--line-strong); background: #edf2f5; } +.markdown figure figcaption { margin-top: 7px; color: #566b7d; font-size: 12px; line-height: 1.5; } +.code-copy { width: 54px; font-size: 10px; } +.mobile-doc-tools { display: none; } +.screenshot-dialog { width: min(96vw, 1440px); height: min(94vh, 1000px); max-width: none; max-height: none; padding: 0; border: 1px solid #aab9c6; background: #f8fafc; color: var(--ink); } +.screenshot-dialog::backdrop { background: rgb(17 31 44 / 78%); } +.viewer-toolbar { position: sticky; top: 0; z-index: 1; min-height: 48px; display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 6px 10px 6px 15px; border-bottom: 1px solid var(--line); background: #fff; color: #526273; font-size: 12px; } +.viewer-controls { display: flex; align-items: center; gap: 7px; } +.viewer-controls button { width: 34px; height: 32px; display: grid; place-items: center; border: 1px solid var(--line); background: #fff; cursor: pointer; color: #40576b; } +.viewer-controls button:disabled { color: #91a0ad; cursor: default; } +.viewer-controls > span { min-width: 42px; text-align: center; font: 11px var(--mono); font-variant-numeric: tabular-nums; } +.viewer-viewport { height: calc(100% - 49px); overflow: auto; display: block; padding: 18px; } +.viewer-viewport img { display: block; max-width: none; height: auto; margin: 0 auto; border: 1px solid #c5d0d9; background: #fff; } + +@media (max-width: 1200px) { + .hero-frame { width: calc(100% - 64px); grid-template-columns: minmax(250px, .62fr) minmax(0, 1.38fr); } +} +@media (max-width: 900px) { + .hero-frame { grid-template-columns: 1fr; } + .hero-copy { max-width: 720px; } + .hero-product-shot { max-width: 760px; width: 100%; } + .tour-gallery { gap: 18px; } + .tour-view > p { min-height: 92px; } + .docs-sidebar { position: static; max-height: none; } +} +@media (max-width: 640px) { + .hero-frame, .product-tour, .use-paths, .trust-note { width: calc(100% - 36px); } + .hero-frame { padding: 35px 0 30px; gap: 24px; } + .hero-copy h1 { font-size: clamp(39px, 11vw, 54px); } + .hero-product-shot figcaption { display: block; font-size: 10px; } + .hero-product-shot figcaption span { display: block; } + .hero-product-shot figcaption span + span { margin-top: 2px; } + .product-tour { padding: 27px 0 30px; } + .product-tour .section-heading { display: block; } + .product-tour .section-heading > .text-link { margin-top: 12px; } + .tour-gallery { grid-template-columns: 1fr; gap: 25px; } + .tour-shot img { aspect-ratio: 1.48; } + .tour-view > p { min-height: 0; max-width: 52ch; } + .use-paths { grid-template-columns: 1fr; gap: 20px; padding: 28px 0; } + .trust-note { padding: 25px 0 32px; } + .docs-layout { display: block; width: calc(100% - 36px); padding: 12px 0 42px; } + .docs-sidebar { display: none; } + .mobile-doc-tools { display: grid; gap: 8px; position: relative; } + .mobile-doc-tools .search-results { position: absolute; z-index: 5; top: 37px; left: 0; right: 0; max-height: 55vh; overflow-y: auto; border: 1px solid var(--line); background: var(--paper); padding: 5px 12px; box-shadow: 0 8px 20px rgb(39 60 80 / 12%); } + .mobile-doc-tools .search-results:has(.empty-search) { padding: 5px 12px; } + .mobile-doc-tools .topics-toggle { width: 100%; display: flex; justify-content: flex-start; align-items: center; gap: 8px; padding: 8px 10px; border: 1px solid var(--line-strong); background: var(--paper); cursor: pointer; color: #3c5468; font-size: 12px; } + .topics-toggle svg:last-child { margin-left: auto; transition: transform 140ms; } + .topics-toggle svg.rotated { transform: rotate(180deg); } + .mobile-topics { position: absolute; z-index: 4; top: 76px; left: 0; right: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 7px 16px; border: 1px solid var(--line); background: #fff; padding: 11px 13px; box-shadow: 0 8px 20px rgb(39 60 80 / 12%); } + .mobile-topics h2 { margin: 0 0 3px; color: #627487; font-size: 10px; text-transform: uppercase; letter-spacing: .06em; } + .mobile-topics a { display: block; padding: 4px 0; color: #455b6f; font-size: 12px; } + .mobile-topics a[aria-current] { color: var(--blue-dark); font-weight: 650; } + .article-head { display: flex; align-items: start; padding: 15px 0 15px; } + .article-head h1 { font-size: 34px; } + .article-summary { font-size: 13px; } + .edit-link { margin-top: 6px; white-space: nowrap; } + .article-grid { grid-template-columns: minmax(0, 1fr); padding-top: 18px; } + .toc { display: none; } + .markdown { font-size: 14px; line-height: 1.68; } + .markdown h2 { font-size: 22px; } + .markdown h3 { font-size: 17px; } + .markdown pre { font-size: 11px; padding: 12px; } + .page-nav { margin-top: 30px; } + .screenshot-dialog { width: 100vw; height: 100dvh; border: 0; } + .viewer-viewport { padding: 10px; } +} diff --git a/site/tests/site.spec.ts b/site/tests/site.spec.ts index 41422050..fbdd4cbc 100644 --- a/site/tests/site.spec.ts +++ b/site/tests/site.spec.ts @@ -1,6 +1,6 @@ import { expect, test } from "@playwright/test"; -const guides = ["get-started", "explore", "metrics", "findings", "data-flow", "reports", "cli", "configuration"]; +const guides = ["overview", "tour", "design", "get-started", "explore", "metrics", "findings", "data-flow", "reports", "cli", "configuration"]; test("every guide has readable static HTML and valid local links", async ({ browser, request }) => { const context = await browser.newContext({ javaScriptEnabled: false }); @@ -11,7 +11,11 @@ test("every guide has readable static HTML and valid local links", async ({ brow expect(response?.status()).toBe(200); await expect(page.locator(".markdown")).toContainText("Srcly"); await expect(page.locator(".markdown h2").first()).toBeVisible(); - expect(await page.locator('link[rel="canonical"]').getAttribute("href")).toBe(`https://byronwall.github.io/srcly/docs/${slug}/`); + expect(await page.locator('link[rel="canonical"]').getAttribute("href")).toBe(`https://byronwall.github.io/srcly/docs/${slug === "overview" ? "" : `${slug}/`}`); + for (const image of await page.locator(".markdown img").all()) { + await image.scrollIntoViewIfNeeded(); + await expect.poll(() => image.evaluate((node) => (node as HTMLImageElement).naturalWidth)).toBeGreaterThan(0); + } for (const link of await page.locator("a[href]").evaluateAll((nodes) => nodes.map((node) => (node as HTMLAnchorElement).href))) { if (link.startsWith("http://127.0.0.1:18588/")) links.add(link.split("#")[0]); } @@ -22,47 +26,76 @@ test("every guide has readable static HTML and valid local links", async ({ brow for (const link of links) { const response = await request.get(link); expect(response.status(), link).toBe(200); - expect(await response.text(), link).not.toContain("This page is not here."); + if (response.headers()["content-type"]?.includes("text/html")) { + expect(await response.text(), link).not.toContain("This page is not here."); + } } await context.close(); }); -test("the example responds to file and metric selection", async ({ page }) => { +test("real screenshots open at full size, zoom, and close by keyboard", async ({ page }) => { const errors: string[] = []; page.on("pageerror", (error) => errors.push(error.message)); await page.goto("./"); - await page.locator('[data-file="cache.ts"]').focus(); - await page.keyboard.press("Enter"); - await expect(page.locator("[data-selected-file]")).toHaveText("cache.ts"); - const before = await page.locator('[data-file="cache.ts"]').evaluate((element) => getComputedStyle(element).backgroundColor); - await page.locator('[data-metric="comment-noise"]').click(); - await expect(page.locator('[data-metric="comment-noise"]')).toHaveAttribute("aria-pressed", "true"); - const after = await page.locator('[data-file="cache.ts"]').evaluate((element) => getComputedStyle(element).backgroundColor); - expect(after).not.toBe(before); + for (const route of ["./", "docs/tour/"]) { + await page.goto(route); + const imageLink = page.locator('a[href$="/screenshots/treemap.jpg"]').first(); + await imageLink.focus(); + await page.keyboard.press("Enter"); + const dialog = page.getByRole("dialog", { name: "Screenshot viewer" }); + await expect(dialog).toBeVisible(); + const before = await dialog.locator("img").evaluate((image) => image.getBoundingClientRect().width); + await dialog.getByRole("button", { name: "Zoom in", exact: true }).click(); + await expect.poll(() => dialog.locator("img").evaluate((image) => image.getBoundingClientRect().width)).toBeGreaterThan(before); + await page.keyboard.press("Escape"); + await expect(dialog).not.toBeVisible(); + await expect(imageLink).toBeFocused(); + } expect(errors).toEqual([]); }); test("search finds guide content and direct navigation survives reload", async ({ page }) => { await page.goto("docs/get-started/"); - await page.locator("[data-doc-search]").fill("ratchet"); - await expect(page.locator('[data-search-result="cli"]')).toBeVisible(); - await page.locator('[data-search-result="cli"]').click(); - await expect(page).toHaveURL(/\/srcly\/docs\/cli\/$/); + await page.locator("[data-doc-search]:visible").fill("ratchet"); + const result = page.locator('[data-search-result="cli"]:visible'); + await expect(result).toBeVisible(); + await expect(result.locator("mark")).toHaveText(/ratchet/i); + await result.click(); + await expect(page).toHaveURL(/\/srcly\/docs\/cli\/#.+/); + expect(await page.evaluate(() => !!document.getElementById(decodeURIComponent(location.hash.slice(1))))).toBe(true); await page.reload(); await expect(page.locator(".markdown")).toContainText("--ratchet"); - await page.locator("[data-doc-search]").fill("no-such-feature-9281"); - await expect(page.locator(".empty-search")).toBeVisible(); + await page.locator("[data-doc-search]:visible").fill("no-such-feature-9281"); + await expect(page.locator(".empty-search:visible")).toBeVisible(); }); -test("mobile navigation works without page overflow", async ({ page }) => { +test("mobile search and topics preserve the reading layout", async ({ page }) => { await page.setViewportSize({ width: 390, height: 844 }); - for (const route of ["./", "docs/get-started/", "docs/cli/"]) { + for (const route of ["./", "docs/", "docs/tour/", "docs/cli/"]) { await page.goto(route); expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), route).toBe(true); } + const before = await page.locator("h1").boundingBox(); await page.locator("[data-topics-toggle]").click(); await expect(page.locator("[data-topics-toggle]")).toHaveAttribute("aria-expanded", "true"); + expect((await page.locator("h1").boundingBox())?.y).toBe(before?.y); await page.locator('[data-mobile-topics] a[href$="/metrics/"]').click(); await expect(page).toHaveURL(/\/srcly\/docs\/metrics\/$/); await expect(page.locator(".markdown")).toContainText("N/A"); + await page.locator("[data-doc-search]:visible").fill("ast-grep"); + await page.locator('[data-search-result="findings"]:visible').click(); + await expect(page).toHaveURL(/\/docs\/findings\/#.+/); + expect(await page.evaluate(() => !!document.getElementById(decodeURIComponent(location.hash.slice(1))))).toBe(true); +}); + +test("copy feedback resets when copying successive code blocks", async ({ page, context }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await page.goto("docs/get-started/"); + const buttons = page.locator("button[data-code-id]"); + await buttons.nth(0).click(); + await buttons.nth(1).click(); + await expect(buttons.nth(0)).toHaveText("Copy"); + await expect(buttons.nth(1)).toHaveText("Copied"); + expect(await page.evaluate(() => navigator.clipboard.readText())).toContain("uvx srcly"); + await expect(buttons.nth(1)).toHaveText("Copy", { timeout: 3000 }); });