import { useVirtualizer } from "@tanstack/react-virtual"; import { formatSize } from "@yaakapp-internal/lib/formatSize"; import type { Flow } from "@yaakapp-internal/proxy-lib"; import { ContextMenu, formatMillis, HttpMethodTagRaw, HttpStatusTagRaw, Icon, } from "@yaakapp-internal/ui"; import classNames from "classnames"; import { useAtom, useAtomValue, useSetAtom } from "jotai"; import type { CSSProperties, KeyboardEvent, MouseEvent, WheelEvent } from "react"; import { memo, useCallback, useLayoutEffect, useRef, useState } from "react"; import { selectedFlowAtom, selectedFlowIdAtom } from "../lib/atoms"; import { shortContentType } from "../lib/body"; import { useFlowActions } from "../lib/flowActions"; import { compareFlows } from "../lib/flowWindow"; import { countNewFlows } from "../lib/follow"; import { activeQueryAtom, followAtom, hasAppsAtom, loadOlderFlowsAtom, newestStartedAtAtom, oldestFlowAtom, searchWindowAtom, shownFlowsAtom, } from "../lib/store"; import { AppIcon } from "./AppIcon"; import { SearchBar } from "./SearchBar"; const ROW_HEIGHT = 24; const BOTTOM_PADDING = 6; /** Rows from the top at which older flows start loading */ const LOAD_OLDER_ROWS = 20; interface Props { sideBySide: boolean; style?: CSSProperties; className?: string; } /** * Follows new traffic until a flow is selected or the list is scrolled, then holds. Scrolling to * the top loads older flows from the database. */ export function FlowList({ sideBySide, style, className }: Props) { const flows = useAtomValue(shownFlowsAtom); const hasApps = useAtomValue(hasAppsAtom); const [menu, setMenu] = useState<{ flow: Flow; x: number; y: number } | null>(null); const flowActions = useFlowActions(); const selectedId = useAtomValue(selectedFlowIdAtom); const setSelectedFlow = useSetAtom(selectedFlowAtom); const loadOlder = useSetAtom(loadOlderFlowsAtom); const oldestFlow = useAtomValue(oldestFlowAtom); const scrollRef = useRef(null); const ignoreScroll = useRef(false); const [following, setFollowing] = useAtom(followAtom); const [heldAt, setHeldAt] = useState(null); // The newest flow across all traffic, not just this list, so a filter change keeps the hold const newestStartedAt = useAtomValue(newestStartedAtAtom); // Read by the callbacks below, which stay the same across new traffic so rows don't re-render const latest = useRef({ flows, following, newestStartedAt }); useLayoutEffect(() => { latest.current = { flows, following, newestStartedAt }; }); const virtualizer = useVirtualizer({ count: flows.length, getScrollElement: () => scrollRef.current, estimateSize: () => ROW_HEIGHT, getItemKey: (index) => flows[index]?.id ?? index, paddingEnd: BOTTOM_PADDING, overscan: 40, }); const setScrollTop = useCallback((top: number) => { const el = scrollRef.current; if (el == null) return; const max = el.scrollHeight - el.clientHeight; const next = Math.max(0, Math.min(top, max)); if (Math.abs(el.scrollTop - next) < 1) return; ignoreScroll.current = true; el.scrollTop = next; }, []); const hold = useCallback(() => { if (!latest.current.following) return; setFollowing(false); setHeldAt(latest.current.newestStartedAt); }, [setFollowing]); const follow = useCallback(() => { setFollowing(true); setHeldAt(null); setScrollTop(Number.MAX_SAFE_INTEGER); }, [setFollowing, setScrollTop]); useLayoutEffect(() => { if (following) setScrollTop(Number.MAX_SAFE_INTEGER); }, [following, flows, setScrollTop]); // Older flows that loaded in above push the rows down; scroll by as much, so they stay put. const anchor = useRef(null); useLayoutEffect(() => { const previous = anchor.current; anchor.current = oldestFlow; if (following || previous == null || oldestFlow == null) return; if (compareFlows(oldestFlow, previous) >= 0) return; const added = flows.findIndex((f) => compareFlows(f, previous) >= 0); const el = scrollRef.current; if (added > 0 && el != null) setScrollTop(el.scrollTop + added * ROW_HEIGHT); }, [oldestFlow, flows, following, setScrollTop]); const loadOlderHeld = useCallback(() => { hold(); void loadOlder(); }, [hold, loadOlder]); const handleScroll = useCallback(() => { if (ignoreScroll.current) { ignoreScroll.current = false; return; } const el = scrollRef.current; if (el == null) return; const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 2; if (atEnd) { setFollowing(true); setHeldAt(null); } else { hold(); if (el.scrollTop < LOAD_OLDER_ROWS * ROW_HEIGHT) void loadOlder(); } }, [hold, loadOlder, setFollowing]); // A list too short to scroll still loads older flows on scrolling up. const handleWheel = useCallback( (e: WheelEvent) => { if (e.deltaY < 0 && e.currentTarget.scrollTop <= 0) loadOlderHeld(); }, [loadOlderHeld], ); const select = useCallback( (index: number) => { const flow = latest.current.flows[index]; if (flow == null) return; setSelectedFlow(flow); hold(); const el = scrollRef.current; if (el == null) return; const top = index * ROW_HEIGHT; if (top < el.scrollTop) setScrollTop(top); else if (top + ROW_HEIGHT > el.scrollTop + el.clientHeight) { setScrollTop(top + ROW_HEIGHT - el.clientHeight); } }, [hold, setSelectedFlow, setScrollTop], ); const handleKeyDown = useCallback( (e: KeyboardEvent) => { if (e.metaKey || e.ctrlKey || e.altKey) return; if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return; e.preventDefault(); const index = flows.findIndex((f) => f.id === selectedId); if (index === -1) select(e.key === "ArrowDown" ? 0 : flows.length - 1); else if (index === 0 && e.key === "ArrowUp") loadOlderHeld(); else select(e.key === "ArrowDown" ? index + 1 : index - 1); }, [flows, loadOlderHeld, select, selectedId], ); const openMenu = useCallback( (index: number, e: MouseEvent) => { const flow = latest.current.flows[index]; if (flow == null) return; e.preventDefault(); select(index); setMenu({ flow, x: e.clientX, y: e.clientY }); }, [select], ); const newCount = following ? 0 : countNewFlows(flows, heldAt); const columns = sideBySide ? hasApps ? "grid-cols-[0.9rem_1rem_2.6rem_minmax(0,2fr)_minmax(0,3fr)_2.4rem_3.6rem]" : "grid-cols-[0.9rem_2.6rem_minmax(0,2fr)_minmax(0,3fr)_2.4rem_3.6rem]" : hasApps ? "grid-cols-[0.9rem_8.5rem_2.6rem_13rem_minmax(0,1fr)_2.4rem_5rem_4.5rem_3.8rem]" : "grid-cols-[0.9rem_2.6rem_13rem_minmax(0,1fr)_2.4rem_5rem_4.5rem_3.8rem]"; return (
{hasApps && {sideBySide ? "" : "App"}} Method Host Path Status {!sideBySide && Type} {!sideBySide && Size} Time
{flows.length === 0 ? ( ) : (
{virtualizer.getVirtualItems().map((item) => { const flow = flows[item.index]; if (flow == null) return null; return ( ); })}
)}
{newCount > 0 && ( )} setMenu(null)} />
); } /** Nothing to list, or nothing a search matches */ function EmptyList() { const query = useAtomValue(activeQueryAtom); const search = useAtomValue(searchWindowAtom); if (search?.loading) return null; return (

{query == null ? "No traffic yet" : "No flows match"}

); } interface RowProps { flow: Flow; index: number; start: number; columns: string; sideBySide: boolean; showApp: boolean; selected: boolean; onSelect: (index: number) => void; onContextMenu: (index: number, e: MouseEvent) => void; } const FlowRow = memo(function FlowRow({ flow, index, start, columns, sideBySide, showApp, selected, onSelect, onContextMenu, }: RowProps) { const { host, path, query } = splitUrl(flow.url); const failed = flow.error != null; // Failed or cancelled before any response; after the headers, the body was cut short mid-way. const noResponse = (failed || flow.cancelled) && flow.status == null; const type = shortContentType(flow.contentType); return (
{ if (e.button === 0) onSelect(index); }} onContextMenu={(e) => onContextMenu(index, e)} style={{ height: ROW_HEIGHT, transform: `translateY(${start}px)` }} className={classNames( columns, "absolute top-0 inset-x-0 grid items-center gap-x-3 px-1.5 rounded-md whitespace-nowrap", "[&>*]:overflow-hidden [&>*]:text-ellipsis [&>*]:min-w-0", selected ? "text-text bg-surface-highlight group-focus-within/flows:bg-surface-active" : index % 2 === 1 && "bg-surface-highlight/30", )} > {flow.savedRequestId != null ? ( ) : failed ? ( ) : flow.cancelled ? ( ) : flow.responseTruncated ? ( ) : null} {showApp && ( {flow.clientPath != null && } {!sideBySide && ( {flow.clientName ?? --} )} )} {host} {path} {query} {flow.cancelled && flow.status == null ? ( -- ) : ( )} {!sideBySide && (failed ? ( {flow.error} ) : flow.cancelled ? ( Cancelled ) : ( {type ?? --} ))} {!sideBySide && ( {noResponse ? ( -- ) : ( formatSize(flow.responseSize) )} )} {flow.elapsedMs == null ? "--" : formatMillis(flow.elapsedMs)}
); }); function splitUrl(url: string): { host: string; path: string; query: string } { try { const u = new URL(url); return { host: u.host, path: u.pathname, query: u.search }; } catch { return { host: "", path: url, query: "" }; } }