/** * HTTP Client tool window: the response history (left) and the selected * exchange (right): status line, timing, body (pretty-printed JSON / XML / * HTML or raw), response headers and the request as sent. */ import { Fragment, useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import clsx from "clsx"; import type { HttpExchange, HttpHistoryEntry } from "@/platform/ipc"; import { Button, EmptyState, IconButton, SplitGroup, SplitHandle, SplitPanel, Spinner, Tabs, T, useSelectionBoundary, } from "@/ui"; import { ConsoleFindBar } from "@/ui/ConsoleFindBar"; import { DEFAULT_FIND_OPTIONS, findInLines, type ConsoleMatch, type FindOptions } from "@/ui/consoleFind"; import { formatBinding, hasPrimaryModifier, hostBinding } from "@/platform/keymap"; import { bodyKind, formatMs, formatSize, prettyBody } from "./format"; import { cancelRunning, clearHistory, refreshHistory, selectEntry, useHttpClient } from "./store"; import styles from "./HttpClient.module.css"; import { tx } from "@/platform/i18n"; function statusTone(status: number | null | undefined): string { if (status == null) return styles.statusError ?? ""; if (status >= 500 || status >= 400) return styles.statusError ?? ""; if (status >= 300) return styles.statusRedirect ?? ""; return styles.statusOk ?? ""; } function time(ms: number | null): string { return new Date(ms ?? 0).toLocaleTimeString(); } function EntryRow({ entry, selected }: { entry: HttpHistoryEntry; selected: boolean }) { return ( ); } type Tab = "body" | "headers" | "request"; function ExchangeView({ ex }: { ex: HttpExchange }) { const [tab, setTab] = useState("body"); const pane = useRef(null); useSelectionBoundary(pane); const [raw, setRaw] = useState(false); const r = ex.response; const kind = r?.body != null ? bodyKind(r.contentType, r.body) : "text"; const body = useMemo(() => (r?.body == null ? null : raw ? r.body : prettyBody(kind, r.body)), [r, raw, kind]); const [findOpen, setFindOpen] = useState(false); const [query, setQuery] = useState(""); const [findOptions, setFindOptions] = useState(DEFAULT_FIND_OPTIONS); const [active, setActive] = useState(0); const findInput = useRef(null); const searchable = findOpen && tab === "body" && body != null; const lines = useMemo(() => (body ?? "").split("\n").map((text, id) => ({ id, text })), [body]); const found = useMemo( () => (searchable ? findInLines(lines, query, findOptions) : { matches: [], overflow: false, invalid: false }), [searchable, lines, query, findOptions], ); const activeIndex = found.matches.length ? Math.min(active, found.matches.length - 1) : -1; useEffect(() => { pane.current?.querySelector("[data-find-current]")?.scrollIntoView({ block: "nearest", inline: "nearest" }); }, [activeIndex, found]); const openFind = () => { setFindOpen(true); // The bar mounts with this render; focus it (and select the query) once it has. requestAnimationFrame(() => findInput.current?.select()); }; const closeFind = () => { setFindOpen(false); pane.current?.focus(); }; const goToMatch = (step: number) => { const n = found.matches.length; if (n) setActive((activeIndex + step + n) % n); }; // ⌘F in the response, as in IDEA's response viewer: the find bar of the Run console. const onKeyDown = (e: KeyboardEvent) => { if ( tab === "body" && body != null && e.key.toLowerCase() === "f" && hasPrimaryModifier(e) && !e.altKey && !e.shiftKey ) { e.preventDefault(); e.stopPropagation(); openFind(); } }; return (
{r ? ( <> {r.status} {r.statusText} {r.version} {formatMs(r.totalMs)} {formatSize(r.size)} ) : ( {ex.entry.error ?? "No response"} )} {ex.request.method} {ex.request.url}
setTab(id as Tab)} items={[ { id: "body", label: "Response" }, { id: "headers", label: r ? tx`Headers (${r.headers.length})` : "Headers" }, { id: "request", label: "Request" }, ]} trailing={ tab === "body" && body != null ? ( <> (findOpen ? closeFind() : openFind())} /> {kind !== "text" && ( setRaw((v) => !v)} /> )} ) : undefined } /> {searchable && ( { setQuery(q); setActive(0); }} options={findOptions} onOptionsChange={(o) => { setFindOptions(o); setActive(0); }} count={found.matches.length} active={activeIndex} overflow={found.overflow} invalid={found.invalid} inputRef={findInput} onNext={() => goToMatch(1)} onPrevious={() => goToMatch(-1)} onClose={closeFind} label="Find in response" /> )} {/* Focusable, so Select All and Copy work on the response like in a read-only editor. */}
{tab === "body" && (r == null ? (
{ex.entry.error}
) : body == null ? ( {r.contentType ?? tx("unknown type")}, {formatSize(r.size)} ) : (
              {found.matches.length ? highlighted(lines, found.matches, activeIndex) : body}
              {r.truncated && (
                {`\n… truncated (${formatSize(r.size)} received)`}
              )}
            
))} {tab === "headers" && r && } {tab === "request" && (
            {`${ex.request.method} ${ex.request.url}\n`}
            {ex.request.headers.map(([k, v]) => `${k}: ${v}\n`).join("")}
            {ex.request.body != null ? `\n${ex.request.body}` : ""}
          
)}
); } /** The body with its find matches marked, the current one distinctly. */ function highlighted(lines: readonly { text: string }[], matches: readonly ConsoleMatch[], current: number): ReactNode { const out: ReactNode[] = []; let m = 0; lines.forEach(({ text }, line) => { if (line > 0) out.push("\n"); let at = 0; for (; m < matches.length && matches[m]!.line === line; m++) { const { start, end } = matches[m]!; if (start > at) out.push(text.slice(at, start)); out.push( {text.slice(start, end)} , ); at = end; } if (at < text.length) out.push(text.slice(at)); }); return {out}; } function HeaderTable({ headers }: { headers: Array<[string, string]> }) { return ( {headers.map(([k, v], i) => ( ))}
{k} {v}
); } export function HttpClientView() { const history = useHttpClient((s) => s.history); const selected = useHttpClient((s) => s.selected); const exchange = useHttpClient((s) => (s.selected ? s.exchanges[s.selected] : undefined)); const running = useHttpClient((s) => s.running); useEffect(() => { void refreshHistory(); }, []); return (
{running && (
{tx`Sending request #${running.index + 1}…`}
)} {history.length === 0 && !running ? ( Run a request from an .http file with the gutter ▶ or ⌘↩. ) : ( history.map((h) => ) )}
{running ? (
{tx`Sending request #${running.index + 1}…`}
{running.method && (
{running.method} {running.url}
)}
) : exchange ? ( ) : selected ? (
) : ( )}
); } export function HttpClientHeaderActions() { const running = useHttpClient((s) => !!s.running); return ( <> void refreshHistory()} /> void clearHistory()} /> ); }