ucode-agent 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,218 @@
1
+ /**
2
+ * symbols.js — a map of what this codebase declares, so "where is the tip
3
+ * calculated" is one lookup rather than five greps.
4
+ *
5
+ * grep finds every line that mentions a name; almost all of them are uses,
6
+ * and the one that matters is the declaration. This reads each source file
7
+ * once and records only the declarations: functions, classes, components,
8
+ * types, and the route a Next.js page answers on.
9
+ *
10
+ * The scan is by pattern, not by a parser. A parser would be exact but would
11
+ * mean carrying TypeScript itself and paying its start-up on every lookup;
12
+ * declarations are one of the few things regular expressions read reliably,
13
+ * because they sit at the start of a line in formatted code. What this can
14
+ * miss is a declaration written unusually — and a miss costs a grep, which
15
+ * is where we started.
16
+ *
17
+ * The index is held per directory and rebuilt when a file's modified time
18
+ * moves, so an edit is picked up without a rescan of everything.
19
+ */
20
+
21
+ import { promises as fs } from 'node:fs';
22
+ import path from 'node:path';
23
+ import { resolveIn, guard, result, walk } from './shared.js';
24
+
25
+ /** Files worth reading for declarations. */
26
+ const SOURCE = /\.(?:[cm]?[jt]sx?|py)$/i;
27
+
28
+ /** How much of a file to read; a declaration past this is a generated file's. */
29
+ const MAX_BYTES = 400_000;
30
+
31
+ const PATTERNS = [
32
+ // export function foo(...) / export default function foo(...)
33
+ { kind: 'function', re: /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/ },
34
+ // class Foo / export class Foo
35
+ { kind: 'class', re: /^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/ },
36
+ // const foo = (...) => / const foo = async (...) => / const foo = function
37
+ { kind: 'function', re: /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*(?::[^=]+)?=>/ },
38
+ { kind: 'function', re: /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?function/ },
39
+ // type Foo = / interface Foo / enum Foo
40
+ { kind: 'type', re: /^\s*(?:export\s+)?type\s+([A-Za-z_$][\w$]*)\s*[<=]/ },
41
+ { kind: 'type', re: /^\s*(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)/ },
42
+ { kind: 'type', re: /^\s*(?:export\s+)?(?:const\s+)?enum\s+([A-Za-z_$][\w$]*)/ },
43
+ // Python
44
+ { kind: 'function', re: /^\s*(?:async\s+)?def\s+([A-Za-z_][\w]*)/ },
45
+ { kind: 'class', re: /^\s*class\s+([A-Za-z_][\w]*)/ },
46
+ ];
47
+
48
+ /** A capitalised function in a .tsx file is a component, and worth saying so. */
49
+ const isComponent = (name, rel) => /^[A-Z]/.test(name) && /\.[jt]sx$/i.test(rel);
50
+
51
+ /**
52
+ * The URL a Next.js app-router file answers on: src/app/blog/[slug]/page.tsx
53
+ * is /blog/[slug]. Route groups in brackets-as-parens are not part of the path.
54
+ */
55
+ export function routeFor(rel) {
56
+ const m = rel.replace(/\\/g, '/').match(/(?:^|\/)app\/(.*)\/(page|route|layout)\.[jt]sx?$/i);
57
+ if (!m) {
58
+ if (/(?:^|\/)app\/(page|route|layout)\.[jt]sx?$/i.test(rel.replace(/\\/g, '/'))) return '/';
59
+ return null;
60
+ }
61
+ const url = m[1].split('/').filter((s) => s && !/^\(.*\)$/.test(s)).join('/');
62
+ return `/${url}`;
63
+ }
64
+
65
+ /** Every declaration in one file's text, with the line it sits on. */
66
+ export function declarationsIn(rel, text) {
67
+ const found = [];
68
+ const lines = text.split('\n');
69
+ for (let i = 0; i < lines.length; i++) {
70
+ const line = lines[i];
71
+ if (line.length > 400) continue;
72
+ for (const { kind, re } of PATTERNS) {
73
+ const m = line.match(re);
74
+ if (!m) continue;
75
+ const name = m[1];
76
+ found.push({
77
+ name,
78
+ kind: isComponent(name, rel) && kind === 'function' ? 'component' : kind,
79
+ file: rel,
80
+ line: i + 1,
81
+ text: line.trim().slice(0, 160),
82
+ });
83
+ break; // one declaration to a line
84
+ }
85
+ }
86
+ return found;
87
+ }
88
+
89
+ const indexes = new Map(); // root -> { files: Map<rel, {at, symbols}> }
90
+
91
+ /**
92
+ * Read the declarations of every source file under `root`, reusing what was
93
+ * read before for files whose modified time has not moved.
94
+ */
95
+ export async function buildIndex(root) {
96
+ let index = indexes.get(root);
97
+ if (!index) { index = { files: new Map() }; indexes.set(root, index); }
98
+
99
+ const rels = (await walk(root, {})).filter((rel) => SOURCE.test(rel));
100
+ const seen = new Set();
101
+
102
+ await Promise.all(rels.map(async (rel) => {
103
+ seen.add(rel);
104
+ const abs = path.join(root, rel);
105
+ let stat;
106
+ try { stat = await fs.stat(abs); } catch { return; }
107
+ if (stat.size > MAX_BYTES) return;
108
+ const had = index.files.get(rel);
109
+ if (had && had.at === stat.mtimeMs) return; // unchanged since last time
110
+ const text = await fs.readFile(abs, 'utf8').catch(() => null);
111
+ if (text === null) return;
112
+ index.files.set(rel, { at: stat.mtimeMs, symbols: declarationsIn(rel, text) });
113
+ }));
114
+
115
+ for (const rel of [...index.files.keys()]) if (!seen.has(rel)) index.files.delete(rel);
116
+
117
+ const symbols = [];
118
+ for (const { symbols: s } of index.files.values()) symbols.push(...s);
119
+ return { symbols, fileCount: index.files.size };
120
+ }
121
+
122
+ /** Forget what was read, so the next lookup starts clean. */
123
+ export function clearIndex() { indexes.clear(); }
124
+
125
+ const KINDS = new Set(['function', 'class', 'type', 'component']);
126
+
127
+ /**
128
+ * Where a name is declared. An exact match wins; failing that, anything
129
+ * containing it, so a half-remembered name still lands.
130
+ */
131
+ export async function findSymbol({ name, kind, path: p = '.' }) {
132
+ const wanted = String(name ?? '').trim();
133
+ if (!wanted) {
134
+ return result('Pass the name of a function, component, class or type to look for.', 'nothing to look for');
135
+ }
136
+
137
+ const target = resolveIn(p || '.', 'find_symbol', 'path');
138
+ await guard(target, `read ${target.abs}`);
139
+
140
+ const { symbols, fileCount } = await buildIndex(target.abs);
141
+ const pool = kind && KINDS.has(kind) ? symbols.filter((s) => s.kind === kind) : symbols;
142
+
143
+ const lower = wanted.toLowerCase();
144
+ let hits = pool.filter((s) => s.name === wanted);
145
+ let how = 'exactly';
146
+ if (!hits.length) {
147
+ hits = pool.filter((s) => s.name.toLowerCase() === lower);
148
+ how = 'ignoring case';
149
+ }
150
+ if (!hits.length) {
151
+ hits = pool.filter((s) => s.name.toLowerCase().includes(lower));
152
+ how = 'containing';
153
+ }
154
+
155
+ if (!hits.length) {
156
+ return result(
157
+ `Nothing declared as "${wanted}" in ${target.show} (read ${fileCount} source files).\n` +
158
+ 'It may be imported from a package, spelled differently, or built at runtime — grep will find uses.',
159
+ 'not declared here'
160
+ );
161
+ }
162
+
163
+ hits.sort((a, b) => a.name.length - b.name.length || a.file.localeCompare(b.file));
164
+ const shown = hits.slice(0, 25);
165
+ const lines = shown.map((s) => {
166
+ const route = routeFor(s.file);
167
+ return `${s.file}:${s.line} ${s.kind} ${s.name}${route ? ` [route ${route}]` : ''}\n ${s.text}`;
168
+ });
169
+
170
+ const more = hits.length > shown.length ? `\n[${hits.length - shown.length} more]` : '';
171
+ return result(
172
+ `Declared ${how} "${wanted}":\n\n${lines.join('\n')}${more}`,
173
+ `${hits.length} declaration${hits.length === 1 ? '' : 's'}`
174
+ );
175
+ }
176
+
177
+ /**
178
+ * What a file declares, and what a folder's files declare — the shape of the
179
+ * code without reading all of it.
180
+ */
181
+ export async function outline({ path: p = '.' }) {
182
+ const target = resolveIn(p || '.', 'outline', 'path');
183
+ await guard(target, `read ${target.abs}`);
184
+
185
+ const stat = await fs.stat(target.abs).catch(() => null);
186
+ if (stat?.isFile()) {
187
+ const text = await fs.readFile(target.abs, 'utf8').catch(() => '');
188
+ const found = declarationsIn(target.show, text);
189
+ if (!found.length) return result(`${target.show} declares nothing this can see.`, 'nothing declared');
190
+ return result(
191
+ `${target.show}\n` + found.map((s) => ` ${s.line}: ${s.kind} ${s.name}`).join('\n'),
192
+ `${found.length} declaration${found.length === 1 ? '' : 's'}`
193
+ );
194
+ }
195
+
196
+ const { symbols, fileCount } = await buildIndex(target.abs);
197
+ if (!symbols.length) return result(`No declarations found under ${target.show}.`, 'nothing declared');
198
+
199
+ const byFile = new Map();
200
+ for (const s of symbols) {
201
+ if (!byFile.has(s.file)) byFile.set(s.file, []);
202
+ byFile.get(s.file).push(s);
203
+ }
204
+
205
+ const files = [...byFile.keys()].sort();
206
+ const shown = files.slice(0, 60);
207
+ const body = shown.map((f) => {
208
+ const route = routeFor(f);
209
+ const names = byFile.get(f).map((s) => s.name).slice(0, 12).join(', ');
210
+ return `${f}${route ? ` [route ${route}]` : ''}\n ${names}`;
211
+ });
212
+
213
+ const more = files.length > shown.length ? `\n[${files.length - shown.length} more files]` : '';
214
+ return result(
215
+ `${symbols.length} declarations across ${fileCount} files in ${target.show}:\n\n${body.join('\n')}${more}`,
216
+ `${symbols.length} declarations`
217
+ );
218
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * types.js — asking the app's own TypeScript what something actually is.
3
+ *
4
+ * The model guesses at APIs. It writes `user.fullName` because that is what
5
+ * the property ought to be called, and finds out from a build forty seconds
6
+ * later that it is `displayName`. Every editor solves this by asking a
7
+ * language service, and the answer is already installed: the project's own
8
+ * TypeScript, the same version and the same tsconfig that its build uses.
9
+ *
10
+ * So this loads the project's typescript — never one of ours, which would
11
+ * answer for a different version of the language — and keeps a language
12
+ * service open on it. Asking is then a few milliseconds, and the answer is
13
+ * the one the build will give.
14
+ *
15
+ * A project without TypeScript installed gets a plain sentence saying so.
16
+ * Nothing is installed to make this work.
17
+ */
18
+
19
+ import { promises as fs } from 'node:fs';
20
+ import { statSync, readFileSync, existsSync } from 'node:fs';
21
+ import path from 'node:path';
22
+ import { pathToFileURL } from 'node:url';
23
+ import { resolveIn, guard, result } from './shared.js';
24
+
25
+ /** The nearest folder above `from` holding both a tsconfig and a typescript. */
26
+ export function projectRootFor(from, root) {
27
+ let dir = path.resolve(from);
28
+ const stop = path.resolve(root);
29
+ for (;;) {
30
+ if (existsSync(path.join(dir, 'tsconfig.json'))) return dir;
31
+ const up = path.dirname(dir);
32
+ if (up === dir || !dir.startsWith(stop)) return null;
33
+ dir = up;
34
+ }
35
+ }
36
+
37
+ /** The project's own typescript, or null if it has none. */
38
+ async function loadTypeScript(projectDir) {
39
+ let dir = projectDir;
40
+ for (;;) {
41
+ const entry = path.join(dir, 'node_modules', 'typescript', 'lib', 'typescript.js');
42
+ if (existsSync(entry)) {
43
+ const mod = await import(pathToFileURL(entry).href);
44
+ return mod.default ?? mod;
45
+ }
46
+ const up = path.dirname(dir);
47
+ if (up === dir) return null;
48
+ dir = up;
49
+ }
50
+ }
51
+
52
+ const services = new Map(); // project dir -> { ts, service, versions }
53
+
54
+ /**
55
+ * A language service for this project, made once and kept. Files are read
56
+ * from disk and their version is their modified time, so an edit made by the
57
+ * model is seen on the next question without rebuilding anything.
58
+ */
59
+ async function serviceFor(projectDir) {
60
+ const had = services.get(projectDir);
61
+ if (had) return had;
62
+
63
+ const ts = await loadTypeScript(projectDir);
64
+ if (!ts) return null;
65
+
66
+ const configPath = path.join(projectDir, 'tsconfig.json');
67
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
68
+ const parsed = ts.parseJsonConfigFileContent(read.config ?? {}, ts.sys, projectDir);
69
+
70
+ const versions = new Map();
71
+ const versionOf = (file) => {
72
+ try { return String(statSync(file).mtimeMs); } catch { return '0'; }
73
+ };
74
+
75
+ const host = {
76
+ getScriptFileNames: () => parsed.fileNames,
77
+ getScriptVersion: (file) => {
78
+ const now = versionOf(file);
79
+ versions.set(file, now);
80
+ return now;
81
+ },
82
+ getScriptSnapshot: (file) => {
83
+ try { return ts.ScriptSnapshot.fromString(readFileSync(file, 'utf8')); } catch { return undefined; }
84
+ },
85
+ getCurrentDirectory: () => projectDir,
86
+ getCompilationSettings: () => parsed.options,
87
+ getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),
88
+ fileExists: ts.sys.fileExists,
89
+ readFile: ts.sys.readFile,
90
+ readDirectory: ts.sys.readDirectory,
91
+ directoryExists: ts.sys.directoryExists,
92
+ getDirectories: ts.sys.getDirectories,
93
+ };
94
+
95
+ const made = { ts, service: ts.createLanguageService(host, ts.createDocumentRegistry()), versions };
96
+ services.set(projectDir, made);
97
+ return made;
98
+ }
99
+
100
+ /** Forget the open services, so the next question starts fresh. */
101
+ export function clearServices() { services.clear(); }
102
+
103
+ /** Character offset of `symbol` used as a name, preferring a given line. */
104
+ export function offsetOf(text, symbol, line) {
105
+ const re = new RegExp(`(?<![\\w$])${symbol.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}(?![\\w$])`, 'g');
106
+ const hits = [...text.matchAll(re)].map((m) => m.index);
107
+ if (!hits.length) return -1;
108
+ if (!line) return hits[0];
109
+ const lineStart = text.split('\n').slice(0, line - 1).join('\n').length;
110
+ // The occurrence nearest the line asked about.
111
+ return hits.reduce((best, at) =>
112
+ Math.abs(at - lineStart) < Math.abs(best - lineStart) ? at : best, hits[0]);
113
+ }
114
+
115
+ /**
116
+ * What TypeScript says a name is: its exact type or signature, the docs
117
+ * written on it, and where it is defined.
118
+ */
119
+ export async function typeOf({ path: p, symbol, line }) {
120
+ const wanted = String(symbol ?? '').trim();
121
+ if (!wanted) return result('Pass the name of something in the file to ask about.', 'nothing to ask about');
122
+
123
+ const target = resolveIn(p, 'type_of', 'path');
124
+ await guard(target, `read ${target.abs}`);
125
+
126
+ const text = await fs.readFile(target.abs, 'utf8').catch(() => null);
127
+ if (text === null) return result(`Could not read ${target.show}.`, 'unreadable');
128
+
129
+ const projectDir = projectRootFor(path.dirname(target.abs), path.parse(target.abs).root);
130
+ if (!projectDir) {
131
+ return result(
132
+ `${target.show} is not inside a TypeScript project (no tsconfig.json above it), so there is ` +
133
+ 'no type information to give. Read the file, or the package it comes from.',
134
+ 'not a typescript project'
135
+ );
136
+ }
137
+
138
+ const made = await serviceFor(projectDir);
139
+ if (!made) {
140
+ return result(
141
+ `This project has no TypeScript installed, so nothing can answer what ${wanted} is. ` +
142
+ 'Once its packages are installed, ask again.',
143
+ 'typescript not installed'
144
+ );
145
+ }
146
+
147
+ const { ts, service } = made;
148
+ const at = offsetOf(text, wanted, line);
149
+ if (at < 0) {
150
+ return result(`"${wanted}" does not appear in ${target.show}.`, 'not in this file');
151
+ }
152
+
153
+ const info = service.getQuickInfoAtPosition(target.abs, at);
154
+ if (!info) {
155
+ return result(
156
+ `TypeScript has nothing to say about ${wanted} in ${target.show} — usually that means the file ` +
157
+ 'has an error above this point, or the project has not been installed.',
158
+ 'no type information'
159
+ );
160
+ }
161
+
162
+ const signature = ts.displayPartsToString(info.displayParts);
163
+ const docs = ts.displayPartsToString(info.documentation ?? []);
164
+
165
+ let where = '';
166
+ const defs = service.getDefinitionAtPosition(target.abs, at) ?? [];
167
+ if (defs.length) {
168
+ const d = defs[0];
169
+ const rel = path.relative(projectDir, d.fileName).replace(/\\/g, '/');
170
+ const body = readFileSync(d.fileName, 'utf8').slice(0, d.textSpan.start);
171
+ where = `\n\nDefined in ${rel}:${body.split('\n').length}`;
172
+ }
173
+
174
+ return result(
175
+ `${signature}${docs ? `\n\n${docs}` : ''}${where}\n\n` +
176
+ 'This is from the project\'s own TypeScript, so it is what the build will say.',
177
+ signature.split('\n')[0].slice(0, 80)
178
+ );
179
+ }
package/src/ui/theme.js CHANGED
@@ -252,7 +252,11 @@ export function asLabel(text) {
252
252
  return String(text ?? '')
253
253
  .trim()
254
254
  .replace(/\s+/g, ' ')
255
- .replace(/(?<=[\w)\]"'`])[.。]+$/, '');
255
+ // A trailing stop, from a model's sentence or a tool's own output
256
+ // ("Building…", "Completing…"), is noise on a one-line label. A dot that
257
+ // is the argument itself — "Listing ." — is not, so a word has to come
258
+ // before it.
259
+ .replace(/(?<=[\w)\]"'`])[.。…]+$/, '');
256
260
  }
257
261
 
258
262
  /**
@@ -0,0 +1,81 @@
1
+ "use client";
2
+
3
+ import { ReactNode, useState } from "react";
4
+ import Link from "next/link";
5
+ import { Button } from "@/components/ui/button";
6
+ import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
7
+
8
+ export type NavItem = { href: string; label: string; icon?: ReactNode };
9
+
10
+ /**
11
+ * The frame every page sits in: a sidebar on a wide screen, the same nav
12
+ * behind a button on a phone. One list of links drives both, so they cannot
13
+ * drift apart.
14
+ */
15
+ export function AppShell({
16
+ nav,
17
+ current,
18
+ title,
19
+ children,
20
+ }: {
21
+ nav: NavItem[];
22
+ current?: string;
23
+ title: string;
24
+ children: ReactNode;
25
+ }) {
26
+ const [open, setOpen] = useState(false);
27
+
28
+ const links = (onNavigate?: () => void) => (
29
+ <nav className="space-y-1" aria-label="Main">
30
+ {nav.map((item) => {
31
+ const active = current === item.href;
32
+ return (
33
+ <Link
34
+ key={item.href}
35
+ href={item.href}
36
+ onClick={onNavigate}
37
+ aria-current={active ? "page" : undefined}
38
+ className={
39
+ active
40
+ ? "flex items-center gap-3 rounded-md bg-muted px-3 py-2 text-sm font-medium"
41
+ : "flex items-center gap-3 rounded-md px-3 py-2 text-sm text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground"
42
+ }
43
+ >
44
+ {item.icon}
45
+ {item.label}
46
+ </Link>
47
+ );
48
+ })}
49
+ </nav>
50
+ );
51
+
52
+ return (
53
+ <div className="flex min-h-svh">
54
+ <aside className="hidden w-60 shrink-0 border-r p-4 md:block">
55
+ <div className="mb-6 px-3 text-sm font-semibold tracking-tight">{title}</div>
56
+ {links()}
57
+ </aside>
58
+
59
+ <div className="flex min-w-0 flex-1 flex-col">
60
+ <header className="flex h-14 items-center gap-3 border-b px-4 md:px-6">
61
+ <Sheet open={open} onOpenChange={setOpen}>
62
+ <SheetTrigger asChild>
63
+ <Button variant="ghost" size="sm" className="md:hidden" aria-label="Open menu">
64
+ Menu
65
+ </Button>
66
+ </SheetTrigger>
67
+ <SheetContent side="left" className="w-64 p-4">
68
+ <SheetTitle className="mb-6 px-3 text-sm font-semibold">{title}</SheetTitle>
69
+ {links(() => setOpen(false))}
70
+ </SheetContent>
71
+ </Sheet>
72
+ <span className="text-sm font-medium md:hidden">{title}</span>
73
+ </header>
74
+
75
+ <main className="min-w-0 flex-1 p-4 md:p-8">
76
+ <div className="mx-auto w-full max-w-6xl space-y-8">{children}</div>
77
+ </main>
78
+ </div>
79
+ </div>
80
+ );
81
+ }
@@ -0,0 +1,117 @@
1
+ "use client";
2
+
3
+ import { useMemo, useState, ReactNode } from "react";
4
+ import { Input } from "@/components/ui/input";
5
+ import {
6
+ Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
7
+ } from "@/components/ui/table";
8
+
9
+ export type Column<T> = {
10
+ key: keyof T & string;
11
+ header: string;
12
+ /** Right-align and tabular-nums, for money and counts. */
13
+ numeric?: boolean;
14
+ render?: (row: T) => ReactNode;
15
+ };
16
+
17
+ /**
18
+ * A table of things you can search and sort.
19
+ *
20
+ * Sorting and filtering happen here, over rows already in memory: it is the
21
+ * right shape up to a few thousand rows and the wrong one past that, where
22
+ * the server should be doing both.
23
+ */
24
+ export function DataTable<T extends { id: string | number }>({
25
+ rows,
26
+ columns,
27
+ searchPlaceholder = "Search…",
28
+ empty,
29
+ }: {
30
+ rows: T[];
31
+ columns: Column<T>[];
32
+ searchPlaceholder?: string;
33
+ empty?: ReactNode;
34
+ }) {
35
+ const [query, setQuery] = useState("");
36
+ const [sort, setSort] = useState<{ key: string; asc: boolean } | null>(null);
37
+
38
+ const shown = useMemo(() => {
39
+ const needle = query.trim().toLowerCase();
40
+ let out = needle
41
+ ? rows.filter((row) =>
42
+ columns.some((c) => String(row[c.key] ?? "").toLowerCase().includes(needle)))
43
+ : rows.slice();
44
+ if (sort) {
45
+ out.sort((a, b) => {
46
+ const x = a[sort.key as keyof T];
47
+ const y = b[sort.key as keyof T];
48
+ if (typeof x === "number" && typeof y === "number") return sort.asc ? x - y : y - x;
49
+ return sort.asc
50
+ ? String(x ?? "").localeCompare(String(y ?? ""))
51
+ : String(y ?? "").localeCompare(String(x ?? ""));
52
+ });
53
+ }
54
+ return out;
55
+ }, [rows, columns, query, sort]);
56
+
57
+ const toggle = (key: string) =>
58
+ setSort((s) => (s?.key === key ? { key, asc: !s.asc } : { key, asc: true }));
59
+
60
+ return (
61
+ <div className="space-y-4">
62
+ <Input
63
+ value={query}
64
+ onChange={(e) => setQuery(e.target.value)}
65
+ placeholder={searchPlaceholder}
66
+ className="max-w-xs"
67
+ aria-label={searchPlaceholder}
68
+ />
69
+
70
+ <div className="overflow-x-auto rounded-lg border">
71
+ <Table>
72
+ <TableHeader>
73
+ <TableRow>
74
+ {columns.map((c) => (
75
+ <TableHead key={c.key} className={c.numeric ? "text-right" : undefined}>
76
+ <button
77
+ type="button"
78
+ onClick={() => toggle(c.key)}
79
+ className="inline-flex items-center gap-1 hover:text-foreground"
80
+ aria-label={`Sort by ${c.header}`}
81
+ >
82
+ {c.header}
83
+ <span aria-hidden className="text-xs text-muted-foreground">
84
+ {sort?.key === c.key ? (sort.asc ? "↑" : "↓") : ""}
85
+ </span>
86
+ </button>
87
+ </TableHead>
88
+ ))}
89
+ </TableRow>
90
+ </TableHeader>
91
+ <TableBody>
92
+ {shown.length === 0 ? (
93
+ <TableRow>
94
+ <TableCell colSpan={columns.length} className="h-28 text-center text-sm text-muted-foreground">
95
+ {query ? `Nothing matches “${query}”.` : empty ?? "Nothing here yet."}
96
+ </TableCell>
97
+ </TableRow>
98
+ ) : (
99
+ shown.map((row) => (
100
+ <TableRow key={row.id}>
101
+ {columns.map((c) => (
102
+ <TableCell
103
+ key={c.key}
104
+ className={c.numeric ? "text-right tabular-nums" : undefined}
105
+ >
106
+ {c.render ? c.render(row) : String(row[c.key] ?? "")}
107
+ </TableCell>
108
+ ))}
109
+ </TableRow>
110
+ ))
111
+ )}
112
+ </TableBody>
113
+ </Table>
114
+ </div>
115
+ </div>
116
+ );
117
+ }
@@ -0,0 +1,41 @@
1
+ import { ReactNode } from "react";
2
+ import { Button } from "@/components/ui/button";
3
+
4
+ /**
5
+ * What a list looks like before anything is in it.
6
+ *
7
+ * An empty screen is where people decide whether a product is working or
8
+ * broken, so this says which it is and offers the one action that fills it.
9
+ */
10
+ export function EmptyState({
11
+ icon,
12
+ title,
13
+ description,
14
+ actionLabel,
15
+ onAction,
16
+ }: {
17
+ icon?: ReactNode;
18
+ title: string;
19
+ description?: string;
20
+ actionLabel?: string;
21
+ onAction?: () => void;
22
+ }) {
23
+ return (
24
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed px-6 py-16 text-center">
25
+ {icon ? (
26
+ <div className="mb-4 flex size-11 items-center justify-center rounded-full bg-muted text-muted-foreground">
27
+ {icon}
28
+ </div>
29
+ ) : null}
30
+ <h3 className="text-base font-medium">{title}</h3>
31
+ {description ? (
32
+ <p className="mt-1.5 max-w-sm text-sm text-muted-foreground text-pretty">{description}</p>
33
+ ) : null}
34
+ {actionLabel ? (
35
+ <Button className="mt-6" onClick={onAction}>
36
+ {actionLabel}
37
+ </Button>
38
+ ) : null}
39
+ </div>
40
+ );
41
+ }
@@ -0,0 +1,27 @@
1
+ import { ReactNode } from "react";
2
+
3
+ /**
4
+ * The top of a page: what it is, what it is for, and what you can do here.
5
+ * Actions sit on the right on a wide screen and wrap underneath on a phone.
6
+ */
7
+ export function PageHeader({
8
+ title,
9
+ description,
10
+ actions,
11
+ }: {
12
+ title: string;
13
+ description?: string;
14
+ actions?: ReactNode;
15
+ }) {
16
+ return (
17
+ <div className="flex flex-col gap-4 border-b pb-6 sm:flex-row sm:items-end sm:justify-between">
18
+ <div className="space-y-1.5">
19
+ <h1 className="text-2xl font-semibold tracking-tight text-balance">{title}</h1>
20
+ {description ? (
21
+ <p className="max-w-2xl text-sm text-muted-foreground text-pretty">{description}</p>
22
+ ) : null}
23
+ </div>
24
+ {actions ? <div className="flex shrink-0 items-center gap-2">{actions}</div> : null}
25
+ </div>
26
+ );
27
+ }