| 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 | |
| 128 | function showToast(ok: boolean, message: string) { |
| 129 | const id = ++toastSeq; |
| 130 | // Three at most; a fourth pushes the oldest out. |
| 131 | setToasts([...toasts.slice(-2), { id, ok, message }]); |
| 132 | setTimeout(() => dismissToast(id), ok ? TOAST_MS : TOAST_MS * 1.5); |
| 133 | } |
| 134 | |
| 135 | function subscribeToasts(listener: () => void) { |
| 136 | toastListeners.add(listener); |
| 137 | return () => toastListeners.delete(listener); |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * The toasts that say what a card's action did. Put once in a conversation; |
| 142 | * along the top on a phone, above the composer on a computer, clear of the |
| 143 | * notification toasts in the corner. |
| 144 | */ |
| 145 | export function CardToasts() { |
| 146 | const list = useSyncExternalStore( |
| 147 | subscribeToasts, |
| 148 | () => toasts, |
| 149 | () => NO_TOASTS, |
| 150 | ); |
| 151 | return ( |
| 152 | <section |
| 153 | aria-label="Card actions" |
| 154 | aria-live="polite" |
| 155 | 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" |
| 156 | > |
| 157 | {list.map((toast) => ( |
| 158 | <div |
| 159 | key={toast.id} |
| 160 | role={toast.ok ? "status" : "alert"} |
| 161 | className={cn( |
| 162 | "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", |
| 163 | toast.ok ? "ring-success/35" : "ring-danger/45", |
| 164 | )} |
| 165 | > |
| 166 | <span className={cn("mt-px shrink-0", toast.ok ? "text-success" : "text-danger")} aria-hidden="true"> |
| 167 | {toast.ok ? <CircleCheck size={16} /> : <CircleAlert size={16} />} |
| 168 | </span> |
| 169 | <p className="min-w-0 grow">{toast.message}</p> |
| 170 | <button |
| 171 | type="button" |
| 172 | aria-label="Dismiss" |
| 173 | onClick={() => dismissToast(toast.id)} |
| 174 | className="flex size-6 shrink-0 items-center justify-center rounded-md text-faint transition-colors hover:bg-raised hover:text-fg" |
| 175 | > |
| 176 | <X size={14} /> |
| 177 | </button> |
| 178 | </div> |
| 179 | ))} |
| 180 | </section> |
| 181 | ); |
| 182 | } |
| 183 | |
| 184 | // ── The card. |
| 185 | |
| 186 | const ACTION_BASE = |
| 187 | "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"; |
| 188 | |
| 189 | const ACTION_STYLES: Record<NonNullable<CardAction["style"]>, string> = { |
| 190 | primary: "bg-accent text-bg hover:bg-accent-hover", |
| 191 | danger: "border border-danger/40 text-danger hover:border-danger hover:bg-danger/10", |
| 192 | default: "border border-line text-fg/85 hover:border-line-strong hover:bg-raised hover:text-fg", |
| 193 | }; |
| 194 | |
| 195 | function actionClass(action: CardAction, active = false) { |
| 196 | return cn(ACTION_BASE, ACTION_STYLES[action.style ?? "default"], active && "border-accent/60 bg-raised text-fg"); |
| 197 | } |
| 198 | |
| 199 | /** Sends a card's action; says what happened in a toast; true when it was done. */ |
| 200 | async function pressAction(slug: string, channelId: string, messageId: string, action: CardAction, input: string | null): Promise<boolean> { |
| 201 | try { |
| 202 | const response = await fetch(`/${slug}/-/chat/api`, { |
| 203 | method: "POST", |
| 204 | headers: { "content-type": "application/json" }, |
| 205 | body: JSON.stringify({ intent: "card_action", channel_id: channelId, message_id: messageId, action_id: action.id, input }), |
| 206 | }); |
| 207 | const result = (await response.json()) as Result<CardActionResult>; |
| 208 | if (!result.ok) { |
| 209 | showToast(false, result.error.message); |
| 210 | return false; |
| 211 | } |
| 212 | showToast(result.value.ok, result.value.message ?? (result.value.ok ? `${action.label}: done.` : `${action.label} didn't work.`)); |
| 213 | return result.value.ok; |
| 214 | } catch { |
| 215 | showToast(false, `${action.label} didn't go through. Try again in a moment.`); |
| 216 | return false; |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | /** |
| 221 | * A card g1t or an agent posted: its title (a link when it goes somewhere), |
| 222 | * its state, a line of detail, a preview, its facts, and its actions. |
| 223 | */ |
| 224 | export function CardBox({ |
| 225 | card, |
| 226 | slug, |
| 227 | code, |
| 228 | channelId, |
| 229 | messageId, |
| 230 | inert = false, |
| 231 | }: { |
| 232 | card: MessageCard; |
| 233 | slug: string; |
| 234 | /** Whether the viewer uses Code, for where links go. */ |
| 235 | code: boolean; |
| 236 | channelId: string; |
| 237 | messageId: string; |
| 238 | /** Not yet sent, or gone: drawn, but nothing on it can be pressed. */ |
| 239 | inert?: boolean; |
| 240 | }) { |
| 241 | const href = cardHref(card.href, slug, code); |
| 242 | const chip = chipOf(card); |
| 243 | const live = card.kind === "session" && !!chip?.live; |
| 244 | const actions = shownActions(card); |
| 245 | const [busy, setBusy] = useState<string | null>(null); |
| 246 | const [asking, setAsking] = useState<string | null>(null); |
| 247 | const [confirming, setConfirming] = useState<CardAction | null>(null); |
| 248 | const triggers = useRef(new Map<string, HTMLButtonElement>()); |
| 249 | const panelId = useId(); |
| 250 | const askingAction = actions.find((a) => a.id === asking && a.input) ?? null; |
| 251 | |
| 252 | // The card changed under an open field (the session finished, say): the |
| 253 | // action it was for is gone, so the field goes too. |
| 254 | useEffect(() => { |
| 255 | if (asking && !askingAction) setAsking(null); |
| 256 | }, [asking, askingAction]); |
| 257 | |
| 258 | const run = async (action: CardAction, input: string | null = null) => { |
| 259 | if (busy || inert) return false; |
| 260 | setBusy(action.id); |
| 261 | const done = await pressAction(slug, channelId, messageId, action, input); |
| 262 | setBusy(null); |
| 263 | return done; |
| 264 | }; |
| 265 | |
| 266 | const press = (action: CardAction) => { |
| 267 | switch (actionMode(action)) { |
| 268 | case "input": |
| 269 | setAsking((now) => (now === action.id ? null : action.id)); |
| 270 | return; |
| 271 | case "confirm": |
| 272 | setConfirming(action); |
| 273 | return; |
| 274 | case "run": |
| 275 | void run(action); |
| 276 | return; |
| 277 | } |
| 278 | }; |
| 279 | |
| 280 | const closeField = (refocus: string | null) => { |
| 281 | setAsking(null); |
| 282 | if (refocus) requestAnimationFrame(() => triggers.current.get(refocus)?.focus()); |
| 283 | }; |
| 284 | |
| 285 | const head = ( |
| 286 | <> |
| 287 | <span |
| 288 | className={cn( |
| 289 | "mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg transition-colors", |
| 290 | live ? "bg-accent/10 text-accent" : "bg-raised text-muted group-hover/card:text-fg", |
| 291 | )} |
| 292 | > |
| 293 | {CARD_ICONS[card.kind] ?? <Sparkles size={16} />} |
| 294 | </span> |
| 295 | <span className="min-w-0 grow"> |
| 296 | <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")}> |
| 297 | {card.title} |
| 298 | </span> |
| 299 | {card.detail && <span className="mt-0.5 block truncate font-mono text-xs text-muted tabular-nums">{card.detail}</span>} |
| 300 | </span> |
| 301 | {card.state && chip && <StateChip state={card.state} chip={chip} />} |
| 302 | </> |
| 303 | ); |
| 304 | |
| 305 | const repository = card.fields?.find((f) => f.label.toLowerCase() === "repository")?.value; |
| 306 | |
| 307 | return ( |
| 308 | <div |
| 309 | className={cn( |
| 310 | "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", |
| 311 | "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", |
| 312 | live ? "border-accent/25" : "border-line", |
| 313 | )} |
| 314 | > |
| 315 | {href ? ( |
| 316 | <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"> |
| 317 | {head} |
| 318 | </Link> |
| 319 | ) : ( |
| 320 | <div className="flex items-start gap-3">{head}</div> |
| 321 | )} |
| 322 | |
| 323 | {card.body && <CardBody body={card.body} repo={repository} />} |
| 324 | |
| 325 | {card.fields && card.fields.length > 0 && ( |
| 326 | <dl className="mt-2.5 grid grid-cols-2 gap-x-4 gap-y-2 sm:pl-11"> |
| 327 | {card.fields.map((field) => ( |
| 328 | <div key={field.label} className="min-w-0"> |
| 329 | <dt className="text-[0.6875rem] font-medium text-faint">{field.label}</dt> |
| 330 | <dd className="line-clamp-2 text-xs break-words text-fg-soft"> |
| 331 | {field.value} |
| 332 | </dd> |
| 333 | </div> |
| 334 | ))} |
| 335 | </dl> |
| 336 | )} |
| 337 | |
| 338 | {actions.length > 0 && ( |
| 339 | <div |
| 340 | role="group" |
| 341 | aria-label={`${card.title}: actions`} |
| 342 | className="mt-3 flex flex-wrap items-center gap-2 sm:pl-11" |
| 343 | aria-busy={busy ? true : undefined} |
| 344 | // A press here is for the button, not the message's long-press sheet. |
| 345 | onTouchStart={(event) => event.stopPropagation()} |
| 346 | > |
| 347 | {actions.map((action) => { |
| 348 | const target = actionMode(action) === "link" ? cardHref(action.href, slug, code) : null; |
| 349 | if (target) { |
| 350 | return ( |
| 351 | <Link key={action.id} to={target} className={actionClass(action)}> |
| 352 | {action.label} |
| 353 | <ArrowUpRight size={14} aria-hidden="true" className="-mr-0.5 text-faint" /> |
| 354 | </Link> |
| 355 | ); |
| 356 | } |
| 357 | const working = busy === action.id; |
| 358 | const opens = !!action.input; |
| 359 | return ( |
| 360 | <button |
| 361 | key={action.id} |
| 362 | ref={(element) => { |
| 363 | if (element) triggers.current.set(action.id, element); |
| 364 | else triggers.current.delete(action.id); |
| 365 | }} |
| 366 | type="button" |
| 367 | disabled={inert || !!busy} |
| 368 | aria-busy={working || undefined} |
| 369 | aria-expanded={opens ? asking === action.id : undefined} |
| 370 | aria-controls={opens && asking === action.id ? panelId : undefined} |
| 371 | aria-haspopup={action.confirm && !opens ? "dialog" : undefined} |
| 372 | onClick={() => press(action)} |
| 373 | className={actionClass(action, opens && asking === action.id)} |
| 374 | > |
| 375 | {working && <LoaderCircle size={14} aria-hidden="true" className="-ml-0.5 animate-spin" />} |
| 376 | {action.label} |
| 377 | </button> |
| 378 | ); |
| 379 | })} |
| 380 | </div> |
| 381 | )} |
| 382 | |
| 383 | {askingAction && ( |
| 384 | <ActionField |
| 385 | key={askingAction.id} |
| 386 | id={panelId} |
| 387 | action={askingAction} |
| 388 | busy={busy === askingAction.id} |
| 389 | disabled={inert || !!busy} |
| 390 | onCancel={() => closeField(askingAction.id)} |
| 391 | onSubmit={async (value) => { |
| 392 | if (await run(askingAction, value)) closeField(null); |
| 393 | }} |
| 394 | /> |
| 395 | )} |
| 396 | |
| 397 | <AlertDialog open={!!confirming} onOpenChange={(open) => !open && setConfirming(null)}> |
| 398 | <AlertDialogContent> |
| 399 | <AlertDialogHeader> |
| 400 | <AlertDialogTitle>{confirming?.label}</AlertDialogTitle> |
| 401 | <AlertDialogDescription>{confirming?.confirm}</AlertDialogDescription> |
| 402 | </AlertDialogHeader> |
| 403 | <AlertDialogFooter> |
| 404 | <AlertDialogCancel>Cancel</AlertDialogCancel> |
| 405 | <AlertDialogAction |
| 406 | className={confirming?.style === "danger" ? undefined : "bg-accent text-bg hover:bg-accent-hover"} |
| 407 | onClick={() => { |
| 408 | const action = confirming; |
| 409 | setConfirming(null); |
| 410 | if (action) void run(action); |
| 411 | }} |
| 412 | > |
| 413 | {confirming?.label} |
| 414 | </AlertDialogAction> |
| 415 | </AlertDialogFooter> |
| 416 | </AlertDialogContent> |
| 417 | </AlertDialog> |
| 418 | </div> |
| 419 | ); |
| 420 | } |
| 421 | |
| 422 | /** A card's Markdown preview: about eight lines, then "Show more". */ |
| 423 | function CardBody({ body, repo }: { body: string; repo?: string }) { |
| 424 | const [open, setOpen] = useState(false); |
| 425 | // Folded by its length at first (the same on the server), then by whether it really overflows. |
| 426 | const [folds, setFolds] = useState(() => foldsBody(body)); |
| 427 | const box = useRef<HTMLDivElement>(null); |
| 428 | const id = useId(); |
| 429 | useEffect(() => { |
| 430 | const element = box.current; |
| 431 | if (!element || open) return; |
| 432 | const measure = () => setFolds(element.scrollHeight > element.clientHeight + 2); |
| 433 | measure(); |
| 434 | const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure); |
| 435 | observer?.observe(element); |
| 436 | return () => observer?.disconnect(); |
| 437 | }, [body, open]); |
| 438 | const folded = folds && !open; |
| 439 | return ( |
| 440 | <div className="mt-2.5 sm:pl-11"> |
| 441 | <div |
| 442 | ref={box} |
| 443 | id={id} |
| 444 | 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")} |
| 445 | > |
| 446 | <Markdown source={body} repo={repoAt(repo)} /> |
| 447 | {folded && ( |
| 448 | <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" /> |
| 449 | )} |
| 450 | </div> |
| 451 | {(folded || open) && ( |
| 452 | <button |
| 453 | type="button" |
| 454 | aria-expanded={open} |
| 455 | aria-controls={id} |
| 456 | onClick={() => setOpen((now) => !now)} |
| 457 | 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" |
| 458 | > |
| 459 | {open ? "Show less" : "Show more"} |
| 460 | </button> |
| 461 | )} |
| 462 | </div> |
| 463 | ); |
| 464 | } |
| 465 | |
| 466 | /** |
| 467 | * The value an action needs, asked right under the card: an amount with a |
| 468 | * "$" before it and the suggestion filled in, or a line of text that grows |
| 469 | * (Enter sends, Shift+Enter is a new line). Escape puts it away. |
| 470 | */ |
| 471 | function ActionField({ |
| 472 | id, |
| 473 | action, |
| 474 | busy, |
| 475 | disabled, |
| 476 | onSubmit, |
| 477 | onCancel, |
| 478 | }: { |
| 479 | id: string; |
| 480 | action: CardAction; |
| 481 | busy: boolean; |
| 482 | disabled: boolean; |
| 483 | onSubmit: (value: string) => void; |
| 484 | onCancel: () => void; |
| 485 | }) { |
| 486 | const input = action.input!; |
| 487 | const money = input.kind === "money"; |
| 488 | const [value, setValue] = useState(() => (money ? moneyInitial(input.initial) : (input.initial ?? ""))); |
| 489 | const [tried, setTried] = useState(false); |
| 490 | const field = useRef<HTMLInputElement & HTMLTextAreaElement>(null); |
| 491 | const labelId = useId(); |
| 492 | const errorId = useId(); |
| 493 | const ready = inputValue(action, value); |
| 494 | const invalid = tried && !ready; |
| 495 | |
| 496 | useEffect(() => { |
| 497 | const element = field.current; |
| 498 | if (!element) return; |
| 499 | element.focus(); |
| 500 | if (money) element.select(); |
| 501 | }, [money]); |
| 502 | |
| 503 | // A line of text grows with what is written, up to about six lines. |
| 504 | useEffect(() => { |
| 505 | const element = field.current; |
| 506 | if (money || !element) return; |
| 507 | element.style.height = "auto"; |
| 508 | element.style.height = `${Math.min(element.scrollHeight, 160)}px`; |
| 509 | }, [value, money]); |
| 510 | |
| 511 | const submit = (event?: FormEvent) => { |
| 512 | event?.preventDefault(); |
| 513 | if (disabled) return; |
| 514 | if (!ready) { |
| 515 | setTried(true); |
| 516 | field.current?.focus(); |
| 517 | return; |
| 518 | } |
| 519 | onSubmit(ready); |
| 520 | }; |
| 521 | |
| 522 | const onKeyDown = (event: KeyboardEvent) => { |
| 523 | if (event.key === "Escape") { |
| 524 | event.preventDefault(); |
| 525 | event.stopPropagation(); |
| 526 | onCancel(); |
| 527 | return; |
| 528 | } |
| 529 | if (!money && event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) { |
| 530 | event.preventDefault(); |
| 531 | submit(); |
| 532 | } |
| 533 | }; |
| 534 | |
| 535 | return ( |
| 536 | <form |
| 537 | id={id} |
| 538 | onSubmit={submit} |
| 539 | onTouchStart={(event) => event.stopPropagation()} |
| 540 | className="mt-3 animate-pop-in sm:pl-11 motion-reduce:animate-none" |
| 541 | aria-labelledby={labelId} |
| 542 | > |
| 543 | <label id={labelId} htmlFor={`${id}-field`} className="mb-1.5 block text-xs font-medium text-muted"> |
| 544 | {input.label || action.label} |
| 545 | </label> |
| 546 | <div className="flex flex-col gap-2 sm:flex-row sm:items-end"> |
| 547 | {money ? ( |
| 548 | <InputGroup className={cn("sm:max-w-44 max-md:h-10", invalid && "border-danger/70")}> |
| 549 | <InputAddon className="pr-0 font-mono text-muted">$</InputAddon> |
| 550 | <input |
| 551 | ref={field} |
| 552 | id={`${id}-field`} |
| 553 | value={value} |
| 554 | onChange={(event) => { |
| 555 | setValue(event.target.value); |
| 556 | setTried(false); |
| 557 | }} |
| 558 | onKeyDown={onKeyDown} |
| 559 | inputMode="decimal" |
| 560 | autoComplete="off" |
| 561 | data-1p-ignore |
| 562 | placeholder={input.placeholder ?? "0.00"} |
| 563 | aria-invalid={invalid || undefined} |
| 564 | aria-describedby={invalid ? errorId : undefined} |
| 565 | 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" |
| 566 | /> |
| 567 | </InputGroup> |
| 568 | ) : ( |
| 569 | <textarea |
| 570 | ref={field} |
| 571 | id={`${id}-field`} |
| 572 | rows={1} |
| 573 | value={value} |
| 574 | onChange={(event) => { |
| 575 | setValue(event.target.value); |
| 576 | setTried(false); |
| 577 | }} |
| 578 | onKeyDown={onKeyDown} |
| 579 | autoComplete="off" |
| 580 | data-1p-ignore |
| 581 | placeholder={input.placeholder ?? undefined} |
| 582 | aria-invalid={invalid || undefined} |
| 583 | aria-describedby={invalid ? errorId : undefined} |
| 584 | 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" |
| 585 | /> |
| 586 | )} |
| 587 | <div className="flex shrink-0 gap-2 max-sm:[&>*]:grow"> |
| 588 | <button type="button" onClick={onCancel} className={actionClass({ id: "cancel", label: "Cancel" })}> |
| 589 | Cancel |
| 590 | </button> |
| 591 | <button type="submit" disabled={disabled} aria-busy={busy || undefined} className={actionClass({ ...action, style: action.style === "danger" ? "danger" : "primary" })}> |
| 592 | {busy && <LoaderCircle size={14} aria-hidden="true" className="-ml-0.5 animate-spin" />} |
| 593 | {action.label} |
| 594 | </button> |
| 595 | </div> |
| 596 | </div> |
| 597 | {invalid ? ( |
| 598 | <p id={errorId} className="mt-1.5 text-xs text-danger"> |
| 599 | {money ? "Enter an amount in dollars, like 5.00." : "Write something first."} |
| 600 | </p> |
| 601 | ) : ( |
| 602 | !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> |
| 603 | )} |
| 604 | </form> |
| 605 | ); |
| 606 | } |