@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
tsx 683 lines 22.1 KB
Raw
1 /** @jsxRuntime automatic */
2 /** @jsxImportSource @alchemy.run/sigil */
3 import { useEffect, useMemo, useState } from "@alchemy.run/sigil/react";
4 import type { ReactNode } from "react";
5 import type {
6 ConfirmOptions,
7 CycleSelectOptions,
8 MultiSelectOptions,
9 PasswordInputOptions,
10 Screen,
11 ScreenController,
12 SelectOptions,
13 TextInputOptions,
14 } from "../types.ts";
15 import { useGlyphs, useKeyGlyphs } from "../ui/Environment.tsx";
16 import { Alert } from "../ui/Feedback.tsx";
17 import {
18 ChoiceGroup,
19 filterChoices,
20 CycleList,
21 BrowserLoginWait,
22 type BrowserLoginWaitProps,
23 jumpSkippingDisabled,
24 Menu,
25 moveSkippingDisabled,
26 PromptFrame,
27 sanitizeTextInsert,
28 TextField,
29 useConfirmKeys,
30 useListNavigation,
31 useSelectedChoices,
32 useTerminalInput,
33 useTerminalPaste,
34 useTerminalSize,
35 useCycleNavigation,
36 type TerminalKey,
37 } from "../ui/Interactive.tsx";
38 import { Box } from "../ui/Layout.tsx";
39 import { AnsweredPrompt } from "../ui/Transcript.tsx";
40 import { Text } from "../ui/Typography.tsx";
41
42 const errorMessage = (value: string | Error | undefined) =>
43 value instanceof Error ? value.message : value;
44
45 const answerText = (value: string, maskGlyph?: string) => {
46 if (maskGlyph !== undefined) {
47 return maskGlyph.repeat(Math.min(value.length, 12));
48 }
49 return value || "(empty)";
50 };
51
52 /**
53 * Escape-to-cancel for standard prompts. Ctrl+C is handled centrally by the
54 * screen runner (SigilRuntime.run), so screens only wire Escape semantics.
55 */
56 const useCancel = (cancel: () => void) =>
57 useTerminalInput((_input, key) => {
58 if (key.escape) cancel();
59 });
60
61 /** One `Screen` factory shape shared by the non-generic prompt screens. */
62 const screen =
63 <Options, Value>(
64 name: string,
65 Component: (props: { readonly options: Options } & ScreenController<Value>) => ReactNode,
66 ) =>
67 (options: Options): Screen<Value> => ({
68 name,
69 render: (controller) => <Component options={options} {...controller} />,
70 });
71
72 /**
73 * Scaffolding shared by the select and multi-select prompts: cursor state
74 * clamped onto enabled rows, the navigation key ladder (arrows, `j`/`k` when
75 * not searchable, Home/End, PageUp/PageDown), Escape-clears-filter-then-
76 * cancels, filter editing, and bracketed paste into the filter. Callers run
77 * their own submit/toggle keys first and delegate the rest to `handleKey`.
78 */
79 const useChoiceList = ({
80 disabled,
81 searchable,
82 visibleCount,
83 query,
84 setQuery,
85 onCancel,
86 initialCursor = 0,
87 }: {
88 readonly disabled: ReadonlyArray<boolean>;
89 readonly searchable: boolean;
90 readonly visibleCount: number;
91 readonly query: string;
92 readonly setQuery: (query: string) => void;
93 readonly onCancel: () => void;
94 readonly initialCursor?: number;
95 }) => {
96 const { cursor, setCursor } = useListNavigation(disabled.length, initialCursor);
97 useEffect(() => {
98 setCursor((current) => {
99 if (disabled.length === 0) return 0;
100 const clamped = Math.min(current, disabled.length - 1);
101 if (!disabled[clamped]) return clamped;
102 const enabled = disabled.findIndex((value) => !value);
103 return enabled === -1 ? clamped : enabled;
104 });
105 }, [disabled, setCursor]);
106 const page = Math.max(1, visibleCount);
107 const resetFilter = (next: string) => {
108 setQuery(next);
109 setCursor(0);
110 };
111 /** Returns true when the keystroke was consumed. */
112 const handleKey = (input: string, key: TerminalKey): boolean => {
113 const plain = !key.ctrl && !key.meta;
114 if (key.up || (!searchable && plain && input === "k"))
115 setCursor(moveSkippingDisabled(disabled, cursor, -1));
116 else if (key.down || (!searchable && plain && input === "j"))
117 setCursor(moveSkippingDisabled(disabled, cursor, 1));
118 else if (key.home) setCursor(jumpSkippingDisabled(disabled, cursor, 0));
119 else if (key.end) setCursor(jumpSkippingDisabled(disabled, cursor, disabled.length - 1));
120 else if (key.pageUp) setCursor(jumpSkippingDisabled(disabled, cursor, cursor - page));
121 else if (key.pageDown) setCursor(jumpSkippingDisabled(disabled, cursor, cursor + page));
122 else if (key.escape) {
123 // An active filter absorbs the first Escape; the second cancels.
124 if (query !== "") resetFilter("");
125 else onCancel();
126 } else if (searchable && (key.backspace || key.delete)) resetFilter(query.slice(0, -1));
127 else if (searchable && plain && !key.tab) {
128 const typed = sanitizeTextInsert(input);
129 if (typed.length === 0) return false;
130 resetFilter(query + typed);
131 } else return false;
132 return true;
133 };
134 useTerminalPaste(
135 (pasted) => {
136 const typed = sanitizeTextInsert(pasted);
137 if (typed.length > 0) resetFilter(query + typed);
138 },
139 { active: searchable },
140 );
141 return { cursor, setCursor, handleKey } as const;
142 };
143
144 /**
145 * fzf-style query row for searchable lists: a `/` prefix, the typed text
146 * with a block cursor, and a right-hand annotation (match count, selection
147 * count). The row is always present so the list does not jump when the first
148 * character is typed.
149 */
150 function FilterLine({
151 query,
152 annotation,
153 }: {
154 readonly query: string;
155 readonly annotation: string;
156 }) {
157 return (
158 <Box gap={2}>
159 <Text>
160 <Text tone="muted">/ </Text>
161 {query === "" ? (
162 <Text tone="muted">type to filter</Text>
163 ) : (
164 <>
165 {query}
166 <Text inverse> </Text>
167 </>
168 )}
169 </Text>
170 <Text tone="muted">{annotation}</Text>
171 </Box>
172 );
173 }
174
175 type TextPromptProps = {
176 readonly options: TextInputOptions | PasswordInputOptions;
177 readonly mask?: boolean;
178 readonly submit: (value: string, summary?: ReactNode) => void;
179 readonly cancel: () => void;
180 };
181
182 function TextPrompt({ options, mask, submit, cancel }: TextPromptProps) {
183 const glyphs = useGlyphs();
184 const keys = useKeyGlyphs();
185 const maskGlyph = mask ? glyphs.mask : undefined;
186 const [error, setError] = useState<string>();
187 useCancel(cancel);
188 const defaultValue = "defaultValue" in options ? options.defaultValue : undefined;
189 const complete = (raw: string) => {
190 const value = raw === "" && defaultValue !== undefined ? defaultValue : raw;
191 const problem = errorMessage(options.validate?.(value));
192 if (problem !== undefined) setError(problem);
193 else
194 submit(
195 value,
196 <AnsweredPrompt message={options.message} answer={answerText(value, maskGlyph)} />,
197 );
198 };
199 return (
200 <PromptFrame
201 message={options.message}
202 description={options.description}
203 layout={options.layout ?? "inline"}
204 error={error}
205 keys={[
206 [keys.enter, "confirm"],
207 ...(defaultValue === undefined ? [] : ([[keys.tab, "fill default"]] as const)),
208 [keys.escape, "cancel"],
209 ]}
210 >
211 <TextField
212 // A default is the value Enter will submit, so show it in the empty
213 // field when the caller did not supply more specific hint text.
214 // Keep it a placeholder (rather than initialValue) so the first
215 // keystroke starts a replacement instead of appending to the default.
216 placeholder={options.placeholder ?? defaultValue}
217 completion={defaultValue}
218 initialValue={"initialValue" in options ? options.initialValue : undefined}
219 mask={maskGlyph}
220 ariaLabel={options.message}
221 onChange={() => setError(undefined)}
222 onSubmit={complete}
223 />
224 </PromptFrame>
225 );
226 }
227
228 export const textScreen = screen<TextInputOptions, string>("text input", TextPrompt);
229
230 export const passwordScreen = screen<PasswordInputOptions, string>("password input", (props) => (
231 <TextPrompt {...props} mask />
232 ));
233
234 type SelectPromptProps<Value> = {
235 readonly options: SelectOptions<Value>;
236 readonly submit: (value: Value, summary?: ReactNode) => void;
237 readonly cancel: () => void;
238 };
239
240 function SelectPrompt<Value>({ options, submit, cancel }: SelectPromptProps<Value>) {
241 const keys = useKeyGlyphs();
242 const { rows } = useTerminalSize();
243 const visibleCount = options.visibleCount ?? Math.max(3, Math.min(16, rows - 8));
244 const searchable = options.searchable === true;
245 const [query, setQuery] = useState("");
246 const filtered = useMemo(
247 () =>
248 searchable
249 ? filterChoices(options.options, query)
250 : options.options.map((choice, index) => ({ choice, index })),
251 [options.options, query, searchable],
252 );
253 const initialOriginalIndex = options.options.findIndex(
254 (choice) => choice.value === options.initialValue,
255 );
256 const initialIndex = filtered.findIndex(({ index }) => index === initialOriginalIndex);
257 const firstEnabled = filtered.findIndex(({ choice }) => !choice.disabled);
258 const disabled = useMemo(
259 () => filtered.map(({ choice }) => choice.disabled !== undefined && choice.disabled !== false),
260 [filtered],
261 );
262 const { cursor, handleKey } = useChoiceList({
263 disabled,
264 searchable,
265 visibleCount,
266 query,
267 setQuery,
268 onCancel: cancel,
269 initialCursor:
270 initialIndex !== -1 && !filtered[initialIndex]?.choice.disabled
271 ? initialIndex
272 : Math.max(0, firstEnabled),
273 });
274 useTerminalInput((input, key) => {
275 if (key.enter) {
276 const choice = filtered[cursor]?.choice;
277 if (choice !== undefined && !choice.disabled) {
278 submit(choice.value, <AnsweredPrompt message={options.message} answer={choice.label} />);
279 }
280 return;
281 }
282 handleKey(input, key);
283 });
284 return (
285 <PromptFrame
286 message={options.message}
287 keys={[
288 [keys.upDown, "navigate"],
289 [keys.enter, "select"],
290 [keys.escape, query === "" ? "cancel" : "clear filter"],
291 ]}
292 >
293 <Box flexDirection="column">
294 {searchable ? (
295 <FilterLine
296 query={query}
297 annotation={
298 query === ""
299 ? `${options.options.length} choices`
300 : `${filtered.length} of ${options.options.length}`
301 }
302 />
303 ) : null}
304 <Menu
305 choices={filtered.map(({ choice }) => choice)}
306 cursor={cursor}
307 visibleCount={visibleCount}
308 empty="No matching choices."
309 descriptionPlacement={options.descriptionPlacement}
310 />
311 </Box>
312 </PromptFrame>
313 );
314 }
315
316 export const selectScreen = <Value,>(options: SelectOptions<Value>): Screen<Value> => ({
317 name: "selection",
318 render: ({ submit, cancel }) => (
319 <SelectPrompt options={options} submit={submit} cancel={cancel} />
320 ),
321 });
322
323 type MultiSelectPromptProps<Value> = {
324 readonly options: MultiSelectOptions<Value>;
325 readonly submit: (value: ReadonlyArray<Value>, summary?: ReactNode) => void;
326 readonly cancel: () => void;
327 };
328
329 function MultiSelectPrompt<Value>({ options, submit, cancel }: MultiSelectPromptProps<Value>) {
330 const keys = useKeyGlyphs();
331 const { rows } = useTerminalSize();
332 const visibleCount = options.visibleCount ?? Math.max(3, Math.min(16, rows - 10));
333 const searchable = options.searchable === true;
334 const [query, setQuery] = useState("");
335 const filtered = useMemo(
336 () =>
337 searchable
338 ? filterChoices(options.options, query)
339 : options.options.map((choice, index) => ({ choice, index })),
340 [options.options, searchable, query],
341 );
342 const listRows = useMemo(() => {
343 const result: Array<
344 | {
345 readonly type: "group";
346 readonly label: string;
347 readonly indices: number[];
348 }
349 | {
350 readonly type: "choice";
351 readonly choice: (typeof filtered)[number]["choice"];
352 readonly index: number;
353 readonly nested: boolean;
354 }
355 > = [];
356 // Each contiguous run of a group gets its own header owning exactly the
357 // run's rows — a group split by ungrouped entries must not produce two
358 // headers that both toggle the whole group.
359 let currentGroup: string | undefined;
360 let currentHeader: { indices: number[] } | undefined;
361 for (const entry of filtered) {
362 const group = entry.choice.group;
363 if (group === undefined) {
364 currentHeader = undefined;
365 } else if (group !== currentGroup || currentHeader === undefined) {
366 const header = {
367 type: "group" as const,
368 label: group,
369 indices: [] as number[],
370 };
371 result.push(header);
372 currentHeader = header;
373 }
374 currentGroup = group;
375 if (group !== undefined && currentHeader !== undefined) {
376 currentHeader.indices.push(entry.index);
377 }
378 result.push({
379 type: "choice",
380 choice: entry.choice,
381 index: entry.index,
382 nested: group !== undefined,
383 });
384 }
385 return result;
386 }, [filtered]);
387 const [selected, setSelected] = useSelectedChoices(options.options, options.initialValues ?? []);
388 const [error, setError] = useState<string>();
389 const disabled = useMemo(
390 () =>
391 listRows.map((row) =>
392 row.type === "choice"
393 ? row.choice.disabled !== undefined && row.choice.disabled !== false
394 : row.indices.every((index) => Boolean(options.options[index]?.disabled)),
395 ),
396 [listRows, options.options],
397 );
398 const { cursor, handleKey } = useChoiceList({
399 disabled,
400 searchable,
401 visibleCount,
402 query,
403 setQuery,
404 onCancel: cancel,
405 });
406 useTerminalInput((input, key) => {
407 if (key.ctrl && input === "a") {
408 const enabledVisible = filtered.flatMap(({ choice, index }) =>
409 choice.disabled !== undefined && choice.disabled !== false ? [] : [index],
410 );
411 if (enabledVisible.length === 0) return;
412 setSelected((current) => {
413 const next = new Set(current);
414 const allSelected = enabledVisible.every((index) => next.has(index));
415 for (const index of enabledVisible) {
416 if (allSelected) next.delete(index);
417 else next.add(index);
418 }
419 return next;
420 });
421 setError(undefined);
422 } else if (input === " " && !key.ctrl && !key.meta) {
423 const row = listRows[cursor];
424 if (row === undefined) return;
425 const indices =
426 row.type === "group"
427 ? row.indices.filter((index) => !options.options[index]?.disabled)
428 : row.choice.disabled
429 ? []
430 : [row.index];
431 if (indices.length === 0) return;
432 setSelected((current) => {
433 const next = new Set(current);
434 const allSelected = indices.every((index) => next.has(index));
435 for (const index of indices) {
436 if (allSelected) next.delete(index);
437 else next.add(index);
438 }
439 return next;
440 });
441 setError(undefined);
442 } else if (key.enter) {
443 if (options.required && selected.size === 0) {
444 setError("Select at least one option.");
445 return;
446 }
447 const values = options.options.flatMap((choice, index) =>
448 selected.has(index) ? [choice.value] : [],
449 );
450 const labels = options.options.flatMap((choice, index) =>
451 selected.has(index) ? [choice.label] : [],
452 );
453 submit(
454 values,
455 <AnsweredPrompt
456 message={options.message}
457 answer={labels.length === 0 ? "none" : labels.join(", ")}
458 />,
459 );
460 } else if (handleKey(input, key)) {
461 setError(undefined);
462 }
463 });
464 const visibleChoices = listRows.map((row) =>
465 row.type === "group"
466 ? {
467 value: row,
468 label: row.label,
469 sticky: true,
470 tone: "info" as const,
471 }
472 : {
473 ...row.choice,
474 value: row,
475 group: undefined,
476 indent: row.nested ? 2 : row.choice.indent,
477 },
478 );
479 const visibleSelected = new Set(
480 listRows.flatMap((row, visibleIndex) => {
481 if (row.type !== "group") {
482 return selected.has(row.index) ? [visibleIndex] : [];
483 }
484 // Match the toggle semantics: disabled children are excluded there, so
485 // they must not keep a fully-toggled group from rendering as selected.
486 const toggleable = row.indices.filter((index) => !options.options[index]?.disabled);
487 return toggleable.length > 0 && toggleable.every((index) => selected.has(index))
488 ? [visibleIndex]
489 : [];
490 }),
491 );
492 return (
493 <PromptFrame
494 message={options.message}
495 error={error}
496 keys={[
497 [keys.upDown, "navigate"],
498 [keys.space, "toggle"],
499 ["ctrl+a", "toggle all"],
500 [keys.enter, "confirm"],
501 [keys.escape, query === "" ? "cancel" : "clear filter"],
502 ]}
503 >
504 <Box flexDirection="column">
505 {searchable ? (
506 <FilterLine
507 query={query}
508 annotation={
509 query === ""
510 ? `${selected.size} selected`
511 : `${filtered.length} of ${options.options.length} · ${selected.size} selected`
512 }
513 />
514 ) : (
515 <Text tone="muted">{selected.size} selected</Text>
516 )}
517 <Menu<(typeof listRows)[number]>
518 choices={visibleChoices}
519 cursor={cursor}
520 selected={visibleSelected}
521 visibleCount={visibleCount}
522 empty="No matching choices."
523 descriptionPlacement={options.descriptionPlacement}
524 />
525 </Box>
526 </PromptFrame>
527 );
528 }
529
530 export const multiSelectScreen = <Value,>(
531 options: MultiSelectOptions<Value>,
532 ): Screen<ReadonlyArray<Value>> => ({
533 name: "multiple selection",
534 render: ({ submit, cancel }) => (
535 <MultiSelectPrompt options={options} submit={submit} cancel={cancel} />
536 ),
537 });
538
539 type CycleSelectPromptProps<State> = {
540 readonly options: CycleSelectOptions<State>;
541 readonly submit: (value: ReadonlyArray<State>, summary?: ReactNode) => void;
542 readonly cancel: () => void;
543 };
544
545 function CycleSelectPrompt<State>({ options, submit, cancel }: CycleSelectPromptProps<State>) {
546 const keys = useKeyGlyphs();
547 const { rows } = useTerminalSize();
548 const visibleCount = options.visibleCount ?? Math.max(3, Math.min(16, rows - 8));
549 const navigation = useCycleNavigation(options.options.map((choice) => choice.states.length));
550 const [unchanged, setUnchanged] = useState(false);
551 useCancel(cancel);
552 const last = Math.max(0, options.options.length - 1);
553 const page = Math.max(1, visibleCount);
554 useTerminalInput((input, key) => {
555 const plain = !key.ctrl && !key.meta;
556 if (key.up || (plain && input === "k")) navigation.move(-1);
557 else if (key.down || (plain && input === "j")) navigation.move(1);
558 else if (key.home) navigation.setCursor(0);
559 else if (key.end) navigation.setCursor(last);
560 else if (key.pageUp) navigation.setCursor(Math.max(0, navigation.cursor - page));
561 else if (key.pageDown) navigation.setCursor(Math.min(last, navigation.cursor + page));
562 else if ((plain && input === " ") || key.right) {
563 navigation.cycle(1);
564 setUnchanged(false);
565 } else if (key.left) {
566 navigation.cycle(-1);
567 setUnchanged(false);
568 } else if (key.enter) {
569 if (options.requireChange && navigation.indices.every((index) => index === 0)) {
570 setUnchanged(true);
571 return;
572 }
573 const values = options.options.flatMap((choice, index) => {
574 const state = choice.states[navigation.indices[index] ?? 0];
575 return state === undefined ? [] : [state.value];
576 });
577 const changed = options.options.flatMap((choice, index) => {
578 if ((navigation.indices[index] ?? 0) === 0) return [];
579 const state = choice.states[navigation.indices[index] ?? 0];
580 return state === undefined ? [] : [`${choice.label}: ${state.label ?? "changed"}`];
581 });
582 submit(
583 values,
584 <AnsweredPrompt
585 message={options.message}
586 answer={changed.length === 0 ? "no changes" : changed.join(", ")}
587 />,
588 );
589 }
590 });
591 return (
592 <PromptFrame
593 message={options.message}
594 keys={[
595 [keys.upDown, "navigate"],
596 [keys.space, "change"],
597 [keys.enter, options.requireChange ? "apply" : "confirm"],
598 [keys.escape, options.requireChange ? "back" : "cancel"],
599 ]}
600 >
601 <Box flexDirection="column">
602 <CycleList
603 choices={options.options}
604 cursor={navigation.cursor}
605 indices={navigation.indices}
606 visibleCount={visibleCount}
607 />
608 {unchanged ? (
609 <Alert variant="warning" title="No changes to apply">
610 {options.unchangedMessage ?? "Press Space to change a selection, or Esc to go back."}
611 </Alert>
612 ) : null}
613 </Box>
614 </PromptFrame>
615 );
616 }
617
618 export const cycleSelectScreen = <State,>(
619 options: CycleSelectOptions<State>,
620 ): Screen<ReadonlyArray<State>> => ({
621 name: "cycle selection",
622 render: ({ submit, cancel }) => (
623 <CycleSelectPrompt options={options} submit={submit} cancel={cancel} />
624 ),
625 });
626
627 export const browserLoginScreen = screen<
628 Omit<BrowserLoginWaitProps, "onSubmit" | "onCancel">,
629 string
630 >("browser login", ({ options, submit, cancel }) => (
631 <BrowserLoginWait {...options} onSubmit={submit} onCancel={cancel} />
632 ));
633
634 type ConfirmPromptProps = {
635 readonly options: ConfirmOptions;
636 readonly submit: (value: boolean, summary?: ReactNode) => void;
637 readonly cancel: () => void;
638 };
639
640 function ConfirmPrompt({ options, submit, cancel }: ConfirmPromptProps) {
641 const keys = useKeyGlyphs();
642 const complete = (answer: boolean) =>
643 submit(
644 answer,
645 <AnsweredPrompt
646 message={options.message}
647 answer={answer ? (options.confirmLabel ?? "yes") : (options.cancelLabel ?? "no")}
648 />,
649 );
650 const value = useConfirmKeys({
651 // Default to "no": most CLI confirms gate destructive operations, so an
652 // absent-minded Enter must never approve one. Benign convenience prompts
653 // opt into default-yes with an explicit `initialValue: true`.
654 initialValue: options.initialValue ?? false,
655 onSubmit: complete,
656 onCancel: cancel,
657 });
658 return (
659 <PromptFrame
660 message={options.message}
661 keys={[
662 [
663 options.confirmLabel === undefined && options.cancelLabel === undefined
664 ? keys.yesNo
665 : keys.leftRight,
666 "choose",
667 ],
668 [keys.enter, "confirm"],
669 [keys.escape, "cancel"],
670 ]}
671 >
672 <ChoiceGroup
673 value={value}
674 choices={[
675 { value: true, label: options.confirmLabel ?? "Yes" },
676 { value: false, label: options.cancelLabel ?? "No" },
677 ]}
678 />
679 </PromptFrame>
680 );
681 }
682
683 export const confirmScreen = screen<ConfirmOptions, boolean>("confirmation", ConfirmPrompt);