Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.
| Cards you act on in chat; agents comment and review as themselves; names shown cleanly; commits on the calendar | 1 | import { |
| 2 | ArrowUpRight, | |
| 3 | Bot, | |
| 4 | CircleAlert, | |
| 5 | CircleCheck, | |
| 6 | CircleDot, | |
| 7 | CircleDotDashed, | |
| 8 | GitPullRequest, | |
| 9 | ListChecks, | |
| 10 | LoaderCircle, | |
| 11 | Rocket, | |
| 12 | ShieldCheck, | |
| 13 | Sparkles, | |
| 14 | X, | |
| 15 | } from "lucide-react"; | |
| 16 | import { | |
| 17 | type FormEvent, | |
| 18 | type KeyboardEvent, | |
| 19 | type ReactNode, | |
| 20 | useEffect, | |
| 21 | useId, | |
| 22 | useRef, | |
| 23 | useState, | |
| 24 | useSyncExternalStore, | |
| 25 | } from "react"; | |
| 26 | import { Link } from "react-router"; | |
| 27 | ||
| 28 | import type { CardAction, CardActionResult, MessageCard, Result } from "@g1t/contracts"; | |
| 29 | ||
| 30 | import { Markdown } from "../markdown"; | |
| 31 | import { | |
| 32 | AlertDialog, | |
| 33 | AlertDialogAction, | |
| 34 | AlertDialogCancel, | |
| 35 | AlertDialogContent, | |
| 36 | AlertDialogDescription, | |
| 37 | AlertDialogFooter, | |
| 38 | AlertDialogHeader, | |
| 39 | AlertDialogTitle, | |
| 40 | } from "../ui/alert-dialog"; | |
| 41 | import { Badge, type BadgeTone } from "../ui/badge"; | |
| 42 | import { InputAddon, InputGroup } from "../ui/input"; | |
| 43 | import { cn } from "../../lib/cn"; | |
| 44 | import { type CardChip, actionMode, cardChip, foldsBody, inputValue, moneyInitial, shownActions } from "../../lib/card-actions"; | |
| 45 | import { repoAt } from "../../lib/markdown-plugins"; | |
| 46 | import { sessionChip } from "../../lib/session-card"; | |
| 47 | import { codeAccessPath } from "../../lib/workspace-nav"; | |
| 48 | ||
| 49 | // A card g1t or an agent posts in chat (docs/WORKSPACE.md, "Cards"): what | |
| 50 | // it is about, its state, a preview, a few facts, and what people can do | |
| 51 | // right here. Pressing an action goes to the site (routes/workspace/chat/ | |
| 52 | // api.ts, `card_action`), then to chat, then to the service that owns the | |
| 53 | // card; the card changes in place when that service updates it | |
| 54 | // (`message.updated`), so nothing here changes it ahead of time. | |
| 55 | ||
| 56 | const CARD_ICONS: Record<string, ReactNode> = { | |
| 57 | pull: <GitPullRequest size={16} />, | |
| 58 | issue: <CircleDot size={16} />, | |
| 59 | draft_issue: <CircleDotDashed size={16} />, | |
| 60 | task: <ListChecks size={16} />, | |
| 61 | deploy: <Rocket size={16} />, | |
| 62 | approval: <ShieldCheck size={16} />, | |
| 63 | session: <Bot size={16} />, | |
| 64 | }; | |
| 65 | ||
| 66 | /** Where a card's link goes for this viewer: a member without Code goes to the workspace's own view of it. */ | |
| 67 | export function cardHref(href: string | null | undefined, slug: string, code: boolean): string | null { | |
| 68 | if (!href) return null; | |
| 69 | if (code || !/^\/[^/]+\/(?!-\/)[^/]+/.test(href)) return href; | |
| 70 | return codeAccessPath(slug, href); | |
| 71 | } | |
| 72 | ||
| 73 | /** How loud a card's state reads, from what it says, for kinds without chips of their own. */ | |
| 74 | function stateTone(state: string): BadgeTone { | |
| 75 | const s = state.toLowerCase(); | |
| 76 | if (/merged/.test(s)) return "merged"; | |
| 77 | if (/fail|error|blocked|over budget|rejected/.test(s)) return "danger"; | |
| 78 | if (/approval|waiting|review|queued|needs/.test(s)) return "warn"; | |
| 79 | if (/pass|done|deployed|ready|approved|live|success/.test(s)) return "success"; | |
| 80 | if (/working|running|in progress|open/.test(s)) return "info"; | |
| 81 | return "neutral"; | |
| 82 | } | |
| 83 | ||
| 84 | function chipOf(card: MessageCard): CardChip | null { | |
| 85 | if (!card.state) return null; | |
| 86 | if (card.kind === "session") return sessionChip(card.state); | |
| 87 | return cardChip(card) ?? { tone: stateTone(card.state), live: false }; | |
| 88 | } | |
| 89 | ||
| 90 | /** | |
| 91 | * A card's state, as a chip: a session's Working pulses softly in lavender, | |
| 92 | * Needs approval is amber, Done green; a draft issue is outlined lavender | |
| 93 | * until it is filed (green) or discarded (quiet). | |
| 94 | */ | |
| 95 | function StateChip({ state, chip }: { state: string; chip: CardChip }) { | |
| 96 | return ( | |
| 97 | <Badge tone={chip.tone} className={cn("mt-0.5", chip.outline && "bg-transparent")}> | |
| 98 | {chip.live && ( | |
| 99 | <span aria-hidden="true" className="relative flex size-1.5"> | |
| 100 | <span className="absolute inline-flex size-full animate-ping rounded-full bg-current opacity-60 motion-reduce:animate-none" /> | |
| 101 | <span className="relative inline-flex size-1.5 rounded-full bg-current" /> | |
| 102 | </span> | |
| 103 | )} | |
| 104 | {state} | |
| 105 | </Badge> | |
| 106 | ); | |
| 107 | } | |
| 108 | ||
| 109 | // ── What pressing an action said, as a toast above the composer. | |
| 110 | ||
| 111 | type CardToast = { id: number; ok: boolean; message: string }; | |
| 112 | ||
| 113 | const TOAST_MS = 4_500; | |
| 114 | const NO_TOASTS: CardToast[] = []; | |
| 115 | let toasts: CardToast[] = NO_TOASTS; | |
| 116 | let toastSeq = 0; | |
| 117 | const toastListeners = new Set<() => void>(); | |
| 118 | ||
| 119 | function setToasts(next: CardToast[]) { | |
| 120 | toasts = next; | |
| 121 | for (const listener of toastListeners) listener(); | |
| 122 | } | |
| 123 | ||
| 124 | function dismissToast(id: number) { | |
| 125 | setToasts(toasts.filter((t) => t.id !== id)); | |
| 126 | } | |
| 127 | ||
| Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread | 128 | /** Says something in the conversation's toasts: what a card's action did, or that a link was copied. */ |
| 129 | export function showToast(ok: boolean, message: string) { | |
| Cards you act on in chat; agents comment and review as themselves; names shown cleanly; commits on the calendar | 130 | const id = ++toastSeq; |
| 131 | // Three at most; a fourth pushes the oldest out. | |
| 132 | setToasts([...toasts.slice(-2), { id, ok, message }]); | |
| 133 | setTimeout(() => dismissToast(id), ok ? TOAST_MS : TOAST_MS * 1.5); | |
| 134 | } | |
| 135 | ||
| 136 | function subscribeToasts(listener: () => void) { | |
| 137 | toastListeners.add(listener); | |
| 138 | return () => toastListeners.delete(listener); | |
| 139 | } | |
| 140 | ||
| 141 | /** | |
| 142 | * The toasts that say what a card's action did. Put once in a conversation; | |
| 143 | * along the top on a phone, above the composer on a computer, clear of the | |
| 144 | * notification toasts in the corner. | |
| 145 | */ | |
| 146 | export function CardToasts() { | |
| 147 | const list = useSyncExternalStore( | |
| 148 | subscribeToasts, | |
| 149 | () => toasts, | |
| 150 | () => NO_TOASTS, | |
| 151 | ); | |
| 152 | return ( | |
| 153 | <section | |
| 154 | aria-label="Card actions" | |
| 155 | aria-live="polite" | |
| 156 | className="pointer-events-none fixed z-[66] flex flex-col items-center gap-2 max-sm:inset-x-3 max-sm:top-[calc(env(safe-area-inset-top)+0.75rem)] sm:bottom-28 sm:left-1/2 sm:w-[min(26rem,calc(100vw-2rem))] sm:-translate-x-1/2" | |
| 157 | > | |
| 158 | {list.map((toast) => ( | |
| 159 | <div | |
| 160 | key={toast.id} | |
| 161 | role={toast.ok ? "status" : "alert"} | |
| 162 | className={cn( | |
| 163 | "pointer-events-auto flex w-full animate-pop-in items-start gap-2.5 rounded-xl bg-[#17171b] py-2.5 pr-2 pl-3 text-[0.8125rem] leading-snug text-fg shadow-[0_0_0_6px_var(--color-bg),0_20px_48px_-12px_rgba(0,0,0,0.9)] ring-1 motion-reduce:animate-none", | |
| 164 | toast.ok ? "ring-success/35" : "ring-danger/45", | |
| 165 | )} | |
| 166 | > | |
| 167 | <span className={cn("mt-px shrink-0", toast.ok ? "text-success" : "text-danger")} aria-hidden="true"> | |
| 168 | {toast.ok ? <CircleCheck size={16} /> : <CircleAlert size={16} />} | |
| 169 | </span> | |
| 170 | <p className="min-w-0 grow">{toast.message}</p> | |
| 171 | <button | |
| 172 | type="button" | |
| 173 | aria-label="Dismiss" | |
| 174 | onClick={() => dismissToast(toast.id)} | |
| 175 | className="flex size-6 shrink-0 items-center justify-center rounded-md text-faint transition-colors hover:bg-raised hover:text-fg" | |
| 176 | > | |
| 177 | <X size={14} /> | |
| 178 | </button> | |
| 179 | </div> | |
| 180 | ))} | |
| 181 | </section> | |
| 182 | ); | |
| 183 | } | |
| 184 | ||
| 185 | // ── The card. | |
| 186 | ||
| 187 | const ACTION_BASE = | |
| 188 | "inline-flex h-8 shrink-0 items-center justify-center gap-1.5 rounded-md px-3 text-[0.8125rem] font-medium transition-colors outline-none focus-visible:ring-2 focus-visible:ring-accent/50 disabled:pointer-events-none disabled:opacity-50 max-md:h-10 max-md:px-3.5"; | |
| 189 | ||
| 190 | const ACTION_STYLES: Record<NonNullable<CardAction["style"]>, string> = { | |
| 191 | primary: "bg-accent text-bg hover:bg-accent-hover", | |
| 192 | danger: "border border-danger/40 text-danger hover:border-danger hover:bg-danger/10", | |
| 193 | default: "border border-line text-fg/85 hover:border-line-strong hover:bg-raised hover:text-fg", | |
| 194 | }; | |
| 195 | ||
| 196 | function actionClass(action: CardAction, active = false) { | |
| 197 | return cn(ACTION_BASE, ACTION_STYLES[action.style ?? "default"], active && "border-accent/60 bg-raised text-fg"); | |
| 198 | } | |
| 199 | ||
| 200 | /** Sends a card's action; says what happened in a toast; true when it was done. */ | |
| 201 | async function pressAction(slug: string, channelId: string, messageId: string, action: CardAction, input: string | null): Promise<boolean> { | |
| 202 | try { | |
| 203 | const response = await fetch(`/${slug}/-/chat/api`, { | |
| 204 | method: "POST", | |
| 205 | headers: { "content-type": "application/json" }, | |
| 206 | body: JSON.stringify({ intent: "card_action", channel_id: channelId, message_id: messageId, action_id: action.id, input }), | |
| 207 | }); | |
| 208 | const result = (await response.json()) as Result<CardActionResult>; | |
| 209 | if (!result.ok) { | |
| 210 | showToast(false, result.error.message); | |
| 211 | return false; | |
| 212 | } | |
| 213 | showToast(result.value.ok, result.value.message ?? (result.value.ok ? `${action.label}: done.` : `${action.label} didn't work.`)); | |
| 214 | return result.value.ok; | |
| 215 | } catch { | |
| 216 | showToast(false, `${action.label} didn't go through. Try again in a moment.`); | |
| 217 | return false; | |
| 218 | } | |
| 219 | } | |
| 220 | ||
| 221 | /** | |
| 222 | * A card g1t or an agent posted: its title (a link when it goes somewhere), | |
| 223 | * its state, a line of detail, a preview, its facts, and its actions. | |
| 224 | */ | |
| 225 | export function CardBox({ | |
| 226 | card, | |
| 227 | slug, | |
| 228 | code, | |
| 229 | channelId, | |
| 230 | messageId, | |
| 231 | inert = false, | |
| 232 | }: { | |
| 233 | card: MessageCard; | |
| 234 | slug: string; | |
| 235 | /** Whether the viewer uses Code, for where links go. */ | |
| 236 | code: boolean; | |
| 237 | channelId: string; | |
| 238 | messageId: string; | |
| 239 | /** Not yet sent, or gone: drawn, but nothing on it can be pressed. */ | |
| 240 | inert?: boolean; | |
| 241 | }) { | |
| 242 | const href = cardHref(card.href, slug, code); | |
| 243 | const chip = chipOf(card); | |
| 244 | const live = card.kind === "session" && !!chip?.live; | |
| 245 | const actions = shownActions(card); | |
| 246 | const [busy, setBusy] = useState<string | null>(null); | |
| 247 | const [asking, setAsking] = useState<string | null>(null); | |
| 248 | const [confirming, setConfirming] = useState<CardAction | null>(null); | |
| 249 | const triggers = useRef(new Map<string, HTMLButtonElement>()); | |
| 250 | const panelId = useId(); | |
| 251 | const askingAction = actions.find((a) => a.id === asking && a.input) ?? null; | |
| 252 | ||
| 253 | // The card changed under an open field (the session finished, say): the | |
| 254 | // action it was for is gone, so the field goes too. | |
| 255 | useEffect(() => { | |
| 256 | if (asking && !askingAction) setAsking(null); | |
| 257 | }, [asking, askingAction]); | |
| 258 | ||
| 259 | const run = async (action: CardAction, input: string | null = null) => { | |
| 260 | if (busy || inert) return false; | |
| 261 | setBusy(action.id); | |
| 262 | const done = await pressAction(slug, channelId, messageId, action, input); | |
| 263 | setBusy(null); | |
| 264 | return done; | |
| 265 | }; | |
| 266 | ||
| 267 | const press = (action: CardAction) => { | |
| 268 | switch (actionMode(action)) { | |
| 269 | case "input": | |
| 270 | setAsking((now) => (now === action.id ? null : action.id)); | |
| 271 | return; | |
| 272 | case "confirm": | |
| 273 | setConfirming(action); | |
| 274 | return; | |
| 275 | case "run": | |
| 276 | void run(action); | |
| 277 | return; | |
| 278 | } | |
| 279 | }; | |
| 280 | ||
| 281 | const closeField = (refocus: string | null) => { | |
| 282 | setAsking(null); | |
| 283 | if (refocus) requestAnimationFrame(() => triggers.current.get(refocus)?.focus()); | |
| 284 | }; | |
| 285 | ||
| 286 | const head = ( | |
| 287 | <> | |
| 288 | <span | |
| 289 | className={cn( | |
| 290 | "mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg transition-colors", | |
| 291 | live ? "bg-accent/10 text-accent" : "bg-raised text-muted group-hover/card:text-fg", | |
| 292 | )} | |
| 293 | > | |
| 294 | {CARD_ICONS[card.kind] ?? <Sparkles size={16} />} | |
| 295 | </span> | |
| 296 | <span className="min-w-0 grow"> | |
| 297 | <span className={cn("line-clamp-2 text-sm font-medium text-fg", href && "group-hover/head:underline group-hover/head:decoration-line-strong group-hover/head:underline-offset-2")}> | |
| 298 | {card.title} | |
| 299 | </span> | |
| 300 | {card.detail && <span className="mt-0.5 block truncate font-mono text-xs text-muted tabular-nums">{card.detail}</span>} | |
| 301 | </span> | |
| 302 | {card.state && chip && <StateChip state={card.state} chip={chip} />} | |
| 303 | </> | |
| 304 | ); | |
| 305 | ||
| 306 | const repository = card.fields?.find((f) => f.label.toLowerCase() === "repository")?.value; | |
| 307 | ||
| 308 | return ( | |
| 309 | <div | |
| 310 | className={cn( | |
| 311 | "group/card mt-1.5 w-full max-w-xl rounded-xl border bg-surface px-3.5 py-3 transition-[transform,box-shadow,border-color] duration-150", | |
| 312 | "hover:-translate-y-px hover:border-line-strong hover:shadow-lg hover:shadow-black/25 motion-reduce:transition-none motion-reduce:hover:translate-y-0", | |
| 313 | live ? "border-accent/25" : "border-line", | |
| 314 | )} | |
| 315 | > | |
| 316 | {href ? ( | |
| 317 | <Link to={href} className="group/head -m-1 flex items-start gap-3 rounded-lg p-1 outline-none focus-visible:ring-2 focus-visible:ring-accent/50"> | |
| 318 | {head} | |
| 319 | </Link> | |
| 320 | ) : ( | |
| 321 | <div className="flex items-start gap-3">{head}</div> | |
| 322 | )} | |
| 323 | ||
| 324 | {card.body && <CardBody body={card.body} repo={repository} />} | |
| 325 | ||
| 326 | {card.fields && card.fields.length > 0 && ( | |
| 327 | <dl className="mt-2.5 grid grid-cols-2 gap-x-4 gap-y-2 sm:pl-11"> | |
| 328 | {card.fields.map((field) => ( | |
| 329 | <div key={field.label} className="min-w-0"> | |
| 330 | <dt className="text-[0.6875rem] font-medium text-faint">{field.label}</dt> | |
| 331 | <dd className="line-clamp-2 text-xs break-words text-fg-soft"> | |
| 332 | {field.value} | |
| 333 | </dd> | |
| 334 | </div> | |
| 335 | ))} | |
| 336 | </dl> | |
| 337 | )} | |
| 338 | ||
| 339 | {actions.length > 0 && ( | |
| 340 | <div | |
| 341 | role="group" | |
| 342 | aria-label={`${card.title}: actions`} | |
| 343 | className="mt-3 flex flex-wrap items-center gap-2 sm:pl-11" | |
| 344 | aria-busy={busy ? true : undefined} | |
| 345 | // A press here is for the button, not the message's long-press sheet. | |
| 346 | onTouchStart={(event) => event.stopPropagation()} | |
| 347 | > | |
| 348 | {actions.map((action) => { | |
| 349 | const target = actionMode(action) === "link" ? cardHref(action.href, slug, code) : null; | |
| 350 | if (target) { | |
| 351 | return ( | |
| 352 | <Link key={action.id} to={target} className={actionClass(action)}> | |
| 353 | {action.label} | |
| 354 | <ArrowUpRight size={14} aria-hidden="true" className="-mr-0.5 text-faint" /> | |
| 355 | </Link> | |
| 356 | ); | |
| 357 | } | |
| 358 | const working = busy === action.id; | |
| 359 | const opens = !!action.input; | |
| 360 | return ( | |
| 361 | <button | |
| 362 | key={action.id} | |
| 363 | ref={(element) => { | |
| 364 | if (element) triggers.current.set(action.id, element); | |
| 365 | else triggers.current.delete(action.id); | |
| 366 | }} | |
| 367 | type="button" | |
| 368 | disabled={inert || !!busy} | |
| 369 | aria-busy={working || undefined} | |
| 370 | aria-expanded={opens ? asking === action.id : undefined} | |
| 371 | aria-controls={opens && asking === action.id ? panelId : undefined} | |
| 372 | aria-haspopup={action.confirm && !opens ? "dialog" : undefined} | |
| 373 | onClick={() => press(action)} | |
| 374 | className={actionClass(action, opens && asking === action.id)} | |
| 375 | > | |
| 376 | {working && <LoaderCircle size={14} aria-hidden="true" className="-ml-0.5 animate-spin" />} | |
| 377 | {action.label} | |
| 378 | </button> | |
| 379 | ); | |
| 380 | })} | |
| 381 | </div> | |
| 382 | )} | |
| 383 | ||
| 384 | {askingAction && ( | |
| 385 | <ActionField | |
| 386 | key={askingAction.id} | |
| 387 | id={panelId} | |
| 388 | action={askingAction} | |
| 389 | busy={busy === askingAction.id} | |
| 390 | disabled={inert || !!busy} | |
| 391 | onCancel={() => closeField(askingAction.id)} | |
| 392 | onSubmit={async (value) => { | |
| 393 | if (await run(askingAction, value)) closeField(null); | |
| 394 | }} | |
| 395 | /> | |
| 396 | )} | |
| 397 | ||
| 398 | <AlertDialog open={!!confirming} onOpenChange={(open) => !open && setConfirming(null)}> | |
| 399 | <AlertDialogContent> | |
| 400 | <AlertDialogHeader> | |
| 401 | <AlertDialogTitle>{confirming?.label}</AlertDialogTitle> | |
| 402 | <AlertDialogDescription>{confirming?.confirm}</AlertDialogDescription> | |
| 403 | </AlertDialogHeader> | |
| 404 | <AlertDialogFooter> | |
| 405 | <AlertDialogCancel>Cancel</AlertDialogCancel> | |
| 406 | <AlertDialogAction | |
| 407 | className={confirming?.style === "danger" ? undefined : "bg-accent text-bg hover:bg-accent-hover"} | |
| 408 | onClick={() => { | |
| 409 | const action = confirming; | |
| 410 | setConfirming(null); | |
| 411 | if (action) void run(action); | |
| 412 | }} | |
| 413 | > | |
| 414 | {confirming?.label} | |
| 415 | </AlertDialogAction> | |
| 416 | </AlertDialogFooter> | |
| 417 | </AlertDialogContent> | |
| 418 | </AlertDialog> | |
| 419 | </div> | |
| 420 | ); | |
| 421 | } | |
| 422 | ||
| 423 | /** A card's Markdown preview: about eight lines, then "Show more". */ | |
| 424 | function CardBody({ body, repo }: { body: string; repo?: string }) { | |
| 425 | const [open, setOpen] = useState(false); | |
| 426 | // Folded by its length at first (the same on the server), then by whether it really overflows. | |
| 427 | const [folds, setFolds] = useState(() => foldsBody(body)); | |
| 428 | const box = useRef<HTMLDivElement>(null); | |
| 429 | const id = useId(); | |
| 430 | useEffect(() => { | |
| 431 | const element = box.current; | |
| 432 | if (!element || open) return; | |
| 433 | const measure = () => setFolds(element.scrollHeight > element.clientHeight + 2); | |
| 434 | measure(); | |
| 435 | const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure); | |
| 436 | observer?.observe(element); | |
| 437 | return () => observer?.disconnect(); | |
| 438 | }, [body, open]); | |
| 439 | const folded = folds && !open; | |
| 440 | return ( | |
| 441 | <div className="mt-2.5 sm:pl-11"> | |
| 442 | <div | |
| 443 | ref={box} | |
| 444 | id={id} | |
| 445 | className={cn("card-md relative rounded-lg border border-line/70 bg-bg/40 px-3 py-2", !open && "max-h-[11.5rem] overflow-hidden")} | |
| 446 | > | |
| 447 | <Markdown source={body} repo={repoAt(repo)} /> | |
| 448 | {folded && ( | |
| 449 | <span aria-hidden="true" className="pointer-events-none absolute inset-x-0 bottom-0 h-12 rounded-b-lg bg-gradient-to-t from-surface to-transparent" /> | |
| 450 | )} | |
| 451 | </div> | |
| 452 | {(folded || open) && ( | |
| 453 | <button | |
| 454 | type="button" | |
| 455 | aria-expanded={open} | |
| 456 | aria-controls={id} | |
| 457 | onClick={() => setOpen((now) => !now)} | |
| 458 | className="mt-1 rounded px-1 py-0.5 text-xs font-medium text-accent transition-colors outline-none hover:bg-raised focus-visible:ring-2 focus-visible:ring-accent/50 max-md:min-h-9" | |
| 459 | > | |
| 460 | {open ? "Show less" : "Show more"} | |
| 461 | </button> | |
| 462 | )} | |
| 463 | </div> | |
| 464 | ); | |
| 465 | } | |
| 466 | ||
| 467 | /** | |
| 468 | * The value an action needs, asked right under the card: an amount with a | |
| 469 | * "$" before it and the suggestion filled in, or a line of text that grows | |
| 470 | * (Enter sends, Shift+Enter is a new line). Escape puts it away. | |
| 471 | */ | |
| 472 | function ActionField({ | |
| 473 | id, | |
| 474 | action, | |
| 475 | busy, | |
| 476 | disabled, | |
| 477 | onSubmit, | |
| 478 | onCancel, | |
| 479 | }: { | |
| 480 | id: string; | |
| 481 | action: CardAction; | |
| 482 | busy: boolean; | |
| 483 | disabled: boolean; | |
| 484 | onSubmit: (value: string) => void; | |
| 485 | onCancel: () => void; | |
| 486 | }) { | |
| 487 | const input = action.input!; | |
| 488 | const money = input.kind === "money"; | |
| 489 | const [value, setValue] = useState(() => (money ? moneyInitial(input.initial) : (input.initial ?? ""))); | |
| 490 | const [tried, setTried] = useState(false); | |
| 491 | const field = useRef<HTMLInputElement & HTMLTextAreaElement>(null); | |
| 492 | const labelId = useId(); | |
| 493 | const errorId = useId(); | |
| 494 | const ready = inputValue(action, value); | |
| 495 | const invalid = tried && !ready; | |
| 496 | ||
| 497 | useEffect(() => { | |
| 498 | const element = field.current; | |
| 499 | if (!element) return; | |
| 500 | element.focus(); | |
| 501 | if (money) element.select(); | |
| 502 | }, [money]); | |
| 503 | ||
| 504 | // A line of text grows with what is written, up to about six lines. | |
| 505 | useEffect(() => { | |
| 506 | const element = field.current; | |
| 507 | if (money || !element) return; | |
| 508 | element.style.height = "auto"; | |
| 509 | element.style.height = `${Math.min(element.scrollHeight, 160)}px`; | |
| 510 | }, [value, money]); | |
| 511 | ||
| 512 | const submit = (event?: FormEvent) => { | |
| 513 | event?.preventDefault(); | |
| 514 | if (disabled) return; | |
| 515 | if (!ready) { | |
| 516 | setTried(true); | |
| 517 | field.current?.focus(); | |
| 518 | return; | |
| 519 | } | |
| 520 | onSubmit(ready); | |
| 521 | }; | |
| 522 | ||
| 523 | const onKeyDown = (event: KeyboardEvent) => { | |
| 524 | if (event.key === "Escape") { | |
| 525 | event.preventDefault(); | |
| 526 | event.stopPropagation(); | |
| 527 | onCancel(); | |
| 528 | return; | |
| 529 | } | |
| 530 | if (!money && event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) { | |
| 531 | event.preventDefault(); | |
| 532 | submit(); | |
| 533 | } | |
| 534 | }; | |
| 535 | ||
| 536 | return ( | |
| 537 | <form | |
| 538 | id={id} | |
| 539 | onSubmit={submit} | |
| 540 | onTouchStart={(event) => event.stopPropagation()} | |
| 541 | className="mt-3 animate-pop-in sm:pl-11 motion-reduce:animate-none" | |
| 542 | aria-labelledby={labelId} | |
| 543 | > | |
| 544 | <label id={labelId} htmlFor={`${id}-field`} className="mb-1.5 block text-xs font-medium text-muted"> | |
| 545 | {input.label || action.label} | |
| 546 | </label> | |
| 547 | <div className="flex flex-col gap-2 sm:flex-row sm:items-end"> | |
| 548 | {money ? ( | |
| 549 | <InputGroup className={cn("sm:max-w-44 max-md:h-10", invalid && "border-danger/70")}> | |
| 550 | <InputAddon className="pr-0 font-mono text-muted">$</InputAddon> | |
| 551 | <input | |
| 552 | ref={field} | |
| 553 | id={`${id}-field`} | |
| 554 | value={value} | |
| 555 | onChange={(event) => { | |
| 556 | setValue(event.target.value); | |
| 557 | setTried(false); | |
| 558 | }} | |
| 559 | onKeyDown={onKeyDown} | |
| 560 | inputMode="decimal" | |
| 561 | autoComplete="off" | |
| 562 | data-1p-ignore | |
| 563 | placeholder={input.placeholder ?? "0.00"} | |
| 564 | aria-invalid={invalid || undefined} | |
| 565 | aria-describedby={invalid ? errorId : undefined} | |
| 566 | className="w-full min-w-0 bg-transparent pr-3 pl-1 font-mono text-sm text-fg tabular-nums outline-none placeholder:text-faint" | |
| 567 | /> | |
| 568 | </InputGroup> | |
| 569 | ) : ( | |
| 570 | <textarea | |
| 571 | ref={field} | |
| 572 | id={`${id}-field`} | |
| 573 | rows={1} | |
| 574 | value={value} | |
| 575 | onChange={(event) => { | |
| 576 | setValue(event.target.value); | |
| 577 | setTried(false); | |
| 578 | }} | |
| 579 | onKeyDown={onKeyDown} | |
| 580 | autoComplete="off" | |
| 581 | data-1p-ignore | |
| 582 | placeholder={input.placeholder ?? undefined} | |
| 583 | aria-invalid={invalid || undefined} | |
| 584 | aria-describedby={invalid ? errorId : undefined} | |
| 585 | className="min-h-9 w-full min-w-0 grow resize-none rounded-md border border-line bg-bg px-3 py-[0.4375rem] text-sm leading-5 text-fg outline-none transition-[border-color,box-shadow] placeholder:text-faint hover:border-line-strong focus-visible:border-accent-dim focus-visible:ring-2 focus-visible:ring-accent/25 aria-invalid:border-danger/70 max-md:min-h-10 max-md:text-base" | |
| 586 | /> | |
| 587 | )} | |
| 588 | <div className="flex shrink-0 gap-2 max-sm:[&>*]:grow"> | |
| 589 | <button type="button" onClick={onCancel} className={actionClass({ id: "cancel", label: "Cancel" })}> | |
| 590 | Cancel | |
| 591 | </button> | |
| 592 | <button type="submit" disabled={disabled} aria-busy={busy || undefined} className={actionClass({ ...action, style: action.style === "danger" ? "danger" : "primary" })}> | |
| 593 | {busy && <LoaderCircle size={14} aria-hidden="true" className="-ml-0.5 animate-spin" />} | |
| 594 | {action.label} | |
| 595 | </button> | |
| 596 | </div> | |
| 597 | </div> | |
| 598 | {invalid ? ( | |
| 599 | <p id={errorId} className="mt-1.5 text-xs text-danger"> | |
| 600 | {money ? "Enter an amount in dollars, like 5.00." : "Write something first."} | |
| 601 | </p> | |
| 602 | ) : ( | |
| 603 | !money && <p className="mt-1.5 text-[0.6875rem] text-faint max-md:hidden">Enter to send, Shift+Enter for a new line, Esc to close</p> | |
| 604 | )} | |
| 605 | </form> | |
| 606 | ); | |
| 607 | } |