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
| 1 | /** @jsxRuntime automatic */ |
| 2 | /** @jsxImportSource @alchemy.run/sigil */ |
| 3 | import { |
| 4 | measureElement, |
| 5 | useCursor, |
| 6 | useInput, |
| 7 | usePaste, |
| 8 | useStdout, |
| 9 | type DOMElement, |
| 10 | } from "@alchemy.run/sigil"; |
| 11 | import { stringWidth } from "@alchemy.run/sigil/ansi"; |
| 12 | import { useEffect, useLayoutEffect, useRef, useState } from "@alchemy.run/sigil/react"; |
| 13 | import type { JSX, ReactNode } from "react"; |
| 14 | import { copyToClipboard } from "../../../Util/Terminal.ts"; |
| 15 | import { theme } from "../../../Util/Theme.ts"; |
| 16 | import type { Choice, CycleChoice } from "../types.ts"; |
| 17 | import { useCliEnvironment, useGlyphs, useKeyGlyphs } from "./Environment.tsx"; |
| 18 | import { KeyBar, Spinner } from "./Feedback.tsx"; |
| 19 | import { Box, overflowListWindow } from "./Layout.tsx"; |
| 20 | import { Link, Text } from "./Typography.tsx"; |
| 21 | |
| 22 | export interface TerminalKey { |
| 23 | readonly up: boolean; |
| 24 | readonly down: boolean; |
| 25 | readonly left: boolean; |
| 26 | readonly right: boolean; |
| 27 | readonly home: boolean; |
| 28 | readonly end: boolean; |
| 29 | readonly pageUp: boolean; |
| 30 | readonly pageDown: boolean; |
| 31 | readonly enter: boolean; |
| 32 | readonly escape: boolean; |
| 33 | readonly backspace: boolean; |
| 34 | readonly delete: boolean; |
| 35 | readonly tab: boolean; |
| 36 | readonly shift: boolean; |
| 37 | readonly ctrl: boolean; |
| 38 | readonly meta: boolean; |
| 39 | } |
| 40 | |
| 41 | /** Backend facade for custom screens; callers never need to import Sigil. */ |
| 42 | export const useTerminalInput = ( |
| 43 | handler: (input: string, key: TerminalKey) => void, |
| 44 | options?: { readonly active?: boolean }, |
| 45 | ) => |
| 46 | useInput( |
| 47 | (input, key) => |
| 48 | handler(input, { |
| 49 | up: key.upArrow, |
| 50 | down: key.downArrow, |
| 51 | left: key.leftArrow, |
| 52 | right: key.rightArrow, |
| 53 | home: key.home, |
| 54 | end: key.end, |
| 55 | pageUp: key.pageUp, |
| 56 | pageDown: key.pageDown, |
| 57 | enter: key.return, |
| 58 | escape: key.escape, |
| 59 | backspace: key.backspace, |
| 60 | delete: key.delete, |
| 61 | tab: key.tab, |
| 62 | shift: key.shift, |
| 63 | ctrl: key.ctrl, |
| 64 | meta: key.meta, |
| 65 | }), |
| 66 | { isActive: options?.active ?? true }, |
| 67 | ); |
| 68 | |
| 69 | /** Bracketed-paste input scoped the same way as {@link useTerminalInput}. */ |
| 70 | export const useTerminalPaste = ( |
| 71 | handler: (text: string) => void, |
| 72 | options?: { readonly active?: boolean }, |
| 73 | ) => { |
| 74 | usePaste(handler, { isActive: options?.active ?? true }); |
| 75 | }; |
| 76 | |
| 77 | export const useTerminalSize = () => { |
| 78 | const { columns, rows } = useCliEnvironment(); |
| 79 | return { columns, rows }; |
| 80 | }; |
| 81 | |
| 82 | export const useListNavigation = (length: number, initialIndex = 0) => { |
| 83 | const [cursor, setCursor] = useState(initialIndex); |
| 84 | const clamped = Math.max(0, Math.min(cursor, Math.max(0, length - 1))); |
| 85 | const move = (delta: number) => |
| 86 | setCursor((current) => { |
| 87 | if (length === 0) return 0; |
| 88 | // Clamp before wrapping: after a filter shrinks the list the raw state |
| 89 | // can point past the end, and wrapping from there jumps arbitrarily. |
| 90 | const base = Math.max(0, Math.min(current, length - 1)); |
| 91 | return (((base + delta) % length) + length) % length; |
| 92 | }); |
| 93 | return { cursor: clamped, move, setCursor } as const; |
| 94 | }; |
| 95 | |
| 96 | /** Step `delta` rows from `cursor`, wrapping and skipping disabled rows. */ |
| 97 | export const moveSkippingDisabled = ( |
| 98 | disabled: ReadonlyArray<boolean>, |
| 99 | cursor: number, |
| 100 | delta: number, |
| 101 | ): number => { |
| 102 | const length = disabled.length; |
| 103 | if (length === 0) return 0; |
| 104 | for (let offset = 1; offset <= length; offset++) { |
| 105 | const next = (((cursor + delta * offset) % length) + length) % length; |
| 106 | if (!disabled[next]) return next; |
| 107 | } |
| 108 | return cursor; |
| 109 | }; |
| 110 | |
| 111 | /** |
| 112 | * Jump to `target` (clamped, no wrap), settling on the nearest enabled row in |
| 113 | * the jump direction and falling back to the other direction. Used for |
| 114 | * Home/End and PageUp/PageDown in list prompts. |
| 115 | */ |
| 116 | export const jumpSkippingDisabled = ( |
| 117 | disabled: ReadonlyArray<boolean>, |
| 118 | cursor: number, |
| 119 | target: number, |
| 120 | ): number => { |
| 121 | const clamped = Math.max(0, Math.min(disabled.length - 1, target)); |
| 122 | if (!disabled[clamped]) return clamped; |
| 123 | const direction = clamped >= cursor ? 1 : -1; |
| 124 | for (let next = clamped + direction; next >= 0 && next < disabled.length; next += direction) { |
| 125 | if (!disabled[next]) return next; |
| 126 | } |
| 127 | for (let next = clamped - direction; next >= 0 && next < disabled.length; next -= direction) { |
| 128 | if (!disabled[next]) return next; |
| 129 | } |
| 130 | return cursor; |
| 131 | }; |
| 132 | |
| 133 | /** "↑ N more" / "↓ N more" indicator row shared by windowed prompt lists. */ |
| 134 | function OverflowRow({ |
| 135 | direction, |
| 136 | count, |
| 137 | }: { |
| 138 | readonly direction: "up" | "down"; |
| 139 | readonly count: number; |
| 140 | }) { |
| 141 | const glyphs = useGlyphs(); |
| 142 | if (count <= 0) return null; |
| 143 | return ( |
| 144 | <Text tone="muted"> |
| 145 | {" "} |
| 146 | {direction === "up" ? glyphs.overflowUp : glyphs.overflowDown} {count} more |
| 147 | </Text> |
| 148 | ); |
| 149 | } |
| 150 | |
| 151 | /** |
| 152 | * List-cursor column shared by every focusable row (prompt lists, the |
| 153 | * edit-accounts list, the profile dashboard): the focused row carries the |
| 154 | * pointer glyph, every other row a same-width blank so labels stay aligned. |
| 155 | * Focus is a shape, not a tint, so it survives ASCII and no-colour terminals. |
| 156 | */ |
| 157 | export function Pointer({ focused }: { readonly focused: boolean }) { |
| 158 | const glyphs = useGlyphs(); |
| 159 | return ( |
| 160 | <Text color={theme.paint.focus} bold> |
| 161 | {focused ? glyphs.pointer : " "} |
| 162 | </Text> |
| 163 | ); |
| 164 | } |
| 165 | |
| 166 | /** |
| 167 | * Focused rows paint their label in the same brand colour as the pointer so |
| 168 | * the cursor reads as one block; unfocused labels stay the plain foreground, |
| 169 | * leaving green to status glyphs alone. |
| 170 | */ |
| 171 | const focusedLabelColor = (focused: boolean): string | undefined => |
| 172 | focused ? theme.paint.focus : undefined; |
| 173 | |
| 174 | /** |
| 175 | * Width of the label column when descriptions sit beside labels: the widest |
| 176 | * label plus one cell, so every description starts in the same column |
| 177 | * (labels and descriptions read as two columns rather than a ragged sentence). |
| 178 | * Sticky/heading rows are excluded — they never carry a description. |
| 179 | */ |
| 180 | const labelColumnWidth = ( |
| 181 | labels: ReadonlyArray<{ readonly label: string; readonly sticky?: boolean }>, |
| 182 | ): number => |
| 183 | Math.max(0, ...labels.map(({ label, sticky }) => (sticky ? 0 : stringWidth(label)))) + 1; |
| 184 | |
| 185 | export interface MenuProps<Value> { |
| 186 | readonly choices: ReadonlyArray<Choice<Value>>; |
| 187 | readonly cursor: number; |
| 188 | readonly selected?: ReadonlySet<number>; |
| 189 | readonly visibleCount?: number; |
| 190 | readonly empty?: string; |
| 191 | readonly descriptionPlacement?: "below" | "inline"; |
| 192 | } |
| 193 | |
| 194 | /** Pure menu presentation used by select prompts and custom applications. */ |
| 195 | export function Menu<Value>({ |
| 196 | choices, |
| 197 | cursor, |
| 198 | selected, |
| 199 | visibleCount = 12, |
| 200 | empty = "No choices.", |
| 201 | descriptionPlacement = "inline", |
| 202 | }: MenuProps<Value>): JSX.Element { |
| 203 | const glyphs = useGlyphs(); |
| 204 | if (choices.length === 0) return <Text tone="muted">{empty}</Text>; |
| 205 | // A sticky heading renders outside the window, in addition to the overflow |
| 206 | // rows the shared windowing already reserves. |
| 207 | const { start, end } = overflowListWindow(choices.length, cursor, visibleCount); |
| 208 | const stickyIndex = |
| 209 | start === 0 ? -1 : choices.findLastIndex((choice, index) => index < start && choice.sticky); |
| 210 | const visible = [ |
| 211 | ...(stickyIndex === -1 ? [] : [stickyIndex]), |
| 212 | ...Array.from({ length: end - start }, (_, offset) => start + offset), |
| 213 | ]; |
| 214 | const alignDescriptions = |
| 215 | descriptionPlacement === "inline" && choices.some((choice) => choice.description !== undefined); |
| 216 | const labelWidth = alignDescriptions ? labelColumnWidth(choices) : undefined; |
| 217 | return ( |
| 218 | <Box |
| 219 | flexDirection="column" |
| 220 | aria-role="listbox" |
| 221 | aria-state={{ multiselectable: selected !== undefined }} |
| 222 | > |
| 223 | <OverflowRow direction="up" count={start} /> |
| 224 | {visible.map((index) => { |
| 225 | const choice = choices[index]; |
| 226 | if (choice === undefined) return null; |
| 227 | const focused = index === cursor; |
| 228 | const checked = selected?.has(index); |
| 229 | const disabled = choice.disabled !== undefined && choice.disabled !== false; |
| 230 | const previous = choices[index - 1]; |
| 231 | const showGroup = |
| 232 | choice.group !== undefined && (index === start || previous?.group !== choice.group); |
| 233 | return ( |
| 234 | <Box |
| 235 | key={index} |
| 236 | flexDirection="column" |
| 237 | marginTop={showGroup && index !== visible[0] ? 1 : 0} |
| 238 | > |
| 239 | {showGroup ? ( |
| 240 | <Box paddingLeft={theme.space.indent}> |
| 241 | <Text bold tone="muted"> |
| 242 | {choice.group.toUpperCase()} |
| 243 | </Text> |
| 244 | </Box> |
| 245 | ) : null} |
| 246 | <Box |
| 247 | gap={1} |
| 248 | paddingRight={1} |
| 249 | paddingLeft={choice.indent ?? 0} |
| 250 | aria-role="option" |
| 251 | aria-label={choice.label} |
| 252 | aria-state={{ |
| 253 | disabled, |
| 254 | selected: selected === undefined ? focused : checked, |
| 255 | }} |
| 256 | > |
| 257 | <Pointer focused={focused} /> |
| 258 | {selected === undefined ? null : ( |
| 259 | <Text color={checked ? theme.color.success : theme.color.muted} dimColor={disabled}> |
| 260 | {checked ? glyphs.checked : glyphs.unchecked} |
| 261 | </Text> |
| 262 | )} |
| 263 | <Box |
| 264 | flexDirection={descriptionPlacement === "inline" ? "row" : "column"} |
| 265 | flexGrow={1} |
| 266 | gap={descriptionPlacement === "inline" ? 1 : 0} |
| 267 | > |
| 268 | <Box width={choice.sticky ? undefined : labelWidth} flexShrink={0}> |
| 269 | <Text |
| 270 | bold={focused || choice.sticky || checked} |
| 271 | color={ |
| 272 | focusedLabelColor(focused) ?? |
| 273 | (choice.tone === "info" ? theme.color.info : undefined) |
| 274 | } |
| 275 | dimColor={disabled} |
| 276 | > |
| 277 | {choice.label} |
| 278 | </Text> |
| 279 | </Box> |
| 280 | {choice.description === undefined ? null : ( |
| 281 | <Text tone="muted" wrap="truncate-end"> |
| 282 | {choice.description} |
| 283 | </Text> |
| 284 | )} |
| 285 | </Box> |
| 286 | {typeof choice.disabled === "string" ? ( |
| 287 | <Text tone="muted">{choice.disabled}</Text> |
| 288 | ) : null} |
| 289 | </Box> |
| 290 | </Box> |
| 291 | ); |
| 292 | })} |
| 293 | <OverflowRow direction="down" count={choices.length - end} /> |
| 294 | </Box> |
| 295 | ); |
| 296 | } |
| 297 | |
| 298 | export interface TextFieldProps { |
| 299 | readonly placeholder?: string; |
| 300 | /** Text Tab fills into the empty field, e.g. the prompt's default. */ |
| 301 | readonly completion?: string; |
| 302 | readonly initialValue?: string; |
| 303 | readonly value?: string; |
| 304 | readonly mask?: string; |
| 305 | readonly onSubmit: (value: string) => void; |
| 306 | readonly onChange?: (value: string) => void; |
| 307 | readonly onCancel?: () => void; |
| 308 | readonly active?: boolean; |
| 309 | readonly ariaLabel?: string; |
| 310 | } |
| 311 | |
| 312 | const graphemeSegmenter = new Intl.Segmenter(); |
| 313 | |
| 314 | /** |
| 315 | * Split into user-perceived characters so cursor movement and deletion never |
| 316 | * land inside a surrogate pair or emoji cluster. |
| 317 | */ |
| 318 | const toGraphemes = (value: string): ReadonlyArray<string> => |
| 319 | Array.from(graphemeSegmenter.segment(value), (segment) => segment.segment); |
| 320 | |
| 321 | /** |
| 322 | * Normalize text before inserting it into a single-line field. Sigil reports |
| 323 | * bracketed paste separately, but pasted content can still contain newlines, |
| 324 | * tabs or other control characters that do not belong in the value. |
| 325 | */ |
| 326 | export const sanitizeTextInsert = (input: string): string => |
| 327 | // eslint-disable-next-line no-control-regex |
| 328 | input.replace(/[\u0000-\u001f\u007f]/g, ""); |
| 329 | |
| 330 | /** Readline-style whitespace word boundary to the left of `cursor`. */ |
| 331 | const wordBoundaryLeft = (chars: ReadonlyArray<string>, cursor: number): number => { |
| 332 | let index = cursor; |
| 333 | while (index > 0 && chars[index - 1] === " ") index--; |
| 334 | while (index > 0 && chars[index - 1] !== " ") index--; |
| 335 | return index; |
| 336 | }; |
| 337 | |
| 338 | /** Readline-style whitespace word boundary to the right of `cursor`. */ |
| 339 | const wordBoundaryRight = (chars: ReadonlyArray<string>, cursor: number): number => { |
| 340 | let index = cursor; |
| 341 | while (index < chars.length && chars[index] === " ") index++; |
| 342 | while (index < chars.length && chars[index] !== " ") index++; |
| 343 | return index; |
| 344 | }; |
| 345 | |
| 346 | /** |
| 347 | * Horizontal scroll window for a single-line field: which grapheme range fits |
| 348 | * in `avail` display cells while keeping the cursor visible. One cell is |
| 349 | * reserved for the cursor sitting past the last character. |
| 350 | */ |
| 351 | const visibleWindow = ( |
| 352 | chars: ReadonlyArray<string>, |
| 353 | cursor: number, |
| 354 | avail: number, |
| 355 | ): { readonly start: number; readonly end: number } => { |
| 356 | const budget = Math.max(1, avail - 1); |
| 357 | const widths = chars.map((char) => stringWidth(char)); |
| 358 | let before = 0; |
| 359 | for (let index = 0; index < cursor; index++) before += widths[index] ?? 0; |
| 360 | let start = 0; |
| 361 | if (before > budget) { |
| 362 | // Scrolled: pin the cursor near the right edge of the window. |
| 363 | let used = 0; |
| 364 | while (start < cursor && before - used > budget) { |
| 365 | used += widths[start] ?? 0; |
| 366 | start++; |
| 367 | } |
| 368 | } |
| 369 | let end = start; |
| 370 | let total = 0; |
| 371 | while (end < chars.length && total + (widths[end] ?? 0) <= budget) { |
| 372 | total += widths[end] ?? 0; |
| 373 | end++; |
| 374 | } |
| 375 | return { start, end }; |
| 376 | }; |
| 377 | |
| 378 | /** |
| 379 | * Single-line editor with insertion, deletion, home/end, word-wise movement |
| 380 | * and the common readline kill bindings (Ctrl+U/K/W, Alt+Backspace). Long |
| 381 | * values scroll horizontally instead of wrapping, so the terminal cursor |
| 382 | * always sits on the field's own row. |
| 383 | */ |
| 384 | export function TextField({ |
| 385 | placeholder, |
| 386 | completion, |
| 387 | initialValue = "", |
| 388 | value: controlledValue, |
| 389 | mask, |
| 390 | onSubmit, |
| 391 | onChange, |
| 392 | onCancel, |
| 393 | active, |
| 394 | ariaLabel, |
| 395 | }: TextFieldProps) { |
| 396 | // Prompts are serialized by the Sigil renderer, so an enabled field owns |
| 397 | // the input stream outright — no Sigil focus negotiation. (Coupling this to |
| 398 | // useFocus({autoFocus}) silently disabled the field whenever any other |
| 399 | // focusable was already mounted.) |
| 400 | const inputActive = active ?? true; |
| 401 | const [internalValue, setInternalValue] = useState(initialValue); |
| 402 | const value = controlledValue ?? internalValue; |
| 403 | const chars = toGraphemes(value); |
| 404 | const [cursor, setCursor] = useState(() => toGraphemes(controlledValue ?? initialValue).length); |
| 405 | const fieldRef = useRef<DOMElement>(null); |
| 406 | const [metrics, setMetrics] = useState({ x: 0, y: 0, measured: false }); |
| 407 | const { setCursorPosition } = useCursor(); |
| 408 | const { columns } = useCliEnvironment(); |
| 409 | useEffect(() => { |
| 410 | setCursor((current) => Math.min(current, toGraphemes(value).length)); |
| 411 | }, [value]); |
| 412 | const update = (nextChars: ReadonlyArray<string>, nextCursor: number) => { |
| 413 | const next = nextChars.join(""); |
| 414 | if (controlledValue === undefined) setInternalValue(next); |
| 415 | setCursor(Math.max(0, Math.min(nextChars.length, nextCursor))); |
| 416 | onChange?.(next); |
| 417 | }; |
| 418 | useTerminalInput( |
| 419 | (input, key) => { |
| 420 | if (key.enter) onSubmit(value); |
| 421 | else if (key.escape) onCancel?.(); |
| 422 | else if (key.left) |
| 423 | setCursor(key.ctrl || key.meta ? wordBoundaryLeft(chars, cursor) : Math.max(0, cursor - 1)); |
| 424 | else if (key.right) |
| 425 | setCursor( |
| 426 | key.ctrl || key.meta |
| 427 | ? wordBoundaryRight(chars, cursor) |
| 428 | : Math.min(chars.length, cursor + 1), |
| 429 | ); |
| 430 | // Sigil distinguishes physical Backspace from Delete. |
| 431 | else if (key.backspace && cursor > 0) { |
| 432 | const target = key.meta ? wordBoundaryLeft(chars, cursor) : cursor - 1; |
| 433 | update([...chars.slice(0, target), ...chars.slice(cursor)], target); |
| 434 | } else if (key.delete && cursor < chars.length) |
| 435 | update([...chars.slice(0, cursor), ...chars.slice(cursor + 1)], cursor); |
| 436 | else if (key.ctrl && input === "d" && cursor < chars.length) |
| 437 | update([...chars.slice(0, cursor), ...chars.slice(cursor + 1)], cursor); |
| 438 | else if (key.ctrl && input === "w" && cursor > 0) { |
| 439 | const target = wordBoundaryLeft(chars, cursor); |
| 440 | update([...chars.slice(0, target), ...chars.slice(cursor)], target); |
| 441 | } else if (key.ctrl && input === "u") update(chars.slice(cursor), 0); |
| 442 | else if (key.ctrl && input === "k") update(chars.slice(0, cursor), cursor); |
| 443 | else if (key.home || (key.ctrl && input === "a")) setCursor(0); |
| 444 | else if (key.end || (key.ctrl && input === "e")) setCursor(chars.length); |
| 445 | else if (key.meta && input === "b") setCursor(wordBoundaryLeft(chars, cursor)); |
| 446 | else if (key.meta && input === "f") setCursor(wordBoundaryRight(chars, cursor)); |
| 447 | else if (key.tab && completion !== undefined && chars.length === 0) { |
| 448 | const completed = toGraphemes(completion); |
| 449 | update(completed, completed.length); |
| 450 | } else if (!key.ctrl && !key.meta && !key.tab) { |
| 451 | const inserted = toGraphemes(sanitizeTextInsert(input)); |
| 452 | if (inserted.length > 0) { |
| 453 | update( |
| 454 | [...chars.slice(0, cursor), ...inserted, ...chars.slice(cursor)], |
| 455 | cursor + inserted.length, |
| 456 | ); |
| 457 | } |
| 458 | } |
| 459 | }, |
| 460 | { active: inputActive }, |
| 461 | ); |
| 462 | useTerminalPaste( |
| 463 | (pasted) => { |
| 464 | const inserted = toGraphemes(sanitizeTextInsert(pasted)); |
| 465 | if (inserted.length === 0) return; |
| 466 | update( |
| 467 | [...chars.slice(0, cursor), ...inserted, ...chars.slice(cursor)], |
| 468 | cursor + inserted.length, |
| 469 | ); |
| 470 | }, |
| 471 | { active: inputActive }, |
| 472 | ); |
| 473 | const shownChars = mask === undefined ? chars : chars.map(() => mask); |
| 474 | // Available width = terminal width minus the field's left offset. The box's |
| 475 | // own measured width is useless here: it shrinks to its content (flexGrow |
| 476 | // only affects height in a column parent), so using it collapses the scroll |
| 477 | // window to whatever is currently typed. |
| 478 | const avail = Math.max(4, columns - (metrics.measured ? metrics.x : 0) - 1); |
| 479 | const { start, end } = visibleWindow(shownChars, cursor, avail); |
| 480 | const display = |
| 481 | shownChars.length === 0 |
| 482 | ? (placeholder ?? " ") |
| 483 | : `${shownChars.slice(start, end).join("")}${cursor === shownChars.length ? " " : ""}`; |
| 484 | // Cursor placement must happen DURING render: useCursor only records the |
| 485 | // position in a ref and propagates it to the renderer from an insertion |
| 486 | // effect, which runs BEFORE layout effects in the same commit. Setting the |
| 487 | // position from a layout effect therefore paints every frame with the |
| 488 | // previous keystroke's cursor (off by one while typing and erasing). The |
| 489 | // ref write is render-safe — propagation is commit-gated, so abandoned |
| 490 | // concurrent renders never reach the terminal. |
| 491 | setCursorPosition( |
| 492 | inputActive && metrics.measured |
| 493 | ? { |
| 494 | x: metrics.x + stringWidth(shownChars.slice(start, cursor).join("")), |
| 495 | y: metrics.y, |
| 496 | } |
| 497 | : undefined, |
| 498 | ); |
| 499 | // Measuring stays post-layout: the Box ref only exists after mutation. |
| 500 | // A metrics change re-renders, which re-runs the render-time cursor |
| 501 | // placement above with the fresh offsets. |
| 502 | useLayoutEffect(() => { |
| 503 | if (fieldRef.current === null) return; |
| 504 | const { x, y } = measureElement(fieldRef.current); |
| 505 | setMetrics((current) => |
| 506 | current.measured && current.x === x && current.y === y ? current : { x, y, measured: true }, |
| 507 | ); |
| 508 | }); |
| 509 | return ( |
| 510 | <Box ref={fieldRef} aria-role="textbox" aria-label={ariaLabel}> |
| 511 | <Text tone={shownChars.length === 0 ? "muted" : "default"} wrap="truncate-end"> |
| 512 | {display} |
| 513 | </Text> |
| 514 | </Box> |
| 515 | ); |
| 516 | } |
| 517 | |
| 518 | export interface CycleListProps<State> { |
| 519 | readonly choices: ReadonlyArray<CycleChoice<State>>; |
| 520 | readonly cursor: number; |
| 521 | readonly indices: ReadonlyArray<number>; |
| 522 | readonly visibleCount?: number; |
| 523 | } |
| 524 | |
| 525 | const stateColor = (variant: CycleChoice<unknown>["states"][number]["variant"]) => |
| 526 | variant === undefined || variant === "neutral" |
| 527 | ? undefined |
| 528 | : theme.color[variant === "error" ? "danger" : variant]; |
| 529 | |
| 530 | export function CycleList<State>({ |
| 531 | choices, |
| 532 | cursor, |
| 533 | indices, |
| 534 | visibleCount = 12, |
| 535 | }: CycleListProps<State>) { |
| 536 | const glyphs = useGlyphs(); |
| 537 | const { start, end } = overflowListWindow(choices.length, cursor, visibleCount); |
| 538 | const labelWidth = labelColumnWidth(choices); |
| 539 | // The state word ("add", "remove", …) gets its own column too, so the |
| 540 | // descriptions line up whether or not a row's current state carries one. |
| 541 | const stateWidth = Math.max( |
| 542 | 0, |
| 543 | ...choices.flatMap((choice) => |
| 544 | choice.states.map((state) => (state.label === undefined ? 0 : stringWidth(state.label))), |
| 545 | ), |
| 546 | ); |
| 547 | return ( |
| 548 | <Box flexDirection="column"> |
| 549 | <OverflowRow direction="up" count={start} /> |
| 550 | {choices.slice(start, end).map((choice, offset) => { |
| 551 | const index = start + offset; |
| 552 | const state = choice.states[indices[index] ?? 0]; |
| 553 | const focused = index === cursor; |
| 554 | const color = stateColor(state?.variant); |
| 555 | return ( |
| 556 | <Box key={index} gap={1} paddingRight={1}> |
| 557 | <Pointer focused={focused} /> |
| 558 | <Text color={color} dimColor={color === undefined}> |
| 559 | {state?.icon ?? glyphs.bullet} |
| 560 | </Text> |
| 561 | <Box width={labelWidth} flexShrink={0}> |
| 562 | <Text bold color={focusedLabelColor(focused)}> |
| 563 | {choice.label} |
| 564 | </Text> |
| 565 | </Box> |
| 566 | {stateWidth === 0 ? null : ( |
| 567 | <Box width={stateWidth} flexShrink={0}> |
| 568 | {state?.label === undefined ? null : <Text color={color}>{state.label}</Text>} |
| 569 | </Box> |
| 570 | )} |
| 571 | {choice.description === undefined ? null : ( |
| 572 | <Text tone="muted">{choice.description}</Text> |
| 573 | )} |
| 574 | </Box> |
| 575 | ); |
| 576 | })} |
| 577 | <OverflowRow direction="down" count={choices.length - end} /> |
| 578 | </Box> |
| 579 | ); |
| 580 | } |
| 581 | |
| 582 | export const useCycleNavigation = (stateCounts: ReadonlyArray<number>) => { |
| 583 | const { cursor, move, setCursor } = useListNavigation(stateCounts.length); |
| 584 | const [indices, setIndices] = useState<ReadonlyArray<number>>(() => stateCounts.map(() => 0)); |
| 585 | const cycle = (delta: number) => |
| 586 | setIndices((current) => |
| 587 | current.map((value, index) => { |
| 588 | if (index !== cursor) return value; |
| 589 | const count = stateCounts[index] ?? 0; |
| 590 | return count <= 0 ? 0 : (value + delta + count) % count; |
| 591 | }), |
| 592 | ); |
| 593 | return { cursor, indices, move, setCursor, cycle } as const; |
| 594 | }; |
| 595 | |
| 596 | export interface BrowserLoginWaitProps { |
| 597 | readonly message: string; |
| 598 | readonly waitingLabel: string; |
| 599 | readonly url: string; |
| 600 | /** Short code the user confirms on the login page. */ |
| 601 | readonly code?: string; |
| 602 | readonly openFailed?: boolean; |
| 603 | /** Open the login URL again from the waiting screen. */ |
| 604 | readonly onOpen?: () => Promise<void>; |
| 605 | /** Allow Enter to switch to manual code entry. */ |
| 606 | readonly allowManualInput: boolean; |
| 607 | readonly inputLabel?: string; |
| 608 | readonly placeholder?: string; |
| 609 | readonly validate?: (value: string) => string | Error | undefined; |
| 610 | readonly onSubmit: (value: string) => void; |
| 611 | readonly onCancel: () => void; |
| 612 | } |
| 613 | |
| 614 | /** |
| 615 | * Yes/no keyboard handling shared by `InlineConfirm` and the confirm prompt |
| 616 | * screen: arrows/tab toggle, Enter commits, y/n answer directly. |
| 617 | */ |
| 618 | export const useConfirmKeys = ({ |
| 619 | initialValue = false, |
| 620 | active, |
| 621 | onSubmit, |
| 622 | onCancel, |
| 623 | }: { |
| 624 | readonly initialValue?: boolean; |
| 625 | readonly active?: boolean; |
| 626 | readonly onSubmit: (value: boolean) => void; |
| 627 | readonly onCancel?: () => void; |
| 628 | }): boolean => { |
| 629 | const [value, setValue] = useState(initialValue); |
| 630 | useTerminalInput( |
| 631 | (input, key) => { |
| 632 | if (key.escape) onCancel?.(); |
| 633 | else if (key.left || key.right || key.tab || key.up || key.down) |
| 634 | setValue((current) => !current); |
| 635 | else if (key.enter) onSubmit(value); |
| 636 | else if (key.ctrl || key.meta) return; |
| 637 | else if (input.toLowerCase() === "y") onSubmit(true); |
| 638 | else if (input.toLowerCase() === "n") onSubmit(false); |
| 639 | }, |
| 640 | { active: active ?? true }, |
| 641 | ); |
| 642 | return value; |
| 643 | }; |
| 644 | |
| 645 | type InlineConfirmProps = { |
| 646 | readonly message: string; |
| 647 | readonly initialValue?: boolean; |
| 648 | readonly confirmLabel?: string; |
| 649 | readonly cancelLabel?: string; |
| 650 | readonly active?: boolean; |
| 651 | readonly onSubmit: (value: boolean) => void; |
| 652 | readonly onCancel?: () => void; |
| 653 | }; |
| 654 | |
| 655 | export function InlineConfirm({ |
| 656 | message, |
| 657 | initialValue = false, |
| 658 | confirmLabel = "Yes", |
| 659 | cancelLabel = "No", |
| 660 | active, |
| 661 | onSubmit, |
| 662 | onCancel, |
| 663 | }: InlineConfirmProps) { |
| 664 | const keys = useKeyGlyphs(); |
| 665 | const value = useConfirmKeys({ initialValue, active, onSubmit, onCancel }); |
| 666 | return ( |
| 667 | <Box flexDirection="column" gap={1}> |
| 668 | <Text bold color={theme.color.brand}> |
| 669 | {message} |
| 670 | </Text> |
| 671 | <ChoiceGroup |
| 672 | value={value} |
| 673 | choices={[ |
| 674 | { value: true, label: confirmLabel }, |
| 675 | { value: false, label: cancelLabel }, |
| 676 | ]} |
| 677 | /> |
| 678 | <KeyBar |
| 679 | marginTop={0} |
| 680 | keys={[ |
| 681 | [confirmLabel === "Yes" && cancelLabel === "No" ? keys.yesNo : keys.leftRight, "choose"], |
| 682 | [keys.enter, "confirm"], |
| 683 | [keys.escape, "cancel"], |
| 684 | ]} |
| 685 | /> |
| 686 | </Box> |
| 687 | ); |
| 688 | } |
| 689 | |
| 690 | export interface ChoiceGroupProps<Value> { |
| 691 | readonly choices: ReadonlyArray<{ |
| 692 | readonly value: Value; |
| 693 | readonly label: string; |
| 694 | readonly description?: string; |
| 695 | }>; |
| 696 | readonly value: Value; |
| 697 | readonly orientation?: "horizontal" | "vertical"; |
| 698 | readonly active?: boolean; |
| 699 | readonly onChange?: (value: Value) => void; |
| 700 | } |
| 701 | |
| 702 | export function ChoiceGroup<Value>({ |
| 703 | choices, |
| 704 | value, |
| 705 | orientation = "horizontal", |
| 706 | active = true, |
| 707 | onChange, |
| 708 | }: ChoiceGroupProps<Value>) { |
| 709 | const selected = Math.max( |
| 710 | 0, |
| 711 | choices.findIndex((choice) => choice.value === value), |
| 712 | ); |
| 713 | useTerminalInput( |
| 714 | (_input, key) => { |
| 715 | if (onChange === undefined || choices.length === 0) return; |
| 716 | const previous = |
| 717 | key.tab && key.shift ? true : orientation === "horizontal" ? key.left : key.up; |
| 718 | const next = key.tab || (orientation === "horizontal" ? key.right : key.down); |
| 719 | if (!previous && !next) return; |
| 720 | const delta = previous ? -1 : 1; |
| 721 | const index = (selected + delta + choices.length) % choices.length; |
| 722 | onChange(choices[index]!.value); |
| 723 | }, |
| 724 | { active: active && onChange !== undefined }, |
| 725 | ); |
| 726 | return ( |
| 727 | <Box |
| 728 | gap={orientation === "horizontal" ? 1 : 0} |
| 729 | paddingLeft={theme.space.indent} |
| 730 | flexDirection={orientation === "horizontal" ? "row" : "column"} |
| 731 | aria-role="radiogroup" |
| 732 | > |
| 733 | {choices.map((choice) => { |
| 734 | const selected = choice.value === value; |
| 735 | return ( |
| 736 | <Box |
| 737 | key={choice.label} |
| 738 | paddingX={1} |
| 739 | backgroundColor={selected ? theme.paint.interactive : undefined} |
| 740 | aria-role="radio" |
| 741 | aria-label={choice.label} |
| 742 | aria-state={{ checked: selected }} |
| 743 | > |
| 744 | <Text bold={selected} color={selected ? theme.color.onAccent : undefined}> |
| 745 | {choice.label} |
| 746 | </Text> |
| 747 | {choice.description === undefined ? null : ( |
| 748 | <Text tone="muted"> · {choice.description}</Text> |
| 749 | )} |
| 750 | </Box> |
| 751 | ); |
| 752 | })} |
| 753 | </Box> |
| 754 | ); |
| 755 | } |
| 756 | |
| 757 | /** Browser login waiting screen with URL controls and manual-entry fallback. */ |
| 758 | export function BrowserLoginWait({ |
| 759 | message, |
| 760 | waitingLabel, |
| 761 | url, |
| 762 | code, |
| 763 | openFailed = false, |
| 764 | onOpen, |
| 765 | allowManualInput, |
| 766 | inputLabel, |
| 767 | placeholder, |
| 768 | validate, |
| 769 | onSubmit, |
| 770 | onCancel, |
| 771 | }: BrowserLoginWaitProps) { |
| 772 | const { stdout } = useStdout(); |
| 773 | const glyphs = useGlyphs(); |
| 774 | const keyGlyphs = useKeyGlyphs(); |
| 775 | const [manual, setManual] = useState(false); |
| 776 | const [copied, setCopied] = useState(false); |
| 777 | const [browserFailed, setBrowserFailed] = useState(openFailed); |
| 778 | const [error, setError] = useState<string>(); |
| 779 | const copiedTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); |
| 780 | useEffect( |
| 781 | () => () => { |
| 782 | clearTimeout(copiedTimer.current); |
| 783 | }, |
| 784 | [], |
| 785 | ); |
| 786 | // Ctrl+C is handled centrally by the screen runner (SigilRuntime.run). |
| 787 | useTerminalInput((input, key) => { |
| 788 | if (manual) { |
| 789 | if (key.escape) { |
| 790 | setError(undefined); |
| 791 | setManual(false); |
| 792 | } |
| 793 | return; |
| 794 | } |
| 795 | const shortcut = input.toLowerCase(); |
| 796 | if (key.enter && allowManualInput) setManual(true); |
| 797 | else if (key.escape) onCancel(); |
| 798 | // Ctrl+C must fall through to the runner's cancel guard, not copy the URL. |
| 799 | else if (key.ctrl || key.meta) return; |
| 800 | else if (shortcut === "o" && onOpen !== undefined) { |
| 801 | setBrowserFailed(false); |
| 802 | void onOpen().catch(() => setBrowserFailed(true)); |
| 803 | } else if (shortcut === "c") { |
| 804 | copyToClipboard(url, stdout ?? process.stdout); |
| 805 | setCopied(true); |
| 806 | clearTimeout(copiedTimer.current); |
| 807 | copiedTimer.current = setTimeout(() => setCopied(false), 2000); |
| 808 | } |
| 809 | }); |
| 810 | if (manual) { |
| 811 | const manualInputLabel = inputLabel ?? "Paste the authorization code or callback URL"; |
| 812 | return ( |
| 813 | <PromptFrame |
| 814 | message={manualInputLabel} |
| 815 | layout="inline" |
| 816 | error={error} |
| 817 | keys={[ |
| 818 | [keyGlyphs.enter, "confirm"], |
| 819 | [keyGlyphs.escape, "back to waiting"], |
| 820 | ]} |
| 821 | > |
| 822 | <TextField |
| 823 | placeholder={placeholder} |
| 824 | ariaLabel={manualInputLabel} |
| 825 | onCancel={() => { |
| 826 | setError(undefined); |
| 827 | setManual(false); |
| 828 | }} |
| 829 | onChange={() => setError(undefined)} |
| 830 | onSubmit={(value) => { |
| 831 | const problem = validate?.(value); |
| 832 | if (problem !== undefined) { |
| 833 | setError(problem instanceof Error ? problem.message : problem); |
| 834 | } else { |
| 835 | onSubmit(value); |
| 836 | } |
| 837 | }} |
| 838 | /> |
| 839 | </PromptFrame> |
| 840 | ); |
| 841 | } |
| 842 | return ( |
| 843 | <PromptFrame |
| 844 | message={message} |
| 845 | keys={[ |
| 846 | ...(allowManualInput ? ([[keyGlyphs.enter, "enter code manually"]] as const) : []), |
| 847 | ...(onOpen === undefined ? [] : ([["o", "open browser"]] as const)), |
| 848 | ["c", copied ? `${glyphs.success} copied` : "copy URL"], |
| 849 | [keyGlyphs.escape, "cancel"], |
| 850 | ]} |
| 851 | > |
| 852 | <Box flexDirection="column" gap={1}> |
| 853 | <Spinner label={waitingLabel} /> |
| 854 | {code === undefined ? null : ( |
| 855 | <Box gap={1}> |
| 856 | <Text tone="muted">Code</Text> |
| 857 | <Text bold color={theme.color.accentBright}> |
| 858 | {code} |
| 859 | </Text> |
| 860 | </Box> |
| 861 | )} |
| 862 | {browserFailed ? ( |
| 863 | <Text tone="warning"> |
| 864 | {glyphs.warning} Could not open the browser. Copy and open the URL manually. |
| 865 | </Text> |
| 866 | ) : null} |
| 867 | <Link href={url}>{url}</Link> |
| 868 | </Box> |
| 869 | </PromptFrame> |
| 870 | ); |
| 871 | } |
| 872 | |
| 873 | export type PromptFrameProps = { |
| 874 | readonly message: string; |
| 875 | readonly description?: ReactNode; |
| 876 | readonly children: JSX.Element; |
| 877 | readonly layout?: "inline" | "stacked"; |
| 878 | readonly error?: string; |
| 879 | readonly keys?: ReadonlyArray<readonly [string, string]>; |
| 880 | }; |
| 881 | |
| 882 | export function PromptFrame({ |
| 883 | message, |
| 884 | description, |
| 885 | children, |
| 886 | layout = "stacked", |
| 887 | error, |
| 888 | keys, |
| 889 | }: PromptFrameProps) { |
| 890 | const glyphs = useGlyphs(); |
| 891 | // The active-step glyph shares the heading's brand colour: `◆ question` is |
| 892 | // the step being answered, `✓ question` (AnsweredPrompt) one that is done. |
| 893 | const heading = (suffix = "") => ( |
| 894 | <Text> |
| 895 | <Text bold color={theme.color.brand}> |
| 896 | {glyphs.active} {message} |
| 897 | {suffix} |
| 898 | </Text> |
| 899 | </Text> |
| 900 | ); |
| 901 | return ( |
| 902 | <Box flexDirection="column"> |
| 903 | {layout === "inline" ? ( |
| 904 | <Box flexDirection="column"> |
| 905 | <Box gap={1}> |
| 906 | {heading(":")} |
| 907 | <Box flexGrow={1}>{children}</Box> |
| 908 | </Box> |
| 909 | {description === undefined ? null : ( |
| 910 | <Box paddingLeft={theme.space.indent}> |
| 911 | <Text tone="muted">{description}</Text> |
| 912 | </Box> |
| 913 | )} |
| 914 | </Box> |
| 915 | ) : ( |
| 916 | <> |
| 917 | {heading()} |
| 918 | {description === undefined ? null : ( |
| 919 | <Box paddingLeft={theme.space.indent}> |
| 920 | <Text tone="muted">{description}</Text> |
| 921 | </Box> |
| 922 | )} |
| 923 | {/* Children sit directly under the heading, indented like the |
| 924 | answered lines' text; grouping is carried by indentation, not |
| 925 | by a rail. */} |
| 926 | <Box paddingLeft={theme.space.indent} flexDirection="column"> |
| 927 | {children} |
| 928 | </Box> |
| 929 | </> |
| 930 | )} |
| 931 | {error === undefined ? null : ( |
| 932 | <Box marginTop={1} paddingLeft={2}> |
| 933 | <Text color={theme.color.danger}> |
| 934 | {glyphs.error} {error} |
| 935 | </Text> |
| 936 | </Box> |
| 937 | )} |
| 938 | {keys === undefined ? null : <KeyBar keys={keys} />} |
| 939 | </Box> |
| 940 | ); |
| 941 | } |
| 942 | |
| 943 | export const filterChoices = <Value,>(choices: ReadonlyArray<Choice<Value>>, query: string) => { |
| 944 | const normalized = query.trim().toLowerCase(); |
| 945 | const indexed = choices.map((choice, index) => ({ choice, index })); |
| 946 | return normalized === "" |
| 947 | ? indexed |
| 948 | : indexed.filter(({ choice }) => |
| 949 | `${choice.group ?? ""} ${choice.label} ${choice.description ?? ""}` |
| 950 | .toLowerCase() |
| 951 | .includes(normalized), |
| 952 | ); |
| 953 | }; |
| 954 | |
| 955 | /** Stable selected-index set for multiselect widgets. */ |
| 956 | export const useSelectedChoices = <Value,>( |
| 957 | choices: ReadonlyArray<Choice<Value>>, |
| 958 | initialValues: ReadonlyArray<Value>, |
| 959 | ) => |
| 960 | useState<ReadonlySet<number>>( |
| 961 | () => |
| 962 | new Set( |
| 963 | initialValues.flatMap((value) => { |
| 964 | const index = choices.findIndex((choice) => choice.value === value); |
| 965 | return index === -1 || choices[index]?.disabled ? [] : [index]; |
| 966 | }), |
| 967 | ), |
| 968 | ); |