POC: Explore request assertions and CLI testing

This commit is contained in:
Gregory Schier committed 2026-09-25 08:32:24 -07:00
1 parent 263a215f7a
commit c71256d800
65 files changed
+4187 -1983

No files matched your search

@@ -0,0 +1,79 @@
import deepEqual from "@gilbarbara/deep-equal";
import { useMutation } from "@tanstack/react-query";
import type { AssertionReport, HttpAssertions, HttpResponse } from "@yaakapp-internal/models";
import { format } from "date-fns";
import { rpc } from "../lib/rpc";
import { Button } from "./core/Button";
import { HttpAssertionReport } from "./HttpAssertionResults";
interface Props {
assertions: HttpAssertions;
response: HttpResponse | null;
}
export function HttpAssertionPreview(props: Props) {
// A response switch (including a new send) discards results and in-flight UI
// state. The old evaluation may finish, but it cannot label the new response.
return <ResponsePreview key={`${props.response?.id}:${props.response?.updatedAt}`} {...props} />;
}
function ResponsePreview({ assertions, response }: Props) {
const preview = useMutation({
mutationFn: (definition: HttpAssertions) =>
rpc<AssertionReport>("cmd_preview_http_assertions", {
responseId: response?.id,
assertions: definition,
}),
retry: false,
gcTime: 0,
});
const unavailable = !response
? "Send a request first to get a response to try."
: response.state !== "closed"
? "Wait for the response to finish."
: !assertions.checks.some((check) => check.enabled)
? "Enable an assertion to try it."
: null;
const changed = preview.data != null && !deepEqual(preview.data.definition, assertions);
return (
<div className="space-y-2">
<Button
size="sm"
variant="border"
disabled={unavailable != null || preview.isPending}
onClick={() => preview.mutate(assertions)}
>
{preview.isPending ? "Trying assertions…" : "Try assertions"}
</Button>
<p className="text-xs text-text-subtle">
{unavailable ?? "Preview against the selected response without sending again."}
</p>
{preview.isError && (
<p className="text-sm text-danger" role="alert">
Could not preview assertions:{" "}
{preview.error instanceof Error ? preview.error.message : String(preview.error)}
</p>
)}
{preview.data && response && (
<section
aria-label="Assertion preview"
aria-live="polite"
className="border border-border-subtle rounded-md p-3 space-y-2"
>
<p className="text-sm font-medium">Preview</p>
<p className="text-xs text-text-subtle">
Response from {format(`${response.createdAt}Z`, "MMM d, h:mm:ss a")}. Recorded results
are unchanged.
</p>
{changed && (
<p className="text-xs text-warning" role="status">
Assertions changed. Try again to update this preview.
</p>
)}
<HttpAssertionReport report={preview.data} />
</section>
)}
</div>
);
}
@@ -0,0 +1,81 @@
import type { AssertionReport, HttpResponse } from "@yaakapp-internal/models";
import classNames from "classnames";
import { EmptyStateText } from "./EmptyStateText";
export function HttpAssertionResults({ response }: { response: HttpResponse }) {
const report = response.assertionResults;
if (!report)
return <EmptyStateText>Assertions were not evaluated for this response.</EmptyStateText>;
if (!report.error && report.results.length === 0)
return <EmptyStateText>Waiting for the response to finish.</EmptyStateText>;
return (
<div className="h-full overflow-auto space-y-2 pb-3">
<p className="text-xs text-text-subtle">Checks saved with this response.</p>
<HttpAssertionReport report={report} />
</div>
);
}
export function HttpAssertionReport({ report }: { report: AssertionReport }) {
const passed = report.results.filter((r) => r.outcome === "passed").length;
const failed = report.results.filter((r) => r.outcome === "failed").length;
const errors = report.results.filter(
(r) => r.outcome === "error" || r.outcome === "invalid",
).length;
const skipped = report.results.filter((r) => r.outcome === "skipped").length;
return (
<div className="space-y-2">
<p className="text-sm">
{passed} passed · {failed} failed · {errors} errors · {skipped} skipped
</p>
{report.error && <p className="text-sm text-danger">{report.error}</p>}
{report.results.map((result, index) => {
const check = report.definition.checks[index];
return (
<div
key={`${result.assertionId}:${index}`}
className="border border-border-subtle rounded-md p-2 text-sm space-y-1"
>
<div className="flex items-start justify-between gap-2">
<span className="font-mono break-all">
{check?.target === "status" ? "Status" : check?.selector}
</span>
<span
className={classNames(
"capitalize shrink-0",
result.outcome === "passed"
? "text-success"
: result.outcome === "skipped"
? "text-text-subtle"
: "text-danger",
)}
>
{result.outcome}
</span>
</div>
{check && (
<p className="text-xs break-all">
{check.operator.replaceAll("_", " ")}
{check.operator !== "exists" && (
<>
{" "}
{check.expectedType === "null"
? "null"
: check.expectedType === "text"
? JSON.stringify(check.expected)
: check.expected}{" "}
({check.expectedType})
</>
)}
</p>
)}
<p className="text-xs text-text-subtle">{result.reason}</p>
{result.actual != null && (
<p className="font-mono text-xs break-all">Actual: {JSON.stringify(result.actual)}</p>
)}
</div>
);
})}
</div>
);
}
@@ -0,0 +1,216 @@
import { useQuery } from "@tanstack/react-query";
import type { HttpAssertion, HttpAssertions, HttpRequest } from "@yaakapp-internal/models";
import { patchModelDebounced } from "@yaakapp-internal/models";
import { usePinnedHttpResponse } from "../hooks/usePinnedHttpResponse";
import { JsonPathInput } from "./JsonPathInput";
import { useRequestUpdateKey } from "../hooks/useRequestUpdateKey";
import { useStateWithDeps } from "../hooks/useStateWithDeps";
import { generateId } from "../lib/generateId";
import { rpc } from "../lib/rpc";
import { Button } from "./core/Button";
import { Checkbox } from "./core/Checkbox";
import { IconButton } from "./core/IconButton";
import { PlainInput } from "./core/PlainInput";
import { Select } from "./core/Select";
import { HttpAssertionPreview } from "./HttpAssertionPreview";
const EMPTY: HttpAssertions = { version: 1, checks: [] };
const operators = [
{ value: "equals", label: "Equals" },
{ value: "not_equals", label: "Does not equal" },
{ value: "greater_than", label: "Greater than" },
{ value: "less_than", label: "Less than" },
{ value: "contains", label: "Contains" },
{ value: "exists", label: "Exists" },
];
export function HttpAssertionsEditor({ request }: { request: HttpRequest }) {
const updateKey = useRequestUpdateKey(request.id);
const { activeResponse } = usePinnedHttpResponse(request.id);
const [definition, setDefinition] = useStateWithDeps(request.assertions ?? EMPTY, [updateKey]);
const validation = useQuery({
queryKey: ["validate_assertions", definition],
queryFn: () =>
rpc<Record<string, string>>("cmd_validate_http_assertions", { assertions: definition }),
staleTime: Infinity,
gcTime: 0,
retry: false,
});
const save = (checks: HttpAssertion[]) => {
const next = { ...definition, checks };
setDefinition(next);
patchModelDebounced(request, { assertions: next });
};
const update = (id: string, patch: Partial<HttpAssertion>) =>
save(definition.checks.map((c) => (c.id === id ? { ...c, ...patch } : c)));
return (
<div className="@container h-full overflow-auto pb-3 space-y-3">
<p className="text-sm text-text-subtle">
Check the response each time you send. Results appear in the response’s Assertions tab.
</p>
{definition.checks.map((check, index) => (
<div key={check.id} className="border border-border-subtle rounded-md p-2 space-y-2">
<div className="flex items-center gap-2">
<Checkbox
title={`Assertion ${index + 1}`}
checked={check.enabled}
onChange={(enabled) => update(check.id, { enabled })}
/>
<IconButton
icon="trash"
size="xs"
title={`Delete assertion ${index + 1}`}
onClick={() => save(definition.checks.filter((c) => c.id !== check.id))}
/>
</div>
<div className="grid grid-cols-[minmax(0,1fr)] @[28rem]:grid-cols-[8rem_minmax(0,1fr)] gap-2">
<Select
name={`target-${check.id}`}
label="Response"
size="sm"
value={check.target}
options={[
{ value: "json", label: "JSON body" },
{ value: "status", label: "Status" },
{ value: "header", label: "Header" },
]}
onChange={(target) =>
update(check.id, {
target,
selector: "",
operator: "equals",
expected: target === "status" ? "200" : "",
expectedType: target === "status" ? "number" : "text",
})
}
/>
{check.target === "json" && (
<JsonPathInput
response={activeResponse}
stateKey={`assertion-path:${request.id}:${check.id}`}
defaultValue={check.selector}
forceUpdateKey={updateKey}
onChange={(selector) => update(check.id, { selector })}
/>
)}
{check.target === "header" && (
<PlainInput
label="Header name"
size="sm"
defaultValue={check.selector}
forceUpdateKey={`${updateKey}:${check.target}`}
placeholder="Content-Type"
onChange={(selector) => update(check.id, { selector })}
/>
)}
</div>
<div className="grid grid-cols-[minmax(0,1fr)] @[28rem]:grid-cols-[8rem_minmax(0,1fr)] gap-2">
<Select
name={`operator-${check.id}`}
label="Comparison"
size="sm"
value={check.operator}
options={operators.filter(
(o) =>
check.target === "json" ||
(check.target === "status"
? o.value !== "contains" && o.value !== "exists"
: !["greater_than", "less_than"].includes(o.value)),
)}
onChange={(operator) =>
update(check.id, {
operator,
...(["greater_than", "less_than"].includes(operator)
? { expectedType: "number" }
: operator === "contains"
? { expectedType: "text" }
: {}),
})
}
/>
{check.operator !== "exists" && (
<div className="flex items-start gap-2 min-w-0">
{check.expectedType !== "null" && (
<div className="flex-1 min-w-0">
<PlainInput
label="Expected value"
size="sm"
defaultValue={check.expected}
forceUpdateKey={`${updateKey}:${check.target}`}
placeholder={check.expectedType === "boolean" ? "true or false" : "Value"}
onChange={(expected) => update(check.id, { expected })}
/>
</div>
)}
{check.target === "json" &&
!["greater_than", "less_than", "contains"].includes(check.operator) && (
<div className="w-24 shrink-0">
<Select
name={`type-${check.id}`}
label="Type"
size="sm"
value={check.expectedType}
options={[
{ value: "text", label: "Text" },
{ value: "number", label: "Number" },
{ value: "boolean", label: "Boolean" },
{ value: "null", label: "Null" },
]}
onChange={(expectedType) => update(check.id, { expectedType })}
/>
</div>
)}
</div>
)}
</div>
{validation.data?.[check.id] && (
<p className="text-xs text-danger" role="status">
{validation.data[check.id]}
</p>
)}
</div>
))}
{validation.data?.[""] && (
<p className="text-sm text-danger" role="status">
{validation.data[""]}
</p>
)}
{validation.isError && (
<p className="text-sm text-danger" role="status">
Unable to validate assertions.
</p>
)}
<Button
size="sm"
variant="border"
disabled={definition.version !== 1 || definition.checks.length >= 100}
onClick={() =>
save([
...definition.checks,
{
id: generateId(),
enabled: true,
target: "json",
selector: "",
operator: "equals",
expected: "",
expectedType: "text",
},
])
}
>
Add assertion
</Button>
{definition.checks.some((c) => c.target === "json") && (
<p className="text-xs text-text-subtle">
Use a JSONPath such as $.user.id or user.id. Comparisons select one value; Exists also
accepts multiple matches. Suggestions use the selected response, one level at a time.
Values are literal and types must match.
</p>
)}
<HttpAssertionPreview assertions={definition} response={activeResponse} />
</div>
);
}
@@ -42,11 +42,12 @@ import { Editor } from "./core/Editor/LazyEditor";
import { InlineCode } from "@yaakapp-internal/ui";
import { PlainInput } from "./core/PlainInput";
import type { TabItem, TabsRef } from "./core/Tabs/Tabs";
import { setActiveTab, TabContent, Tabs } from "./core/Tabs/Tabs";
import { TabContent, Tabs } from "./core/Tabs/Tabs";
import { EmptyStateText } from "./EmptyStateText";
import { FormMultipartEditor } from "./FormMultipartEditor";
import { FormUrlencodedEditor } from "./FormUrlencodedEditor";
import { HeadersEditor } from "./HeadersEditor";
import { HttpAssertionsEditor } from "./HttpAssertionsEditor";
import { HttpAuthenticationEditor } from "./HttpAuthenticationEditor";
import { JsonBodyEditor } from "./JsonBodyEditor";
import { MarkdownEditor } from "./MarkdownEditor";
@@ -72,6 +73,7 @@ const TAB_HEADERS = "headers";
const TAB_AUTH = "auth";
const TAB_SETTINGS = "settings";
const TAB_DESCRIPTION = "description";
const TAB_ASSERTIONS = "assertions";
const TABS_STORAGE_KEY = "http_request_tabs";
// Derived from the identity-stable URL list so this only recomputes when a URL
@@ -171,6 +173,7 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
() => [
{
value: TAB_BODY,
menuLabel: "Body",
rightSlot: numParams > 0 ? <CountBadge count={numParams} /> : null,
options: {
value: activeRequest.bodyType,
@@ -264,6 +267,16 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
label: "Info",
rightSlot: hasDescription && <CountBadge count={true} />,
},
{
value: TAB_ASSERTIONS,
label: "Assertions",
rightSlot: (
<CountBadge
count={activeRequest.assertions?.checks.filter((c) => c.enabled).length ?? 0}
/>
),
hiddenByDefault: !activeRequest.assertions?.checks.length,
},
],
[
activeRequest,
@@ -310,11 +323,7 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
e.preventDefault(); // Prevent input onChange
await patchModel(activeRequest, patch);
await setActiveTab({
storageKey: TABS_STORAGE_KEY,
activeTabKey: activeRequestId,
value: TAB_PARAMS,
});
tabsRef.current?.setActiveTab(TAB_PARAMS);
// Wait for request to update, then refresh the UI
// TODO: Somehow make this deterministic
@@ -368,8 +377,12 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
tabs={tabs}
tabListClassName="mt-1 -mb-1.5"
storageKey={TABS_STORAGE_KEY}
visibilityStorageKey={[TABS_STORAGE_KEY, "visibility", activeRequest.workspaceId]}
activeTabKey={activeRequestId}
>
<TabContent value={TAB_ASSERTIONS}>
<HttpAssertionsEditor key={activeRequest.id} request={activeRequest} />
</TabContent>
<TabContent value={TAB_AUTH}>
<HttpAuthenticationEditor model={activeRequest} />
</TabContent>
@@ -2,7 +2,7 @@ import type { HttpResponse, HttpResponseEvent } from "@yaakapp-internal/models";
import { Banner, HStack, Icon, LoadingIcon, VStack } from "@yaakapp-internal/ui";
import classNames from "classnames";
import type { ComponentType, CSSProperties } from "react";
import { lazy, Suspense, useMemo } from "react";
import { lazy, Suspense, useMemo, useRef } from "react";
import { useCancelHttpResponse } from "../hooks/useCancelHttpResponse";
import { useCopyHttpResponse } from "../hooks/useCopyHttpResponse";
import { useHttpResponseEvents } from "../hooks/useHttpResponseEvents";
@@ -23,11 +23,12 @@ import { HttpResponseDurationTag } from "./core/HttpResponseDurationTag";
import { HttpStatusTag } from "./core/HttpStatusTag";
import { PillButton } from "./core/PillButton";
import { SizeTag } from "./core/SizeTag";
import type { TabItem } from "./core/Tabs/Tabs";
import type { TabItem, TabsRef } from "./core/Tabs/Tabs";
import { TabContent, Tabs } from "./core/Tabs/Tabs";
import { Tooltip } from "./core/Tooltip";
import { EmptyStateText } from "./EmptyStateText";
import { ErrorBoundary } from "./ErrorBoundary";
import { HttpAssertionResults } from "./HttpAssertionResults";
import { HttpResponseTimeline } from "./HttpResponseTimeline";
import { RecentHttpResponsesDropdown } from "./RecentHttpResponsesDropdown";
import { RequestBodyViewer } from "./RequestBodyViewer";
@@ -56,6 +57,7 @@ const TAB_BODY = "body";
const TAB_REQUEST = "request";
const TAB_HEADERS = "headers";
const TAB_COOKIES = "cookies";
const TAB_ASSERTIONS = "assertions";
const TAB_TIMELINE = "timeline";
export type TimelineViewMode = "timeline" | "text";
@@ -67,6 +69,7 @@ interface RedirectDropWarning {
export function HttpResponsePane({ style, className, activeRequestId }: Props) {
const { activeResponse, setPinnedResponseId, responses } = usePinnedHttpResponse(activeRequestId);
const tabsRef = useRef<TabsRef>(null);
const [viewMode, setViewMode] = useResponseViewMode(activeResponse?.requestId);
const [timelineViewMode, setTimelineViewMode] = useTimelineViewMode();
const contentType = getContentTypeFromHeaders(activeResponse?.headers ?? null);
@@ -83,9 +86,53 @@ export function HttpResponsePane({ style, className, activeRequestId }: Props) {
const cookieCounts = useMemo(() => getCookieCounts(responseEvents.data), [responseEvents.data]);
const saveResponse = useSaveResponse(activeResponse ?? null);
const copyResponse = useCopyHttpResponse(activeResponse ?? null);
const assertionReport = activeResponse?.assertionResults;
// Native sends save the definition before evaluation. Wait for actual outcomes,
// and leave the tab hidden when every check was disabled.
const hasAssertionResults =
activeResponse?.state === "closed" &&
assertionReport != null &&
(assertionReport.error != null ||
assertionReport.results.some((result) => result.outcome !== "skipped"));
const failedAssertions =
assertionReport?.results.filter((result) => result.outcome === "failed").length ?? 0;
const assertionErrors =
assertionReport?.results.filter(
(result) => result.outcome === "error" || result.outcome === "invalid",
).length ?? 0;
const assertionFailures = failedAssertions + assertionErrors;
const assertionFailureLabel = [
failedAssertions > 0
? `${failedAssertions} assertion${failedAssertions === 1 ? "" : "s"} failed`
: null,
assertionErrors > 0
? `${assertionErrors} assertion error${assertionErrors === 1 ? "" : "s"}`
: assertionReport?.error != null
? "Assertion error"
: null,
]
.filter(Boolean)
.join(" · ");
const assertionPasses =
assertionReport?.results.filter((result) => result.outcome === "passed").length ?? 0;
const assertionsHaveErrors = assertionFailures > 0 || assertionReport?.error != null;
const tabs = useMemo<TabItem[]>(
() => [
...(hasAssertionResults
? [
{
value: TAB_ASSERTIONS,
label: "Assertions",
rightSlot: (
<CountBadge
count={assertionsHaveErrors ? assertionFailures || true : assertionPasses}
color={assertionsHaveErrors ? "danger" : "success"}
/>
),
},
]
: []),
{
value: TAB_BODY,
label: "Response",
@@ -162,6 +209,10 @@ export function HttpResponsePane({ style, className, activeRequestId }: Props) {
activeResponse?.requestHeaders.length,
activeResponse?.state,
activeResponse?.status,
hasAssertionResults,
assertionFailures,
assertionPasses,
assertionsHaveErrors,
cookieCounts.sent,
cookieCounts.received,
copyResponse.mutate,
@@ -210,6 +261,17 @@ export function HttpResponsePane({ style, className, activeRequestId }: Props) {
<HStack space={2} className="w-full shrink-0">
{activeResponse.state !== "closed" && <LoadingIcon size="sm" />}
<HttpStatusTag showReason response={activeResponse} />
{hasAssertionResults && assertionsHaveErrors && (
<PillButton
color="danger"
className="font-sans"
title="View assertion results"
leftSlot={<Icon icon="alert_triangle" size="xs" />}
onClick={() => tabsRef.current?.setActiveTab(TAB_ASSERTIONS)}
>
{assertionFailureLabel}
</PillButton>
)}
<span>&bull;</span>
<HttpResponseDurationTag response={activeResponse} />
<span>&bull;</span>
@@ -282,13 +344,18 @@ export function HttpResponsePane({ style, className, activeRequestId }: Props) {
)}
{/* Show tabs if we have any data (headers, body, etc.) even if there's an error */}
<Tabs
ref={tabsRef}
tabs={tabs}
defaultValue={TAB_BODY}
label="Response"
className="ml-3 mr-3 mb-3 min-h-0 flex-1"
tabListClassName="mt-0.5 -mb-1.5"
storageKey="http_response_tabs"
activeTabKey={activeRequestId}
>
<TabContent value={TAB_ASSERTIONS}>
<HttpAssertionResults response={activeResponse} />
</TabContent>
<TabContent value={TAB_BODY}>
<ErrorBoundary name="Http Response Viewer">
<Suspense>
@@ -0,0 +1,76 @@
import { autocompletion, startCompletion } from "@codemirror/autocomplete";
import { EditorView } from "@codemirror/view";
import { useQueryClient } from "@tanstack/react-query";
import type { HttpResponse } from "@yaakapp-internal/models";
import { useMemo, useRef, useState } from "react";
import { rpc } from "../lib/rpc";
import { Input } from "./core/Input";
import type { InputProps } from "./core/Input";
import { jsonPathCompletion } from "./core/Editor/json/pathCompletion";
import type { JsonPathChildren, LoadJsonPathChildren } from "./core/Editor/json/pathCompletion";
type Props = Pick<InputProps, "defaultValue" | "onChange" | "forceUpdateKey" | "stateKey"> & {
response: HttpResponse | null;
};
export function JsonPathInput({ response, ...props }: Props) {
const client = useQueryClient();
const [sampled, setSampled] = useState(false);
const responseKey = response?.state === "closed" ? `${response.id}:${response.updatedAt}` : null;
const currentResponseKey = useRef(responseKey);
currentResponseKey.current = responseKey;
const load = useRef<LoadJsonPathChildren>(async () => null);
load.current = async (parent) => {
if (!response || !responseKey) return null;
try {
const result = await client.fetchQuery({
queryKey: ["json_path_children", response.id, response.updatedAt, parent],
queryFn: () =>
rpc<JsonPathChildren>("cmd_http_response_json_children", {
responseId: response.id,
parent,
}),
staleTime: Infinity,
gcTime: 60_000,
retry: false,
});
if (responseKey !== currentResponseKey.current) return null;
setSampled(result.truncated);
return result;
} catch {
return null;
} // Non-JSON bodies and incomplete expressions still allow normal typing.
};
// The editor installs extraExtensions once. A ref keeps the response current without rebuilding
// the input and losing focus/selection when a new response arrives.
const extensions = useMemo(
() => [
autocompletion({ override: [jsonPathCompletion((parent) => load.current(parent))] }),
EditorView.domEventHandlers({
focus: (_event, view) => {
startCompletion(view);
},
}),
],
[],
);
return (
<div className="min-w-0">
<Input
{...props}
label="JSONPath"
size="sm"
placeholder="$.user.id"
language="text"
autocompleteFunctions={false}
autocompleteVariables={false}
extraExtensions={extensions}
/>
{sampled && (
<p className="text-xs text-text-subtle mt-1">
Suggestions are sampled. You can enter any path.
</p>
)}
</div>
);
}
@@ -0,0 +1,93 @@
import { CompletionContext } from "@codemirror/autocomplete";
import { EditorState } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { describe, expect, it, vi } from "vite-plus/test";
import { jsonPathCompletion, jsonPathCompletionTarget } from "./pathCompletion";
import type { JsonPathChildren } from "./pathCompletion";
const root: JsonPathChildren = {
children: [
{ label: "users", selector: ".users", kind: "array" },
{ label: "total", selector: ".total", kind: "number" },
{ label: "a.b", selector: '["a.b"]', kind: "text" },
{ label: "a,b", selector: '["a,b"]', kind: "text" },
],
truncated: false,
};
function context(text: string, explicit = false, pos = text.length) {
return new CompletionContext(EditorState.create({ doc: text }), pos, explicit);
}
describe("progressive JSONPath completion", () => {
it.each([
["", "$", ""],
["$", "$", ""],
["$.", "$", "."],
["us", "$", "us"],
["users.na", "$.users", ".na"],
["$.users[", "$.users", "["],
["$.users[0].na", "$.users[0]", ".na"],
["$.users[*].", "$.users[*]", "."],
['$["a.b"].', '$["a.b"]', "."],
['$["a.b', "$", '["a.b'],
["$['a.b", "$", "['a.b"],
['$["a,b', "$", '["a,b'],
['$.users[?(@.name == "a.b")].', '$.users[?(@.name == "a.b")]', "."],
])("finds the next level in %s", (text, parent, fragment) => {
expect(jsonPathCompletionTarget(text)).toEqual({ parent, fragment });
});
it("loads only the parent, filters the typed prefix, and inserts a complete escaped path", async () => {
const load = vi.fn(async () => root);
const complete = jsonPathCompletion(load);
const result = await complete(context("us"));
expect(load).toHaveBeenCalledExactlyOnceWith("$");
expect(result?.options.map((o) => o.label)).toEqual(["users"]);
const quoted = await complete(context('$["a.b'));
const option = quoted!.options[0]!;
const dispatch = vi.fn();
expect(option.label).toBe("a.b");
if (typeof option.apply !== "function") throw new Error("Expected a completion function");
option.apply({ dispatch } as unknown as EditorView, option, 0, 6);
expect(dispatch.mock.calls[0]?.[0].changes).toEqual({ from: 0, to: 6, insert: '$["a.b"]' });
expect((await complete(context("$['a.b")))?.options.map((o) => o.label)).toEqual(["a.b"]);
});
it("explores a completed container without turning the path into an invalid draft", async () => {
const array: JsonPathChildren = {
children: [
{ label: "[*]", selector: "[*]", kind: "all items" },
{ label: "[0]", selector: "[0]", kind: "object" },
],
truncated: false,
};
const load = vi.fn(async (parent: string) => (parent === "$.users" ? array : root));
const result = await jsonPathCompletion(load)(context("$.users", true));
expect(load).toHaveBeenCalledExactlyOnceWith("$.users");
expect(result?.options.map((o) => o.label)).toEqual(["[*]", "[0]"]);
expect(
(await jsonPathCompletion(load)(context("$.users[0")))?.options.map((o) => o.label),
).toEqual(["[0]"]);
});
it("does not suggest descendants at the root or duplicate the current scalar path", async () => {
const load = vi.fn(async (parent: string) =>
parent === "$" ? root : { children: [], truncated: false },
);
const result = await jsonPathCompletion(load)(context(""));
expect(result?.options.map((o) => o.label)).toEqual(["users", "total", "a.b", "a,b"]);
expect(await jsonPathCompletion(load)(context("$.total", true))).toBeNull();
});
it("leaves complex expressions, mid-path editing, unavailable data, and stale results alone", async () => {
const load = vi.fn(async () => root);
expect(await jsonPathCompletion(load)(context("$.users[?(@.na"))).toBeNull();
expect(await jsonPathCompletion(load)(context("$..na"))).toBeNull();
expect(await jsonPathCompletion(load)(context("$.users[0].name", false, 5))).toBeNull();
expect(load).not.toHaveBeenCalled();
expect(await jsonPathCompletion(async () => null)(context("$"))).toBeNull();
const stale = context("$.");
Object.defineProperty(stale, "aborted", { get: () => true });
expect(await jsonPathCompletion(load)(stale)).toBeNull();
});
});
@@ -0,0 +1,119 @@
import type { CompletionContext, CompletionResult } from "@codemirror/autocomplete";
import { startCompletion } from "@codemirror/autocomplete";
import type { RpcSchema } from "@yaakapp-internal/rpc-schema";
export type JsonPathChildren = RpcSchema["cmd_http_response_json_children"][1];
export type LoadJsonPathChildren = (parent: string) => Promise<JsonPathChildren | null>;
export function normalizeJsonPath(value: string): string {
const text = value.trim();
if (!text) return "$";
return text.startsWith("$") ? text : text.startsWith("[") ? `$${text}` : `$.${text}`;
}
/** Locate the unfinished child accessor, leaving complete JSONPath expressions to Rust. */
export function jsonPathCompletionTarget(
text: string,
): { parent: string; fragment: string } | null {
text = text.trim();
if (text.length > 1024) return null;
if (!text || text === "$") return { parent: "$", fragment: "" };
let quote = "";
let escaped = false;
let depth = 0;
let boundary = -1;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (quote) {
if (escaped) escaped = false;
else if (c === "\\") escaped = true;
else if (c === quote) quote = "";
continue;
}
if (depth > 0 && (c === '"' || c === "'")) quote = c;
else if (c === "[") {
if (depth === 0) boundary = i;
depth++;
} else if (c === "]") {
if (--depth < 0) return null;
} else if (depth === 0 && c === ".") boundary = i;
}
if (depth === 0 && text.endsWith("]")) return { parent: normalizeJsonPath(text), fragment: "" };
if (boundary === -1) return text.startsWith("$") ? null : { parent: "$", fragment: text };
const fragment = text.slice(boundary);
// Don't try to complete inside filters, unions, or recursive descent.
if (
depth > 1 ||
fragment.startsWith("[?") ||
fragment.startsWith("[(") ||
text[boundary - 1] === "." ||
fragment.startsWith("[...") ||
(fragment.includes(",") && !fragment.startsWith('["') && !fragment.startsWith("['"))
)
return null;
return { parent: normalizeJsonPath(text.slice(0, boundary)), fragment };
}
function matches(child: JsonPathChildren["children"][number], fragment: string): boolean {
if (!fragment) return true;
if (!fragment.startsWith("[")) return child.label.startsWith(fragment.replace(/^\./, ""));
if (child.selector.startsWith("[") && !child.selector.startsWith('["'))
return child.selector.startsWith(fragment);
const quoted = JSON.stringify(child.label);
const accessor = fragment.startsWith("['")
? `['${quoted.slice(1, -1).replace(/\\"/g, '"').replace(/'/g, "\\'")}']`
: `[${quoted}]`;
return accessor.startsWith(fragment);
}
/** Complete a path progressively. Discovery is cached by response + parent in the caller. */
export function jsonPathCompletion(load: LoadJsonPathChildren) {
return async (context: CompletionContext): Promise<CompletionResult | null> => {
// Never replace later path segments while the user edits the middle of an expression.
if (context.pos !== context.state.doc.length) return null;
context.addEventListener("abort", () => {}, { onDocChange: true });
const text = context.state.doc.toString();
let target = jsonPathCompletionTarget(text);
if (!target) return null;
let children: JsonPathChildren | null = null;
if (context.explicit && text.trim()) {
// Accepting a container or explicitly opening completion explores its children, without
// inserting an unfinished dot/bracket (the container itself may be the assertion target).
const parent = normalizeJsonPath(text);
children = await load(parent);
if (context.aborted) return null;
if (children?.children.length) target = { parent, fragment: "" };
else children = null;
}
children ??= await load(target.parent);
if (context.aborted || !children) return null;
const parent = target.parent;
const options = children.children
.filter((child) => matches(child, target.fragment))
.filter((child) => `${parent}${child.selector}` !== normalizeJsonPath(text))
.map((child) => {
const path = `${parent}${child.selector}`;
return {
label: child.label,
displayLabel: child.selector.startsWith('["') ? child.selector : child.label,
detail: child.kind,
type: child.selector.startsWith("[") ? "variable" : "property",
apply(
view: Parameters<typeof startCompletion>[0],
_completion: unknown,
from: number,
to: number,
) {
view.dispatch({
changes: { from, to, insert: path },
selection: { anchor: from + path.length },
userEvent: "input.complete",
});
if (["object", "array", "all items", "mixed"].includes(child.kind))
startCompletion(view);
},
};
});
return options.length ? { from: 0, to: context.pos, options, filter: false } : null;
};
}
+300 -67
View File
@@ -10,7 +10,7 @@ import {
useSensors,
} from "@dnd-kit/core";
import classNames from "classnames";
import type { ReactNode, Ref } from "react";
import type { CSSProperties, ReactNode, Ref } from "react";
import {
forwardRef,
memo,
@@ -27,11 +27,19 @@ import { fireAndForget } from "../../../lib/fireAndForget";
import { ErrorBoundary } from "../../ErrorBoundary";
import type { ButtonProps } from "../Button";
import { Button } from "../Button";
import { Dropdown } from "../Dropdown";
import { IconButton } from "../IconButton";
import { Icon } from "@yaakapp-internal/ui";
import type { RadioDropdownProps } from "../RadioDropdown";
import { RadioDropdown } from "../RadioDropdown";
import { useFittingTabs } from "./useFittingTabs";
import { MIN_TAB_GAP_SCALE, MIN_TAB_PADDING_SCALE } from "./fitTabs";
export type TabItem =
export type TabItem = {
/** Stable label for the visibility menu, including tabs with dropdown labels. */
menuLabel?: string;
hiddenByDefault?: boolean;
} & (
| {
value: string;
label: string;
@@ -44,7 +52,8 @@ export type TabItem =
options: Omit<RadioDropdownProps, "children">;
leftSlot?: ReactNode;
rightSlot?: ReactNode;
};
}
);
interface TabsStorage {
order: string[];
@@ -72,6 +81,8 @@ interface Props {
storageKey?: string | string[];
/** Key to identify which context this tab belongs to (e.g., request ID). Used for per-context active tab persistence. */
activeTabKey?: string;
/** Enables show/hide controls, scoped independently of tab order and selection. */
visibilityStorageKey?: string | string[];
}
export const Tabs = forwardRef<TabsRef, Props>(function Tabs(
@@ -87,6 +98,7 @@ export const Tabs = forwardRef<TabsRef, Props>(function Tabs(
layout = "vertical",
storageKey,
activeTabKey,
visibilityStorageKey,
}: Props,
forwardedRef: Ref<TabsRef>,
) {
@@ -108,10 +120,33 @@ export const Tabs = forwardRef<TabsRef, Props>(function Tabs(
const savedOrder = storage.order;
const visibilityKey = visibilityStorageKey ?? ["tabs", "default_visibility"];
const { value: visibility, set: setVisibility } = useKeyValue<Record<string, boolean>>({
namespace: "no_sync",
key: visibilityKey,
fallback: {},
});
const { value: wrapPreference, set: setWrapPreference } = useKeyValue<boolean>({
namespace: "no_sync",
key: [...(Array.isArray(visibilityKey) ? visibilityKey : [visibilityKey]), "wrap"],
fallback: false,
});
const isVisible = useCallback(
(tab: TabItem) =>
!("hidden" in tab && tab.hidden) &&
(!visibilityStorageKey || (visibility?.[tab.value] ?? !tab.hiddenByDefault)),
[visibility, visibilityStorageKey],
);
// Get the active tab value - prefer storage (if activeTabKey), then defaultValue, then first tab
const storedActiveTab = activeTabKey ? storage?.activeTabs?.[activeTabKey] : undefined;
const [internalValue, setInternalValue] = useState<string | undefined>(undefined);
const value = storedActiveTab ?? internalValue ?? defaultValue ?? originalTabs[0]?.value;
const requestedValue = storedActiveTab ?? internalValue ?? defaultValue ?? originalTabs[0]?.value;
// Dynamic tabs can disappear when switching responses or other contexts.
// Keep the saved preference, but display an available tab until it returns.
const value = originalTabs.some((t) => t.value === requestedValue && isVisible(t))
? requestedValue
: originalTabs.find(isVisible)?.value;
// Helper to normalize storage (handle migration from old format)
const normalizeStorage = useCallback(
@@ -123,6 +158,9 @@ export const Tabs = forwardRef<TabsRef, Props>(function Tabs(
// Handle tab change - update internal state, storage if we have a key, and call prop callback
const onChangeValue = useCallback(
async (newValue: string) => {
if (visibilityStorageKey) {
await setVisibility((s) => ({ ...s, [newValue]: true }));
}
setInternalValue(newValue);
if (storageKey && activeTabKey) {
await setStorage((s) => {
@@ -135,7 +173,15 @@ export const Tabs = forwardRef<TabsRef, Props>(function Tabs(
}
onChangeValueProp?.(newValue);
},
[storageKey, activeTabKey, setStorage, onChangeValueProp, normalizeStorage],
[
storageKey,
activeTabKey,
setStorage,
onChangeValueProp,
normalizeStorage,
visibilityStorageKey,
setVisibility,
],
);
// Expose imperative methods via ref
@@ -199,6 +245,18 @@ export const Tabs = forwardRef<TabsRef, Props>(function Tabs(
}, [originalTabs, savedOrder, storageKey]);
const tabs = storageKey ? orderedTabs : originalTabs;
const responsive = !!visibilityStorageKey && layout === "vertical";
const wrapTabs = responsive && !!wrapPreference;
const { viewportRef, measurementsRef, fittedTabs } = useFittingTabs(
responsive && !wrapTabs,
value,
);
const fitsInStrip = useCallback(
(tab: TabItem) =>
isVisible(tab) && (fittedTabs == null || fittedTabs.some((t) => t.value === tab.value)),
[isVisible, fittedTabs],
);
const overflowTabs = tabs.filter((tab) => isVisible(tab) && !fitsInStrip(tab));
// Update tabs when value changes
useEffect(() => {
@@ -290,69 +348,168 @@ export const Tabs = forwardRef<TabsRef, Props>(function Tabs(
const tabButtons = useMemo(() => {
const items: ReactNode[] = [];
tabs.forEach((t, i) => {
if ("hidden" in t && t.hidden) {
if (!fitsInStrip(t)) {
return;
}
const isActive = t.value === value;
const showDropMarkerBefore = hoveredIndex === i;
if (showDropMarkerBefore) {
items.push(
<div
key={`marker-${t.value}`}
className={classNames("relative", layout === "vertical" ? "w-0" : "h-0")}
>
<DropMarker orientation={layout === "vertical" ? "vertical" : "horizontal"} />
</div>,
);
}
const next = tabs[i + 1];
const fitted = fittedTabs?.find((tab) => tab.value === t.value);
items.push(
<TabButton
key={t.value}
tab={t}
isActive={isActive}
isActive={t.value === value}
addBorders={addBorders}
layout={layout}
reorderable={reorderable}
isDragging={isDragging?.value === t.value}
onChangeValue={onChangeValue}
width={fitted?.width}
spacingCompression={fitted?.spacingCompression}
wrap={wrapTabs}
dropBefore={hoveredIndex === i}
// A drop after the last fitted tab still inserts into the full saved order.
dropAfter={hoveredIndex === i + 1 && (!next || !fitsInStrip(next))}
/>,
);
});
return items;
}, [tabs, value, addBorders, layout, reorderable, isDragging, onChangeValue, hoveredIndex]);
}, [
tabs,
value,
addBorders,
layout,
reorderable,
isDragging,
onChangeValue,
hoveredIndex,
fitsInStrip,
fittedTabs,
wrapTabs,
]);
const tabList = (
const tabStrip = (
<div
ref={viewportRef}
role="tablist"
aria-label={label}
className={classNames(
tabListClassName,
!visibilityStorageKey && tabListClassName,
addBorders && layout === "horizontal" && "pl-3 -ml-1",
addBorders && layout === "vertical" && "ml-0 mb-2",
"flex items-center hide-scrollbars",
layout === "horizontal" && "h-full overflow-auto p-2",
layout === "vertical" && "overflow-x-auto overflow-y-visible ",
layout === "vertical" &&
(responsive ? "relative overflow-hidden py-1" : "overflow-x-auto overflow-y-visible"),
// Give space for button focus states within overflow boundary.
!addBorders && layout === "vertical" && "py-1 pl-3 -ml-5 pr-1",
!responsive && !addBorders && layout === "vertical" && "py-1 pl-3 -ml-5 pr-1",
)}
>
<div
className={classNames(
layout === "horizontal" && "flex flex-col w-full pb-3 mb-auto",
layout === "vertical" && "flex flex-row shrink-0 w-full",
wrapTabs && "flex-wrap gap-y-1",
)}
>
{tabButtons}
{hoveredIndex === tabs.length && (
<div className={classNames("relative", layout === "vertical" ? "w-0" : "h-0")}>
<DropMarker orientation={layout === "vertical" ? "vertical" : "horizontal"} />
</div>
</div>
{responsive && !wrapTabs && (
<div
ref={measurementsRef}
aria-hidden
inert
className="absolute invisible pointer-events-none flex w-max"
>
{tabs.filter(isVisible).map((tab) => (
<div key={tab.value} data-measure-tab={tab.value} className="flex shrink-0">
<TabButton
tab={tab}
isActive={tab.value === value}
addBorders={addBorders}
layout={layout}
reorderable={false}
isDragging={false}
/>
</div>
))}
</div>
)}
</div>
);
// Keep the menu outside the scroll viewport so tabs cannot paint behind or past it.
const tabList = visibilityStorageKey ? (
<div
className={classNames(
tabListClassName,
"flex shrink-0 min-w-0 min-h-0",
layout === "vertical" ? "items-start" : "flex-col",
)}
>
<div className="min-w-0 min-h-0 flex-1">{tabStrip}</div>
<div
className={classNames(
"shrink-0 pl-1",
layout === "vertical" && "flex items-center h-md my-1",
)}
>
<Dropdown
items={[
...(overflowTabs.length > 0
? [
{ type: "separator" as const, label: "More tabs" },
...overflowTabs.map((tab) => ({
label: tab.menuLabel ?? ("label" in tab ? tab.label : tab.value),
icon: tab.value === value ? ("check" as const) : ("empty" as const),
rightSlot: tab.rightSlot,
onSelect: () => onChangeValue(tab.value),
})),
{ type: "separator" as const },
]
: []),
{
label: "Show tabs",
submenu: [
{ type: "separator", label: "In this workspace" },
...tabs
.filter((t) => !("hidden" in t && t.hidden))
.map((tab) => ({
label: tab.menuLabel ?? ("label" in tab ? tab.label : tab.value),
icon: isVisible(tab)
? ("check_square_checked" as const)
: ("check_square_unchecked" as const),
disabled: isVisible(tab) && tabs.filter(isVisible).length <= 1,
keepOpenOnSelect: true,
onSelect: async () => {
if (!isVisible(tab)) {
await onChangeValue(tab.value);
} else {
if (tab.value === value) {
const next = tabs.find((t) => t.value !== tab.value && isVisible(t));
if (next) await onChangeValue(next.value);
}
await setVisibility((s) => ({ ...s, [tab.value]: false }));
}
},
})),
],
},
{
label: "Wrap tabs",
hidden: layout !== "vertical",
icon: wrapTabs ? "check_square_checked" : "check_square_unchecked",
keepOpenOnSelect: true,
onSelect: () => setWrapPreference((wrap) => !wrap),
},
]}
>
<IconButton icon="ellipsis" title="More tabs and visibility" size="sm" />
</Dropdown>
</div>
</div>
) : (
tabStrip
);
return (
@@ -361,9 +518,13 @@ export const Tabs = forwardRef<TabsRef, Props>(function Tabs(
className={classNames(
className,
"tabs-container",
"h-full grid",
"h-full",
// Size wrapped rows at the resolved pane width instead of using an intrinsic grid track.
responsive
? "flex flex-col min-h-0 [&>.tab-content]:flex-1 [&>.tab-content]:min-h-0"
: "grid",
layout === "horizontal" && "grid-rows-1 grid-cols-[auto_minmax(0,1fr)]",
layout === "vertical" && "grid-rows-[auto_minmax(0,1fr)] grid-cols-1",
!responsive && layout === "vertical" && "grid-rows-[auto_minmax(0,1fr)] grid-cols-1",
)}
>
{reorderable ? (
@@ -409,6 +570,11 @@ interface TabButtonProps {
isDragging: boolean;
onChangeValue?: (value: string) => void;
overlay?: boolean;
width?: number;
spacingCompression?: number;
wrap?: boolean;
dropBefore?: boolean;
dropAfter?: boolean;
}
function TabButton({
@@ -420,35 +586,26 @@ function TabButton({
isDragging,
onChangeValue,
overlay = false,
width,
spacingCompression = 0,
wrap = false,
dropBefore = false,
dropAfter = false,
}: TabButtonProps) {
const {
attributes,
listeners,
setNodeRef: setDraggableRef,
} = useDraggable({
id: tab.value,
disabled: !reorderable,
// The button inside handles focus
attributes: { tabIndex: -1 },
});
const { setNodeRef: setDroppableRef } = useDroppable({
id: tab.value,
disabled: !reorderable,
});
const handleSetWrapperRef = useCallback(
(n: HTMLDivElement | null) => {
if (reorderable) {
setDraggableRef(n);
setDroppableRef(n);
}
},
[reorderable, setDraggableRef, setDroppableRef],
);
const constrained = width !== undefined;
const btnProps: Partial<ButtonProps> = {
color: "custom",
justify: layout === "horizontal" ? "start" : "center",
innerClassName: classNames(
"tab-button-label",
constrained && "w-auto! shrink-0 overflow-visible! text-clip!",
wrap && "whitespace-normal! overflow-visible! text-clip! [overflow-wrap:anywhere]",
),
style: constrained
? {
paddingInline: `calc(var(--spacing) * ${2 * (1 - spacingCompression * (1 - MIN_TAB_PADDING_SCALE))})`,
}
: undefined,
onClick: isActive
? undefined
: (e: React.MouseEvent) => {
@@ -457,7 +614,8 @@ function TabButton({
},
className: classNames(
"flex items-center rounded-sm whitespace-nowrap",
"px-2! ml-px",
"ml-px",
!constrained && "px-2!",
"outline-hidden",
"ring-none",
"focus-visible-or-class:outline-2",
@@ -471,6 +629,9 @@ function TabButton({
layout === "horizontal" && "min-w-40",
isDragging && "opacity-50",
overlay && "opacity-80",
constrained && "w-[calc(100%_-_1px)]",
wrap && "max-w-[calc(100%_-_1px)]! h-auto! min-h-md",
(constrained || wrap) && "[&>div:not(.tab-button-label)]:shrink-0",
),
};
@@ -487,6 +648,9 @@ function TabButton({
onChange={tab.options.onChange}
>
<Button
title={
(constrained || wrap) && typeof option?.label === "string" ? option.label : undefined
}
leftSlot={tab.leftSlot}
rightSlot={
<div className="flex items-center">
@@ -511,22 +675,91 @@ function TabButton({
);
}
return (
<Button leftSlot={tab.leftSlot} rightSlot={tab.rightSlot} {...btnProps}>
<Button
title={(constrained || wrap) && "label" in tab ? tab.label : undefined}
leftSlot={tab.leftSlot}
rightSlot={tab.rightSlot}
{...btnProps}
>
{"label" in tab && tab.label ? tab.label : tab.value}
</Button>
);
})();
// Apply drag handlers to wrapper, not button
const wrapperProps = reorderable && !overlay ? { ...attributes, ...listeners } : {};
const wrapperClassName = classNames(
"relative shrink-0",
layout === "vertical" && (constrained ? "min-w-0" : "mr-2"),
wrap && "min-w-0 max-w-[calc(100%_-_0.5rem)]",
);
const wrapperStyle: CSSProperties = {
width,
paddingRight: constrained
? `calc(var(--spacing) * ${2 * (1 - spacingCompression * (1 - MIN_TAB_GAP_SCALE))})`
: undefined,
};
// Anchor markers to their tabs so they follow the tab when it wraps onto another row.
const content = (
<>
{dropBefore && (
<DropMarker
key="before"
orientation={layout === "vertical" ? "vertical" : "horizontal"}
className={layout === "vertical" ? "left-0" : "top-0"}
/>
)}
{buttonContent}
{dropAfter && (
<DropMarker
key="after"
orientation={layout === "vertical" ? "vertical" : "horizontal"}
className={layout === "vertical" ? "right-0" : "bottom-0"}
/>
)}
</>
);
return reorderable && !overlay ? (
<DraggableTab value={tab.value} className={wrapperClassName} style={wrapperStyle}>
{content}
</DraggableTab>
) : (
<div className={wrapperClassName} style={wrapperStyle}>
{content}
</div>
);
}
// Measurement copies and drag overlays must not register duplicate draggable IDs.
function DraggableTab({
value,
className,
style,
children,
}: {
value: string;
className: string;
style?: CSSProperties;
children: ReactNode;
}) {
const {
attributes,
listeners,
setNodeRef: setDraggableRef,
} = useDraggable({
id: value,
attributes: { tabIndex: -1 },
});
const { setNodeRef: setDroppableRef } = useDroppable({ id: value });
const setRef = useCallback(
(node: HTMLDivElement | null) => {
setDraggableRef(node);
setDroppableRef(node);
},
[setDraggableRef, setDroppableRef],
);
return (
<div
ref={handleSetWrapperRef}
className={classNames("relative", layout === "vertical" && "mr-2")}
{...wrapperProps}
>
{buttonContent}
<div ref={setRef} className={className} style={style} {...attributes} {...listeners}>
{children}
</div>
);
}
@@ -0,0 +1,113 @@
import { describe, expect, test } from "vite-plus/test";
import { fitTabs } from "./fitTabs";
const tabs = [
{ value: "body", width: 80, compactWidth: 66 },
{ value: "headers", width: 100, compactWidth: 86 },
{ value: "info", width: 60, compactWidth: 46 },
{ value: "assertions", width: 120, compactWidth: 106 },
];
describe("responsive request tabs", () => {
test("restores the saved order when the pane has room for every tab", () => {
expect(fitTabs(tabs, 500, "assertions")).toEqual(
tabs.map(({ value, width }) => ({ value, width, spacingCompression: 0 })),
);
});
test("tightens gaps and padding without taking any space from labels", () => {
expect(fitTabs(tabs, 332, "assertions")).toEqual([
{ value: "body", width: 73, spacingCompression: 0.5 },
{ value: "headers", width: 93, spacingCompression: 0.5 },
{ value: "info", width: 53, spacingCompression: 0.5 },
{ value: "assertions", width: 113, spacingCompression: 0.5 },
]);
expect(fitTabs(tabs, 304, "assertions")).toEqual(
tabs.map(({ value, compactWidth }) => ({
value,
width: compactWidth,
spacingCompression: 1,
})),
);
});
test("moves whole tabs into overflow when compact spacing is not enough", () => {
expect(fitTabs(tabs, 258, "assertions")).toEqual([
{ value: "body", width: 66, spacingCompression: 1 },
{ value: "headers", width: 86, spacingCompression: 1 },
{ value: "assertions", width: 106, spacingCompression: 1 },
]);
expect(fitTabs(tabs, 257, "assertions").map((tab) => tab.value)).toEqual([
"body",
"assertions",
]);
});
test("keeps an active tab from the end visible without reordering it", () => {
expect(fitTabs(tabs, 172, "assertions")).toEqual([
{ value: "body", width: 66, spacingCompression: 1 },
{ value: "assertions", width: 106, spacingCompression: 1 },
]);
expect(fitTabs(tabs, 170, "headers").map((tab) => tab.value)).toEqual(["body", "headers"]);
});
test("puts even the active tab into overflow if it cannot fit on its own", () => {
expect(fitTabs(tabs, 40, "assertions")).toEqual([]);
expect(fitTabs(tabs, 0, "assertions")).toEqual([]);
expect(fitTabs(tabs, 90, "assertions")).toEqual([
{ value: "body", width: 80, spacingCompression: 0 },
]);
});
test("recalculates after a dropdown label or badge changes width", () => {
const longLabel = [{ value: "body", width: 200, compactWidth: 186 }, ...tabs.slice(1)];
const result = fitTabs(longLabel, 300, "body");
expect(result.map((tab) => tab.value)).toEqual(["body", "headers"]);
expect(result.reduce((sum, tab) => sum + tab.width, 0)).toBeCloseTo(300);
const largeBadge = [{ value: "body", width: 240, compactWidth: 226 }, ...tabs.slice(1)];
expect(fitTabs(largeBadge, 280, "body").map((tab) => tab.value)).toEqual(["body"]);
});
test("does not skip a long tab to squeeze later tabs into the leading group", () => {
expect(fitTabs(tabs, 200, "assertions").map((tab) => tab.value)).toEqual([
"body",
"assertions",
]);
expect(fitTabs(tabs, 160).map((tab) => tab.value)).toEqual(["body", "headers"]);
});
test("handles tabs with no spacing to compress", () => {
const shortTabs = tabs.filter((tab) => tab.value === "body" || tab.value === "info");
expect(fitTabs(shortTabs, 126, "body")).toEqual([
{ value: "body", width: 73, spacingCompression: 0.5 },
{ value: "info", width: 53, spacingCompression: 0.5 },
]);
const fixedTabs = shortTabs.map((tab) => ({ ...tab, compactWidth: tab.width }));
expect(fitTabs(fixedTabs, 126, "body")).toEqual([
{ value: "body", width: 80, spacingCompression: 0 },
]);
expect(fitTabs(fixedTabs, 40, "body")).toEqual([]);
});
test("stays within the pane and each label's bounds throughout resizing", () => {
for (let width = 0; width <= 500; width++) {
for (const active of tabs) {
const result = fitTabs(tabs, width, active.value);
expect(result.some((tab) => tab.value === active.value)).toBe(width >= active.compactWidth);
expect(result.reduce((sum, tab) => sum + tab.width, 0)).toBeLessThanOrEqual(width + 0.001);
for (const tab of result) {
const original = tabs.find((t) => t.value === tab.value)!;
expect(tab.width).toBeGreaterThanOrEqual(original.compactWidth);
expect(tab.width).toBeLessThanOrEqual(original.width);
expect(tab.spacingCompression).toBeGreaterThanOrEqual(0);
expect(tab.spacingCompression).toBeLessThanOrEqual(1);
// All removed width must come from spacing, at every pane size.
expect(original.width - tab.width).toBeCloseTo(
tab.spacingCompression * (original.width - original.compactWidth),
);
}
}
}
});
});
@@ -0,0 +1,38 @@
export const MIN_TAB_PADDING_SCALE = 0.5;
export const MIN_TAB_GAP_SCALE = 0.25;
export interface TabWidth {
value: string;
width: number;
/** Full label and badges, with the smallest padding and gap. */
compactWidth: number;
}
/** Tighten spacing to fit whole tabs, keeping every visible label intact. */
export function fitTabs(
tabs: TabWidth[],
availableWidth: number,
activeValue?: string,
): { value: string; width: number; spacingCompression: number }[] {
const available = Math.max(0, availableWidth);
// Even the active tab goes into overflow if it cannot fit on its own.
const active = tabs.find((tab) => tab.value === activeValue && tab.compactWidth <= available);
let remaining = available - (active?.compactWidth ?? 0);
const fitted = new Set(active ? [active.value] : []);
for (const tab of tabs) {
if (tab === active) continue;
if (tab.compactWidth > remaining) break;
fitted.add(tab.value);
remaining -= tab.compactWidth;
}
const visible = tabs.filter((tab) => fitted.has(tab.value));
const naturalWidth = visible.reduce((sum, tab) => sum + tab.width, 0);
const deficit = Math.max(0, naturalWidth - available);
const spareSpacing = visible.reduce((sum, tab) => sum + tab.width - tab.compactWidth, 0);
const spacingCompression = spareSpacing > 0 ? Math.min(1, deficit / spareSpacing) : 0;
return visible.map((tab) => ({
value: tab.value,
spacingCompression,
width: tab.width - spacingCompression * (tab.width - tab.compactWidth),
}));
}
@@ -0,0 +1,55 @@
import { useLayoutEffect, useRef, useState } from "react";
import { fitTabs, MIN_TAB_GAP_SCALE, MIN_TAB_PADDING_SCALE } from "./fitTabs";
export function useFittingTabs(enabled: boolean, activeValue?: string) {
const viewportRef = useRef<HTMLDivElement>(null);
const measurementsRef = useRef<HTMLDivElement>(null);
const [fittedTabs, setFittedTabs] = useState<ReturnType<typeof fitTabs> | null>(null);
// Reobserve after render: tab labels, badges and available tabs can all change.
useLayoutEffect(() => {
const viewport = viewportRef.current;
const measurements = measurementsRef.current;
if (!enabled || !viewport || !measurements) return;
const measure = () => {
const widths = Array.from(measurements.children, (child) => {
const width = child.getBoundingClientRect().width;
const button = child.querySelector("button");
const buttonStyle = button ? getComputedStyle(button) : null;
const padding = buttonStyle
? Number.parseFloat(buttonStyle.paddingLeft) + Number.parseFloat(buttonStyle.paddingRight)
: 0;
const gap = child.firstElementChild
? Number.parseFloat(getComputedStyle(child.firstElementChild).marginRight)
: 0;
const compactWidth =
width - padding * (1 - MIN_TAB_PADDING_SCALE) - gap * (1 - MIN_TAB_GAP_SCALE);
return {
value: child.getAttribute("data-measure-tab") ?? "",
width,
compactWidth,
};
});
const next = fitTabs(widths, viewport.clientWidth, activeValue);
setFittedTabs((previous) =>
previous?.length === next.length &&
previous.every(
(tab, i) =>
tab.value === next[i]?.value &&
tab.width === next[i]?.width &&
tab.spacingCompression === next[i]?.spacingCompression,
)
? previous
: next,
);
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(viewport);
for (const child of measurements.children) observer.observe(child);
return () => observer.disconnect();
});
return { viewportRef, measurementsRef, fittedTabs: enabled ? fittedTabs : null };
}