The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 359 lines 11.3 KB
Raw
1 /** @jsxRuntime automatic */
2 /** @jsxImportSource @alchemy.run/sigil */
3 /** Branded help screens + the CliOutput formatter that renders them. */
4 import { stripVTControlCharacters } from "node:util";
5 import * as CliOutput from "effect/cli/CliOutput";
6 import type { HelpDoc } from "effect/cli/HelpDoc";
7 import * as Option from "effect/Option";
8 import type { JSX } from "react";
9 import packageJson from "../../../../package.json" with { type: "json" };
10 import type { Interaction } from "../../../Interaction.ts";
11 import { ANSI_BOLD, ANSI_DIM, ansiFg, paint, truncate } from "../../../Util/Terminal.ts";
12 import { glyphsFor, theme } from "../../../Util/Theme.ts";
13 import { Box, Heading, Text, useGlyphs } from "../ui/index.ts";
14 import { formatView } from "./Format.tsx";
15 import { Logo } from "./Logo.tsx";
16
17 const commandLabel = (command: { readonly name: string; readonly alias?: string | undefined }) =>
18 command.alias ? `${command.name}, ${command.alias}` : command.name;
19
20 /** Shell-like highlighting shared by usage lines, examples, and help hints. */
21 function CommandText({ command }: { readonly command: string }): JSX.Element {
22 const tokens = command.match(/\s+|"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^\s]+/g) ?? [command];
23 let word = 0;
24 let valueAfterFlag = false;
25
26 return (
27 <Text>
28 {tokens.map((token, index) => {
29 if (/^\s+$/.test(token)) return token;
30
31 const currentWord = word++;
32 const isFlag = token.startsWith("-");
33 const isPlaceholder =
34 (token.startsWith("<") && token.endsWith(">")) ||
35 (token.startsWith("[") && token.endsWith("]"));
36 const isQuoted =
37 (token.startsWith('"') && token.endsWith('"')) ||
38 (token.startsWith("'") && token.endsWith("'"));
39 const isValue = valueAfterFlag || isQuoted;
40 valueAfterFlag = isFlag;
41
42 return (
43 <Text
44 key={`${index}:${token}`}
45 bold={currentWord <= 1 || isFlag}
46 color={
47 currentWord === 0
48 ? theme.color.accent
49 : isFlag
50 ? theme.color.info
51 : isPlaceholder
52 ? theme.color.warning
53 : isValue
54 ? theme.color.success
55 : currentWord === 1
56 ? theme.color.accentBright
57 : undefined
58 }
59 >
60 {token}
61 </Text>
62 );
63 })}
64 </Text>
65 );
66 }
67
68 /** One aligned help row: fixed-width bold label cell + description. */
69 type RowProps = {
70 label: JSX.Element | string;
71 description: string;
72 width: number;
73 };
74
75 function Row({ label, description, width }: RowProps) {
76 return (
77 <Box paddingLeft={2}>
78 <Box width={width} flexShrink={0}>
79 {typeof label === "string" ? (
80 <Text bold tone="emphasis">
81 {label}
82 </Text>
83 ) : (
84 label
85 )}
86 </Box>
87 <Text>{description}</Text>
88 </Box>
89 );
90 }
91
92 function BrandLine(): JSX.Element {
93 const glyphs = useGlyphs();
94 return (
95 <Text>
96 <Text tone="brand">{glyphs.selected}</Text>{" "}
97 <Text bold tone="emphasis">
98 alchemy
99 </Text>{" "}
100 <Text tone="muted">— Infrastructure as Effects</Text>
101 </Text>
102 );
103 }
104
105 /**
106 * Branded help for every command. The root gets a brand header and shows
107 * only `--help`/`--version` (as OPTIONS); subcommands list all global flags.
108 */
109 type SubHelpProps = {
110 doc: HelpDoc;
111 root?: boolean;
112 };
113
114 function SubHelp({ doc, root = false }: SubHelpProps): JSX.Element {
115 const commands = doc.subcommands?.flatMap((group) => group.commands) ?? [];
116 const flags = doc.flags ?? [];
117 const globalFlags = root
118 ? (doc.globalFlags ?? []).filter((flag) => flag.name === "help" || flag.name === "version")
119 : (doc.globalFlags ?? []);
120 const args = doc.args ?? [];
121
122 const flagLabel = (flag: (typeof flags)[number]) => {
123 const aliases = flag.aliases.length > 0 ? `, ${flag.aliases.join(", ")}` : "";
124 return `--${flag.name}${aliases}`;
125 };
126 const argLabel = (arg: (typeof args)[number]) =>
127 arg.required ? `<${arg.name}>` : `[${arg.name}]`;
128 // width from labels only — enum types (--log-level's choice list) would
129 // otherwise blow the column out; long types truncate inside the cell
130 const nameWidth =
131 Math.min(
132 30,
133 Math.max(
134 12,
135 ...commands.map((c) => commandLabel(c).length),
136 ...[...flags, ...globalFlags].map((f) => flagLabel(f).length),
137 ...args.map((a) => argLabel(a).length),
138 ),
139 ) + 4;
140
141 type FlagRowProps = { readonly flag: (typeof flags)[number] };
142
143 function FlagRow({ flag }: FlagRowProps) {
144 const label = flagLabel(flag);
145 const typeRoom = nameWidth - label.length - 2;
146 return (
147 <Row
148 width={nameWidth}
149 description={Option.getOrElse(flag.description, () => "")}
150 label={
151 <Text>
152 <Text bold color={theme.color.info}>
153 --{flag.name}
154 </Text>
155 {flag.aliases.map((alias) => (
156 <Text key={alias} color={theme.color.info}>
157 , {alias}
158 </Text>
159 ))}
160 {flag.type === "boolean" || typeRoom < 8 ? null : (
161 <Text color={theme.color.warning}> {truncate(flag.type, typeRoom)}</Text>
162 )}
163 </Text>
164 }
165 />
166 );
167 }
168
169 return (
170 <Box flexDirection="column" flexShrink={root ? 0 : 1}>
171 {root ? <BrandLine /> : null}
172 {doc.description === "" ? null : (
173 <Box marginTop={root ? 1 : 0}>
174 <Text>{doc.description}</Text>
175 </Box>
176 )}
177 <Box marginTop={doc.description === "" && !root ? 0 : 1}>
178 <Heading glyph={false}>USAGE</Heading>
179 </Box>
180 <Text>
181 {" "}
182 <Text tone="brand">$</Text> <CommandText command={doc.usage} />
183 </Text>
184 {args.length === 0 ? null : (
185 <>
186 <Box marginTop={1}>
187 <Heading glyph={false}>ARGUMENTS</Heading>
188 </Box>
189 {args.map((arg) => (
190 <Row
191 key={arg.name}
192 width={nameWidth}
193 label={
194 <Text bold color={theme.color.warning}>
195 {argLabel(arg)}
196 </Text>
197 }
198 description={Option.getOrElse(arg.description, () => "")}
199 />
200 ))}
201 </>
202 )}
203 {commands.length === 0 ? null : (
204 <>
205 <Box marginTop={1}>
206 <Heading glyph={false}>COMMANDS</Heading>
207 </Box>
208 {commands.map((command) => (
209 <Row
210 key={command.name}
211 width={nameWidth}
212 label={
213 <Text>
214 <Text bold color={theme.color.accentBright}>
215 {command.name}
216 </Text>
217 {command.alias === undefined ? null : (
218 <Text color={theme.color.info}>, {command.alias}</Text>
219 )}
220 </Text>
221 }
222 description={command.description || ""}
223 />
224 ))}
225 </>
226 )}
227 {flags.length === 0 ? null : (
228 <>
229 <Box marginTop={1}>
230 <Heading glyph={false}>FLAGS</Heading>
231 </Box>
232 {flags.map((flag) => (
233 <FlagRow key={flag.name} flag={flag} />
234 ))}
235 </>
236 )}
237 {globalFlags.length === 0 ? null : (
238 <>
239 <Box marginTop={1}>
240 <Heading glyph={false}>{root ? "OPTIONS" : "GLOBAL FLAGS"}</Heading>
241 </Box>
242 {globalFlags.map((flag) => (
243 <FlagRow key={flag.name} flag={flag} />
244 ))}
245 </>
246 )}
247 {doc.examples === undefined || doc.examples.length === 0 ? null : (
248 <>
249 <Box marginTop={1}>
250 <Heading glyph={false}>EXAMPLES</Heading>
251 </Box>
252 {doc.examples.map((example) => (
253 <Text key={example.command}>
254 {" "}
255 <Text tone="brand">$</Text> <CommandText command={example.command} />
256 </Text>
257 ))}
258 </>
259 )}
260 {commands.length === 0 ? null : (
261 <Box marginTop={1}>
262 <Text>
263 <Text color={theme.color.muted}>Run '</Text>
264 <CommandText
265 command={`${doc.usage.replace(/\s*<subcommand>.*$/, "")} <command> --help`}
266 />
267 <Text color={theme.color.muted}>' for more information on a command.</Text>
268 </Text>
269 </Box>
270 )}
271 </Box>
272 );
273 }
274
275 const formatSubHelp = (cli: Interaction["Service"], doc: HelpDoc) => {
276 const termCols = cli.terminal.columns;
277 return formatView(
278 <Box width={termCols}>
279 <SubHelp doc={doc} />
280 </Box>,
281 cli.terminal,
282 { columns: termCols },
283 );
284 };
285
286 /** Hide the logo entirely when it can't be at least this many columns wide. */
287 const MIN_LOGO_COLS = 20;
288
289 const formatRootHelp = (cli: Interaction["Service"], doc: HelpDoc) => {
290 const termCols = cli.terminal.columns;
291
292 // First pass: render the text alone to measure its exact footprint (post
293 // ANSI codes and wrapping), then size the logo into the leftover space.
294 const text = formatView(
295 <Box width={termCols}>
296 <SubHelp doc={doc} root />
297 </Box>,
298 cli.terminal,
299 { columns: termCols },
300 );
301
302 // The braille logo is mojibake without Unicode support.
303 if (!cli.terminal.unicode) return text;
304
305 const lines = text.split("\n");
306 const textWidth = Math.max(
307 ...lines.map((line) => stripVTControlCharacters(line).trimEnd().length),
308 );
309 const textHeight = lines.length;
310
311 // Fill the free space beside the text: a logo of C columns is C/2 rows
312 // tall (braille cell is 1:2). Reserve two rows for the wordmark caption.
313 const logoCols = Math.min(termCols - textWidth - 2, (textHeight - 2) * 2);
314
315 if (logoCols < MIN_LOGO_COLS) return text;
316
317 return formatView(
318 <Box flexDirection="row" width={termCols}>
319 <SubHelp doc={doc} root />
320 <Box flexGrow={1} flexDirection="column" justifyContent="center" alignItems="center">
321 <Logo cols={logoCols} />
322 <Box marginTop={1}>
323 <Text>
324 <Text bold color={theme.color.accent}>
325 ALCHEMY
326 </Text>{" "}
327 <Text tone="muted">v{packageJson.version}</Text>
328 </Text>
329 </Box>
330 </Box>
331 </Box>,
332 cli.terminal,
333 { columns: termCols },
334 );
335 };
336
337 export const brandedCliFormatter = (cli: Interaction["Service"]): CliOutput.Formatter => {
338 const fallback = CliOutput.defaultFormatter();
339 const glyphs = glyphsFor(cli.terminal.unicode);
340 const formatErrorLine = (message: string) =>
341 `${paint(ansiFg(theme.color.danger), `${glyphs.error} error:`)} ${message}`;
342 return {
343 formatCliError: fallback.formatCliError,
344 formatHelpDoc: (doc) =>
345 doc.usage.startsWith("alchemy <subcommand>")
346 ? formatRootHelp(cli, doc)
347 : formatSubHelp(cli, doc),
348 formatVersion: (name, version) =>
349 `${paint(ansiFg(theme.color.brand), glyphs.selected)} ${paint(ANSI_BOLD, name)} ${paint(ANSI_DIM, `v${version}`)}`,
350 formatError: (error) => `\n${formatErrorLine(error.message)}`,
351 formatErrors: (errors) => {
352 if (errors.length === 0) return "";
353 if (errors.length === 1) return `\n${formatErrorLine(errors[0].message)}`;
354 return `\n${formatErrorLine(`${errors.length} problems`)}\n${errors
355 .map((error) => ` ${paint(ANSI_DIM, glyphs.bullet)} ${error.message}`)
356 .join("\n")}`;
357 },
358 };
359 };