mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-21 16:01:46 +01:00
Merge remote-tracking branch 'origin/main' into stetta/tk_mwaxu5pizxqxbmzj
# Conflicts: # apps/yaak-proxy/components/FlowCard.tsx
This commit is contained in:
commit
a4355b956a
36 files changed
+1875
-218
No files matched your search
@@ -0,0 +1,46 @@
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
/** For the positioned element an `ActionsBar` sits in: hovering it brings the bar's actions in */
|
||||
export const ACTIONS_BAR_CONTAINER = "relative group/actions";
|
||||
|
||||
/** Set on an action's outermost element to keep it in view, as a control that shows state does */
|
||||
export const PINNED_ACTION = { "data-pinned": true } as const;
|
||||
|
||||
/**
|
||||
* Where every bar sits in its container, the same for every viewer: flush with the content's
|
||||
* right edge, which a text viewer's scrollbar sits just past, and lifted off the bottom edge
|
||||
* above its horizontal scrollbar. Not overridable, so bars line up from pane to pane.
|
||||
*/
|
||||
const ACTIONS_BAR_INSET = "bottom-2 right-0 left-0";
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* A row of actions over the bottom-right corner of the content in an `ACTIONS_BAR_CONTAINER`:
|
||||
* small bordered buttons on the surface colour, so they read over text, each held to the height
|
||||
* and radius of an `sm` icon button and centred on the row. Each fades in while the
|
||||
* container is hovered or the action has focus, unless it carries `PINNED_ACTION`. The row lets
|
||||
* clicks through to the content between its actions. Place the container over the whole tab
|
||||
* content, not a viewer's inner box, so the bar's inset is the pane's.
|
||||
*/
|
||||
export function ActionsBar({ children }: Props) {
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
"absolute z-10 flex items-center justify-end gap-1",
|
||||
ACTIONS_BAR_INSET,
|
||||
"pointer-events-none",
|
||||
"*:pointer-events-auto *:bg-surface *:shadow *:transition-opacity *:transform-gpu",
|
||||
// Every action as tall and as round as a small icon button, so they line up
|
||||
"*:h-sm *:rounded-md",
|
||||
"[&>:not([data-pinned])]:opacity-0",
|
||||
"group-hover/actions:*:opacity-100! *:focus-within:opacity-100! *:hover:opacity-100!",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, test, vi } from "vite-plus/test";
|
||||
import { FormatAction, type FormattableEditor, formatEditor } from "./FormatAction";
|
||||
|
||||
/** An editor as far as formatting reaches into one, recording its changes and blurs */
|
||||
function fakeEditor(text: string) {
|
||||
const changes: string[] = [];
|
||||
const blur = vi.fn();
|
||||
let state = EditorState.create({ doc: text });
|
||||
const editor: FormattableEditor & { changes: string[]; blur: typeof blur } = {
|
||||
get state() {
|
||||
return state;
|
||||
},
|
||||
dispatch: ((spec: { changes: { from: number; to: number; insert: string } }) => {
|
||||
state = state.update(spec).state;
|
||||
changes.push(state.doc.toString());
|
||||
}) as FormattableEditor["dispatch"],
|
||||
contentDOM: { blur } as unknown as HTMLElement,
|
||||
changes,
|
||||
blur,
|
||||
};
|
||||
return editor;
|
||||
}
|
||||
|
||||
describe("formatEditor", () => {
|
||||
test("replaces the document with its formatted version and blurs", async () => {
|
||||
const editor = fakeEditor('{"a":1}');
|
||||
await formatEditor(editor, async (t) => JSON.stringify(JSON.parse(t), null, 2));
|
||||
expect(editor.state.doc.toString()).toBe('{\n "a": 1\n}');
|
||||
expect(editor.changes).toHaveLength(1);
|
||||
expect(editor.blur).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("leaves a document that is already formatted alone", async () => {
|
||||
const editor = fakeEditor("same");
|
||||
await formatEditor(editor, async (t) => t);
|
||||
expect(editor.changes).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("drops a result for text that changed while it was formatting", async () => {
|
||||
const editor = fakeEditor("before");
|
||||
await formatEditor(editor, async () => {
|
||||
editor.dispatch({ changes: { from: 0, to: 6, insert: "typed" } });
|
||||
return "formatted";
|
||||
});
|
||||
expect(editor.state.doc.toString()).toBe("typed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("FormatAction", () => {
|
||||
test("is offered for an editable editor only", () => {
|
||||
const editor = { current: null };
|
||||
const format = async (t: string) => t;
|
||||
expect(renderToStaticMarkup(<FormatAction editor={editor} format={format} />)).toContain(
|
||||
"Reformat contents",
|
||||
);
|
||||
expect(renderToStaticMarkup(<FormatAction editor={editor} format={format} readOnly />)).toBe(
|
||||
"",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import type { RefObject } from "react";
|
||||
import { IconButton } from "./IconButton";
|
||||
|
||||
/** What reformatting needs of an editor; the `EditorView` an editor's `setRef` hands over has it */
|
||||
export type FormattableEditor = Pick<EditorView, "state" | "dispatch" | "contentDOM">;
|
||||
|
||||
/**
|
||||
* Replaces the editor's document with `format`'s version of it, and blurs it, since the cursor
|
||||
* resets anyway. The change goes through the editor's own `onChange`, as typing does.
|
||||
*/
|
||||
export async function formatEditor(
|
||||
editor: FormattableEditor,
|
||||
format: (text: string) => Promise<string>,
|
||||
): Promise<void> {
|
||||
const before = editor.state.doc.toString();
|
||||
const formatted = await format(before);
|
||||
// Typed into while formatting: the result is out of date
|
||||
if (editor.state.doc.toString() !== before) return;
|
||||
if (formatted === before) return;
|
||||
editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: formatted } });
|
||||
editor.contentDOM.blur();
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** The editor to reformat, as its `setRef` set it */
|
||||
editor: RefObject<FormattableEditor | null>;
|
||||
format: (text: string) => Promise<string>;
|
||||
/** A read-only editor can't be reformatted, so offers nothing */
|
||||
readOnly?: boolean;
|
||||
}
|
||||
|
||||
/** Reformats an editable editor's contents, for an `ActionsBar` */
|
||||
export function FormatAction({ editor, format, readOnly }: Props) {
|
||||
if (readOnly) return null;
|
||||
return (
|
||||
<IconButton
|
||||
showConfirm
|
||||
size="sm"
|
||||
title="Reformat contents"
|
||||
icon="magic_wand"
|
||||
variant="border"
|
||||
onClick={async () => {
|
||||
if (editor.current == null) return;
|
||||
await formatEditor(editor.current, format);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { generateId } from "@yaakapp-internal/lib/generateId";
|
||||
import classNames from "classnames";
|
||||
import { type ReactNode, useRef } from "react";
|
||||
import { useStateWithDeps } from "../hooks/useStateWithDeps";
|
||||
import { Button, CONTROL_TOOLTIP_DELAY } from "./Button";
|
||||
import type { IconProps } from "./Icon";
|
||||
import { IconButton, type IconButtonProps } from "./IconButton";
|
||||
import { IconTooltip } from "./IconTooltip";
|
||||
import { Label } from "./Label";
|
||||
import { HStack } from "./Stacks";
|
||||
import { Tooltip } from "./Tooltip";
|
||||
|
||||
export interface SegmentedControlOption<T extends string> {
|
||||
value: T;
|
||||
label: string;
|
||||
icon?: IconProps["icon"];
|
||||
/** Shown on hover over a text option, leaving its label as its name */
|
||||
tooltip?: string;
|
||||
}
|
||||
|
||||
export interface SegmentedControlProps<T extends string> {
|
||||
options: SegmentedControlOption<T>[];
|
||||
onChange: (value: T) => void;
|
||||
value: T;
|
||||
name: string;
|
||||
size?: IconButtonProps["size"];
|
||||
label: string;
|
||||
className?: string;
|
||||
/** Replaces the full width the control takes by default */
|
||||
containerClassName?: string;
|
||||
hideLabel?: boolean;
|
||||
labelClassName?: string;
|
||||
help?: ReactNode;
|
||||
}
|
||||
|
||||
export function SegmentedControl<T extends string>({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
size = "xs",
|
||||
label,
|
||||
hideLabel,
|
||||
labelClassName,
|
||||
help,
|
||||
className,
|
||||
containerClassName = "w-full",
|
||||
}: SegmentedControlProps<T>) {
|
||||
const [selectedValue, setSelectedValue] = useStateWithDeps<T>(value, [value]);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const id = useRef(`input-${generateId()}`);
|
||||
|
||||
// A visually hidden label has nowhere to show the help, so the last option carries it
|
||||
const inlineHelp =
|
||||
hideLabel && help ? <IconTooltip tabIndex={-1} content={help} iconSize="xs" /> : null;
|
||||
|
||||
const focusOption = (index: number) => {
|
||||
const option = containerRef.current?.querySelectorAll<HTMLElement>('[role="radio"]')[index];
|
||||
option?.focus();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classNames(containerClassName, "grid")}>
|
||||
<Label
|
||||
htmlFor={id.current}
|
||||
help={hideLabel ? undefined : help}
|
||||
visuallyHidden={hideLabel}
|
||||
className={classNames(labelClassName)}
|
||||
>
|
||||
{label}
|
||||
</Label>
|
||||
<HStack
|
||||
id={id.current}
|
||||
ref={containerRef}
|
||||
role="group"
|
||||
dir="ltr"
|
||||
space={1}
|
||||
className={classNames(
|
||||
className,
|
||||
"bg-surface-highlight rounded-lg mb-auto mr-auto",
|
||||
"transition-opacity transform-gpu p-1",
|
||||
)}
|
||||
onKeyDown={(e) => {
|
||||
const selectedIndex = options.findIndex((o) => o.value === selectedValue);
|
||||
if (e.key === "ArrowRight") {
|
||||
e.preventDefault();
|
||||
const newIndex = Math.abs((selectedIndex + 1) % options.length);
|
||||
if (options[newIndex]) {
|
||||
setSelectedValue(options[newIndex].value);
|
||||
}
|
||||
focusOption(newIndex);
|
||||
} else if (e.key === "ArrowLeft") {
|
||||
e.preventDefault();
|
||||
const newIndex = Math.abs((selectedIndex - 1) % options.length);
|
||||
if (options[newIndex]) {
|
||||
setSelectedValue(options[newIndex].value);
|
||||
}
|
||||
focusOption(newIndex);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{options.map((o, i) => {
|
||||
const isSelected = selectedValue === o.value;
|
||||
const isActive = value === o.value;
|
||||
const rightSlot = i === options.length - 1 ? inlineHelp : null;
|
||||
if (o.icon == null) {
|
||||
const button = (
|
||||
<Button
|
||||
key={o.label}
|
||||
aria-checked={isActive}
|
||||
size={size}
|
||||
variant="solid"
|
||||
color={isActive ? "secondary" : undefined}
|
||||
role="radio"
|
||||
tabIndex={isSelected ? 0 : -1}
|
||||
className={classNames(
|
||||
isActive && "text-text!",
|
||||
"focus:ring-1 focus:ring-border-focus",
|
||||
)}
|
||||
rightSlot={rightSlot}
|
||||
onClick={() => onChange(o.value)}
|
||||
>
|
||||
{o.label}
|
||||
</Button>
|
||||
);
|
||||
return o.tooltip == null ? (
|
||||
button
|
||||
) : (
|
||||
<Tooltip key={o.label} wrap content={o.tooltip} delay={CONTROL_TOOLTIP_DELAY}>
|
||||
{button}
|
||||
</Tooltip>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<IconButton
|
||||
key={o.label}
|
||||
aria-checked={isActive}
|
||||
size={size}
|
||||
variant="solid"
|
||||
color={isActive ? "secondary" : undefined}
|
||||
role="radio"
|
||||
tabIndex={isSelected ? 0 : -1}
|
||||
className={classNames(
|
||||
isActive && "text-text!",
|
||||
"px-1.5! w-auto!",
|
||||
"focus:ring-border-focus",
|
||||
)}
|
||||
title={o.label}
|
||||
icon={o.icon}
|
||||
rightSlot={rightSlot}
|
||||
onClick={() => onChange(o.value)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
})}
|
||||
</HStack>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeaderCell, TableRow } from "./Table";
|
||||
import { CsvViewerInner } from "./viewers/CsvViewer";
|
||||
|
||||
function table(density?: "default" | "compact") {
|
||||
return renderToStaticMarkup(
|
||||
<Table density={density}>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableHeaderCell>Name</TableHeaderCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>Accept</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("Table density", () => {
|
||||
test("a compact table trims its cells' and header's padding", () => {
|
||||
const markup = table("compact");
|
||||
expect(markup).toContain('data-density="compact"');
|
||||
expect(markup).toContain("[&_td]:py-0.5");
|
||||
expect(markup).toContain("[&_th]:py-0.5");
|
||||
});
|
||||
|
||||
test("other tables keep their spacing", () => {
|
||||
const markup = table();
|
||||
expect(markup).toContain('data-density="default"');
|
||||
expect(markup).not.toContain("py-0.5");
|
||||
expect(markup).toContain("py-2");
|
||||
});
|
||||
|
||||
test("the CSV viewer's table is compact", () => {
|
||||
expect(renderToStaticMarkup(<CsvViewerInner text={"a,b\n1,2"} />)).toContain(
|
||||
'data-density="compact"',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -6,11 +6,14 @@ export function Table({
|
||||
children,
|
||||
className,
|
||||
scrollable,
|
||||
density = "default",
|
||||
style,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
scrollable?: boolean;
|
||||
/** Compact rows, as dense as the proxy's flow list, for tables of data rather than settings */
|
||||
density?: "default" | "compact";
|
||||
style?: React.CSSProperties;
|
||||
}) {
|
||||
return (
|
||||
@@ -21,7 +24,10 @@ export function Table({
|
||||
"w-full text-sm mb-auto min-w-full max-w-full",
|
||||
"border-separate border-spacing-0",
|
||||
scrollable && "[&_thead]:sticky [&_thead]:top-0 [&_thead]:z-10",
|
||||
// Overrides the cells' own padding, which outranks theirs as it names the table too
|
||||
density === "compact" && "[&_td]:py-0.5 [&_th]:py-0.5",
|
||||
)}
|
||||
data-density={density}
|
||||
>
|
||||
{children}
|
||||
</table>
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { ActionsBar } from "../ActionsBar";
|
||||
import { IconButton } from "../IconButton";
|
||||
import { BodyViewModeSwitch, prettyViewFor, viewModeLabels } from "./BodyViewModeSwitch";
|
||||
|
||||
describe("prettyViewFor", () => {
|
||||
test("names the formatted view for each format", () => {
|
||||
const cases: [string | null, string | null, boolean, string | null][] = [
|
||||
["application/json", "json", false, "formatted"],
|
||||
["application/xml", "xml", false, "formatted"],
|
||||
["text/html", "html", false, "formatted"],
|
||||
["text/html", "html", true, "preview"],
|
||||
["text/csv", "text", false, "table"],
|
||||
["text/tab-separated-values", "text", false, "table"],
|
||||
["multipart/form-data", null, false, "parts"],
|
||||
["image/svg+xml", "xml", false, "preview"],
|
||||
];
|
||||
for (const [mimeType, language, previewHtml, expected] of cases) {
|
||||
expect(prettyViewFor({ mimeType, language, previewHtml }), `${mimeType}`).toBe(expected);
|
||||
}
|
||||
});
|
||||
|
||||
test("a body with one view has no switch", () => {
|
||||
expect(prettyViewFor({ mimeType: "text/plain", language: "text" })).toBeNull();
|
||||
expect(prettyViewFor({ mimeType: null, language: "text" })).toBeNull();
|
||||
expect(prettyViewFor({ mimeType: "application/javascript", language: "javascript" })).toBe(
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("a body's text decides over a missing content type", () => {
|
||||
expect(prettyViewFor({ mimeType: null, language: "json" })).toBe("formatted");
|
||||
});
|
||||
});
|
||||
|
||||
describe("BodyViewModeSwitch", () => {
|
||||
test("its first state is named for the format, its second is Raw", () => {
|
||||
expect(viewModeLabels("formatted")).toEqual(["Pretty", "Raw"]);
|
||||
expect(viewModeLabels("table")).toEqual(["Table", "Raw"]);
|
||||
expect(viewModeLabels("parts")).toEqual(["Parts", "Raw"]);
|
||||
expect(viewModeLabels("preview")).toEqual(["Preview", "Raw"]);
|
||||
expect(viewModeLabels("form")).toEqual(["Form", "Raw"]);
|
||||
});
|
||||
|
||||
test("marks the chosen state, and stays in view in an actions bar", () => {
|
||||
const pretty = renderToStaticMarkup(
|
||||
<BodyViewModeSwitch pretty="table" value="pretty" onChange={() => {}} />,
|
||||
);
|
||||
expect(pretty).toContain("data-pinned");
|
||||
expect(pretty).toMatch(/aria-checked="true"[^>]*>.*?Table/);
|
||||
expect(pretty).toMatch(/aria-checked="false"[^>]*>.*?Raw/);
|
||||
|
||||
const raw = renderToStaticMarkup(
|
||||
<BodyViewModeSwitch pretty="table" value="raw" onChange={() => {}} />,
|
||||
);
|
||||
expect(raw).toMatch(/aria-checked="false"[^>]*>.*?Table/);
|
||||
expect(raw).toMatch(/aria-checked="true"[^>]*>.*?Raw/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ActionsBar", () => {
|
||||
test("fades its actions in on hover, except a pinned one", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ActionsBar>
|
||||
<IconButton icon="filter" title="Filter" />
|
||||
<BodyViewModeSwitch pretty="formatted" value="pretty" onChange={() => {}} />
|
||||
</ActionsBar>,
|
||||
);
|
||||
expect(markup).toContain("[&>:not([data-pinned])]:opacity-0");
|
||||
expect(markup).toContain("group-hover/actions:*:opacity-100!");
|
||||
expect(markup).toContain('title="Filter"');
|
||||
expect(markup).toContain("data-pinned");
|
||||
});
|
||||
|
||||
test("holds every action to one height and radius, centred on the row", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ActionsBar>
|
||||
<IconButton icon="filter" title="Filter" />
|
||||
</ActionsBar>,
|
||||
);
|
||||
expect(markup).toContain("items-center");
|
||||
expect(markup).toContain("*:h-sm");
|
||||
expect(markup).toContain("*:rounded-md");
|
||||
});
|
||||
|
||||
test("the switch is sized to the bar's small icon buttons", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<BodyViewModeSwitch pretty="formatted" value="pretty" onChange={() => {}} />,
|
||||
);
|
||||
expect(markup).toContain("h-sm!");
|
||||
expect(markup).toContain("[&_[role=radio]]:h-full!");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import classNames from "classnames";
|
||||
import { PINNED_ACTION } from "../ActionsBar";
|
||||
import { SegmentedControl } from "../SegmentedControl";
|
||||
import type { ResponseViewMode } from "./ResponseBodyViewer";
|
||||
|
||||
/** What a body's formatted view shows, which names it in the switch */
|
||||
export type PrettyView = "formatted" | "table" | "parts" | "preview" | "form";
|
||||
|
||||
const PRETTY_OPTIONS: Record<PrettyView, { label: string; tooltip: string }> = {
|
||||
formatted: { label: "Pretty", tooltip: "Formatted" },
|
||||
table: { label: "Table", tooltip: "As a table" },
|
||||
parts: { label: "Parts", tooltip: "Split into parts" },
|
||||
preview: { label: "Preview", tooltip: "Rendered" },
|
||||
form: { label: "Form", tooltip: "As fields" },
|
||||
};
|
||||
|
||||
const RAW_OPTION = { label: "Raw", tooltip: "As received" };
|
||||
|
||||
/** The switch's labels for a body whose formatted view is `pretty`, its first state first */
|
||||
export function viewModeLabels(pretty: PrettyView): [string, string] {
|
||||
return [PRETTY_OPTIONS[pretty].label, RAW_OPTION.label];
|
||||
}
|
||||
|
||||
/**
|
||||
* The formatted view a text body has, or null when it has only the one view: a table for CSV,
|
||||
* parts for multipart, a rendering for SVG (and HTML, where `previewHtml`), and formatted text
|
||||
* for JSON, XML and HTML.
|
||||
*/
|
||||
export function prettyViewFor({
|
||||
mimeType,
|
||||
language,
|
||||
previewHtml = false,
|
||||
}: {
|
||||
/** The media type, without parameters */
|
||||
mimeType: string | null;
|
||||
/** The language the text viewer would show the body in */
|
||||
language: string | null | undefined;
|
||||
/** HTML renders as a page, rather than formatted text */
|
||||
previewHtml?: boolean;
|
||||
}): PrettyView | null {
|
||||
const mime = mimeType?.toLowerCase() ?? "";
|
||||
if (mime.startsWith("multipart/")) return "parts";
|
||||
if (/csv|tab-separated/.test(mime)) return "table";
|
||||
if (mime.startsWith("image/svg")) return "preview";
|
||||
if (language === "html") return previewHtml ? "preview" : "formatted";
|
||||
if (language === "json" || language === "xml") return "formatted";
|
||||
return null;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
/** The body's formatted view, named in the first state */
|
||||
pretty: PrettyView;
|
||||
value: ResponseViewMode;
|
||||
onChange: (value: ResponseViewMode) => void;
|
||||
}
|
||||
|
||||
/** Shows a body formatted for its type, or raw as received; for an `ActionsBar`, always in view */
|
||||
export function BodyViewModeSwitch({ pretty, value, onChange }: Props) {
|
||||
const prettyOption = PRETTY_OPTIONS[pretty];
|
||||
return (
|
||||
<div {...PINNED_ACTION} className="rounded-md">
|
||||
<SegmentedControl<ResponseViewMode>
|
||||
name="body_view_mode"
|
||||
label="View"
|
||||
hideLabel
|
||||
size="2xs"
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
containerClassName="w-auto h-full"
|
||||
// As tall as the bar's `sm` icon buttons, its options filling the height inside the border
|
||||
className={classNames(
|
||||
"h-sm! m-0! p-0.5! gap-0.5! rounded-md! bg-surface! border border-border-subtle",
|
||||
"[&_[role=radio]]:h-full!",
|
||||
)}
|
||||
options={[
|
||||
{ value: "pretty", ...prettyOption },
|
||||
{ value: "raw", ...RAW_OPTION },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -24,7 +24,8 @@ interface Props {
|
||||
renderCopyButton?: (getText: () => Promise<string | null>) => ReactNode;
|
||||
}
|
||||
|
||||
const LARGE_BYTES = 2 * 1000 * 1000;
|
||||
/** Bytes above which a body is held back until asked for, and opens raw once shown */
|
||||
export const LARGE_BODY_BYTES = 2 * 1000 * 1000;
|
||||
|
||||
/** Holds back a body big enough to slow the window down, until asked to show it */
|
||||
export function ConfirmLargeResponse({
|
||||
@@ -40,14 +41,14 @@ export function ConfirmLargeResponse({
|
||||
const [showLargeResponse, toggleShowLargeResponse] = useToggle();
|
||||
const isProbablyText = useMemo(() => isProbablyTextContentType(contentType), [contentType]);
|
||||
|
||||
const isLarge = (contentLength ?? 0) > LARGE_BYTES;
|
||||
const isLarge = (contentLength ?? 0) > LARGE_BODY_BYTES;
|
||||
if (!showLargeResponse && isLarge) {
|
||||
return (
|
||||
<Banner color="primary" className="flex flex-col gap-3">
|
||||
<p>
|
||||
Showing {noun} over{" "}
|
||||
<InlineCode>
|
||||
<SizeTag contentLength={LARGE_BYTES} />
|
||||
<SizeTag contentLength={LARGE_BODY_BYTES} />
|
||||
</InlineCode>{" "}
|
||||
may impact performance
|
||||
</p>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { type ReactNode, useCallback, useMemo } from "react";
|
||||
import type { Pair, PairEditorProps } from "../pairs/PairEditor";
|
||||
import { PairOrBulkEditor } from "../pairs/PairOrBulkEditor";
|
||||
import type { HttpFormFieldView, HttpRequestBodyView } from "./types";
|
||||
@@ -11,6 +11,8 @@ type Props = {
|
||||
onChange?: (body: HttpRequestBodyView) => void;
|
||||
/** Show the fields without a way to change them */
|
||||
readOnly?: boolean;
|
||||
/** Drawn in one bar with the bulk-edit toggle, like a view-mode switch */
|
||||
actions?: ReactNode;
|
||||
};
|
||||
|
||||
export function FormUrlencodedEditor({
|
||||
@@ -19,6 +21,7 @@ export function FormUrlencodedEditor({
|
||||
forceUpdateKey,
|
||||
onChange,
|
||||
readOnly,
|
||||
actions,
|
||||
}: Props) {
|
||||
const pairs = useMemo<Pair[]>(
|
||||
() =>
|
||||
@@ -52,6 +55,7 @@ export function FormUrlencodedEditor({
|
||||
pairs={pairs}
|
||||
onChange={handleChange}
|
||||
readOnly={readOnly}
|
||||
actions={actions}
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
stateKey={`urlencoded.${requestId}`}
|
||||
/>
|
||||
|
||||
@@ -109,8 +109,6 @@ export interface HttpRequestPaneViewProps {
|
||||
|
||||
/** Replaces the URL bar, as the proxy's card shows a captured request's method and URL */
|
||||
urlLine?: ReactNode;
|
||||
/** Tabs with nothing in them read in the subtlest colour */
|
||||
dimEmptyTabs?: boolean;
|
||||
/**
|
||||
* The tab to open on for a request with no tab of its own; with it, a tab chosen for one
|
||||
* request doesn't carry to the next
|
||||
@@ -168,7 +166,6 @@ export function HttpRequestPaneView({
|
||||
authContent,
|
||||
extraTabs,
|
||||
urlLine,
|
||||
dimEmptyTabs = false,
|
||||
defaultTab,
|
||||
activeTab,
|
||||
onTabChange,
|
||||
@@ -193,20 +190,17 @@ export function HttpRequestPaneView({
|
||||
bodyTab ?? {
|
||||
value: REQUEST_TAB_BODY,
|
||||
label: bodyTypeLabel(request.bodyType, request.contentType),
|
||||
empty: dimEmptyTabs && request.bodyType == null,
|
||||
rightSlot: numParams > 0 ? <CountBadge count={numParams} /> : null,
|
||||
},
|
||||
{
|
||||
value: REQUEST_TAB_PARAMS,
|
||||
rightSlot: <CountBadge count={paramPairs.length} />,
|
||||
label: "Params",
|
||||
empty: dimEmptyTabs && paramPairs.length === 0,
|
||||
},
|
||||
...(headersTabs ?? [
|
||||
{
|
||||
value: REQUEST_TAB_HEADERS,
|
||||
label: "Headers",
|
||||
empty: dimEmptyTabs && headerCount === 0,
|
||||
rightSlot: <CountBadge count={headerCount} />,
|
||||
},
|
||||
]),
|
||||
@@ -224,7 +218,6 @@ export function HttpRequestPaneView({
|
||||
[
|
||||
authTabs,
|
||||
bodyTab,
|
||||
dimEmptyTabs,
|
||||
extraTabs,
|
||||
headerCount,
|
||||
headersTabs,
|
||||
|
||||
@@ -43,8 +43,12 @@ export interface HttpResponsePaneViewProps {
|
||||
className?: string;
|
||||
/** Shown before there's a response */
|
||||
emptyState: ReactNode;
|
||||
viewMode: ResponseViewMode;
|
||||
onViewModeChange: (viewMode: ResponseViewMode) => void;
|
||||
viewMode?: ResponseViewMode;
|
||||
/**
|
||||
* Offers the raw view in the Response tab's menu. Left out where the body tab has a view-mode
|
||||
* switch of its own, as the proxy's does
|
||||
*/
|
||||
onViewModeChange?: (viewMode: ResponseViewMode) => void;
|
||||
/** Where the tab order and the active tab are remembered */
|
||||
tabsStorageKey?: string;
|
||||
/** Remembers the active tab per request or flow */
|
||||
@@ -76,8 +80,6 @@ export interface HttpResponsePaneViewProps {
|
||||
requestShownApart?: boolean;
|
||||
/** Drawn inside a card the app draws, without a card of its own */
|
||||
bare?: boolean;
|
||||
/** Tabs with nothing in them read in the subtlest colour */
|
||||
dimEmptyTabs?: boolean;
|
||||
/**
|
||||
* The tab to open on for a key with no tab of its own; with it, a tab chosen under one key
|
||||
* doesn't carry to the next
|
||||
@@ -97,7 +99,7 @@ export function HttpResponsePaneView({
|
||||
style,
|
||||
className,
|
||||
emptyState,
|
||||
viewMode,
|
||||
viewMode = "pretty",
|
||||
onViewModeChange,
|
||||
tabsStorageKey = "http_response_tabs",
|
||||
activeTabKey,
|
||||
@@ -115,7 +117,6 @@ export function HttpResponsePaneView({
|
||||
renderCopyButton,
|
||||
requestShownApart = false,
|
||||
bare = false,
|
||||
dimEmptyTabs = false,
|
||||
defaultTab,
|
||||
activeTab,
|
||||
onTabChange,
|
||||
@@ -162,27 +163,24 @@ export function HttpResponsePaneView({
|
||||
: []),
|
||||
];
|
||||
|
||||
const noBody = response == null || (response.contentLength ?? 0) === 0;
|
||||
const headerCount = response?.headers.length ?? 0;
|
||||
const cookieCount = requestShownApart
|
||||
? cookieCounts.received
|
||||
: cookieCounts.sent + cookieCounts.received;
|
||||
return [
|
||||
{
|
||||
value: RESPONSE_TAB_BODY,
|
||||
empty: dimEmptyTabs && noBody,
|
||||
options: {
|
||||
value: viewMode,
|
||||
onChange: (v) => onViewModeChange(v === "raw" ? "raw" : "pretty"),
|
||||
items: [
|
||||
{ label: "Response", value: "pretty" },
|
||||
...(mimeType?.startsWith("image")
|
||||
? []
|
||||
: [{ label: "Response (Raw)", shortLabel: "Raw", value: "raw" }]),
|
||||
],
|
||||
itemsAfter: itemsAfter.length > 0 ? itemsAfter : undefined,
|
||||
},
|
||||
},
|
||||
onViewModeChange == null && itemsAfter.length === 0
|
||||
? { value: RESPONSE_TAB_BODY, label: "Response" }
|
||||
: {
|
||||
value: RESPONSE_TAB_BODY,
|
||||
options: {
|
||||
value: viewMode,
|
||||
onChange: (v: string | null) => onViewModeChange?.(v === "raw" ? "raw" : "pretty"),
|
||||
items: [
|
||||
{ label: "Response", value: "pretty" },
|
||||
...(onViewModeChange == null || mimeType?.startsWith("image")
|
||||
? []
|
||||
: [{ label: "Response (Raw)", shortLabel: "Raw", value: "raw" }]),
|
||||
],
|
||||
itemsAfter: itemsAfter.length > 0 ? itemsAfter : undefined,
|
||||
},
|
||||
},
|
||||
...(requestShownApart
|
||||
? []
|
||||
: [
|
||||
@@ -196,7 +194,6 @@ export function HttpResponsePaneView({
|
||||
{
|
||||
value: RESPONSE_TAB_HEADERS,
|
||||
label: "Headers",
|
||||
empty: dimEmptyTabs && headerCount === 0,
|
||||
rightSlot: requestShownApart ? (
|
||||
<CountBadge count={headerCount} />
|
||||
) : (
|
||||
@@ -206,7 +203,6 @@ export function HttpResponsePaneView({
|
||||
{
|
||||
value: RESPONSE_TAB_COOKIES,
|
||||
label: "Cookies",
|
||||
empty: dimEmptyTabs && cookieCount === 0,
|
||||
rightSlot: requestShownApart ? (
|
||||
<CountBadge count={cookieCounts.received} />
|
||||
) : cookieCounts.sent > 0 || cookieCounts.received > 0 ? (
|
||||
@@ -217,7 +213,6 @@ export function HttpResponsePaneView({
|
||||
];
|
||||
}, [
|
||||
cookieCounts,
|
||||
dimEmptyTabs,
|
||||
extraTabs,
|
||||
mimeType,
|
||||
onCopyAsCurl,
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import type { HostInputProps } from "../EditorHost";
|
||||
import { EditorHostProvider } from "../EditorHost";
|
||||
import { PairOrBulkEditor } from "./PairOrBulkEditor";
|
||||
|
||||
function StubInput({ name, defaultValue }: HostInputProps) {
|
||||
return <div data-input={name}>{defaultValue}</div>;
|
||||
}
|
||||
|
||||
function render(actions?: string) {
|
||||
return renderToStaticMarkup(
|
||||
<EditorHostProvider value={{ Input: StubInput }}>
|
||||
<PairOrBulkEditor
|
||||
readOnly
|
||||
preferenceName="test"
|
||||
stateKey="test"
|
||||
forceUpdateKey=""
|
||||
pairs={[{ id: "p1", enabled: true, name: "a", value: "1" }]}
|
||||
onChange={() => {}}
|
||||
actions={actions == null ? undefined : <span data-action>{actions}</span>}
|
||||
/>
|
||||
</EditorHostProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("PairOrBulkEditor", () => {
|
||||
test("with actions, its bulk toggle shares one actions bar with them", () => {
|
||||
const markup = render("SWITCH");
|
||||
expect(markup).toContain("group/actions");
|
||||
// The toggle, then the given actions, inside the bar
|
||||
expect(markup).toMatch(/group-hover\/actions[^>]*>.*Enable bulk edit.*SWITCH/);
|
||||
});
|
||||
|
||||
test("without actions, its toggle keeps its own corner", () => {
|
||||
const markup = render();
|
||||
expect(markup).not.toContain("group/actions");
|
||||
expect(markup).toContain("Enable bulk edit");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,6 @@
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode } from "react";
|
||||
import { ACTIONS_BAR_CONTAINER, ActionsBar } from "../ActionsBar";
|
||||
import { useEditorHost } from "../EditorHost";
|
||||
import { IconButton } from "../IconButton";
|
||||
import { BulkPairEditor } from "./BulkPairEditor";
|
||||
@@ -8,9 +10,14 @@ import { PairEditor } from "./PairEditor";
|
||||
interface Props extends PairEditorProps {
|
||||
preferenceName: string;
|
||||
forcedEnvironmentId?: string;
|
||||
/**
|
||||
* Drawn after the bulk-edit toggle in one `ActionsBar`, like a view-mode switch. Giving it puts
|
||||
* the toggle in that bar rather than its own corner; once every site has moved, it always is
|
||||
*/
|
||||
actions?: ReactNode;
|
||||
}
|
||||
|
||||
export function PairOrBulkEditor({ preferenceName, ...props }: Props) {
|
||||
export function PairOrBulkEditor({ preferenceName, actions, ...props }: Props) {
|
||||
const { useStoredValue } = useEditorHost();
|
||||
const [useBulk, setUseBulk] = useStoredValue<boolean>(
|
||||
["bulk_edit", preferenceName],
|
||||
@@ -18,20 +25,37 @@ export function PairOrBulkEditor({ preferenceName, ...props }: Props) {
|
||||
"global",
|
||||
);
|
||||
|
||||
const editor = useBulk ? <BulkPairEditor {...props} /> : <PairEditor {...props} />;
|
||||
const toggleProps = {
|
||||
size: "sm",
|
||||
variant: "border",
|
||||
title: useBulk ? "Enable form edit" : "Enable bulk edit",
|
||||
onClick: () => setUseBulk((b) => !b),
|
||||
icon: useBulk ? "table" : "file_code",
|
||||
} as const;
|
||||
|
||||
if (actions != null) {
|
||||
return (
|
||||
<div className={classNames(ACTIONS_BAR_CONTAINER, "h-full w-full")}>
|
||||
{editor}
|
||||
<ActionsBar>
|
||||
<IconButton {...toggleProps} />
|
||||
{actions}
|
||||
</ActionsBar>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative h-full w-full group/wrapper">
|
||||
{useBulk ? <BulkPairEditor {...props} /> : <PairEditor {...props} />}
|
||||
{editor}
|
||||
<div className="absolute right-0 bottom-0">
|
||||
<IconButton
|
||||
size="sm"
|
||||
variant="border"
|
||||
title={useBulk ? "Enable form edit" : "Enable bulk edit"}
|
||||
{...toggleProps}
|
||||
className={classNames(
|
||||
"transition-opacity opacity-0 group-hover:opacity-80 hover:opacity-100! shadow",
|
||||
"bg-surface hover:text group-hover/wrapper:opacity-100",
|
||||
)}
|
||||
onClick={() => setUseBulk((b) => !b)}
|
||||
icon={useBulk ? "table" : "file_code"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -41,8 +41,6 @@ export type TabItem =
|
||||
value: string;
|
||||
label: string;
|
||||
hidden?: boolean;
|
||||
/** Nothing in it: the label reads in the subtlest colour */
|
||||
empty?: boolean;
|
||||
leftSlot?: ReactNode;
|
||||
rightSlot?: ReactNode;
|
||||
}
|
||||
@@ -59,8 +57,6 @@ export type TabItem =
|
||||
export interface TabOptionsItem {
|
||||
value: string;
|
||||
options: Omit<RadioDropdownProps, "children">;
|
||||
/** Nothing in it: the label reads in the subtlest colour */
|
||||
empty?: boolean;
|
||||
leftSlot?: ReactNode;
|
||||
rightSlot?: ReactNode;
|
||||
}
|
||||
@@ -526,15 +522,7 @@ function TabButton({
|
||||
) : "options" in tab ? (
|
||||
<TabOptionsButton tab={tab} buttonProps={btnProps} isActive={isActive} />
|
||||
) : (
|
||||
<Button
|
||||
leftSlot={tab.leftSlot}
|
||||
rightSlot={tab.rightSlot}
|
||||
{...btnProps}
|
||||
className={classNames(
|
||||
btnProps.className,
|
||||
!isActive && "empty" in tab && tab.empty && "text-text-subtlest!",
|
||||
)}
|
||||
>
|
||||
<Button leftSlot={tab.leftSlot} rightSlot={tab.rightSlot} {...btnProps}>
|
||||
{"label" in tab && tab.label ? tab.label : tab.value}
|
||||
</Button>
|
||||
);
|
||||
@@ -607,7 +595,6 @@ function TabOptionsButton({
|
||||
</div>
|
||||
}
|
||||
{...buttonProps}
|
||||
className={classNames(buttonProps.className, !isActive && tab.empty && "text-text-subtlest!")}
|
||||
>
|
||||
{option && "shortLabel" in option && option.shortLabel
|
||||
? option.shortLabel
|
||||
|
||||
@@ -31,7 +31,7 @@ export function CsvViewerInner({ text, className }: { text: string | null; class
|
||||
|
||||
return (
|
||||
<div className="overflow-auto h-full">
|
||||
<Table className={classNames(className, "text-sm")}>
|
||||
<Table density="compact" className={classNames(className, "text-sm")}>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
{columnIndexes.map((columnIndex) => (
|
||||
|
||||
@@ -275,7 +275,7 @@ function LeafBody({
|
||||
}
|
||||
|
||||
if (mediaType?.match(/csv|tab-separated/i)) {
|
||||
return <CsvViewer text={content} className="bg-primary h-10 w-10" />;
|
||||
return <CsvViewer text={content} className="pb-2" />;
|
||||
}
|
||||
|
||||
if (mediaType?.match(/^text\/html/i) || (!binary && detectedLanguage === "html")) {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode } from "react";
|
||||
import { Children, useCallback, useMemo, useState } from "react";
|
||||
import { type TextFilterApi, useTextFilter } from "../../hooks/useTextFilter";
|
||||
import { docFingerprint } from "../../lib/docFingerprint";
|
||||
import { ACTIONS_BAR_CONTAINER, ActionsBar } from "../ActionsBar";
|
||||
import type { CodeEditorProps } from "../editor/CodeEditor";
|
||||
import { jsonBreadcrumbExtension } from "../editor/json/breadcrumbExtension";
|
||||
import type { JsonPathSegment } from "../editor/json/jsonPath";
|
||||
@@ -20,6 +22,13 @@ export interface TextViewerProps {
|
||||
pretty?: boolean;
|
||||
className?: string;
|
||||
footerActions?: ReactNode;
|
||||
/** Last of the actions and kept while filtering, like a view-mode switch */
|
||||
pinnedActions?: ReactNode;
|
||||
/**
|
||||
* Draws the actions in an `ActionsBar` over the viewer rather than in the editor's own row.
|
||||
* Only the proxy's body tabs set it for now; once every site has moved it goes away
|
||||
*/
|
||||
ownActionsBar?: boolean;
|
||||
extensions?: Extension[];
|
||||
/** Pretty-prints the text when `pretty` is set */
|
||||
formatText?: (text: string, language: CodeEditorProps["language"]) => Promise<string>;
|
||||
@@ -42,6 +51,8 @@ export function TextViewer({
|
||||
pretty,
|
||||
className,
|
||||
footerActions,
|
||||
pinnedActions,
|
||||
ownActionsBar = false,
|
||||
extensions,
|
||||
formatText,
|
||||
filterText,
|
||||
@@ -121,8 +132,9 @@ export function TextViewer({
|
||||
|
||||
const actions = useMemo<ReactNode[]>(() => {
|
||||
const nodes: ReactNode[] = isSearching ? [] : Children.toArray(footerActions);
|
||||
const pinned = Children.toArray(pinnedActions);
|
||||
|
||||
if (!canFilter) return nodes;
|
||||
if (!canFilter) return [...nodes, ...pinned];
|
||||
|
||||
if (isSearching) {
|
||||
nodes.push(
|
||||
@@ -173,10 +185,11 @@ export function TextViewer({
|
||||
);
|
||||
}
|
||||
|
||||
return nodes;
|
||||
return [...nodes, ...pinned];
|
||||
}, [
|
||||
canFilter,
|
||||
footerActions,
|
||||
pinnedActions,
|
||||
filter,
|
||||
filterResult.isPending,
|
||||
filterResult.isFetching,
|
||||
@@ -221,16 +234,19 @@ export function TextViewer({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative h-full w-full">
|
||||
<div
|
||||
className={classNames("h-full w-full", ownActionsBar ? ACTIONS_BAR_CONTAINER : "relative")}
|
||||
>
|
||||
{renderEditor({
|
||||
readOnly: true,
|
||||
className,
|
||||
defaultValue: body,
|
||||
language,
|
||||
actions,
|
||||
actions: ownActionsBar ? undefined : actions,
|
||||
extensions: extraExtensions,
|
||||
stateKey,
|
||||
})}
|
||||
{ownActionsBar && actions.length > 0 && <ActionsBar>{actions}</ActionsBar>}
|
||||
{showBreadcrumbs && (
|
||||
<div className="absolute top-0 right-3 max-w-[70%] pointer-events-none">
|
||||
<ResponseBreadcrumbBar
|
||||
|
||||
Reference in new issue
Block a user