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

main
tsx 1,057 lines 34.8 KB
Raw
1 /** @jsxRuntime automatic */
2 /** @jsxImportSource @alchemy.run/sigil */
3 import { useEffect, useMemo, useState, useSyncExternalStore } from "@alchemy.run/sigil/react";
4 import * as Cause from "effect/Cause";
5 import * as Context from "effect/Context";
6 import * as Effect from "effect/Effect";
7 import * as Exit from "effect/Exit";
8 import type * as Fiber from "effect/Fiber";
9 import * as Option from "effect/Option";
10 import type { JSX } from "react";
11 import { Screen, type ScreenController } from "../../../Interaction.ts";
12 import type { InvalidStatePath, StateStoreError } from "../../../State/index.ts";
13 import { theme } from "../../../Util/Theme.ts";
14 import { formatYamlLines, matchYamlKey } from "../../PropertyDiff.ts";
15 import {
16 Box,
17 KeyBar,
18 Spinner,
19 Text,
20 TextField,
21 Viewport,
22 useBorderStyle,
23 useCliEnvironment,
24 useKeyGlyphs,
25 useTerminalInput,
26 useTerminalSize,
27 } from "../ui/index.ts";
28
29 export type StateFileRef =
30 | {
31 readonly kind: "resource";
32 readonly stack: string;
33 readonly stage: string;
34 readonly fqn: string;
35 }
36 | {
37 readonly kind: "output";
38 readonly stack: string;
39 readonly stage: string;
40 };
41
42 export type StateExplorerError = InvalidStatePath | StateStoreError;
43
44 export interface StateExplorerSource {
45 readonly backend: string;
46 readonly listStacks: Effect.Effect<ReadonlyArray<string>, StateExplorerError>;
47 readonly listStages: (stack: string) => Effect.Effect<ReadonlyArray<string>, StateExplorerError>;
48 readonly listResources: (
49 stack: string,
50 stage: string,
51 ) => Effect.Effect<ReadonlyArray<string>, StateExplorerError>;
52 readonly readFile: (file: StateFileRef) => Effect.Effect<unknown, StateExplorerError>;
53 readonly deleteNodes: (
54 nodes: ReadonlyArray<StateBrowserNode>,
55 ) => Effect.Effect<void, StateExplorerError>;
56 }
57
58 export type StateBrowserNode =
59 | {
60 readonly kind: "stack";
61 readonly id: string;
62 readonly name: string;
63 readonly path: string;
64 readonly stack: string;
65 }
66 | {
67 readonly kind: "stage";
68 readonly id: string;
69 readonly name: string;
70 readonly path: string;
71 readonly stack: string;
72 readonly stage: string;
73 }
74 | {
75 readonly kind: "namespace";
76 readonly id: string;
77 readonly name: string;
78 readonly path: string;
79 readonly stack: string;
80 readonly stage: string;
81 readonly children: ReadonlyArray<StateBrowserNode>;
82 }
83 | {
84 readonly kind: "resource";
85 readonly id: string;
86 readonly name: string;
87 readonly path: string;
88 readonly file: StateFileRef & { readonly kind: "resource" };
89 }
90 | {
91 readonly kind: "output";
92 readonly id: string;
93 readonly name: string;
94 readonly path: string;
95 readonly file: StateFileRef & { readonly kind: "output" };
96 };
97
98 type LoadState<Value> =
99 | { readonly status: "idle" }
100 | { readonly status: "loading" }
101 | { readonly status: "ready"; readonly value: Value }
102 | { readonly status: "error"; readonly message: string };
103
104 interface ExplorerSnapshot {
105 readonly root: LoadState<ReadonlyArray<StateBrowserNode>>;
106 readonly children: ReadonlyMap<string, LoadState<ReadonlyArray<StateBrowserNode>>>;
107 readonly files: ReadonlyMap<string, LoadState<unknown>>;
108 }
109
110 const errorMessage = (error: StateExplorerError) =>
111 error._tag === "InvalidStatePath" ? `${error.path}: ${error.reason}` : error.message;
112
113 const causeMessage = (cause: Cause.Cause<StateExplorerError>) =>
114 Option.match(Cause.findErrorOption(cause), {
115 onSome: errorMessage,
116 onNone: () => {
117 const defect = Cause.squash(cause);
118 return defect instanceof Error ? defect.message : String(defect);
119 },
120 });
121
122 /** Mutable async cache: every state-store read is initiated by a selection. */
123 export class StateExplorerStore {
124 private state: ExplorerSnapshot = {
125 root: { status: "idle" },
126 children: new Map(),
127 files: new Map(),
128 };
129 private readonly listeners = new Set<() => void>();
130 private readonly fibers = new Set<Fiber.Fiber<unknown, unknown>>();
131
132 constructor(
133 readonly source: StateExplorerSource,
134 private readonly services: Context.Context<never> = Context.empty(),
135 ) {}
136
137 readonly subscribe = (listener: () => void) => {
138 this.listeners.add(listener);
139 return () => this.listeners.delete(listener);
140 };
141 readonly snapshot = () => this.state;
142 private commit(next: ExplorerSnapshot) {
143 this.state = next;
144 for (const listener of this.listeners) listener();
145 }
146
147 /**
148 * Fork the effect in the CLI's ambient services and hand its exit to the
149 * caller. A fiber the store no longer tracks — dropped by `refresh` or
150 * `dispose` — is stale, and its result is discarded even if it managed to
151 * complete before the interrupt landed.
152 */
153 private run<A>(
154 effect: Effect.Effect<A, StateExplorerError>,
155 handlers: {
156 readonly onSuccess: (value: A) => void;
157 readonly onFailure: (message: string) => void;
158 },
159 ) {
160 const fiber = Effect.runForkWith(this.services)(effect);
161 this.fibers.add(fiber);
162 fiber.addObserver((exit) => {
163 if (!this.fibers.delete(fiber)) return;
164 if (Exit.isSuccess(exit)) handlers.onSuccess(exit.value);
165 else if (!Cause.hasInterrupts(exit.cause)) handlers.onFailure(causeMessage(exit.cause));
166 });
167 }
168
169 private interruptAll() {
170 for (const fiber of this.fibers) fiber.interruptUnsafe();
171 this.fibers.clear();
172 }
173
174 readonly loadRoot = () => {
175 if (this.state.root.status !== "idle") return;
176 this.commit({ ...this.state, root: { status: "loading" } });
177 this.run(this.source.listStacks, {
178 onSuccess: (stacks) => {
179 this.commit({
180 ...this.state,
181 root: {
182 status: "ready",
183 value: [...stacks].sort().map((stack) => ({
184 kind: "stack",
185 id: `stack:${stack}`,
186 name: stack,
187 path: stack,
188 stack,
189 })),
190 },
191 });
192 },
193 onFailure: (message) => {
194 this.commit({ ...this.state, root: { status: "error", message } });
195 },
196 });
197 };
198
199 readonly refresh = () => {
200 this.interruptAll();
201 this.commit({
202 root: { status: "idle" },
203 children: new Map(),
204 files: new Map(),
205 });
206 this.loadRoot();
207 };
208
209 /**
210 * Re-list only what a deletion could have changed — the parent listing of
211 * each target — and drop cached files under it. Every other cached column
212 * survives, so the explorer keeps its position instead of collapsing to
213 * the stack list the way `refresh` does.
214 */
215 readonly invalidate = (targets: ReadonlyArray<StateBrowserNode>) => {
216 const children = new Map(this.state.children);
217 const files = new Map(this.state.files);
218 const parents = new Map<string, StateBrowserNode | undefined>();
219 for (const target of targets) {
220 for (const id of files.keys()) {
221 if (id.slice(id.indexOf(":") + 1).startsWith(`${target.path}/`)) files.delete(id);
222 }
223 if (target.kind === "stack") {
224 for (const id of children.keys()) {
225 if (id === `stack:${target.stack}` || id.startsWith(`stage:${target.stack}/`))
226 children.delete(id);
227 }
228 parents.set("root", undefined);
229 } else if (target.kind === "stage") {
230 children.delete(target.id);
231 parents.set(`stack:${target.stack}`, {
232 kind: "stack",
233 id: `stack:${target.stack}`,
234 name: target.stack,
235 path: target.stack,
236 stack: target.stack,
237 });
238 } else if (target.kind !== "output") {
239 const { stack, stage } = target.kind === "resource" ? target.file : target;
240 parents.set(`stage:${stack}/${stage}`, {
241 kind: "stage",
242 id: `stage:${stack}/${stage}`,
243 name: stage,
244 path: `${stack}/${stage}`,
245 stack,
246 stage,
247 });
248 }
249 }
250 for (const id of parents.keys()) {
251 if (id !== "root") children.delete(id);
252 }
253 this.commit({
254 ...this.state,
255 root: parents.has("root") ? { status: "idle" } : this.state.root,
256 children,
257 files,
258 });
259 for (const parent of parents.values()) {
260 if (parent === undefined) this.loadRoot();
261 else this.loadChildren(parent);
262 }
263 };
264
265 readonly loadChildren = (node: StateBrowserNode) => {
266 if (node.kind === "namespace" || node.kind === "resource" || node.kind === "output") {
267 return;
268 }
269 if ((this.state.children.get(node.id)?.status ?? "idle") !== "idle") return;
270 const children = new Map(this.state.children);
271 children.set(node.id, { status: "loading" });
272 this.commit({ ...this.state, children });
273
274 const request =
275 node.kind === "stack"
276 ? Effect.map(this.source.listStages(node.stack), (stages) =>
277 [...stages].sort().map((stage): StateBrowserNode => ({
278 kind: "stage",
279 id: `stage:${node.stack}/${stage}`,
280 name: stage,
281 path: `${node.stack}/${stage}`,
282 stack: node.stack,
283 stage,
284 })),
285 )
286 : Effect.map(this.source.listResources(node.stack, node.stage!), (fqns) =>
287 buildStageNodes(node.stack, node.stage!, fqns),
288 );
289 this.run(request, {
290 onSuccess: (value) => {
291 const next = new Map(this.state.children);
292 next.set(node.id, { status: "ready", value });
293 this.commit({ ...this.state, children: next });
294 },
295 onFailure: (message) => {
296 const next = new Map(this.state.children);
297 next.set(node.id, { status: "error", message });
298 this.commit({ ...this.state, children: next });
299 },
300 });
301 };
302
303 readonly loadFile = (node: StateBrowserNode) => {
304 if (node.kind !== "resource" && node.kind !== "output") return;
305 if ((this.state.files.get(node.id)?.status ?? "idle") !== "idle") return;
306 const files = new Map(this.state.files);
307 files.set(node.id, { status: "loading" });
308 this.commit({ ...this.state, files });
309 this.run(this.source.readFile(node.file), {
310 onSuccess: (value) => {
311 const next = new Map(this.state.files);
312 next.set(node.id, { status: "ready", value });
313 this.commit({ ...this.state, files: next });
314 },
315 onFailure: (message) => {
316 const next = new Map(this.state.files);
317 next.set(node.id, { status: "error", message });
318 this.commit({ ...this.state, files: next });
319 },
320 });
321 };
322
323 readonly deleteNodes = (
324 targets: ReadonlyArray<StateBrowserNode>,
325 handlers: {
326 readonly onSuccess: () => void;
327 readonly onFailure: (message: string) => void;
328 },
329 ) => this.run(this.source.deleteNodes(targets), handlers);
330
331 readonly dispose = () => {
332 this.interruptAll();
333 this.listeners.clear();
334 };
335 }
336
337 interface MutableNamespace {
338 readonly name: string;
339 readonly path: string;
340 readonly children: Map<string, MutableNamespace>;
341 readonly files: StateBrowserNode[];
342 }
343
344 /** Convert listed FQNs to namespace columns without reading any state values. */
345 export const buildStageNodes = (
346 stack: string,
347 stage: string,
348 fqns: ReadonlyArray<string>,
349 ): ReadonlyArray<StateBrowserNode> => {
350 const root: MutableNamespace = {
351 name: "",
352 path: `${stack}/${stage}`,
353 children: new Map(),
354 files: [],
355 };
356 for (const fqn of [...fqns].sort()) {
357 const parts = fqn.split("/").filter(Boolean);
358 let current = root;
359 for (const part of parts.slice(0, -1)) {
360 let child = current.children.get(part);
361 if (child === undefined) {
362 child = {
363 name: part,
364 path: `${current.path}/${part}`,
365 children: new Map(),
366 files: [],
367 };
368 current.children.set(part, child);
369 }
370 current = child;
371 }
372 const name = parts.at(-1) ?? fqn;
373 current.files.push({
374 kind: "resource",
375 id: `resource:${stack}/${stage}/${fqn}`,
376 name,
377 path: `${stack}/${stage}/${fqn}`,
378 file: { kind: "resource", stack, stage, fqn },
379 });
380 }
381
382 const freeze = (namespace: MutableNamespace): StateBrowserNode[] => [
383 ...[...namespace.children.values()]
384 .sort((a, b) => a.name.localeCompare(b.name))
385 .map((child): StateBrowserNode => ({
386 kind: "namespace",
387 id: `namespace:${child.path}`,
388 name: child.name,
389 path: child.path,
390 stack,
391 stage,
392 children: freeze(child),
393 })),
394 ...namespace.files,
395 ];
396 return [
397 ...freeze(root),
398 {
399 kind: "output",
400 id: `output:${stack}/${stage}`,
401 name: "output",
402 path: `${stack}/${stage}/output`,
403 file: { kind: "output", stack, stage },
404 },
405 ];
406 };
407
408 const nodeStyle: Record<
409 StateBrowserNode["kind"],
410 { readonly color: string; readonly icon: string; readonly asciiIcon: string }
411 > = {
412 stack: { color: theme.color.brand, icon: "◆", asciiIcon: "#" },
413 stage: { color: theme.color.warning, icon: "●", asciiIcon: "@" },
414 namespace: { color: theme.color.accent, icon: "▸", asciiIcon: ">" },
415 resource: { color: theme.color.info, icon: "▪", asciiIcon: "-" },
416 output: { color: theme.color.success, icon: "◇", asciiIcon: "=" },
417 };
418
419 const childrenFor = (
420 node: StateBrowserNode,
421 state: ExplorerSnapshot,
422 ): LoadState<ReadonlyArray<StateBrowserNode>> | undefined =>
423 node.kind === "namespace"
424 ? { status: "ready", value: node.children }
425 : node.kind === "stack" || node.kind === "stage"
426 ? (state.children.get(node.id) ?? { status: "idle" })
427 : undefined;
428
429 interface BrowserColumn {
430 readonly id: string;
431 readonly title: string;
432 readonly state: LoadState<ReadonlyArray<StateBrowserNode>>;
433 }
434
435 const buildColumns = (
436 state: ExplorerSnapshot,
437 selection: ReadonlyArray<string>,
438 ): BrowserColumn[] => {
439 const columns: BrowserColumn[] = [{ id: "root", title: "Stacks", state: state.root }];
440 let current = state.root;
441 for (let depth = 0; depth < selection.length; depth++) {
442 if (current.status !== "ready") break;
443 const selected = current.value.find((node) => node.id === selection[depth]);
444 if (selected === undefined) break;
445 const children = childrenFor(selected, state);
446 if (children === undefined) break;
447 columns.push({
448 id: selected.id,
449 title:
450 selected.kind === "stack" ? "Stages" : selected.kind === "stage" ? "State" : selected.name,
451 state: children,
452 });
453 current = children;
454 }
455 return columns;
456 };
457
458 type ColumnProps = {
459 readonly column: BrowserColumn;
460 readonly selected: string | undefined;
461 readonly focused: boolean;
462 readonly height: number;
463 readonly query: string;
464 readonly marked: ReadonlySet<string>;
465 };
466
467 function Column({ column, selected, focused, height, query, marked }: ColumnProps) {
468 const { unicode } = useCliEnvironment();
469 const borderStyle = useBorderStyle();
470 if (column.state.status === "idle" || column.state.status === "loading") {
471 return <Spinner label="Loading" />;
472 }
473 if (column.state.status === "error") {
474 return <Text tone="danger">{column.state.message}</Text>;
475 }
476 const needle = query.trim().toLowerCase();
477 const items =
478 needle === ""
479 ? column.state.value
480 : column.state.value.filter((node) => node.path.toLowerCase().includes(needle));
481 const selectedIndex = Math.max(
482 0,
483 items.findIndex((node) => node.id === selected),
484 );
485 return (
486 <Viewport
487 items={items}
488 cursor={selectedIndex}
489 height={height}
490 getKey={(node) => node.id}
491 empty={<Text tone="muted">No matches.</Text>}
492 renderItem={(node) => {
493 const active = node.id === selected;
494 const style = nodeStyle[node.kind];
495 return (
496 <Box
497 width="100%"
498 paddingLeft={active ? 0 : 1}
499 borderStyle={borderStyle}
500 borderLeft={active}
501 borderRight={false}
502 borderTop={false}
503 borderBottom={false}
504 borderColor={focused ? theme.color.accent : theme.color.muted}
505 >
506 <Box width={2} flexShrink={0}>
507 <Text color={style.color}>
508 {marked.has(node.id)
509 ? unicode
510 ? "● "
511 : "* "
512 : `${unicode ? style.icon : style.asciiIcon} `}
513 </Text>
514 </Box>
515 <Text
516 bold={active}
517 color={
518 active ? (focused ? theme.color.accentBright : theme.color.emphasis) : undefined
519 }
520 wrap="truncate-end"
521 >
522 {node.name}
523 </Text>
524 {(node.kind === "stack" || node.kind === "stage" || node.kind === "namespace") && (
525 <Box flexGrow={1} justifyContent="flex-end">
526 <Text tone="muted">{unicode ? "›" : ">"}</Text>
527 </Box>
528 )}
529 </Box>
530 );
531 }}
532 />
533 );
534 }
535
536 type YamlLineProps = { readonly line: string };
537
538 function YamlLine({ line }: YamlLineProps) {
539 const key = matchYamlKey(line);
540 if (key !== undefined) {
541 return (
542 <Text wrap="truncate-end">
543 {key.indent}
544 <Text color={theme.color.info}>{key.key}</Text>
545 <YamlValue value={key.value} />
546 </Text>
547 );
548 }
549 return (
550 <Text wrap="truncate-end">
551 <YamlValue value={line} />
552 </Text>
553 );
554 }
555
556 type YamlValueProps = { readonly value: string };
557
558 function YamlValue({ value }: YamlValueProps) {
559 const trimmed = value.trimStart();
560 const color = /^(["'])/.test(trimmed)
561 ? theme.color.success
562 : /^(true|false)/.test(trimmed)
563 ? theme.color.accent
564 : /^-?\d/.test(trimmed)
565 ? theme.color.warning
566 : trimmed.startsWith("null")
567 ? theme.color.danger
568 : undefined;
569 return <Text color={color}>{value}</Text>;
570 }
571
572 type PreviewProps = {
573 readonly node: StateBrowserNode | undefined;
574 readonly state: LoadState<unknown> | undefined;
575 readonly lines: ReadonlyArray<string> | undefined;
576 readonly offset: number;
577 readonly height: number;
578 };
579
580 function Preview({ node, state, lines = [], offset, height }: PreviewProps) {
581 if (node === undefined || (node.kind !== "resource" && node.kind !== "output")) {
582 return <Text tone="muted">Select a state file to preview it.</Text>;
583 }
584 if (state === undefined || state.status === "idle" || state.status === "loading") {
585 return <Spinner label="Reading state" detail={node.name} />;
586 }
587 if (state.status === "error") return <Text tone="danger">{state.message}</Text>;
588 if (state.value === undefined) {
589 return <Text tone="muted">No stored value.</Text>;
590 }
591 const bodyHeight = Math.max(1, height - 2);
592 const start = Math.max(0, Math.min(offset, Math.max(0, lines.length - bodyHeight)));
593 return (
594 <Box flexDirection="column" height={height}>
595 <Text bold color={nodeStyle[node.kind].color} wrap="truncate-middle">
596 {node.path}
597 </Text>
598 <Box flexDirection="column">
599 {lines.slice(start, start + bodyHeight).map((line, index) => (
600 <YamlLine key={`${start + index}:${line}`} line={line} />
601 ))}
602 </Box>
603 </Box>
604 );
605 }
606
607 function StateExplorer({
608 store,
609 controller,
610 }: {
611 readonly store: StateExplorerStore;
612 readonly controller: ScreenController<void>;
613 }): JSX.Element {
614 const state = useSyncExternalStore(store.subscribe, store.snapshot);
615 const [selection, setSelection] = useState<ReadonlyArray<string>>([]);
616 const [columnIndex, setColumnIndex] = useState(0);
617 const [query, setQuery] = useState("");
618 const [searching, setSearching] = useState(false);
619 const [previewOffset, setPreviewOffset] = useState(0);
620 const [previewFocused, setPreviewFocused] = useState(false);
621 const [marked, setMarked] = useState<ReadonlyMap<string, StateBrowserNode>>(new Map());
622 const [deletion, setDeletion] = useState<
623 | {
624 readonly status: "confirm" | "deleting";
625 readonly targets: ReadonlyArray<StateBrowserNode>;
626 }
627 | {
628 readonly status: "error";
629 readonly message: string;
630 readonly targets: ReadonlyArray<StateBrowserNode>;
631 }
632 >();
633 const [notice, setNotice] = useState<string>();
634 const { columns: terminalColumns, rows: terminalRows } = useTerminalSize();
635 const borderStyle = useBorderStyle();
636 const keys = useKeyGlyphs();
637
638 useEffect(() => {
639 store.loadRoot();
640 return store.dispose;
641 }, [store]);
642 const columns = useMemo(() => buildColumns(state, selection), [selection, state]);
643 const markedIds = useMemo(() => new Set(marked.keys()), [marked]);
644 const activeColumn = Math.min(columnIndex, columns.length - 1);
645 const column = columns[activeColumn]!;
646 const filteredItems =
647 column.state.status !== "ready"
648 ? []
649 : query.trim() === ""
650 ? column.state.value
651 : column.state.value.filter((node) =>
652 node.path.toLowerCase().includes(query.trim().toLowerCase()),
653 );
654 const selectedId = selection[activeColumn];
655 const selectedIndex = filteredItems.findIndex((node) => node.id === selectedId);
656 const selected = filteredItems[selectedIndex];
657 const lastSelected = (() => {
658 for (let index = columns.length - 1; index >= 0; index--) {
659 const candidate = columns[index];
660 if (candidate?.state.status !== "ready") continue;
661 const node = candidate.state.value.find((item) => item.id === selection[index]);
662 if (node !== undefined) return node;
663 }
664 return undefined;
665 })();
666 const file =
667 lastSelected?.kind === "resource" || lastSelected?.kind === "output" ? lastSelected : undefined;
668 const fileState = file === undefined ? undefined : state.files.get(file.id);
669 // The delete prompt replaces the key bar (a margin row + the keys) with a
670 // bordered panel: border, header line, one line per target (capped, with
671 // a "+N more" line), and its own key bar. KeyBar is a full-width block,
672 // so it gets its own row rather than sharing one with the header.
673 const promptTargets = deletion === undefined ? [] : deletion.targets.slice(0, MAX_PROMPT_TARGETS);
674 const promptOverflow =
675 deletion === undefined ? 0 : deletion.targets.length - promptTargets.length;
676 const footerHeight =
677 deletion === undefined ? 2 : 3 + promptTargets.length + (promptOverflow > 0 ? 1 : 0);
678 const contentHeight = Math.max(6, terminalRows - 8 - footerHeight);
679 const previewLines = useMemo(
680 () =>
681 fileState?.status === "ready" && fileState.value !== undefined
682 ? formatYamlLines(fileState.value)
683 : undefined,
684 [fileState],
685 );
686 const maxPreviewOffset =
687 previewLines === undefined
688 ? 0
689 : Math.max(0, previewLines.length - Math.max(1, contentHeight - 2));
690
691 const choose = (index: number, node: StateBrowserNode) => {
692 setSelection((current) => [...current.slice(0, index), node.id]);
693 setPreviewOffset(0);
694 if (node.kind === "resource" || node.kind === "output") store.loadFile(node);
695 else store.loadChildren(node);
696 };
697 const move = (delta: number) => {
698 if (filteredItems.length === 0) return;
699 const next =
700 selectedIndex < 0
701 ? delta < 0
702 ? filteredItems.length - 1
703 : 0
704 : Math.max(0, Math.min(filteredItems.length - 1, selectedIndex + delta));
705 choose(activeColumn, filteredItems[next]!);
706 };
707
708 const beginDelete = () => {
709 const targets = marked.size > 0 ? [...marked.values()] : selected ? [selected] : [];
710 if (targets.length === 0) return;
711 if (targets.some((node) => node.kind === "output")) {
712 setDeletion({
713 status: "error",
714 message: "output cannot be deleted independently",
715 targets,
716 });
717 return;
718 }
719 setDeletion({ status: "confirm", targets });
720 };
721
722 const confirmDelete = () => {
723 if (deletion === undefined || deletion.status === "deleting") return;
724 const targets = deletion.targets;
725 const deletes = (node: StateBrowserNode) =>
726 targets.some((target) => node.id === target.id || node.path.startsWith(`${target.path}/`));
727 // The shallowest column whose selected node is going away: the cursor
728 // moves there, onto the next surviving sibling (or the previous one).
729 // Deeper selection is dropped; everything above it is untouched.
730 const landing = (() => {
731 for (let index = 0; index < columns.length; index++) {
732 const column = columns[index]!;
733 if (column.state.status !== "ready") return undefined;
734 const items = column.state.value;
735 const position = items.findIndex((node) => node.id === selection[index]);
736 if (position < 0 || !deletes(items[position]!)) continue;
737 const fallback =
738 items.slice(position + 1).find((node) => !deletes(node)) ??
739 items.slice(0, position).findLast((node) => !deletes(node));
740 return { index, fallback };
741 }
742 return undefined;
743 })();
744 setDeletion({ status: "deleting", targets });
745 store.deleteNodes(targets, {
746 onSuccess: () => {
747 setDeletion(undefined);
748 setMarked(new Map());
749 if (landing !== undefined) {
750 setSelection((current) =>
751 landing.fallback === undefined
752 ? current.slice(0, landing.index)
753 : [...current.slice(0, landing.index), landing.fallback.id],
754 );
755 setColumnIndex(landing.index);
756 setPreviewOffset(0);
757 setPreviewFocused(false);
758 }
759 setNotice(
760 `Deleted state at ${targets.map((target) => `${target.path}${target.kind === "resource" ? "" : "/"}`).join(", ")}`,
761 );
762 store.invalidate(targets);
763 },
764 onFailure: (message) => setDeletion({ status: "error", message, targets }),
765 });
766 };
767
768 useTerminalInput(
769 (input, key) => {
770 if (deletion !== undefined) {
771 if (deletion.status === "deleting") return;
772 if (key.escape || input === "n" || input === "q") setDeletion(undefined);
773 else if (deletion.status === "confirm" && input === "y") confirmDelete();
774 return;
775 }
776 if (input === "q") return controller.submit(undefined);
777 if (key.escape) {
778 if (query !== "") setQuery("");
779 else controller.submit(undefined);
780 return;
781 }
782 if (!key.ctrl && !key.meta && input === "/") {
783 setSearching(true);
784 setPreviewFocused(false);
785 return;
786 }
787 if (!key.ctrl && !key.meta && input === "r") {
788 setSelection([]);
789 setColumnIndex(0);
790 setPreviewFocused(false);
791 setNotice(undefined);
792 store.refresh();
793 return;
794 }
795 if (input === " " && selected !== undefined) {
796 setMarked((current) => {
797 const next = new Map(current);
798 if (next.has(selected.id)) next.delete(selected.id);
799 else next.set(selected.id, selected);
800 return next;
801 });
802 return;
803 }
804 if (input === "d") {
805 beginDelete();
806 return;
807 }
808 if (key.tab) {
809 if (file !== undefined) setPreviewFocused((current) => !current);
810 return;
811 }
812 if (previewFocused) {
813 if (key.left) setPreviewFocused(false);
814 else if (key.up) setPreviewOffset((value) => Math.max(0, value - 1));
815 else if (key.down) setPreviewOffset((value) => Math.min(maxPreviewOffset, value + 1));
816 else if (key.pageUp) setPreviewOffset((value) => Math.max(0, value - contentHeight));
817 else if (key.pageDown)
818 setPreviewOffset((value) => Math.min(maxPreviewOffset, value + contentHeight));
819 else if (key.home) setPreviewOffset(0);
820 else if (key.end) setPreviewOffset(maxPreviewOffset);
821 return;
822 }
823 if (key.up || input === "k") move(-1);
824 else if (key.down || input === "j") move(1);
825 else if (key.home && filteredItems[0]) choose(activeColumn, filteredItems[0]);
826 else if (key.end && filteredItems.at(-1)) choose(activeColumn, filteredItems.at(-1)!);
827 else if (key.left && activeColumn > 0) setColumnIndex(activeColumn - 1);
828 else if (key.right || key.enter) {
829 if (selected === undefined) return;
830 choose(activeColumn, selected);
831 if (selected.kind === "resource" || selected.kind === "output") {
832 setPreviewFocused(true);
833 } else {
834 setColumnIndex(activeColumn + 1);
835 }
836 }
837 },
838 { active: !searching },
839 );
840
841 const previewWidth = file === undefined ? 0 : Math.max(34, Math.floor(terminalColumns * 0.42));
842 const columnWidth = Math.max(20, Math.min(28, Math.floor((terminalColumns - previewWidth) / 2)));
843 const availableForColumns = Math.max(columnWidth, terminalColumns - previewWidth - 2);
844 const visibleColumnCount = Math.max(1, Math.floor(availableForColumns / (columnWidth + 1)));
845 const visibleStart = Math.max(0, columns.length - visibleColumnCount);
846 const visibleColumns = columns.slice(visibleStart);
847 const currentPath = selected?.path ?? "/";
848 const displayPath =
849 selected === undefined || selected.kind === "resource" || selected.kind === "output"
850 ? currentPath
851 : `${currentPath}/`;
852
853 return (
854 // Pinned to the terminal width: without it the root sizes to its content,
855 // and the layout visibly narrows whenever the full-width key bar is
856 // swapped out for the delete panel.
857 <Box flexDirection="column" width={terminalColumns} height={Math.max(12, terminalRows - 2)}>
858 <Box
859 justifyContent="space-between"
860 flexShrink={0}
861 paddingX={1}
862 marginBottom={1}
863 borderStyle={borderStyle}
864 borderBottom
865 borderTop={false}
866 borderLeft={false}
867 borderRight={false}
868 borderColor={theme.color.muted}
869 borderDimColor
870 >
871 <Box gap={1}>
872 <Text color={theme.color.brand}>●</Text>
873 <Text bold>state</Text>
874 <Text color={theme.color.accent} wrap="truncate-middle">
875 · {displayPath}
876 </Text>
877 </Box>
878 <Text bold color={theme.color.brand}>
879 {store.source.backend}
880 </Text>
881 </Box>
882 {notice === undefined ? null : (
883 <Box paddingX={1} flexShrink={0}>
884 <Text color={theme.color.success}>✓ {notice}</Text>
885 </Box>
886 )}
887 {searching ? (
888 <Box gap={1} paddingX={1} flexShrink={0}>
889 <Text color={theme.color.brand}>/</Text>
890 <TextField
891 value={query}
892 placeholder="filter this column"
893 active
894 onChange={setQuery}
895 onSubmit={() => setSearching(false)}
896 onCancel={() => setSearching(false)}
897 />
898 </Box>
899 ) : query === "" ? null : (
900 <Box paddingX={1}>
901 <Text tone="muted">filter · {query}</Text>
902 </Box>
903 )}
904 <Box flexGrow={1}>
905 {visibleColumns.map((item, offset) => {
906 const index = visibleStart + offset;
907 return (
908 <Box
909 key={item.id}
910 width={columnWidth}
911 flexDirection="column"
912 paddingX={1}
913 borderStyle={borderStyle}
914 borderLeft={offset > 0}
915 borderRight={false}
916 borderTop={false}
917 borderBottom={false}
918 borderColor={
919 !previewFocused && index === activeColumn ? theme.color.accent : theme.color.muted
920 }
921 >
922 <Text
923 bold
924 color={
925 !previewFocused && index === activeColumn ? theme.color.accent : theme.color.muted
926 }
927 >
928 {item.title.toUpperCase()}
929 </Text>
930 <Box height={contentHeight} flexDirection="column">
931 <Column
932 column={item}
933 selected={selection[index]}
934 focused={!previewFocused && index === activeColumn}
935 height={contentHeight}
936 query={index === activeColumn ? query : ""}
937 marked={markedIds}
938 />
939 </Box>
940 </Box>
941 );
942 })}
943 {file === undefined ? null : (
944 <Box
945 flexGrow={1}
946 flexDirection="column"
947 paddingLeft={1}
948 borderStyle={borderStyle}
949 borderLeft
950 borderRight={false}
951 borderTop={false}
952 borderBottom={false}
953 borderColor={previewFocused ? theme.color.accent : theme.color.muted}
954 >
955 <Text bold color={previewFocused ? theme.color.accent : theme.color.muted}>
956 PREVIEW
957 </Text>
958 <Preview
959 node={file}
960 state={fileState}
961 lines={previewLines}
962 offset={previewOffset}
963 height={contentHeight}
964 />
965 </Box>
966 )}
967 </Box>
968 {deletion === undefined ? (
969 <Box paddingX={1} flexShrink={0}>
970 <KeyBar
971 keys={[
972 [keys.upDown, previewFocused ? "scroll" : "select"],
973 [keys.leftRight, "columns"],
974 ["/", "search"],
975 ["r", "refresh"],
976 [keys.space, "select"],
977 ["d", "delete"],
978 ...(file === undefined ? [] : ([[keys.tab, "preview"]] as const)),
979 ["q", "quit"],
980 ]}
981 />
982 </Box>
983 ) : (
984 <Box
985 flexDirection="column"
986 paddingX={1}
987 flexShrink={0}
988 height={footerHeight}
989 borderStyle={borderStyle}
990 borderTop
991 borderBottom={false}
992 borderLeft={false}
993 borderRight={false}
994 borderColor={theme.color.danger}
995 >
996 <Box height={1}>
997 {deletion.status === "deleting" ? (
998 <Spinner label="Deleting state" />
999 ) : deletion.status === "error" ? (
1000 <Text tone="danger" wrap="truncate-end">
1001 {deletion.message}
1002 </Text>
1003 ) : (
1004 <Text wrap="truncate-end">
1005 <Text bold color={theme.color.danger}>
1006 Delete state records?
1007 </Text>
1008 <Text tone="muted"> · Cloud resources will not be deleted.</Text>
1009 </Text>
1010 )}
1011 </Box>
1012 <Box flexDirection="column">
1013 {promptTargets.map((target) => (
1014 <Text key={target.id} wrap="truncate-middle">
1015 {" "}
1016 {target.path}
1017 {target.kind === "resource" ? "" : "/"}
1018 </Text>
1019 ))}
1020 {promptOverflow > 0 ? <Text tone="muted">{` +${promptOverflow} more`}</Text> : null}
1021 </Box>
1022 <DeletionAction status={deletion.status} />
1023 </Box>
1024 )}
1025 </Box>
1026 );
1027 }
1028
1029 const MAX_PROMPT_TARGETS = 4;
1030
1031 type DeletionActionProps = {
1032 status: "confirm" | "deleting" | "error";
1033 };
1034
1035 function DeletionAction({ status }: DeletionActionProps) {
1036 if (status === "deleting") return null;
1037 if (status === "error") return <KeyBar marginTop={0} keys={[["esc", "dismiss"]]} />;
1038 return (
1039 <KeyBar
1040 marginTop={0}
1041 keys={[
1042 ["y", "delete"],
1043 ["n/esc", "cancel"],
1044 ]}
1045 />
1046 );
1047 }
1048
1049 export const stateExplorerScreen = (
1050 source: StateExplorerSource,
1051 services?: Context.Context<never>,
1052 ) => {
1053 const store = new StateExplorerStore(source, services);
1054 return Screen.make<void>("state explorer", (controller) => (
1055 <StateExplorer store={store} controller={controller} />
1056 ));
1057 };