Flow list columns, multi-column sorting and header and cell menus (#833)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and GitHub committed 2026-11-10 00:24:03 -07:00
1 parent a43c3f7c2c
commit b5951b36ae
38 files changed
+3073 -479

No files matched your search

@@ -0,0 +1,97 @@
import { Compartment, type Extension } from "@codemirror/state";
import type { Schema } from "@yaakapp-internal/query";
import {
Dialog,
DialogFooter,
Input,
type InputHandle,
LazyCodeEditor,
} from "@yaakapp-internal/ui";
import { queryFilter } from "@yaakapp-internal/ui/editor";
import { atom, useAtom, useSetAtom } from "jotai";
import { useEffect, useMemo, useRef, useState } from "react";
import { useRpcQuery } from "../hooks/useRpcQuery";
import { addCustomColumn, customPath } from "../lib/columns";
import { loadSeenValues } from "../lib/searchBox";
import { columnPrefsAtom } from "../lib/store";
/** The Add Column dialog is open */
export const addColumnDialogAtom = atom(false);
const FORM_ID = "add-column";
/**
* Adds a column for a header or query parameter, named by its field as the search names it,
* `header.x-request-id` or `query.page`, completed as the search box completes it
*/
export function AddColumnDialog() {
const [open, setOpen] = useAtom(addColumnDialogAtom);
if (!open) return null;
return <AddColumnForm onClose={() => setOpen(false)} />;
}
function AddColumnForm({ onClose }: { onClose: () => void }) {
const [text, setText] = useState("");
const setPrefs = useSetAtom(columnPrefsAtom);
const handleRef = useRef<InputHandle | null>(null);
const schema = useRpcQuery("query_schema", {}, { staleTime: Infinity }).data?.schema;
// Only the fields a column can show: the maps of headers and query parameters. It goes in
// once the schema is read, through a compartment, as the search box's does.
const compartment = useRef(new Compartment());
const filter = useMemo<Extension>(() => {
if (schema == null) return [];
const maps: Schema = { ...schema, fields: schema.fields.filter((f) => f.map) };
return queryFilter({ schema: maps, loadValues: loadSeenValues });
}, [schema]);
const extensions = useMemo(() => [compartment.current.of(filter)], [filter]);
useEffect(() => {
handleRef.current?.dispatch({ effects: compartment.current.reconfigure(filter) });
}, [filter]);
const path = customPath(text);
const submit = () => {
if (path == null) return;
setPrefs((p) => addCustomColumn(p, path));
onClose();
};
return (
<Dialog open onClose={onClose} size="dynamic" title="Add Column" className="w-[26rem]">
<form
id={FORM_ID}
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<Input
renderEditor={(props) => <LazyCodeEditor {...props} />}
setRef={(h) => {
handleRef.current = h;
}}
label="Field"
autoFocus
className="font-mono text-xs"
stateKey={null}
language={null}
placeholder="@header.x-request-id"
defaultValue=""
onChange={setText}
extensions={extensions}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.defaultPrevented) {
e.preventDefault();
submit();
}
}}
/>
</form>
<DialogFooter
actions={[
{ label: "Cancel", variant: "border", onClick: onClose },
{ label: "Add", color: "primary", form: FORM_ID, disabled: path == null },
]}
/>
</Dialog>
);
}
+4 -4
View File
@@ -24,8 +24,8 @@ function loadIcon(path: string): Promise<string | null> {
return promise;
}
/** An app's icon, read once per path for the whole session */
export function AppIcon({ path, className }: { path: string; className?: string }) {
/** An app's icon, read once per path for the whole session; `className` sets its size */
export function AppIcon({ path, className = "size-4" }: { path: string; className?: string }) {
const [url, setUrl] = useState(() => icons.get(path));
useEffect(() => {
if (icons.has(path)) {
@@ -42,8 +42,8 @@ export function AppIcon({ path, className }: { path: string; className?: string
}, [path]);
return url == null ? (
<span aria-hidden className={classNames(className, "inline-block w-4 h-4 shrink-0")} />
<span aria-hidden className={classNames(className, "inline-block shrink-0")} />
) : (
<img alt="" src={url} className={classNames(className, "w-4 h-4 shrink-0")} />
<img alt="" src={url} className={classNames(className, "shrink-0")} />
);
}
+1 -1
View File
@@ -35,7 +35,7 @@ export function FlowInfo({ flow }: { flow: Flow }) {
"Name",
flow.clientName == null ? null : (
<span className="flex items-center gap-1.5">
{flow.clientPath != null && <AppIcon path={flow.clientPath} className="size-4" />}
{flow.clientPath != null && <AppIcon path={flow.clientPath} className="size-5" />}
{flow.clientName}
{folder != null && <span className="text-text-subtlest">{folder}</span>}
</span>
+310 -63
View File
@@ -1,10 +1,11 @@
import { useVirtualizer } from "@tanstack/react-virtual";
import { formatSize } from "@yaakapp-internal/lib/formatSize";
import type { Flow } from "@yaakapp-internal/proxy-lib";
import type { Flow, FlowSortKey, SortColumn } from "@yaakapp-internal/proxy-lib";
import {
ContextMenu,
CONTROL_TOOLTIP_DELAY,
CountBadge,
type DropdownItem,
formatMillis,
HttpMethodTagRaw,
HttpStatusTagRaw,
@@ -12,7 +13,7 @@ import {
Tooltip,
} from "@yaakapp-internal/ui";
import classNames from "classnames";
import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";
import type { CSSProperties, KeyboardEvent, MouseEvent, ReactElement, WheelEvent } from "react";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { selectedFlowAtom, selectedFlowIdAtom } from "../lib/atoms";
@@ -21,33 +22,49 @@ import { utcTimestamp } from "../lib/flowViews";
import {
type Column,
type ColumnId,
cellFilterTerm,
customValue,
gridTemplate,
gridWidth,
hostOf,
isCustomColumn,
nextSort,
operationOf,
showOperationFor,
shownColumns,
tlsVersionOf,
toggleSortKey,
unavailableColumns,
urlParts,
} from "../lib/columns";
import { useExportShownHar, useFlowActions } from "../lib/flowActions";
import { compareFlows } from "../lib/flowWindow";
import { countNewFlows } from "../lib/follow";
import { countNewFlows, isAtEnd, resumesFollowing } from "../lib/follow";
import { asOneTerm } from "../lib/query";
import { folderOf } from "../lib/search";
import {
columnPrefsAtom,
hasAppsAtom,
flowSortAtom,
followAtom,
loadMoreSortedAtom,
loadOlderFlowsAtom,
newestStartedAtAtom,
oldestFlowAtom,
proxyStateAtom,
searchLoadingAtom,
searchTextAtom,
setSearchTextAtom,
flowsAtom,
shownFlowsAtom,
} from "../lib/store";
import { useShowToast } from "../lib/toast";
import { AppIcon } from "./AppIcon";
import { FlowListEmpty, PausedRow } from "./FlowListEmpty";
import { FlowListHeader } from "./FlowListHeader";
const BOTTOM_PADDING = 6;
/** Rows from the top at which older flows start loading */
/** Rows from the top at which older flows start loading, or from the bottom, sorted, more */
const LOAD_OLDER_ROWS = 20;
/** How long a row that arrives while following stays tinted */
const ARRIVAL_MS = 1400;
@@ -68,20 +85,37 @@ interface Props {
/**
* 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. Catching up leaves a divider where the hold
* began. Sorting by a column sorts the flows loaded and stops following. The columns keep their
* widths, and the list scrolls sideways when they are wider than it, the header with it.
* began. Sorting by columns reads the flows from the database in that order, a page at a time on
* scrolling down, and stops following. The columns keep their widths, and the list scrolls
* sideways when they are wider than it, the header with it.
*/
export function FlowList({ style, className }: Props) {
const flows = useAtomValue(shownFlowsAtom);
const [menu, setMenu] = useState<{ flow: Flow; x: number; y: number } | null>(null);
const [menu, setMenu] = useState<{
flow: Flow;
column: ColumnId | null;
x: number;
y: number;
} | null>(null);
const flowActions = useFlowActions();
const cellActions = useCellActions();
const exportShown = useExportShownHar();
const selectedId = useAtomValue(selectedFlowIdAtom);
const setSelectedFlow = useSetAtom(selectedFlowAtom);
const loadOlder = useSetAtom(loadOlderFlowsAtom);
const loadMoreSorted = useSetAtom(loadMoreSortedAtom);
const oldestFlow = useAtomValue(oldestFlowAtom);
const prefs = useAtomValue(columnPrefsAtom);
const [prefs, setPrefs] = useAtom(columnPrefsAtom);
const [sort, setSort] = useAtom(flowSortAtom);
const sorted = sort.length > 0;
const allFlows = useAtomValue(flowsAtom);
// Operation shows itself the first time a flow has one, unless the person set it already.
useEffect(() => {
if (prefs.visible.operation !== undefined) return;
const next = showOperationFor(prefs, allFlows);
if (next !== prefs) setPrefs(next);
}, [prefs, allFlows, setPrefs]);
const proxyState = useAtomValue(proxyStateAtom);
const paused = proxyState?.state === "running" && proxyState.recording === false;
const scrollRef = useRef<HTMLDivElement>(null);
@@ -89,6 +123,8 @@ export function FlowList({ style, className }: Props) {
const lastScrollTop = useRef(0);
// The list's vertical scrollbar, which the header leaves room for so the two scroll as far
const [scrollbarWidth, setScrollbarWidth] = useState(0);
// The list's visible height, so a resize that leaves it at its end follows again
const [viewportHeight, setViewportHeight] = useState(0);
const ignoreScroll = useRef(false);
const [following, setFollowing] = useAtom(followAtom);
const [heldAt, setHeldAt] = useState<string | null>(null);
@@ -105,14 +141,11 @@ export function FlowList({ style, className }: Props) {
// Where the platform cannot tell which app sent a flow, there is no App column.
const hasApps = useAtomValue(hasAppsAtom);
const columns = useMemo(
() => shownColumns(prefs).filter((c) => hasApps || c.id !== "app"),
[prefs, hasApps],
);
const columns = useMemo(() => shownColumns(prefs, unavailableColumns(hasApps)), [prefs, hasApps]);
const template = useMemo(() => gridTemplate(columns), [columns]);
// A row's grid, its padding and the list's margins: `px-1.5` and `left-1.5 right-1.5`
const contentWidth = useMemo(() => `calc(${gridWidth(columns)} + 1.5rem)`, [columns]);
const arrivals = useArrivals(flows, following && sort == null);
const arrivals = useArrivals(flows, following && !sorted);
const virtualizer = useVirtualizer({
count: flows.length,
@@ -142,48 +175,83 @@ export function FlowList({ style, className }: Props) {
const follow = useCallback(() => {
const { flows, heldAt, following, sort } = latest.current;
// Catching up from a hold marks where it began.
if (!following && sort == null) {
if (!following && sort.length === 0) {
const count = countNewFlows(flows, heldAt);
const first = flows[flows.length - count];
setDivider(count > 0 && first != null ? { id: first.id, count } : null);
}
setSort(null);
setSort([]);
setFollowing(true);
setHeldAt(null);
setScrollTop(Number.MAX_SAFE_INTEGER);
}, [setFollowing, setScrollTop, setSort]);
// A sorted list never follows, whether the sort was just set, kept from the last launch, or
// kept through a clear.
useLayoutEffect(() => {
if (following) setScrollTop(Number.MAX_SAFE_INTEGER);
}, [following, flows, paused, setScrollTop]);
if (sorted && following) setFollowing(false);
}, [sorted, following, setFollowing]);
// A held list follows again once it is at its end, not only when scrolled there: a sidebar row,
// search or resize can leave it there with no scroll to make, as one that fits its viewport
// always is, and its flows would otherwise count as new while all are on screen. Judged when
// which flows are listed changes, or the list's height, not when one listed is updated or
// `following` itself changes, so selecting a row at the end still holds; and not while a
// search's first page loads, as its empty list is at its end only until the page is in.
const searchLoading = useAtomValue(searchLoadingAtom);
const listed = `${flows.length}:${flows[0]?.id ?? ""}:${flows.at(-1)?.id ?? ""}`;
useLayoutEffect(() => {
const el = scrollRef.current;
if (el == null || searchLoading) return;
if (!resumesFollowing({ following: latest.current.following, sorted, el })) return;
setFollowing(true);
setHeldAt(null);
}, [listed, sorted, searchLoading, viewportHeight, setFollowing]);
useLayoutEffect(() => {
if (following && !sorted) setScrollTop(Number.MAX_SAFE_INTEGER);
}, [following, sorted, flows, paused, setScrollTop]);
// Sorted, rows that leave, deleted or moved past what is read, can leave the end of the list
// in view with no scroll to load the next page; it loads as they go.
useEffect(() => {
const el = scrollRef.current;
if (!sorted || el == null) return;
const toEnd = el.scrollHeight - el.scrollTop - el.clientHeight;
if (toEnd < LOAD_OLDER_ROWS * ROW_HEIGHT) void loadMoreSorted();
}, [sorted, flows, loadMoreSorted, ROW_HEIGHT]);
// A new sort starts from its top.
const sortKey = JSON.stringify(sort);
useLayoutEffect(() => {
if (sort != null) setScrollTop(0);
}, [sort, setScrollTop]);
if (sortKey !== "[]") setScrollTop(0);
}, [sortKey, setScrollTop]);
// Older flows that loaded in above push the rows down; scroll by as much, so they stay put.
const anchor = useRef<Flow | null>(null);
useLayoutEffect(() => {
const previous = anchor.current;
anchor.current = oldestFlow;
if (following || sort != null || previous == null || oldestFlow == null) return;
if (following || sorted || 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, sort, setScrollTop, ROW_HEIGHT]);
}, [oldestFlow, flows, following, sorted, setScrollTop, ROW_HEIGHT]);
// Sorted, the flows loaded are what is sorted; older ones would land anywhere.
const loadOlderHeld = useCallback(() => {
hold();
if (latest.current.sort == null) void loadOlder();
if (latest.current.sort.length === 0) void loadOlder();
}, [hold, loadOlder]);
useEffect(() => {
const el = scrollRef.current;
if (el == null) return;
const measure = () => setScrollbarWidth(el.offsetWidth - el.clientWidth);
const measure = () => {
setScrollbarWidth(el.offsetWidth - el.clientWidth);
setViewportHeight(el.clientHeight);
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(el);
@@ -203,17 +271,20 @@ export function FlowList({ style, className }: Props) {
return;
}
if (!moved) return;
const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 2;
if (atEnd && latest.current.sort == null) {
const sortedNow = latest.current.sort.length > 0;
if (isAtEnd(el) && !sortedNow) {
setFollowing(true);
setHeldAt(null);
} else {
hold();
if (el.scrollTop < LOAD_OLDER_ROWS * ROW_HEIGHT && latest.current.sort == null) {
if (el.scrollTop < LOAD_OLDER_ROWS * ROW_HEIGHT && !sortedNow) {
void loadOlder();
}
}
}, [hold, loadOlder, setFollowing, ROW_HEIGHT]);
// Sorted, the next page of the sort loads near the bottom.
const toEnd = el.scrollHeight - el.scrollTop - el.clientHeight;
if (sortedNow && toEnd < LOAD_OLDER_ROWS * ROW_HEIGHT) void loadMoreSorted();
}, [hold, loadOlder, loadMoreSorted, setFollowing, ROW_HEIGHT]);
// Focus moving to a sort button out of view scrolls the header itself; the rows follow.
const handleHeaderScroll = useCallback(() => {
@@ -269,9 +340,12 @@ export function FlowList({ style, className }: Props) {
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);
else {
if (sorted && index >= flows.length - 2 && e.key === "ArrowDown") void loadMoreSorted();
select(e.key === "ArrowDown" ? index + 1 : index - 1);
}
},
[flows, follow, loadOlderHeld, select, selectedId],
[flows, follow, loadOlderHeld, loadMoreSorted, select, selectedId, sorted],
);
const openMenu = useCallback(
@@ -280,16 +354,21 @@ export function FlowList({ style, className }: Props) {
if (flow == null) return;
e.preventDefault();
select(index);
setMenu({ flow, x: e.clientX, y: e.clientY });
// The cell under the pointer, for the menu's items on its value
const cellEl = (e.target as HTMLElement).closest<HTMLElement>("[data-column]");
const column = (cellEl?.dataset.column as ColumnId | undefined) ?? null;
setMenu({ flow, column, x: e.clientX, y: e.clientY });
},
[select],
);
// A third click on a column goes back to start time, following as Sort by Start Time does.
// A click sorts by the column alone; a third goes back to arrival order, following as Reset
// Sort does. Option-click adds the column to the sort, reverses it, then takes it out.
const handleSort = useCallback(
(column: ColumnId) => {
const next = nextSort(latest.current.sort, column);
if (next == null) {
(column: SortColumn, add: boolean) => {
const current = latest.current.sort;
const next = add ? toggleSortKey(current, column) : nextSort(current, column);
if (next.length === 0) {
follow();
return;
}
@@ -299,7 +378,30 @@ export function FlowList({ style, className }: Props) {
[follow, hold, setSort],
);
const newCount = following || sort != null ? 0 : countNewFlows(flows, heldAt);
const handleSetSort = useCallback(
(next: FlowSortKey[]) => {
if (next.length === 0) {
follow();
return;
}
hold();
setSort(next);
},
[follow, hold, setSort],
);
const menuItems = useMemo((): DropdownItem[] => {
if (menu == null) return [];
// The cell's value first, as it is what was right-clicked
const cell = menu.column == null ? [] : cellActions(menu.flow, menu.column);
return [
...(cell.length > 0 ? [...cell, { type: "separator" } as const] : []),
...flowActions(menu.flow),
exportShown(),
];
}, [menu, flowActions, cellActions, exportShown]);
const newCount = following || sorted ? 0 : countNewFlows(flows, heldAt);
const dividerIndex = divider == null ? -1 : flows.findIndex((f) => f.id === divider.id);
const totalSize = virtualizer.getTotalSize();
@@ -326,7 +428,8 @@ export function FlowList({ style, className }: Props) {
prefs={prefs}
sort={sort}
onSort={handleSort}
onSortByStart={follow}
onSetSort={handleSetSort}
onResetSort={follow}
/>
</div>
<div className="relative min-h-0">
@@ -398,11 +501,7 @@ export function FlowList({ style, className }: Props) {
{newCount === 1 ? "1 new flow" : `${newCount} new flows`}
</button>
)}
<ContextMenu
triggerPosition={menu}
items={menu == null ? [] : [...flowActions(menu.flow), exportShown()]}
onClose={() => setMenu(null)}
/>
<ContextMenu triggerPosition={menu} items={menuItems} onClose={() => setMenu(null)} />
</div>
</div>
);
@@ -475,8 +574,9 @@ const FlowRow = memo(function FlowRow({
// 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 ids = columns.map((c) => c.id);
// A failure's reason, or Cancelled, takes the type and size cells together.
const spanReason = noResponse && ids.includes("type") && ids.includes("size");
// A failure's reason, or Cancelled, takes the type and size cells together, side by side.
const typeAt = ids.indexOf("type");
const spanReason = noResponse && typeAt !== -1 && ids[typeAt + 1] === "size";
const sinceArrival = arrivedAt == null ? null : Date.now() - arrivedAt;
return (
@@ -510,7 +610,10 @@ const FlowRow = memo(function FlowRow({
{columns.map((c) => {
if (spanReason && c.id === "size") return null;
return (
<FlowCell key={c.id} column={c.id} flow={flow} span={spanReason && c.id === "type"} />
// Names the cell's column for its menu, without a box of its own in the row's grid
<div key={c.id} data-column={c.id} className="contents">
<FlowCell column={c.id} flow={flow} span={spanReason && c.id === "type"} />
</div>
);
})}
</div>
@@ -585,9 +688,7 @@ function FlowCell({ column, flow, span }: { column: ColumnId; flow: Flow; span:
switch (column) {
case "number":
return (
<span className={classNames(cell, mono, "text-right text-text-subtlest")}>
{flow.number || ""}
</span>
<span className={classNames(cell, mono, "text-text-subtlest")}>{flow.number || ""}</span>
);
case "app": {
if (flow.clientPath == null) return <span className={cell} />;
@@ -601,7 +702,7 @@ function FlowCell({ column, flow, span }: { column: ColumnId; flow: Flow; span:
delay={CONTROL_TOOLTIP_DELAY}
>
<span className={classNames(cell, "flex items-center")}>
<AppIcon path={flow.clientPath} />
<AppIcon path={flow.clientPath} className="size-5" />
</span>
</Tooltip>
);
@@ -632,26 +733,20 @@ function FlowCell({ column, flow, span }: { column: ColumnId; flow: Flow; span:
if (flow.tunnelled) {
return <span className={classNames(cell, "text-text-subtlest")}>Not decrypted</span>;
}
const { path, query } = splitPath(flow.url);
const path = pathOf(flow.url);
if (flow.streamKind == null) {
return (
<Truncated text={path + query}>
<span className={cell}>
{path}
<span className="text-text-subtlest">{query}</span>
</span>
<Truncated text={path}>
<span className={cell}>{path}</span>
</Truncated>
);
}
// A stream's message count rides the end of the path, so it survives the narrow width,
// ticking while the stream is open.
return (
<Truncated text={path + query}>
<Truncated text={path}>
<span className={classNames(cell, "flex items-center")}>
<span className="truncate">
{path}
<span className="text-text-subtlest">{query}</span>
</span>
<span className="truncate">{path}</span>
<CountBadge
count={flow.messageCount}
showZero
@@ -732,14 +827,166 @@ function FlowCell({ column, flow, span }: { column: ColumnId; flow: Flow; span:
{flow.upstreamHttpVersion ?? flow.clientHttpVersion}
</span>
);
case "query": {
const query = flow.tunnelled ? "" : (urlParts(flow.url).query ?? "");
return (
<Truncated text={query}>
<span className={classNames(cell, "text-text-subtle")}>{query}</span>
</Truncated>
);
}
case "started": {
const at = new Date(utcTimestamp(flow.startedAt));
if (Number.isNaN(at.getTime())) return <span className={cell} />;
return (
<Tooltip wrap content={at.toLocaleString()} delay={CONTROL_TOOLTIP_DELAY}>
<span className={classNames(cell, mono, "text-text-subtle")}>{clockTime(at)}</span>
</Tooltip>
);
}
case "requestSize":
return (
<span
className={classNames(
cell,
mono,
"text-right",
flow.requestTruncated ? "text-notice" : "text-text-subtle",
)}
>
{flow.requestSize === 0 ? "--" : formatSize(flow.requestSize)}
</span>
);
case "latency":
return (
<span className={classNames(cell, mono, "text-right text-text-subtle")}>
{flow.elapsedHeadersMs == null ? "--" : formatMillis(flow.elapsedHeadersMs)}
</span>
);
case "tls":
return (
<span className={classNames(cell, mono, "text-text-subtle")}>{tlsVersionOf(flow)}</span>
);
case "operation": {
const operation = operationOf(flow) ?? "";
return (
<Truncated text={operation}>
<span className={classNames(cell, "text-text-subtle")}>{operation}</span>
</Truncated>
);
}
default: {
if (!isCustomColumn(column)) return <span className={cell} />;
const value = customValue(flow, column.slice("field:".length)) ?? "";
return (
<Truncated text={value}>
<span className={classNames(cell, mono, "text-text-subtle")}>{value}</span>
</Truncated>
);
}
}
}
function splitPath(url: string): { path: string; query: string } {
/** The URL's path as the browser reads it, `/` for none, without the query */
function pathOf(url: string): string {
try {
const u = new URL(url);
return { path: u.pathname, query: u.search };
return new URL(url).pathname;
} catch {
return { path: url, query: "" };
return url;
}
}
/** `14:03:27.481`, in local time */
function clockTime(at: Date): string {
const two = (n: number) => String(n).padStart(2, "0");
const ms = String(at.getMilliseconds()).padStart(3, "0");
return `${two(at.getHours())}:${two(at.getMinutes())}:${two(at.getSeconds())}.${ms}`;
}
/**
* The items a cell's menu adds for its value: a search term for it, either way, where its column
* has a field to match it by, and copying it
*/
function useCellActions(): (flow: Flow, column: ColumnId) => DropdownItem[] {
const store = useStore();
const setSearchText = useSetAtom(setSearchTextAtom);
const showToast = useShowToast();
return useCallback(
(flow: Flow, column: ColumnId) => {
const add = (term: string) => {
// A search with `OR` at its top is grouped first, so the term narrows all of it.
const text = store.get(searchTextAtom).trim();
setSearchText(text === "" ? term : `${asOneTerm(text)} ${term}`);
};
const include = cellFilterTerm(flow, column, false);
const exclude = cellFilterTerm(flow, column, true);
const value = cellText(flow, column);
const items: DropdownItem[] = [];
if (include != null && exclude != null) {
items.push(
{ label: "Filter by This Value", icon: "filter", onSelect: () => add(include) },
{ label: "Exclude This Value", icon: "minus_circle", onSelect: () => add(exclude) },
);
}
if (value !== "") {
items.push({
label: "Copy Value",
icon: "copy",
onSelect: async () => {
try {
await navigator.clipboard.writeText(value);
showToast({ message: "Copied value" });
} catch (err) {
showToast({ message: `Failed to copy value: ${String(err)}`, color: "danger" });
}
},
});
}
return items;
},
[store, setSearchText, showToast],
);
}
/** A cell's value as text, as it shows it, for copying */
function cellText(flow: Flow, column: ColumnId): string {
if (isCustomColumn(column)) return customValue(flow, column.slice("field:".length)) ?? "";
switch (column) {
case "number":
return flow.number ? String(flow.number) : "";
case "app":
return flow.clientName ?? flow.clientPath ?? "";
case "method":
return flow.method;
case "host":
return hostOf(flow.url);
case "path":
return flow.tunnelled ? "" : pathOf(flow.url);
case "query":
return flow.tunnelled ? "" : (urlParts(flow.url).query ?? "");
case "status":
return flow.status == null ? "" : String(flow.status);
case "type":
return flow.contentType ?? "";
case "size":
return String(flow.responseSize);
case "requestSize":
return String(flow.requestSize);
case "time":
return flow.elapsedMs == null ? "" : String(flow.elapsedMs);
case "latency":
return flow.elapsedHeadersMs == null ? "" : String(flow.elapsedHeadersMs);
case "started": {
const at = new Date(utcTimestamp(flow.startedAt));
return Number.isNaN(at.getTime()) ? "" : at.toISOString();
}
case "remote":
return flow.remoteAddr ?? "";
case "version":
return flow.upstreamHttpVersion ?? flow.clientHttpVersion;
case "tls":
return tlsVersionOf(flow);
case "operation":
return operationOf(flow) ?? "";
}
}
+166 -67
View File
@@ -1,3 +1,4 @@
import type { FlowSortKey, SortColumn } from "@yaakapp-internal/proxy-lib";
import {
ContextMenu,
Dropdown,
@@ -7,21 +8,27 @@ import {
ResizeHandle,
} from "@yaakapp-internal/ui";
import classNames from "classnames";
import { useSetAtom } from "jotai";
import { useAtomValue, useSetAtom } from "jotai";
import { memo, type MouseEvent, useCallback, useRef, useState } from "react";
import {
addSortKey,
allColumns,
type Column,
COLUMNS,
type ColumnDef,
type ColumnId,
type ColumnPrefs,
type FlowSort,
canHide,
hideOtherColumns,
isCustomColumn,
removeCustomColumn,
resetWidth,
resetWidths,
resizeColumn,
toggleColumn,
unavailableColumns,
} from "../lib/columns";
import { useExportShownHar } from "../lib/flowActions";
import { columnPrefsAtom } from "../lib/store";
import { columnPrefsAtom, hasAppsAtom } from "../lib/store";
import { addColumnDialogAtom } from "./AddColumnDialog";
interface Props {
columns: Column[];
@@ -29,16 +36,19 @@ interface Props {
/** The rows' width, as CSS, so the header scrolls sideways with them */
width: string;
prefs: ColumnPrefs;
sort: FlowSort | null;
onSort: (column: ColumnId) => void;
onSortByStart: () => void;
sort: FlowSortKey[];
/** A click on a label, or with `add`, an Option-click */
onSort: (column: SortColumn, add: boolean) => void;
/** Sets the sort from the menus; empty goes back to arrival order */
onSetSort: (sort: FlowSortKey[]) => void;
onResetSort: () => void;
}
/**
* The list's only control surface: a click on a label sorts by it, a second reverses it and a
* third goes back to start time. Dragging the edge after a label resizes its column and a
* double-click on it resets it. The picker sits in the empty corner on hover, or anywhere on a
* right-click.
* The list's only control surface: a click on a label sorts by it alone, a second reverses it
* and a third goes back to arrival order; Option-click adds it to the sort as a further key.
* Dragging the edge after a label resizes its column and a double-click on it resets it. A
* right-click on a label opens the column's menu; the picker sits in the empty corner on hover.
*/
export const FlowListHeader = memo(function FlowListHeader({
columns,
@@ -47,49 +57,113 @@ export const FlowListHeader = memo(function FlowListHeader({
prefs,
sort,
onSort,
onSortByStart,
onSetSort: setSort,
onResetSort,
}: Props) {
const setPrefs = useSetAtom(columnPrefsAtom);
const exportShown = useExportShownHar();
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);
const unavailable = unavailableColumns(useAtomValue(hasAppsAtom));
const openAddColumn = useSetAtom(addColumnDialogAtom);
const [menu, setMenu] = useState<{ x: number; y: number; column: ColumnDef | null } | null>(null);
// Widths when a drag began, so each move sets the width from where it started.
const startWidth = useRef(0);
const items: DropdownItem[] = [
const pickerItems: DropdownItem[] = [
{
type: "content",
label: <div className="px-1.5 pt-1 text-xs text-text-subtlest">Columns</div>,
},
...COLUMNS.map((c): DropdownItem => ({
label: c.label,
keepOpenOnSelect: true,
disabled: c.id === "path",
leftSlot:
(prefs.visible[c.id] ?? c.defaultVisible) || c.id === "path" ? (
...allColumns(prefs).map((c): DropdownItem => {
const shown = prefs.visible[c.id] ?? c.defaultVisible;
return {
label: c.label,
keepOpenOnSelect: true,
disabled: shown && !canHide(prefs, c.id, unavailable),
leftSlot: shown ? (
<Icon icon="check" size="sm" />
) : (
<span aria-hidden className="inline-block w-4 h-4" />
),
rightSlot:
c.id === "path" ? <span className="text-xs text-text-subtlest">always</span> : undefined,
onSelect: () => setPrefs((p) => toggleColumn(p, c.id)),
})),
onSelect: () => setPrefs((p) => toggleColumn(p, c.id, unavailable)),
...(isCustomColumn(c.id)
? {
submenuTrigger: "button" as const,
submenu: [
{
label: "Remove Column",
icon: "trash" as const,
color: "danger" as const,
onSelect: () => setPrefs((p) => removeCustomColumn(p, c.id as `field:${string}`)),
},
],
}
: {}),
};
}),
{ label: "Add Column…", icon: "plus", onSelect: () => openAddColumn(true) },
{ type: "separator" },
{ label: "Sort by Start Time", disabled: sort == null, onSelect: onSortByStart },
{ label: "Reset Sort", disabled: sort.length === 0, onSelect: onResetSort },
{ label: "Reset Column Widths", onSelect: () => setPrefs((p) => resetWidths(p)) },
{ type: "separator" },
exportShown(),
];
const openMenu = useCallback((e: MouseEvent) => {
e.preventDefault();
setMenu({ x: e.clientX, y: e.clientY });
}, []);
const columnItems = (c: ColumnDef): DropdownItem[] => {
const column = c.sortable ? (c.id as SortColumn) : null;
const sortBy = (descending: boolean) => {
if (column != null) setSort([{ column, descending }]);
};
const addTo = (descending: boolean) => {
if (column != null) setSort(addSortKey(sort, column, descending));
};
return [
...(column == null
? []
: ([
{ label: "Sort Ascending", onSelect: () => sortBy(false) },
{ label: "Sort Descending", onSelect: () => sortBy(true) },
{ label: "Add to Sort Ascending", onSelect: () => addTo(false) },
{ label: "Add to Sort Descending", onSelect: () => addTo(true) },
] satisfies DropdownItem[])),
{ label: "Clear Sorting", disabled: sort.length === 0, onSelect: onResetSort },
{ type: "separator" },
{
label: "Hide Column",
disabled: !canHide(prefs, c.id, unavailable),
onSelect: () => setPrefs((p) => toggleColumn(p, c.id, unavailable)),
},
{
label: "Hide Other Columns",
disabled: columns.length <= 1,
onSelect: () => setPrefs((p) => hideOtherColumns(p, c.id)),
},
...(isCustomColumn(c.id)
? [
{
label: "Remove Column",
color: "danger" as const,
onSelect: () => setPrefs((p) => removeCustomColumn(p, c.id as `field:${string}`)),
},
]
: []),
{ type: "separator" },
{ label: "Reset Column Widths", onSelect: () => setPrefs((p) => resetWidths(p)) },
];
};
// A right-click on a label is for its column; anywhere else in the header, the picker.
const openMenu = useCallback(
(e: MouseEvent) => {
e.preventDefault();
const el = (e.target as HTMLElement).closest<HTMLElement>("[data-column]");
const id = el?.dataset.column as ColumnId | undefined;
const column = columns.find((c) => c.id === id) ?? null;
setMenu({ x: e.clientX, y: e.clientY, column });
},
[columns],
);
return (
// The same margins and padding as the rows, so each label sits over its cells.
<div style={{ width, minWidth: "100%" }} className="px-1.5">
{/* oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- a right-click opens the same menu as the picker */}
{/* oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- a right-click opens the column's menu */}
<div
onContextMenu={openMenu}
style={{ gridTemplateColumns: template }}
@@ -99,7 +173,7 @@ export const FlowListHeader = memo(function FlowListHeader({
)}
>
<span className="flex items-center justify-center">
<Dropdown items={items}>
<Dropdown items={pickerItems}>
<IconButton
size="xs"
icon="settings_2"
@@ -110,44 +184,69 @@ export const FlowListHeader = memo(function FlowListHeader({
/>
</Dropdown>
</span>
{columns.map((c) => (
<span key={c.id} className="relative h-full flex items-center min-w-0 px-1.5">
<button
type="button"
onClick={() => onSort(c.id)}
// No tooltip: the header sits under the search field, and a tooltip here covered it
aria-label={`Sort by ${c.label}`}
className={classNames(
"flex items-center gap-0.5 min-w-0 w-full h-full whitespace-nowrap hover:text-text-subtle",
c.align === "right" && "justify-end",
sort?.column === c.id && "text-text-subtle",
)}
>
{sort?.column === c.id && (
{columns.map((c) => {
const at = sort.findIndex((k) => k.column === c.id);
const key = sort[at];
const label = (
<>
{key != null && (
<Icon
icon="chevron_down"
size="xs"
className={classNames("shrink-0", !sort.descending && "rotate-180")}
className={classNames("shrink-0", !key.descending && "rotate-180")}
/>
)}
{key != null && sort.length > 1 && (
<span className="shrink-0 -ml-0.5 text-2xs tabular-nums">{at + 1}</span>
)}
<span className="truncate">{c.id === "app" ? "" : c.label}</span>
</button>
{/* On the column's right edge, the boundary with the next, resizing this one */}
<ResizeHandle
side="right"
justify="center"
className="absolute top-0 translate-x-1/2"
onResizeStart={() => {
startWidth.current = c.current;
}}
onResizeMove={(e) =>
setPrefs((p) => resizeColumn(p, c.id, startWidth.current + e.x - e.xStart))
}
onReset={() => setPrefs((p) => resetWidth(p, c.id))}
/>
</span>
))}
<ContextMenu triggerPosition={menu} items={items} onClose={() => setMenu(null)} />
</>
);
const labelClass = classNames(
"flex items-center gap-0.5 min-w-0 w-full h-full whitespace-nowrap",
c.align === "right" && "justify-end",
key != null && "text-text-subtle",
);
return (
<span
key={c.id}
data-column={c.id}
className="relative h-full flex items-center min-w-0 px-1.5"
>
{c.sortable ? (
<button
type="button"
onClick={(e) => onSort(c.id as SortColumn, e.altKey)}
// No tooltip: the header sits under the search field, and a tooltip here covered it
aria-label={`Sort by ${c.label}`}
className={classNames(labelClass, "hover:text-text-subtle")}
>
{label}
</button>
) : (
<span className={labelClass}>{label}</span>
)}
{/* On the column's right edge, the boundary with the next, resizing this one */}
<ResizeHandle
side="right"
justify="center"
className="absolute top-0 translate-x-1/2"
onResizeStart={() => {
startWidth.current = c.current;
}}
onResizeMove={(e) =>
setPrefs((p) => resizeColumn(p, c.id, startWidth.current + e.x - e.xStart))
}
onReset={() => setPrefs((p) => resetWidth(p, c.id))}
/>
</span>
);
})}
<ContextMenu
triggerPosition={menu}
items={menu == null ? [] : menu.column == null ? pickerItems : columnItems(menu.column)}
onClose={() => setMenu(null)}
/>
</div>
</div>
);
@@ -12,8 +12,10 @@ import { useState } from "react";
import { useLocalStorage } from "react-use";
import { flowLayoutAtom } from "../lib/atoms";
import { setupIncomplete } from "../lib/firstRun";
import { useMenuExportHar } from "../lib/flowActions";
import { lockedAtom, noFlowsAtom, systemProxyEverOnAtom } from "../lib/store";
import { getOsType } from "../lib/tauri";
import { AddColumnDialog } from "./AddColumnDialog";
import { ClearFlowsButton } from "./ClearFlowsButton";
import { FirstRun } from "./FirstRun";
import { FlowDetail } from "./FlowDetail";
@@ -32,6 +34,7 @@ export function ProxyLayout() {
const os = getOsType();
const [flowLayout, setFlowLayout] = useAtom(flowLayoutAtom);
const openSettings = useOpenSettings();
useMenuExportHar();
const [sidebarWidth, setSidebarWidth] = useLocalStorage("sidebar_width", 250);
const [sidebarHidden, setSidebarHidden] = useLocalStorage("sidebar_hidden", false);
const [floatingSidebarHidden, setFloatingSidebarHidden] = useLocalStorage(
@@ -164,6 +167,7 @@ export function ProxyLayout() {
</SidebarLayout>
<SaveDialog />
<SavedSearchDialog />
<AddColumnDialog />
<HelperDialog />
<SettingsWindow />
<Toasts />
+3
View File
@@ -23,6 +23,7 @@ import {
useState,
} from "react";
import { useRpcQuery } from "../hooks/useRpcQuery";
import { useExportShownHar } from "../lib/flowActions";
import { loadSeenValues, savedCompletions, searchProblems } from "../lib/searchBox";
import {
allTrafficTotalAtom,
@@ -54,6 +55,7 @@ export const SearchBar = memo(function SearchBar() {
const total = useAtomValue(allTrafficTotalAtom);
const store = useStore();
const setSavedDialog = useSetAtom(savedSearchDialogAtom);
const exportShown = useExportShownHar();
// Nothing to search while captured traffic is locked.
const locked = useAtomValue(lockedAtom) != null;
const schema = useRpcQuery("query_schema", {}, { staleTime: Infinity }).data?.schema;
@@ -179,6 +181,7 @@ export const SearchBar = memo(function SearchBar() {
leftSlot: <Icon icon="bookmark" />,
onSelect: () => setSavedDialog({ mode: "save", query: text.trim() }),
},
exportShown(),
]}
>
<IconButton
+1 -1
View File
@@ -71,7 +71,7 @@ function ItemInner({ item }: { item: SidebarItem }) {
{item.kind === "tunnelled" && <Icon icon="lock" size="sm" className="text-text-subtle" />}
{item.kind === "saved" && <Icon icon="bookmark" size="sm" className="text-text-subtle" />}
{item.kind === "folder" && <Icon icon="folder" size="sm" className="text-text-subtle" />}
{item.appPath != null && <AppIcon path={item.appPath} />}
{item.appPath != null && <AppIcon path={item.appPath} className="size-[1.125rem]" />}
{item.kind === "folder" && item.path != null ? (
// Named by its last part; the whole path on hover
<Tooltip wrap content={item.path} delay={CONTROL_TOOLTIP_DELAY}>
+25 -1
View File
@@ -1,5 +1,6 @@
import { useSetAtom } from "jotai";
import { useLayoutEffect, useState } from "react";
import { useEffect, useLayoutEffect, useState } from "react";
import { AddColumnDialog } from "../components/AddColumnDialog";
import { FlowDetail } from "../components/FlowDetail";
import { FlowList } from "../components/FlowList";
import { selectedFlowAtom } from "../lib/atoms";
@@ -34,6 +35,7 @@ export function FlowPanesHarness() {
))}
</div>
<FixtureCard key={fixture.flow.id} fixture={fixture} />
<AddColumnDialog />
</div>
);
}
@@ -54,6 +56,28 @@ function FixtureCard({ fixture }: { fixture: FlowFixture }) {
setReady(true);
// oxlint-disable-next-line react-hooks/exhaustive-deps -- once per fixture
}, [fixture]);
// `&arrive=3`: that many new flows, one a second, as traffic would bring them
useEffect(() => {
const count = Number(params.get("arrive") ?? 0);
let added = 0;
const timer = setInterval(() => {
if (added >= count) return clearInterval(timer);
added++;
const source = fixtures[added % fixtures.length]?.flow;
if (source == null) return;
const flow = {
...source,
// The fixture's id first, so the backend finds its bodies, as `manyFlows` does
id: `${source.id}~arrived_${added}`,
number: 1500 + added,
startedAt: new Date().toISOString().slice(0, 23),
};
setWindow((w) => ({ ...w, flows: [...w.flows, flow], total: w.total + 1 }));
}, 1000);
return () => clearInterval(timer);
// oxlint-disable-next-line react-hooks/exhaustive-deps -- once per fixture
}, [fixture]);
if (!ready) return null;
if (params.has("list")) {
+25 -6
View File
@@ -1,5 +1,5 @@
import type { Flow, GetProxyStateResponse } from "@yaakapp-internal/proxy-lib";
import { fixtures } from "./fixtures";
import { appIconPng, fixtures } from "./fixtures";
/**
* Dev only: answers the engine's RPCs the harness pages need, from fixtures, so the card and
@@ -13,8 +13,9 @@ export function installFixtureBackend() {
if (cmd.startsWith("plugin:event|")) return 0;
throw new Error(`Not in the harness: ${cmd}`);
};
(window as unknown as { __TAURI_OS_PLUGIN_INTERNALS__: Record<string, string> })
.__TAURI_OS_PLUGIN_INTERNALS__ = {
(
window as unknown as { __TAURI_OS_PLUGIN_INTERNALS__: Record<string, string> }
).__TAURI_OS_PLUGIN_INTERNALS__ = {
os_type: "macos",
platform: "macos",
family: "unix",
@@ -58,7 +59,7 @@ function answer(cmd: string, payload: unknown): unknown {
}
}
case "app_icon":
return null;
return appIconPng;
case "get_proxy_state":
return HARNESS_STATE;
case "get_storage_size":
@@ -127,11 +128,29 @@ function answer(cmd: string, payload: unknown): unknown {
info: "A request or response header",
example: "@header.accept:*json*",
},
{
name: "res.header",
kind: { type: "text" },
map: true,
info: "A response header",
example: "@res.header.x-cache:hit",
},
{
name: "query",
kind: { type: "text" },
map: true,
info: "A query parameter",
example: "@query.page:2",
},
],
},
};
case "query_values":
return [];
// Header and query parameter names, for completing a map's keys
case "query_values": {
const path = (payload as { path?: string } | undefined)?.path ?? "";
if (path.endsWith("header")) return ["x-cache", "x-request-id", "content-type"];
return path === "query" ? ["expand", "limit"] : [];
}
case "validate_query":
return [];
default:
+44
View File
@@ -50,6 +50,7 @@ const base: Flow = {
grpcMethod: null,
grpcStatus: null,
grpcMessage: null,
graphqlOperation: null,
tunnelled: false,
agentRead: false,
clientAddr: "127.0.0.1:54321",
@@ -69,6 +70,10 @@ const jsonResponse = JSON.stringify({
status: "succeeded",
charges: { data: [{ id: "ch_1", paid: true }] },
});
const graphqlRequest = JSON.stringify({
query: "query GetViewer { viewer { login } }",
operationName: "GetViewer",
});
const formRequest = "grant_type=client_credentials&client_id=yaak-proxy&scope=read+write";
const htmlResponse =
"<!doctype html><html><body style='font-family:sans-serif'><h1>Signed in</h1><p>You can close this window.</p></body></html>";
@@ -176,4 +181,43 @@ export const fixtures: FlowFixture[] = [
requestBody: body(""),
responseBody: body(""),
},
{
label: "GraphQL POST",
flow: {
...base,
id: "fl_graphql",
method: "POST",
url: "https://api.github.com/graphql",
contentType: "application/json",
requestHeaders: [{ name: "Content-Type", value: "application/json" }],
responseHeaders: [{ name: "X-Cache", value: "MISS" }],
requestSize: graphqlRequest.length,
responseSize: 64,
graphqlOperation: "GetViewer",
},
requestBody: body(graphqlRequest),
responseBody: body('{"data":{"viewer":{"login":"yaak"}}}'),
},
{
label: "gRPC call",
flow: {
...base,
id: "fl_grpc",
method: "POST",
url: "https://grpc.example.com/pkg.Greeter/SayHello",
contentType: "application/grpc",
clientHttpVersion: "HTTP/2",
upstreamHttpVersion: "HTTP/2",
requestHeaders: [{ name: "Content-Type", value: "application/grpc" }],
responseHeaders: [{ name: "Content-Type", value: "application/grpc" }],
grpcService: "pkg.Greeter",
grpcMethod: "SayHello",
grpcStatus: 0,
},
requestBody: body(""),
responseBody: body(""),
},
];
/** An app icon for every flow in the harness, as base64 PNG */
export const appIconPng = btoa(String.fromCharCode(...png));
+16 -9
View File
@@ -1,6 +1,7 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { applyThemeToDocument, defaultDarkTheme, defaultLightTheme } from "@yaakapp-internal/theme";
import { createStore, Provider } from "jotai";
import { LazyMotion, MotionConfig } from "motion/react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { installFixtureBackend } from "./backend";
@@ -11,6 +12,8 @@ import { SettingsHarness } from "./SettingsHarness";
import "../main.css";
const params = new URLSearchParams(location.search);
// As the app loads them, so dialogs fade in
const motionFeatures = () => import("framer-motion").then((mod) => mod.domAnimation);
const dark = params.get("theme") !== "light";
applyThemeToDocument(dark ? defaultDarkTheme : defaultLightTheme);
if (params.has("locked")) installLockedBackend();
@@ -20,15 +23,19 @@ createRoot(document.getElementById("root") as HTMLElement).render(
<StrictMode>
<QueryClientProvider client={new QueryClient()}>
<Provider store={createStore()}>
{params.has("locked") || params.has("window") ? (
<LockedHarness />
) : params.has("settings") ? (
<SettingsHarness />
) : params.has("stream") ? (
<MessagesHarness />
) : (
<FlowPanesHarness />
)}
<LazyMotion strict features={motionFeatures}>
<MotionConfig transition={{ duration: 0.1 }}>
{params.has("locked") || params.has("window") ? (
<LockedHarness />
) : params.has("settings") ? (
<SettingsHarness />
) : params.has("stream") ? (
<MessagesHarness />
) : (
<FlowPanesHarness />
)}
</MotionConfig>
</LazyMotion>
</Provider>
</QueryClientProvider>
</StrictMode>,
@@ -49,6 +49,7 @@ const flowBase: Flow = {
grpcMethod: null,
grpcStatus: null,
grpcMessage: null,
graphqlOperation: null,
tunnelled: false,
agentRead: false,
clientAddr: null,
+211 -60
View File
@@ -1,35 +1,59 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
import type { Flow, FlowSortKey } from "@yaakapp-internal/proxy-lib";
import { describe, expect, test } from "vite-plus/test";
import {
addCustomColumn,
addSortKey,
cellFilterTerm,
type ColumnPrefs,
customPath,
customValue,
defaultColumnPrefs,
gridTemplate,
gridWidth,
hideOtherColumns,
nextSort,
operationOf,
parseColumnPrefs,
removeCustomColumn,
resetWidth,
resetWidths,
resizeColumn,
showOperationFor,
shownColumns,
sortFlows,
toggleColumn,
toggleSortKey,
urlParts,
} from "./columns";
function flow(number: number, extra: Partial<Flow> = {}): Flow {
return {
id: `fl_${number}`,
id: `fl_${String(number).padStart(3, "0")}`,
number,
startedAt: `2026-11-09T12:00:${String(number).padStart(2, "0")}`,
url: "https://example.com/",
method: "GET",
status: 200,
error: null,
requestSize: 0,
responseSize: 0,
elapsedMs: null,
elapsedHeadersMs: null,
contentType: null,
clientName: null,
clientBundleId: null,
clientPath: null,
clientCwd: null,
clientHttpVersion: "HTTP/1.1",
upstreamHttpVersion: null,
upstreamTlsVersion: null,
remoteAddr: null,
requestHeaders: [],
responseHeaders: [],
grpcService: null,
grpcMethod: null,
graphqlOperation: null,
tunnelled: false,
...extra,
} as Flow;
}
@@ -37,13 +61,14 @@ function flow(number: number, extra: Partial<Flow> = {}): Flow {
const ids = (prefs: ColumnPrefs) => shownColumns(prefs).map((c) => c.id);
describe("shownColumns", () => {
test("shows every visible column, however narrow the list", () => {
test("shows every visible column, Query after Path", () => {
expect(ids(defaultColumnPrefs)).toEqual([
"number",
"app",
"method",
"host",
"path",
"query",
"status",
"type",
"size",
@@ -51,29 +76,33 @@ describe("shownColumns", () => {
]);
});
test("follows the picker, and always keeps the path", () => {
test("follows the picker, Path included, but keeps the last column", () => {
let prefs = toggleColumn(defaultColumnPrefs, "remote");
prefs = toggleColumn(prefs, "type");
prefs = toggleColumn(prefs, "path");
expect(ids(prefs)).toContain("remote");
expect(ids(prefs)).not.toContain("type");
expect(ids(prefs)).toContain("path");
expect(ids(prefs)).not.toContain("path");
const alone = hideOtherColumns(defaultColumnPrefs, "host");
expect(ids(alone)).toEqual(["host"]);
expect(toggleColumn(alone, "host")).toBe(alone);
// Where App has nothing to show, the last other column is the last one.
const withApp = hideOtherColumns(defaultColumnPrefs, "app");
const both = toggleColumn(withApp, "host");
expect(toggleColumn(both, "host", ["app"])).toBe(both);
expect(ids(both)).toEqual(["app", "host"]);
expect(shownColumns(both, ["app"]).map((c) => c.id)).toEqual(["host"]);
});
test("lays out every column at a fixed width, the path included", () => {
test("lays out every column at a fixed width", () => {
let prefs = resizeColumn(defaultColumnPrefs, "host", 240.4);
prefs = resizeColumn(prefs, "path", 500);
const columns = shownColumns(prefs);
const pad = (w: number) => `calc(${w}px + 0.75rem)`;
expect(gridTemplate(columns)).toBe(
["24px", ...[46, 18, 50, 240, 500, 46, 50, 72, 64].map(pad)].join(" "),
["24px", ...[46, 20, 50, 240, 500, 120, 46, 50, 72, 64].map(pad)].join(" "),
);
expect(gridWidth(columns)).toBe("calc(1110px + 9 * 0.75rem)");
});
test("keeps the host's width in a narrow list", () => {
const host = shownColumns(defaultColumnPrefs).find((c) => c.id === "host");
expect(host?.current).toBe(190);
expect(gridWidth(columns)).toBe("calc(1232px + 10 * 0.75rem)");
});
});
@@ -81,11 +110,32 @@ describe("column preferences", () => {
test("persist through storage and drop what no longer applies", () => {
let prefs = resizeColumn(defaultColumnPrefs, "host", 10);
prefs = toggleColumn(prefs, "number");
prefs = addCustomColumn(prefs, "header.x-cache");
prefs = { ...prefs, sort: [{ column: "status", descending: true }] };
const stored = JSON.parse(JSON.stringify(prefs));
expect(parseColumnPrefs(stored)).toEqual({ visible: { number: false }, widths: { host: 60 } });
expect(parseColumnPrefs(stored)).toEqual({
visible: { number: false, "field:header.x-cache": true },
widths: { host: 60 },
custom: ["field:header.x-cache"],
sort: [{ column: "status", descending: true }],
});
expect(
parseColumnPrefs({ visible: { gone: true, size: "yes" }, widths: { time: -1, size: 90 } }),
).toEqual({ visible: {}, widths: { size: 90 } });
parseColumnPrefs({
visible: { gone: true, size: "yes" },
widths: { time: -1, size: 90 },
custom: ["field:nope.x", 3, "field:query.page"],
sort: [
{ column: "gone", descending: true },
{ column: "host" },
{ column: "time", descending: false },
],
}),
).toEqual({
visible: {},
widths: { size: 90 },
custom: ["field:query.page"],
sort: [{ column: "time", descending: false }],
});
expect(parseColumnPrefs(null)).toEqual(defaultColumnPrefs);
expect(resetWidths(prefs).widths).toEqual({});
});
@@ -95,61 +145,162 @@ describe("column preferences", () => {
prefs = resizeColumn(prefs, "path", 400);
expect(resetWidth(prefs, "path").widths).toEqual({ host: 300 });
});
test("custom columns are added at the end and removed with their settings", () => {
let prefs = addCustomColumn(defaultColumnPrefs, "res.header.x-cache");
prefs = resizeColumn(prefs, "field:res.header.x-cache", 200);
expect(ids(prefs).at(-1)).toBe("field:res.header.x-cache");
prefs = removeCustomColumn(prefs, "field:res.header.x-cache");
expect(prefs).toEqual(defaultColumnPrefs);
});
test("Operation shows itself once, unless the person set it", () => {
const grpc = flow(1, { grpcService: "pkg.Greeter", grpcMethod: "SayHello" });
const anonymous = flow(2, { graphqlOperation: "" });
expect(showOperationFor(defaultColumnPrefs, [flow(3), anonymous])).toBe(defaultColumnPrefs);
expect(showOperationFor(defaultColumnPrefs, [grpc]).visible.operation).toBe(true);
const hidden = { ...defaultColumnPrefs, visible: { operation: false } };
expect(showOperationFor(hidden, [grpc])).toBe(hidden);
});
});
describe("sorting", () => {
test("sorts numbers largest first and names from A, reverses, then goes back to start", () => {
expect(nextSort(null, "size")).toEqual({ column: "size", descending: true });
expect(nextSort(null, "host")).toEqual({ column: "host", descending: false });
expect(nextSort({ column: "host", descending: false }, "host")).toEqual({
column: "host",
descending: true,
});
expect(nextSort({ column: "host", descending: true }, "host")).toBeNull();
expect(nextSort({ column: "size", descending: true }, "size")).toEqual({
column: "size",
descending: false,
});
expect(nextSort({ column: "size", descending: false }, "size")).toBeNull();
// Another column starts over.
expect(nextSort({ column: "host", descending: true }, "size")).toEqual({
column: "size",
descending: true,
});
const one = (column: FlowSortKey["column"], descending: boolean) => [{ column, descending }];
test("a click sorts by a column alone, reverses it, then goes back to arrival order", () => {
expect(nextSort([], "size")).toEqual(one("size", true));
expect(nextSort([], "host")).toEqual(one("host", false));
expect(nextSort(one("host", false), "host")).toEqual(one("host", true));
expect(nextSort(one("host", true), "host")).toEqual([]);
expect(nextSort(one("size", true), "size")).toEqual(one("size", false));
expect(nextSort(one("size", false), "size")).toEqual([]);
// Another column, or a sort on several, starts over.
expect(nextSort(one("host", true), "size")).toEqual(one("size", true));
const two = [...one("host", false), ...one("size", true)];
expect(nextSort(two, "host")).toEqual(one("host", false));
});
test("sorts the loaded flows, those without a value lowest, ties in arrival order", () => {
const a = flow(1, { responseSize: 10, elapsedMs: 5, url: "https://b.com/" });
const b = flow(2, { responseSize: 300, elapsedMs: null, url: "https://a.com/" });
const c = flow(3, { responseSize: 10, elapsedMs: 50, url: "https://c.com/" });
const d = flow(4, { error: "DNS lookup failed", status: null, url: "https://a.com/" });
const flows = [a, b, c, d];
const by = (column: Parameters<typeof nextSort>[1], descending: boolean) =>
sortFlows(flows, { column, descending }).map((f) => f.number);
test("Option-click adds a key ascending, reverses it, then takes it out", () => {
let sort = toggleSortKey(one("status", true), "host");
expect(sort).toEqual([...one("status", true), ...one("host", false)]);
sort = toggleSortKey(sort, "host");
expect(sort).toEqual([...one("status", true), ...one("host", true)]);
expect(toggleSortKey(sort, "host")).toEqual(one("status", true));
expect(addSortKey(sort, "status", false)).toEqual([
...one("status", false),
...one("host", true),
]);
expect(addSortKey([], "time", true)).toEqual(one("time", true));
});
// The same flows and orders as `a_sort_on_several_columns_pages_in_its_order` in the lib's
// `flows.rs`, so the app places a flow where the database would.
const flows = [
flow(0, { url: "https://B.com/x", status: 200 }),
flow(1, { url: "https://a.com/y", status: 404 }),
flow(2, { url: "https://a.com/z", status: null }),
flow(3, { url: "https://c.com/", status: 200 }),
flow(4, { url: "https://a.com/", status: null, error: "boom" }),
flow(5, { url: "https://b.com/q", status: 200 }),
flow(6, { url: "https://A.com/", status: 404 }),
flow(7, { url: "https://c.com/", status: 200 }),
];
const numbers = (sort: FlowSortKey[]) => sortFlows(flows, sort).map((f) => f.number);
test("sorts on several columns as the database does", () => {
const status = [...one("status", true), ...one("host", false)];
expect(numbers(status)).toEqual([1, 6, 0, 5, 3, 7, 4, 2]);
const ascending = [...one("status", false), ...one("host", false)];
expect(numbers(ascending)).toEqual([2, 4, 0, 5, 3, 7, 1, 6]);
expect(numbers(one("query", true))).toEqual([0, 1, 2, 3, 4, 5, 6, 7]);
expect(sortFlows(flows, [])).toBe(flows);
});
test("sizes, times and the rest put flows without a value lowest", () => {
const a = flow(1, { responseSize: 10, elapsedMs: 5, requestSize: 3, elapsedHeadersMs: 2 });
const b = flow(2, { responseSize: 300, elapsedMs: null, requestSize: 0 });
const c = flow(3, { responseSize: 10, elapsedMs: 50, elapsedHeadersMs: 40 });
const d = flow(4, { error: "DNS lookup failed", status: null, responseSize: 99 });
const four = [a, b, c, d];
const by = (column: FlowSortKey["column"], descending: boolean) =>
sortFlows(four, one(column, descending)).map((f) => f.number);
expect(by("size", true)).toEqual([2, 1, 3, 4]);
expect(by("size", false)).toEqual([4, 1, 3, 2]);
expect(by("time", true)).toEqual([3, 1, 2, 4]);
expect(by("time", false)).toEqual([2, 4, 1, 3]);
expect(by("host", false)).toEqual([2, 4, 1, 3]);
expect(by("latency", true)).toEqual([3, 1, 2, 4]);
expect(by("requestSize", true)).toEqual([1, 2, 3, 4]);
expect(by("number", true)).toEqual([4, 3, 2, 1]);
// Failures sort below every status.
expect(by("status", true)).toEqual([1, 2, 3, 4]);
expect(by("status", false)).toEqual([4, 1, 2, 3]);
expect(sortFlows(flows, null)).toBe(flows);
});
test("flips flows with no status, type, size or time to the other end", () => {
const done = flow(1, { status: 200, contentType: "text/html", responseSize: 5, elapsedMs: 9 });
const pending = flow(2, { status: null, contentType: null, responseSize: 0, elapsedMs: null });
const cancelled = flow(3, { status: null, cancelled: true, contentType: "" });
const flows = [done, pending, cancelled];
for (const column of ["status", "type", "size", "time"] as const) {
expect(sortFlows(flows, { column, descending: true }).map((f) => f.number)).toEqual([
1, 2, 3,
]);
expect(sortFlows(flows, { column, descending: false }).map((f) => f.number)).toEqual([
2, 3, 1,
]);
}
});
});
describe("values", () => {
test("splits URLs as the lib does", () => {
expect(urlParts("https://a.com:8080/v1/x?page=2&q=1#top")).toEqual({
authority: "a.com:8080",
path: "/v1/x",
query: "page=2&q=1",
});
expect(urlParts("https://a.com?x")).toEqual({ authority: "a.com", path: "", query: "x" });
expect(urlParts("bank.example.com:443")).toEqual({
authority: "bank.example.com:443",
path: "",
query: null,
});
});
test("reads a custom column's path from what was typed", () => {
expect(customPath("@header.X-Request-Id:")).toBe("header.x-request-id");
expect(customPath("query.page")).toBe("query.page");
expect(customPath(" res.header.x-cache ")).toBe("res.header.x-cache");
expect(customPath("@host")).toBeNull();
expect(customPath("header.")).toBeNull();
expect(customPath("header.a b")).toBeNull();
expect(customPath("query.filter[status]")).toBeNull();
});
test("a custom column shows the first value, the response's header before the request's", () => {
const f = flow(1, {
url: "https://a.com/?Page=2&page=3",
requestHeaders: [
{ name: "X-Cache", value: "req" },
{ name: "Accept", value: "a" },
{ name: "accept", value: "b" },
],
responseHeaders: [{ name: "x-cache", value: "HIT" }],
});
expect(customValue(f, "header.x-cache")).toBe("HIT");
expect(customValue(f, "req.header.x-cache")).toBe("req");
expect(customValue(f, "header.accept")).toBe("a");
expect(customValue(f, "query.page")).toBe("2");
expect(customValue(f, "query.nope")).toBeNull();
});
test("a cell's filter terms, where its column has a field to match", () => {
const f = flow(1, {
url: "https://api.stripe.com:443/v1/charges?x=1",
status: 404,
clientName: "Google Chrome",
contentType: "application/json; charset=utf-8",
responseHeaders: [{ name: "X-Cache", value: "HIT" }],
});
expect(cellFilterTerm(f, "host", false)).toBe("@host:api.stripe.com");
expect(cellFilterTerm(f, "status", true)).toBe("-@status:404");
expect(cellFilterTerm(f, "app", false)).toBe('@app:"Google Chrome"');
expect(cellFilterTerm(f, "path", false)).toBe("@path:/v1/charges");
expect(cellFilterTerm(f, "type", false)).toBe("@type:application/json");
expect(cellFilterTerm(f, "field:header.x-cache", false)).toBe("@header.x-cache:HIT");
for (const column of ["number", "size", "time", "query", "started"] as const) {
expect(cellFilterTerm(f, column, false)).toBeNull();
}
const grpc = flow(2, { grpcService: "pkg.Greeter", grpcMethod: "SayHello" });
expect(operationOf(grpc)).toBe("pkg.Greeter/SayHello");
expect(cellFilterTerm(grpc, "operation", true)).toBe(
"-(@grpc.service:pkg.Greeter @grpc.method:SayHello)",
);
const graphql = flow(3, { graphqlOperation: "GetUser" });
expect(cellFilterTerm(graphql, "operation", false)).toBe("@graphql.operation:GetUser");
});
});
+389 -186
View File
@@ -1,18 +1,15 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
import { appKeyOf } from "./search";
import type { Flow, FlowSortKey, SortColumn } from "@yaakapp-internal/proxy-lib";
import { compareFlows } from "./flowWindow";
import { fieldTerm } from "./query";
import { sidebarPath } from "./search";
export type ColumnId =
| "number"
| "app"
| "method"
| "host"
| "path"
| "status"
| "type"
| "size"
| "time"
| "remote"
| "version";
/** The columns the list has built in; each sorts by the `SortColumn` of the same name */
export type BuiltinColumnId = SortColumn;
/** A column of a header or query parameter the person added, by its field's path */
export type CustomColumnId = `field:${string}`;
export type ColumnId = BuiltinColumnId | CustomColumnId;
export interface ColumnDef {
id: ColumnId;
@@ -24,102 +21,81 @@ export interface ColumnDef {
align: "left" | "right";
/** Shown until the person hides it */
defaultVisible: boolean;
/** Sorted by in the database; custom columns are not */
sortable: boolean;
/** The header or query parameter a custom column shows: `header.x-request-id` */
path?: string;
}
const builtin = (
id: BuiltinColumnId,
label: string,
width: number,
minWidth: number,
align: "left" | "right",
defaultVisible: boolean,
): ColumnDef => ({ id, label, width, minWidth, align, defaultVisible, sortable: true });
export const COLUMNS: ColumnDef[] = [
{
id: "number",
label: "#",
width: 46,
minWidth: 30,
align: "right",
defaultVisible: true,
},
{
id: "app",
label: "App",
width: 18,
minWidth: 18,
align: "left",
defaultVisible: true,
},
{
id: "method",
label: "Method",
width: 50,
builtin("number", "#", 46, 30, "left", true),
builtin("app", "App", 20, 20, "left", true),
builtin("method", "Method", 50, 40, "left", true),
builtin("host", "Host", 190, 60, "left", true),
builtin("path", "Path", 300, 60, "left", true),
builtin("query", "Query", 120, 40, "left", true),
builtin("status", "Status", 46, 34, "left", true),
builtin("type", "Type", 50, 34, "left", true),
builtin("requestSize", "Request Size", 80, 44, "right", false),
builtin("size", "Size", 72, 44, "right", true),
builtin("time", "Time", 64, 44, "right", true),
builtin("latency", "Latency", 64, 44, "right", false),
builtin("started", "Started", 92, 60, "left", false),
builtin("remote", "Remote Address", 150, 60, "left", false),
builtin("version", "HTTP Version", 70, 44, "left", false),
builtin("tls", "TLS Version", 70, 34, "left", false),
builtin("operation", "Operation", 160, 60, "left", false),
];
const DEFS = new Map<ColumnId, ColumnDef>(COLUMNS.map((c) => [c.id, c]));
/** Map fields a custom column can show, as the query language names them */
const CUSTOM_MAPS = ["req.header.", "res.header.", "header.", "query."];
/** `header.x-request-id` from what was typed, `@header.X-Request-Id:` included, or null */
export function customPath(typed: string): string | null {
const path = typed.trim().replace(/^@/, "").replace(/:$/, "").trim();
const map = CUSTOM_MAPS.find((m) => path.toLowerCase().startsWith(m));
if (map == null) return null;
const key = path.slice(map.length);
// As a field path takes it, so the column's filter items make a term the search can run
if (!/^[A-Za-z0-9_-]+$/.test(key)) return null;
return map + key.toLowerCase();
}
export function customColumnId(path: string): CustomColumnId {
return `field:${path}`;
}
export function isCustomColumn(id: ColumnId): id is CustomColumnId {
return id.startsWith("field:");
}
function customDef(id: CustomColumnId): ColumnDef {
const path = id.slice("field:".length);
return {
id,
label: path,
width: 140,
minWidth: 40,
align: "left",
defaultVisible: true,
},
{
id: "host",
label: "Host",
width: 190,
minWidth: 60,
align: "left",
defaultVisible: true,
},
{
id: "path",
label: "Path",
width: 360,
minWidth: 80,
align: "left",
defaultVisible: true,
},
{
id: "status",
label: "Status",
width: 46,
minWidth: 34,
align: "left",
defaultVisible: true,
},
{
id: "type",
label: "Type",
width: 50,
minWidth: 34,
align: "left",
defaultVisible: true,
},
{
id: "size",
label: "Size",
width: 72,
minWidth: 44,
align: "right",
defaultVisible: true,
},
{
id: "time",
label: "Time",
width: 64,
minWidth: 44,
align: "right",
defaultVisible: true,
},
{
id: "remote",
label: "Remote Address",
width: 150,
minWidth: 60,
align: "left",
defaultVisible: false,
},
{
id: "version",
label: "HTTP Version",
width: 70,
minWidth: 44,
align: "left",
defaultVisible: false,
},
];
const DEFS = new Map(COLUMNS.map((c) => [c.id, c]));
sortable: false,
path,
};
}
export function columnDef(id: ColumnId): ColumnDef {
if (isCustomColumn(id)) return customDef(id);
const def = DEFS.get(id);
if (def == null) throw new Error(`No column ${id}`);
return def;
@@ -131,27 +107,48 @@ export const MARK_WIDTH = 24;
/** Each cell's padding, both sides together, added to its column's width; `px-1.5` per side */
export const CELL_PADDING = "0.75rem";
/** What the person chose: which columns show, and the widths they dragged, by id */
/**
* What the person chose: which columns show, the widths they dragged, by id, the header and
* query parameter columns they added, in order, and the list's sort
*/
export interface ColumnPrefs {
visible: Partial<Record<ColumnId, boolean>>;
widths: Partial<Record<ColumnId, number>>;
custom: CustomColumnId[];
/** The keys in order; empty for the order flows arrive in */
sort: FlowSortKey[];
}
export const defaultColumnPrefs: ColumnPrefs = { visible: {}, widths: {} };
export const defaultColumnPrefs: ColumnPrefs = { visible: {}, widths: {}, custom: [], sort: [] };
export interface Column extends ColumnDef {
/** Its width now, in pixels of content */
current: number;
}
/** Every column the picker lists: the built-in ones, then those the person added */
export function allColumns(prefs: ColumnPrefs): ColumnDef[] {
return [...COLUMNS, ...prefs.custom.map(customDef)];
}
function isVisible(prefs: ColumnPrefs, def: ColumnDef): boolean {
return prefs.visible[def.id] ?? def.defaultVisible;
}
/**
* The columns shown, in order: the visible ones, the path always. Each keeps its width however
* narrow the list is; the list scrolls sideways instead.
* The columns shown, in order. Each keeps its width however narrow the list is; the list scrolls
* sideways instead. At least one always shows.
*/
export function shownColumns(prefs: ColumnPrefs): Column[] {
return COLUMNS.filter((c) => c.id === "path" || (prefs.visible[c.id] ?? c.defaultVisible)).map(
(c) => ({ ...c, current: columnWidth(prefs, c.id) }),
);
export function shownColumns(prefs: ColumnPrefs, unavailable: ColumnId[] = []): Column[] {
const all = allColumns(prefs).filter((c) => !unavailable.includes(c.id));
const shown = all.filter((c) => isVisible(prefs, c));
const columns = shown.length > 0 ? shown : all.filter((c) => c.id === "path");
return columns.map((c) => ({ ...c, current: columnWidth(prefs, c.id) }));
}
/** Columns the platform has nothing for: App, where it cannot tell which app sent a flow */
export function unavailableColumns(hasApps: boolean): ColumnId[] {
return hasApps ? [] : ["app"];
}
export function columnWidth(prefs: ColumnPrefs, id: ColumnId): number {
@@ -171,12 +168,42 @@ export function gridWidth(columns: Column[]): string {
return `calc(${px}px + ${columns.length} * ${CELL_PADDING})`;
}
export function toggleColumn(prefs: ColumnPrefs, id: ColumnId): ColumnPrefs {
if (id === "path") return prefs;
const shown = prefs.visible[id] ?? columnDef(id).defaultVisible;
/** Whether the picker may uncheck `id`: any column but the last one shown */
export function canHide(prefs: ColumnPrefs, id: ColumnId, unavailable: ColumnId[] = []): boolean {
const shown = allColumns(prefs).filter((c) => !unavailable.includes(c.id) && isVisible(prefs, c));
return !shown.every((c) => c.id === id);
}
export function toggleColumn(
prefs: ColumnPrefs,
id: ColumnId,
unavailable: ColumnId[] = [],
): ColumnPrefs {
const shown = isVisible(prefs, columnDef(id));
if (shown && !canHide(prefs, id, unavailable)) return prefs;
return { ...prefs, visible: { ...prefs.visible, [id]: !shown } };
}
/** Shows `id` alone */
export function hideOtherColumns(prefs: ColumnPrefs, id: ColumnId): ColumnPrefs {
const visible: ColumnPrefs["visible"] = {};
for (const c of allColumns(prefs)) visible[c.id] = c.id === id;
return { ...prefs, visible };
}
/** Adds a column for a header or query parameter's path, shown at the end; already there, shown */
export function addCustomColumn(prefs: ColumnPrefs, path: string): ColumnPrefs {
const id = customColumnId(path);
const custom = prefs.custom.includes(id) ? prefs.custom : [...prefs.custom, id];
return { ...prefs, custom, visible: { ...prefs.visible, [id]: true } };
}
export function removeCustomColumn(prefs: ColumnPrefs, id: CustomColumnId): ColumnPrefs {
const { [id]: _v, ...visible } = prefs.visible;
const { [id]: _w, ...widths } = prefs.widths;
return { ...prefs, custom: prefs.custom.filter((c) => c !== id), visible, widths };
}
export function resizeColumn(prefs: ColumnPrefs, id: ColumnId, width: number): ColumnPrefs {
const w = Math.max(columnDef(id).minWidth, Math.round(width));
return { ...prefs, widths: { ...prefs.widths, [id]: w } };
@@ -192,109 +219,285 @@ export function resetWidth(prefs: ColumnPrefs, id: ColumnId): ColumnPrefs {
return { ...prefs, widths };
}
/** Shows Operation the first time a flow has one, unless the person ever set it themselves */
export function showOperationFor(prefs: ColumnPrefs, flows: Flow[]): ColumnPrefs {
if (prefs.visible.operation !== undefined) return prefs;
if (!flows.some((f) => (operationOf(f) ?? "") !== "")) return prefs;
return { ...prefs, visible: { ...prefs.visible, operation: true } };
}
/**
* Reads stored preferences, dropping what no longer applies: unknown ids, and values of the
* wrong type, so a change to the columns never breaks the list.
*/
export function parseColumnPrefs(value: unknown): ColumnPrefs {
const prefs: ColumnPrefs = { visible: {}, widths: {} };
const prefs: ColumnPrefs = { visible: {}, widths: {}, custom: [], sort: [] };
if (value == null || typeof value !== "object") return prefs;
const { visible, widths } = value as Record<string, unknown>;
for (const def of COLUMNS) {
const { visible, widths, custom, sort } = value as Record<string, unknown>;
if (Array.isArray(custom)) {
for (const id of custom) {
if (typeof id !== "string" || !id.startsWith("field:")) continue;
const path = customPath(id.slice("field:".length));
if (path != null && !prefs.custom.includes(customColumnId(path))) {
prefs.custom.push(customColumnId(path));
}
}
}
for (const def of allColumns(prefs)) {
const v = (visible as Record<string, unknown> | undefined)?.[def.id];
if (typeof v === "boolean") prefs.visible[def.id] = v;
const w = (widths as Record<string, unknown> | undefined)?.[def.id];
if (typeof w === "number" && Number.isFinite(w) && w > 0) prefs.widths[def.id] = w;
}
if (Array.isArray(sort)) {
for (const key of sort) {
if (key == null || typeof key !== "object") continue;
const { column, descending } = key as Record<string, unknown>;
if (typeof column !== "string" || typeof descending !== "boolean") continue;
const def = DEFS.get(column as ColumnId);
if (def == null || prefs.sort.some((k) => k.column === column)) continue;
prefs.sort.push({ column: def.id as SortColumn, descending });
}
}
return prefs;
}
/** A sort by a column, or by start time when null */
export interface FlowSort {
column: ColumnId;
descending: boolean;
}
// -- Sorting --
/** Numbers sort largest first on the first click, names from A */
export function firstDirection(column: ColumnId): boolean {
return column === "number" || column === "size" || column === "time" || column === "status";
}
/**
* A click on a column's label: sort by it, reverse the sort it has, then, from the reversed sort,
* go back to start time
*/
export function nextSort(sort: FlowSort | null, column: ColumnId): FlowSort | null {
const first = firstDirection(column);
if (sort?.column !== column) return { column, descending: first };
if (sort.descending === first) return { column, descending: !first };
return null;
}
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
type Key = string | number | null;
function sortKey(flow: Flow, column: ColumnId): Key {
export function firstDirection(column: SortColumn): boolean {
switch (column) {
case "number":
return flow.number;
case "app":
return appKeyOf(flow);
case "method":
return flow.method;
case "host":
return hostOf(flow.url);
case "path":
return pathOf(flow.url);
case "status":
return flow.error != null ? -1 : flow.status;
case "type":
return flow.contentType;
case "size":
return flow.error != null && flow.status == null ? null : flow.responseSize;
case "requestSize":
case "time":
return flow.elapsedMs;
case "remote":
return flow.remoteAddr;
case "version":
return flow.upstreamHttpVersion ?? flow.clientHttpVersion;
case "latency":
return true;
default:
return false;
}
}
/**
* The flows in `sort`'s order, those without a value (none, empty or zero) lowest, so first
* ascending and last descending, then by start so equal values keep arrival order. Sorts the
* flows given, which are the ones loaded, not the whole database: the database only ever reads
* by start time, so no `ORDER BY` follows the column sort.
* A click on a column's label: sort by it alone, reverse the sort it has alone, then, from the
* reversed sort, go back to the order flows arrive in
*/
export function sortFlows(flows: Flow[], sort: FlowSort | null): Flow[] {
if (sort == null) return flows;
const dir = sort.descending ? -1 : 1;
const keyed = flows.map((flow, i) => ({ flow, i, key: sortKey(flow, sort.column) || null }));
keyed.sort((a, b) => {
let c: number;
if (a.key == null || b.key == null) c = Number(b.key == null) - Number(a.key == null);
else if (typeof a.key === "number" && typeof b.key === "number") c = a.key - b.key;
else c = collator.compare(String(a.key), String(b.key));
return c === 0 ? a.i - b.i : c * dir;
});
return keyed.map((k) => k.flow);
export function nextSort(sort: FlowSortKey[], column: SortColumn): FlowSortKey[] {
const first = firstDirection(column);
const only = sort.length === 1 ? sort[0] : null;
if (only?.column !== column) return [{ column, descending: first }];
if (only.descending === first) return [{ column, descending: !first }];
return [];
}
/**
* An Option-click on a column's label: adds it as the last key, ascending; again reverses it, and
* a third time takes it out
*/
export function toggleSortKey(sort: FlowSortKey[], column: SortColumn): FlowSortKey[] {
const key = sort.find((k) => k.column === column);
if (key == null) return [...sort, { column, descending: false }];
if (!key.descending)
return sort.map((k) => (k.column === column ? { column, descending: true } : k));
return sort.filter((k) => k.column !== column);
}
/** Adds `column` as a key in `descending` order: the last key, or in its place if it is one */
export function addSortKey(
sort: FlowSortKey[],
column: SortColumn,
descending: boolean,
): FlowSortKey[] {
if (sort.some((k) => k.column === column)) {
return sort.map((k) => (k.column === column ? { column, descending } : k));
}
return [...sort, { column, descending }];
}
/** What an empty number sorts as, below every value; `EMPTY_NUMBER` in the lib's `flows.rs` */
const EMPTY_NUMBER = -1e18;
/** Text as SQLite's `NOCASE` compares it: ASCII letters lowercased, nothing else changed */
function noCase(text: string | null | undefined): string {
return (text ?? "").replace(/[A-Z]/g, (c) => c.toLowerCase());
}
function emptyNumber(n: number | null | undefined): number {
return n == null || n === 0 ? EMPTY_NUMBER : n;
}
/**
* The value `column` sorts `flow` by, as `SortColumn::sql` in the lib's `flows.rs` makes it in
* the database, so a flow placed here lands where a page read from there would have it
*/
export function columnSortKey(flow: Flow, column: SortColumn): string | number {
switch (column) {
case "number":
return flow.number;
case "app":
return noCase(flow.clientName ?? flow.clientBundleId ?? flow.clientPath);
case "method":
return noCase(flow.method);
case "host":
return noCase(urlParts(flow.url).authority);
case "path":
return noCase(urlParts(flow.url).path);
case "query":
return noCase(urlParts(flow.url).query);
case "status":
return flow.error != null ? -1 : emptyNumber(flow.status);
case "type":
return noCase(flow.contentType);
case "size":
return flow.error != null && flow.status == null
? EMPTY_NUMBER
: emptyNumber(flow.responseSize);
case "requestSize":
return emptyNumber(flow.requestSize);
case "time":
return emptyNumber(flow.elapsedMs);
case "latency":
return emptyNumber(flow.elapsedHeadersMs);
case "started":
return flow.startedAt;
case "remote":
return noCase(flow.remoteAddr);
case "version":
return noCase(flow.upstreamHttpVersion ?? flow.clientHttpVersion);
case "tls":
return noCase(flow.upstreamTlsVersion);
case "operation":
return noCase(
flow.grpcService != null && flow.grpcMethod != null
? `${flow.grpcService}/${flow.grpcMethod}`
: flow.graphqlOperation,
);
}
}
function compareKeys(a: string | number, b: string | number): number {
if (a === b) return 0;
return a < b ? -1 : 1;
}
/**
* Orders flows as `list_flows` orders them for `sort`: each key in turn, then by start and id,
* oldest first
*/
export function sortComparator(sort: FlowSortKey[]): (a: Flow, b: Flow) => number {
return (a, b) => {
for (const { column, descending } of sort) {
const c = compareKeys(columnSortKey(a, column), columnSortKey(b, column));
if (c !== 0) return descending ? -c : c;
}
return compareFlows(a, b);
};
}
/** The flows in `sort`'s order, as the database orders them */
export function sortFlows(flows: Flow[], sort: FlowSortKey[]): Flow[] {
if (sort.length === 0) return flows;
return [...flows].sort(sortComparator(sort));
}
// -- Values --
/**
* A URL's parts as the lib's `url_parts` reads them: no scheme, all host; otherwise the
* authority up to the first `/`, `?` or `#`, then the path and the query without its `?`
*/
export function urlParts(url: string): { authority: string; path: string; query: string | null } {
const start = url.indexOf("://");
if (start === -1) return { authority: url, path: "", query: null };
const rest = url.slice(start + 3);
const end = rest.search(/[/?#]/);
const authority = end === -1 ? rest : rest.slice(0, end);
const tail = (end === -1 ? "" : rest.slice(end)).split("#")[0] ?? "";
const q = tail.indexOf("?");
return q === -1
? { authority, path: tail, query: null }
: { authority, path: tail.slice(0, q), query: tail.slice(q + 1) };
}
/** The URL's host, with its port */
export function hostOf(url: string): string {
const start = url.indexOf("://");
if (start === -1) return "";
const rest = url.slice(start + 3);
const end = rest.search(/[/?#]/);
return end === -1 ? rest : rest.slice(0, end);
return url.includes("://") ? urlParts(url).authority : "";
}
function pathOf(url: string): string {
const start = url.indexOf("://");
if (start === -1) return url;
const rest = url.slice(start + 3);
const end = rest.search(/[/?#]/);
return end === -1 ? "/" : rest.slice(end);
/** `Service/Method` for a gRPC call, the operation's name for GraphQL, or null */
export function operationOf(flow: Flow): string | null {
if (flow.grpcService != null && flow.grpcMethod != null) {
return `${flow.grpcService}/${flow.grpcMethod}`;
}
return flow.graphqlOperation ?? null;
}
/** `1.3` from `TLSv1.3` */
export function tlsVersionOf(flow: Flow): string {
return (flow.upstreamTlsVersion ?? "").replace(/^TLSv?/i, "");
}
/**
* The value of a custom column's path for `flow`: a header's first value, the response's before
* the request's for `header.`, or a query parameter's first value
*/
export function customValue(flow: Flow, path: string): string | null {
const header = (headers: Flow["requestHeaders"], name: string) =>
headers.find((h) => h.name.toLowerCase() === name)?.value ?? null;
if (path.startsWith("req.header.")) {
return header(flow.requestHeaders, path.slice("req.header.".length));
}
if (path.startsWith("res.header.")) {
return header(flow.responseHeaders, path.slice("res.header.".length));
}
if (path.startsWith("header.")) {
const name = path.slice("header.".length);
return header(flow.responseHeaders, name) ?? header(flow.requestHeaders, name);
}
if (path.startsWith("query.")) {
const query = urlParts(flow.url).query;
if (query == null) return null;
const name = path.slice("query.".length);
for (const [key, value] of new URLSearchParams(query)) {
if (key.toLowerCase() === name) return value;
}
}
return null;
}
/**
* The search term that finds flows with `flow`'s value in `column`, or excludes them, for the
* cell's menu; null for columns with no field to match their value exactly
*/
export function cellFilterTerm(flow: Flow, column: ColumnId, negated: boolean): string | null {
const term = (field: string, value: string | null | undefined) =>
value == null || value === "" ? null : fieldTerm(field, value, negated);
if (isCustomColumn(column)) {
const path = column.slice("field:".length);
return term(path, customValue(flow, path));
}
switch (column) {
case "app":
return term("app", flow.clientName ?? flow.clientBundleId ?? flow.clientPath);
case "method":
return term("method", flow.method);
case "host":
return term("host", sidebarPath(flow.url).split("/")[0]);
case "path":
return flow.tunnelled ? null : term("path", urlParts(flow.url).path);
case "status":
return flow.status == null ? null : term("status", String(flow.status));
case "type":
return term("type", flow.contentType?.split(";")[0]?.trim());
case "operation": {
if (flow.grpcService != null && flow.grpcMethod != null) {
const both = `${fieldTerm("grpc.service", flow.grpcService)} ${fieldTerm("grpc.method", flow.grpcMethod)}`;
return negated ? `-(${both})` : both;
}
return term("graphql.operation", flow.graphqlOperation);
}
default:
return null;
}
}
+44 -18
View File
@@ -3,11 +3,13 @@ import type { DropdownItem } from "@yaakapp-internal/ui";
import { save } from "@tauri-apps/plugin-dialog";
import { formatSize } from "@yaakapp-internal/lib/formatSize";
import { atom, useAtomValue, useSetAtom } from "jotai";
import { useCallback } from "react";
import { useCallback, useEffect } from "react";
import { base64ToBytes, bodyFileName } from "./body";
import { curlBodyText, toCurl } from "./curl";
import type { FlowQuery } from "./query";
import { rpc } from "./rpc";
import { activeQueryAtom, lockedAtom } from "./store";
import { subscribe } from "./tauri";
import { useShowToast } from "./toast";
/** The flow the save dialog is open for */
@@ -61,12 +63,32 @@ export async function exportHar(
return rpc("export_har", { ...req, path });
}
/** Exports every flow `query` covers, or all of them, as HAR, saying how many it wrote */
function useExportHarOf(): (query: FlowQuery | null) => Promise<void> {
const showToast = useShowToast();
return useCallback(
async (query: FlowQuery | null) => {
try {
const written = await exportHar(query == null ? {} : { filter: query }, "flows.har");
if (written != null) {
showToast({
message: written === 1 ? "Exported 1 flow as HAR" : `Exported ${written} flows as HAR`,
});
}
} catch (err) {
showToast({ message: `Failed to export HAR: ${String(err)}`, color: "danger" });
}
},
[showToast],
);
}
/**
* Exporting every flow the list covers as HAR, all of them or the search's, for the list's menus:
* it acts on flows, so it lives where they are chosen.
* Exporting every flow the list covers as HAR, all of them or the search's, for the list's and
* the search box's menus: it acts on flows, so it lives where they are chosen.
*/
export function useExportShownHar(): () => DropdownItem {
const showToast = useShowToast();
const exportOf = useExportHarOf();
const query = useAtomValue(activeQueryAtom);
// Nothing can be read to export while captured traffic is locked.
const locked = useAtomValue(lockedAtom) != null;
@@ -75,24 +97,28 @@ export function useExportShownHar(): () => DropdownItem {
label: query == null ? "Export All Flows as HAR" : "Export Matching Flows as HAR",
icon: "download",
disabled: locked,
onSelect: async () => {
try {
const written = await exportHar(query == null ? {} : { filter: query }, "flows.har");
if (written != null) {
showToast({
message:
written === 1 ? "Exported 1 flow as HAR" : `Exported ${written} flows as HAR`,
});
}
} catch (err) {
showToast({ message: `Failed to export HAR: ${String(err)}`, color: "danger" });
}
},
onSelect: () => exportOf(query),
}),
[query, locked, showToast],
[query, locked, exportOf],
);
}
/** File's Export All Flows as HAR, which the app menu sends as an event */
export function useMenuExportHar() {
const exportOf = useExportHarOf();
const locked = useAtomValue(lockedAtom) != null;
useEffect(
() =>
subscribe<null>(MENU_EXPORT_HAR_EVENT, () => {
if (!locked) void exportOf(null);
}),
[exportOf, locked],
);
}
/** `EXPORT_HAR_EVENT` in the app's `window_menu.rs` */
const MENU_EXPORT_HAR_EVENT = "menu_export_har";
/** What a flow's context menu and the detail pane's menu offer */
export function useFlowActions(): (flow: Flow) => DropdownItem[] {
const showToast = useShowToast();
+1
View File
@@ -58,6 +58,7 @@ const flow: Flow = {
grpcMethod: null,
grpcStatus: null,
grpcMessage: null,
graphqlOperation: null,
tunnelled: false,
agentRead: false,
clientAddr: null,
+26 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vite-plus/test";
import { countNewFlows } from "./follow";
import { countNewFlows, isAtEnd, resumesFollowing } from "./follow";
const at = (...times: string[]) => times.map((t) => ({ startedAt: `2026-10-26T10:00:${t}` }));
@@ -26,3 +26,28 @@ describe("countNewFlows", () => {
expect(countNewFlows(at("03", "03.25"), "2026-10-26T10:00:03.2")).toBe(1);
});
});
describe("resumesFollowing", () => {
const fits = { scrollHeight: 300, scrollTop: 0, clientHeight: 300 };
const scrolledUp = { scrollHeight: 3000, scrollTop: 1200, clientHeight: 300 };
const atBottom = { scrollHeight: 3000, scrollTop: 2700, clientHeight: 300 };
test("follows again when the list fits its viewport, so it never shows new flows as unseen", () => {
expect(isAtEnd(fits)).toBe(true);
expect(resumesFollowing({ following: false, sorted: false, el: fits })).toBe(true);
});
test("follows again at the end of a list that overflows", () => {
expect(resumesFollowing({ following: false, sorted: false, el: atBottom })).toBe(true);
});
test("stays held while scrolled up in a list that overflows", () => {
expect(isAtEnd(scrolledUp)).toBe(false);
expect(resumesFollowing({ following: false, sorted: false, el: scrolledUp })).toBe(false);
});
test("never follows while sorted, and has nothing to do while following", () => {
expect(resumesFollowing({ following: false, sorted: true, el: fits })).toBe(false);
expect(resumesFollowing({ following: true, sorted: false, el: fits })).toBe(false);
});
});
+25
View File
@@ -1,5 +1,30 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
/** Where a list's scroll is, as its element reports it */
export interface ScrollPosition {
scrollHeight: number;
scrollTop: number;
clientHeight: number;
}
/** The list is scrolled to its end, or fits its viewport and has no scroll at all */
export function isAtEnd(el: ScrollPosition): boolean {
return el.scrollHeight - el.scrollTop - el.clientHeight < 2;
}
/**
* A held list follows new traffic again once it is at its end, unless it is sorted: after a
* scroll there, or after its flows, filter or size change leave it there, as a list that fits its
* viewport always is. One scrolled up in a list that overflows stays held.
*/
export function resumesFollowing(state: {
following: boolean;
sorted: boolean;
el: ScrollPosition;
}): boolean {
return !state.following && !state.sorted && isAtEnd(state.el);
}
/**
* Flows in the list that started after the list was held. `heldAt` is the start of the newest
* flow across all traffic at that moment, or null when there was none, so it still holds when
+89
View File
@@ -0,0 +1,89 @@
import type { Flow, ModelPayload } from "@yaakapp-internal/proxy-lib";
import { describe, expect, test } from "vite-plus/test";
import { sortComparator } from "./columns";
import { appendPage, applySortedChanges, type SortedWindow } from "./sortedWindow";
function flow(n: number, status: number | null): Flow {
return {
id: `fl_${n}`,
number: n,
startedAt: `2026-11-09T12:00:0${n}`,
status,
error: null,
} as Flow;
}
const bySize = sortComparator([{ column: "status", descending: true }]);
const upsert = (model: Flow, search?: ModelPayload["search"]): ModelPayload => ({
model,
change: { type: "upsert", created: true },
...(search == null ? {} : { search }),
});
const remove = (model: Flow): ModelPayload => ({ model, change: { type: "delete" } });
const numbers = (flows: Flow[]) => flows.map((f) => f.number);
describe("applySortedChanges", () => {
const held = [flow(1, 500), flow(2, 404), flow(3, 200)];
test("places a new or changed flow by the sort, and drops a deleted one", () => {
let flows = applySortedChanges(held, null, [upsert(flow(4, 300))], bySize, null);
expect(numbers(flows)).toEqual([1, 2, 4, 3]);
flows = applySortedChanges(flows, null, [upsert(flow(3, 503))], bySize, null);
expect(numbers(flows)).toEqual([3, 1, 2, 4]);
flows = applySortedChanges(flows, null, [remove(flow(1, 500))], bySize, null);
expect(numbers(flows)).toEqual([3, 2, 4]);
});
test("leaves a flow past the last one read for paging to bring", () => {
const boundary = held[2] ?? null;
const flows = applySortedChanges(held, boundary, [upsert(flow(4, 100))], bySize, null);
expect(numbers(flows)).toEqual([1, 2, 3]);
// The last flow read, written again unchanged, stays.
const same = applySortedChanges(held, boundary, [upsert(flow(3, 200))], bySize, null);
expect(numbers(same)).toEqual([1, 2, 3]);
// A held flow that moves past the end leaves until paging reaches it.
const moved = applySortedChanges(held, boundary, [upsert(flow(1, 100))], bySize, null);
expect(numbers(moved)).toEqual([2, 3]);
});
test("searching, takes only flows the search matched, and keeps ones it can't tell", () => {
const changes = [
upsert(flow(4, 300), { key: "k", matches: true }),
upsert(flow(5, 300), { key: "k", matches: false }),
upsert(flow(2, 404), { key: "k", matches: false }),
upsert(flow(3, 999), { key: "other", matches: true }),
];
const flows = applySortedChanges(held, null, changes, bySize, "k");
expect(numbers(flows)).toEqual([1, 4, 3]);
});
});
test("a page adds what it does not already hold", () => {
const win: SortedWindow = {
key: "1",
sort: [],
query: null,
flows: [flow(1, 500), flow(2, 404)],
boundary: flow(2, 404),
cursor: [404, "fl_2"],
loading: false,
buffered: [],
};
const next = appendPage(win, [flow(2, 404), flow(3, 200)], [200, "fl_3"], 2);
expect(numbers(next.flows)).toEqual([1, 2, 3]);
expect(next.boundary?.id).toBe("fl_3");
expect(next.cursor).toEqual([200, "fl_3"]);
// A short page is the last: nothing is past it.
const last = appendPage(win, [flow(3, 200)], [200, "fl_3"], 2);
expect([last.boundary, last.cursor]).toEqual([null, null]);
// One the sweep deleted meanwhile is left out, but still marks where the page ended.
const swept = appendPage(
win,
[flow(3, 200), flow(4, 100)],
[100, "fl_4"],
2,
(f) => f.id !== "fl_4",
);
expect(numbers(swept.flows)).toEqual([1, 2, 3]);
expect(swept.boundary?.id).toBe("fl_4");
});
+97
View File
@@ -0,0 +1,97 @@
import type { Flow, FlowSortKey, ModelPayload, SortValue } from "@yaakapp-internal/proxy-lib";
import type { FlowQuery } from "./query";
/**
* The flows the list shows while it is sorted: read from the database in the sort's order, a
* page at a time from the top, as `list_flows` orders them for `sort`. Flows that change are
* placed by the same comparison, and only up to where the pages read end, so paging on never
* skips or repeats one.
*/
export interface SortedWindow {
/** Unique to this load, so a page read for an earlier sort or search is dropped */
key: string;
sort: FlowSortKey[];
query: FlowQuery | null;
/** In the sort's order */
flows: Flow[];
/**
* The last flow of the last page, as it was read, while the database has more after it: where
* the next page starts. Null once every flow is read.
*/
boundary: Flow | null;
/** The next page's `cursor`, from the last page: the boundary's sort values as read */
cursor: SortValue[] | null;
/** The first page has not arrived yet */
loading: boolean;
/** Changes that came while the first page loaded, applied once it is in */
buffered: ModelPayload[];
}
/** Where `flow` goes in `flows`, which `compare` orders */
function insertionIndex(flows: Flow[], flow: Flow, compare: (a: Flow, b: Flow) => number): number {
let lo = 0;
let hi = flows.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
const item = flows[mid];
if (item != null && compare(item, flow) < 0) lo = mid + 1;
else hi = mid;
}
return lo;
}
/**
* Applies flow events to a sorted window's flows: a changed flow moves to where `compare` puts
* it, a deleted one leaves, and one that sorts after `boundary`, where the pages read end, is
* left for paging. With `searchKey`, only flows the backend matched against that search join or
* stay; a flow matched against another search is left as it is, to be matched again.
*/
export function applySortedChanges(
flows: Flow[],
boundary: Flow | null,
changes: ModelPayload[],
compare: (a: Flow, b: Flow) => number,
searchKey: string | null,
): Flow[] {
if (changes.length === 0) return flows;
const next = flows.slice();
for (const c of changes) {
const deleted = c.change.type === "delete";
if (!deleted && searchKey != null && c.search?.key !== searchKey) continue;
const existing = next.findIndex((f) => f.id === c.model.id);
if (existing !== -1) next.splice(existing, 1);
if (deleted || (searchKey != null && c.search?.matches !== true)) continue;
if (boundary != null && compare(c.model, boundary) > 0) continue;
next.splice(insertionIndex(next, c.model, compare), 0, c.model);
}
return next;
}
/** A page from `list_flows` as a sorted window takes it: where it ends, and where the next starts */
export function pageBoundary(
page: Flow[],
cursor: SortValue[] | null,
limit: number,
): Pick<SortedWindow, "boundary" | "cursor"> {
const more = page.length >= limit;
return { boundary: more ? (page.at(-1) ?? null) : null, cursor: more ? cursor : null };
}
/**
* Adds the next page from `list_flows`, read after the window's boundary, less any it has and
* any `keep` leaves out
*/
export function appendPage(
win: SortedWindow,
page: Flow[],
cursor: SortValue[] | null,
limit: number,
keep: (flow: Flow) => boolean = () => true,
): SortedWindow {
const held = new Set(win.flows.map((f) => f.id));
return {
...win,
flows: [...win.flows, ...page.filter((f) => !held.has(f.id) && keep(f))],
...pageBoundary(page, cursor, limit),
};
}
+159 -7
View File
@@ -1,8 +1,10 @@
import type {
Flow,
FlowSortKey,
GetProxyStateResponse,
ModelPayload,
SavedQuery,
SortValue,
} from "@yaakapp-internal/proxy-lib";
import { selectedIdsFamily } from "@yaakapp-internal/ui";
import { atom, type createStore } from "jotai";
@@ -11,10 +13,11 @@ import { followingAtom, SIDEBAR_TREE_ID, selectedFlowAtom } from "./atoms";
import {
type ColumnPrefs,
defaultColumnPrefs,
type FlowSort,
parseColumnPrefs,
sortComparator,
sortFlows,
} from "./columns";
import { appendPage, applySortedChanges, pageBoundary, type SortedWindow } from "./sortedWindow";
import {
applyChanges,
emptyWindow,
@@ -158,7 +161,7 @@ const storedColumnPrefsAtom = atomWithStorage<unknown>(
},
);
/** Which columns the list shows and how wide, as the person left them */
/** Which columns the list shows, how wide, and its sort, as the person left them */
export const columnPrefsAtom = atom(
(get) => parseColumnPrefs(get(storedColumnPrefsAtom)),
(get, set, update: ColumnPrefs | ((prev: ColumnPrefs) => ColumnPrefs)) => {
@@ -167,8 +170,14 @@ export const columnPrefsAtom = atom(
},
);
/** The list's sort, or null for start time, the order flows arrive in */
export const flowSortAtom = atom<FlowSort | null>(null);
/** The list's sort keys, in order, kept with the columns; empty for the order flows arrive in */
export const flowSortAtom = atom(
(get) => get(columnPrefsAtom).sort,
(_get, set, sort: FlowSortKey[]) => set(columnPrefsAtom, (p) => ({ ...p, sort })),
);
/** The flows the list shows while sorted, read from the database in the sort's order */
export const sortedWindowAtom = atom<SortedWindow | null>(null);
/** A window onto the flows a search covers, loaded from the database as the main one is */
export interface SearchWindow {
@@ -189,12 +198,26 @@ const shownWindowAtom = atom((get) => get(searchWindowAtom)?.win ?? get(flowWind
/** The flows loaded for the list, oldest first */
export const windowFlowsAtom = atom((get) => get(shownWindowAtom).flows);
/** The flows the list shows: oldest first, or in the sort's order, over those loaded */
export const shownFlowsAtom = atom((get) => sortFlows(get(windowFlowsAtom), get(flowSortAtom)));
/**
* The flows the list shows: oldest first, or in the sort's order from the database. Until a
* sort's first page is in, the flows loaded, sorted here, stand in for it.
*/
export const shownFlowsAtom = atom((get) => {
const sort = get(flowSortAtom);
if (sort.length === 0) return get(windowFlowsAtom);
const sorted = get(sortedWindowAtom);
if (sorted == null || (sorted.loading && sorted.flows.length === 0)) {
return sortFlows(get(windowFlowsAtom), sort);
}
return sorted.flows;
});
/** Flows in the database the list covers: every one, or those the search matches */
export const shownTotalAtom = atom((get) => get(shownWindowAtom).total);
/** The search's first page has not arrived, so the list shows none of its flows yet */
export const searchLoadingAtom = atom((get) => get(searchWindowAtom)?.loading ?? false);
/** Start and id of the oldest flow shown, which loading older flows moves back */
export const oldestFlowAtom = atom((get) => get(windowFlowsAtom)[0] ?? null);
@@ -288,6 +311,54 @@ export const loadOlderFlowsAtom = atom(null, async (get, set) => {
}
});
/** Changes applied while a page of a sort loads, applied again over it once it is in */
let changesDuringSortedPage: ModelPayload[] | null = null;
/** The key flow events mark matches of the search shown with, or null for all traffic */
function searchKeyOf(search: SearchWindow | null): string | null {
return search?.key ?? null;
}
/** Loads the sort's next page, after the last flow shown, on scrolling to the bottom */
export const loadMoreSortedAtom = atom(null, async (get, set) => {
const win = get(sortedWindowAtom);
const cursor = win?.cursor;
if (win == null || win.loading || win.boundary == null || cursor == null) return;
if (changesDuringSortedPage != null) return;
const changes: ModelPayload[] = [];
changesDuringSortedPage = changes;
pageStarted();
try {
const res = await rpc("list_flows", {
...win.query,
sort: win.sort,
cursor,
limit: PAGE_SIZE,
});
set(sortedWindowAtom, (s) => {
if (s?.key !== win.key || s.cursor !== cursor) return s;
const kept = new Set(withoutRemoved(res.flows).map((f) => f.id));
const merged = appendPage(s, res.flows, res.cursor, PAGE_SIZE, (f) => kept.has(f.id));
const compare = sortComparator(s.sort);
const key = searchKeyOf(get(searchWindowAtom));
return {
...merged,
flows: applySortedChanges(merged.flows, merged.boundary, changes, compare, key),
};
});
} catch (err) {
// Read the sort again from its top.
console.warn("Failed to load more sorted flows", err);
reloadSorted?.();
} finally {
changesDuringSortedPage = null;
pageSettled();
}
});
/** Reads the sort's first page again, once `syncFlows` has started */
let reloadSorted: (() => void) | null = null;
/** `changesFor`, with flows matched against another search sent to be matched again */
function changesOf(
search: Pick<SearchWindow, "key" | "query">,
@@ -320,6 +391,7 @@ function matchLater(search: Pick<SearchWindow, "key" | "query">, changes: ModelP
search: { key: search.key, matches: covered.has(c.model.id) },
}));
if (marked.length === 0) return;
applySortedChangesTo(store, marked);
const following = store.get(followingAtom);
store.set(searchWindowAtom, (s) => {
if (s?.key !== search.key) return s;
@@ -331,6 +403,19 @@ function matchLater(search: Pick<SearchWindow, "key" | "query">, changes: ModelP
.catch((err) => console.warn("Failed to match flows", err));
}
/** Applies flow events to the sorted window, or holds them while its first page loads */
function applySortedChangesTo(store: Store, changes: ModelPayload[]) {
if (store.get(sortedWindowAtom) == null) return;
changesDuringSortedPage?.push(...changes);
const key = searchKeyOf(store.get(searchWindowAtom));
store.set(sortedWindowAtom, (s) => {
if (s == null) return s;
if (s.loading) return { ...s, buffered: [...s.buffered, ...changes] };
const flows = applySortedChanges(s.flows, s.boundary, changes, sortComparator(s.sort), key);
return flows === s.flows ? s : { ...s, flows };
});
}
/**
* Loads the newest flows, then keeps them current with the engine's events, or with reads of the
* database while another process owns the engine. Events gather for `FLUSH_MS` and apply
@@ -366,6 +451,7 @@ export function syncFlows(store: Store) {
const next = applyChanges(s.win, changesOf(s, s.win, changes));
return { ...s, win: following ? trimWindow(next) : next };
});
applySortedChangesTo(store, changes);
const selected = store.get(selectedFlowAtom);
const change = changes.findLast((c) => c.model.id === selected?.id);
if (change != null) {
@@ -477,6 +563,16 @@ export function syncFlows(store: Store) {
dropRemovedChanges(buffered, removed);
return { ...s, win: drop(s.win), buffered };
});
if (changesDuringSortedPage != null) dropRemovedChanges(changesDuringSortedPage, removed);
store.set(sortedWindowAtom, (s) => {
if (s == null) return s;
const buffered = [...s.buffered];
dropRemovedChanges(buffered, removed);
const flows = s.flows.some((f) => removed.has(f.id))
? s.flows.filter((f) => !removed.has(f.id))
: s.flows;
return { ...s, flows, buffered };
});
if (removed.has(store.get(selectedFlowAtom)?.id ?? "")) store.set(selectedFlowAtom, null);
if (recountTimer == null) recountTimer = setTimeout(recount, RECOUNT_MS);
});
@@ -503,9 +599,62 @@ export function syncFlows(store: Store) {
})
.finally(pageSettled);
loadSearch(store.get(activeQueryAtom));
loadSorted();
}
reloadFlows = load;
/**
* Reads the first page of the list's sort from the database, over the search shown, or drops
* the sorted window when there is no sort. Until the page is in, the flows loaded, sorted here,
* stand in for it.
*/
let sortedLoads = 0;
function loadSorted() {
const sort = store.get(flowSortAtom);
if (sort.length === 0) {
store.set(sortedWindowAtom, null);
return;
}
const query = store.get(activeQueryAtom);
const key = `${++sortedLoads}:${JSON.stringify({ sort, query })}`;
store.set(sortedWindowAtom, {
key,
sort,
query,
flows: [],
boundary: null,
cursor: null,
loading: true,
buffered: [],
});
const settle = (page: Flow[] | null, cursor: SortValue[] | null) =>
store.set(sortedWindowAtom, (s) => {
if (s?.key !== key) return s;
const ends = pageBoundary(page ?? [], cursor, PAGE_SIZE);
const base = page == null ? s.flows : withoutRemoved(page);
const search = searchKeyOf(store.get(searchWindowAtom));
const compare = sortComparator(sort);
const flows = applySortedChanges(base, ends.boundary, s.buffered, compare, search);
return { ...s, ...ends, flows, loading: false, buffered: [] };
});
pageStarted();
void rpc("list_flows", { ...query, sort, limit: PAGE_SIZE })
.then((res) => settle(res.flows, res.cursor))
.catch((err) => {
console.warn("Failed to read the sorted flows", err);
settle(null, null);
})
.finally(pageSettled);
}
reloadSorted = loadSorted;
let sortJson = JSON.stringify(store.get(flowSortAtom));
store.sub(flowSortAtom, () => {
const json = JSON.stringify(store.get(flowSortAtom));
if (json === sortJson) return;
sortJson = json;
loadSorted();
});
/**
* Loads the first page of `query`'s flows into a window of its own, or drops it for null. The
* backend matches the flows written from now on against it, and their events say so.
@@ -590,6 +739,7 @@ export function syncFlows(store: Store) {
if (key === activeKey) return;
activeKey = key;
loadSearch(query);
loadSorted();
});
// While another process owns the engine no events come, so new flows are read from the
@@ -652,9 +802,11 @@ const emptyFlowsAtom = atom(null, (_get, set) => {
set(flowWindowAtom, emptyWindow);
set(nonSystemTotalAtom, 0);
set(searchWindowAtom, (s) => (s == null ? s : { ...s, win: emptyWindow, buffered: [] }));
set(sortedWindowAtom, (s) =>
s == null ? s : { ...s, flows: [], boundary: null, cursor: null, buffered: [] },
);
set(selectedFlowAtom, null);
set(followingAtom, true);
set(flowSortAtom, null);
});
/**
+65
View File
@@ -0,0 +1,65 @@
import { beforeEach, describe, expect, test, vi } from "vite-plus/test";
type Handler = (e: { payload: unknown }) => void;
/** Listeners Tauri holds, and the registrations not yet resolved */
const listeners = new Set<Handler>();
let pending: (() => void)[] = [];
vi.mock("@tauri-apps/api/event", () => ({
// Registers asynchronously, as Tauri does, resolving only when the test lets it.
listen: (_event: string, handler: Handler) =>
new Promise<() => void>((resolve) => {
pending.push(() => {
listeners.add(handler);
resolve(() => listeners.delete(handler));
});
}),
}));
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));
vi.mock("@tauri-apps/api/webviewWindow", () => ({ getCurrentWebviewWindow: vi.fn() }));
vi.mock("@tauri-apps/plugin-os", () => ({ type: vi.fn() }));
const { subscribe } = await import("./tauri");
async function register() {
for (const resolve of pending) resolve();
pending = [];
await Promise.resolve();
await Promise.resolve();
}
function emit(payload: unknown) {
for (const handler of listeners) handler({ payload });
}
describe("subscribe", () => {
beforeEach(() => {
listeners.clear();
pending = [];
});
test("an effect cleaned up before its listener registers hears nothing, as in strict mode", async () => {
const heard = vi.fn();
// Strict mode: subscribe, clean up at once, subscribe again
const first = subscribe("menu_export_har", heard);
first();
const second = subscribe("menu_export_har", heard);
await register();
emit(null);
expect(heard).toHaveBeenCalledTimes(1);
expect(listeners.size).toBe(1);
second();
expect(listeners.size).toBe(0);
});
test("delivers events until unsubscribed", async () => {
const heard = vi.fn();
const unsubscribe = subscribe<number>("menu_export_har", heard);
await register();
emit(1);
unsubscribe();
emit(2);
expect(heard.mock.calls).toEqual([[1]]);
});
});
+12 -8
View File
@@ -9,15 +9,19 @@ export function command<T>(cmd: string, args?: Record<string, unknown>): Promise
return invoke(cmd, args) as Promise<T>;
}
/** Subscribe to a Tauri event. Returns an unsubscribe function. */
/**
* Subscribe to a Tauri event. Returns an unsubscribe function, which also removes a listener
* still being registered once it is, and stops it delivering meanwhile: an effect cleaned up
* that fast, as strict mode does to every one, would otherwise leave its listener attached and
* hear each event twice.
*/
export function subscribe<T>(event: string, callback: (payload: T) => void): () => void {
let unsub: (() => void) | null = null;
tauriListen<T>(event, (e) => callback(e.payload))
.then((fn) => {
unsub = fn;
})
.catch(console.error);
return () => unsub?.();
const subscription = unsubscribeWhenReady(
tauriListen<T>(event, (e) => {
if (subscription.active()) callback(e.payload);
}),
);
return subscription.unsubscribe;
}
/** Calls `callback` each time the window regains focus. Returns an unsubscribe function. */