snapshot of https://github.com/mountain-loop/yaak.git (main, 2026-09-23; blobs > 131072B omitted)
This commit is contained in:
30
apps/yaak-client/components/responseViewers/AudioViewer.tsx
Normal file
30
apps/yaak-client/components/responseViewers/AudioViewer.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
interface Props {
|
||||
/** A URL for the body the host already stored. */
|
||||
bodyUrl?: string;
|
||||
data?: Uint8Array;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
export function AudioViewer({ bodyUrl, data, mimeType }: Props) {
|
||||
const [src, setSrc] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
if (bodyUrl) {
|
||||
setSrc(bodyUrl);
|
||||
} else if (data) {
|
||||
// The type matters here in a way it doesn't for an image: a media element goes by what
|
||||
// the blob declares rather than sniffing it, so an Ogg labelled as MP3 won't play
|
||||
const blob = new Blob([new Uint8Array(data)], { type: mimeType ?? "audio/mpeg" });
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
setSrc(objectUrl);
|
||||
return () => URL.revokeObjectURL(objectUrl);
|
||||
} else {
|
||||
setSrc(undefined);
|
||||
}
|
||||
}, [bodyUrl, data, mimeType]);
|
||||
|
||||
// oxlint-disable-next-line jsx-a11y/media-has-caption
|
||||
return <audio className="w-full" controls src={src} />;
|
||||
}
|
||||
37
apps/yaak-client/components/responseViewers/BinaryViewer.tsx
Normal file
37
apps/yaak-client/components/responseViewers/BinaryViewer.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import { useSaveResponse } from "../../hooks/useSaveResponse";
|
||||
import { getContentTypeFromHeaders } from "../../lib/model_util";
|
||||
import { Button } from "../core/Button";
|
||||
import { Banner, InlineCode, LoadingIcon } from "@yaakapp-internal/ui";
|
||||
import { EmptyStateText } from "../EmptyStateText";
|
||||
|
||||
interface Props {
|
||||
response: HttpResponse;
|
||||
}
|
||||
|
||||
export function BinaryViewer({ response }: Props) {
|
||||
const saveResponse = useSaveResponse(response);
|
||||
const contentType = getContentTypeFromHeaders(response.headers) ?? "unknown";
|
||||
|
||||
// Wait until the response has been fully-downloaded
|
||||
if (response.state !== "closed") {
|
||||
return (
|
||||
<EmptyStateText>
|
||||
<LoadingIcon size="sm" />
|
||||
</EmptyStateText>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Banner color="primary" className="h-full flex flex-col gap-3">
|
||||
<p>
|
||||
Content type <InlineCode>{contentType}</InlineCode> cannot be previewed
|
||||
</p>
|
||||
<div>
|
||||
<Button variant="border" size="sm" onClick={() => saveResponse.mutate()}>
|
||||
Save to File
|
||||
</Button>
|
||||
</div>
|
||||
</Banner>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, test, vi } from "vite-plus/test";
|
||||
import { CsvViewerInner } from "./CsvViewer";
|
||||
|
||||
vi.mock("@yaakapp-internal/ui", () => ({
|
||||
Table: ({ children }: { children: ReactNode }) => <table>{children}</table>,
|
||||
TableBody: ({ children }: { children: ReactNode }) => <tbody>{children}</tbody>,
|
||||
TableCell: ({ children }: { children: ReactNode }) => <td>{children}</td>,
|
||||
TableHead: ({ children }: { children: ReactNode }) => <thead>{children}</thead>,
|
||||
TableHeaderCell: ({ children }: { children: ReactNode }) => <th>{children}</th>,
|
||||
TableRow: ({ children }: { children: ReactNode }) => <tr>{children}</tr>,
|
||||
}));
|
||||
|
||||
describe("CsvViewer", () => {
|
||||
test("renders columns that extend beyond the first row", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<CsvViewerInner
|
||||
text={[
|
||||
"startDate,2026-02-03T00:00-03:00",
|
||||
"endDate,2026-02-03T23:59:59-03:00",
|
||||
"id,Fecha de inicio,Nombre,Estado,Perfil de puesto,ID de sucursal,Sucursal,Fecha de fin,ID de usuario",
|
||||
"391118210,2026-02-03 12:58:55,atencion1,Disponible,ATD,3549,sucursal,2026-02-03 12:59:08,42041",
|
||||
].join("\n")}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("ID de usuario");
|
||||
expect(markup).toContain("42041");
|
||||
expect(markup.match(/<td>/g)).toHaveLength(20);
|
||||
});
|
||||
});
|
||||
63
apps/yaak-client/components/responseViewers/CsvViewer.tsx
Normal file
63
apps/yaak-client/components/responseViewers/CsvViewer.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import classNames from "classnames";
|
||||
import Papa from "papaparse";
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeaderCell,
|
||||
TableRow,
|
||||
} from "@yaakapp-internal/ui";
|
||||
|
||||
interface Props {
|
||||
text: string | null;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function CsvViewer({ text, className }: Props) {
|
||||
return (
|
||||
<div className="overflow-auto h-full">
|
||||
<CsvViewerInner text={text} className={className} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CsvViewerInner({ text, className }: { text: string | null; className?: string }) {
|
||||
const parsed = useMemo(() => {
|
||||
if (text == null) return null;
|
||||
return Papa.parse<string[]>(text, { skipEmptyLines: true });
|
||||
}, [text]);
|
||||
|
||||
if (parsed === null) return null;
|
||||
|
||||
const header = parsed.data[0] ?? [];
|
||||
const rows = parsed.data.slice(1);
|
||||
const columnCount = parsed.data.reduce((count, row) => Math.max(count, row.length), 0);
|
||||
const columnIndexes = Array.from({ length: columnCount }, (_, index) => index);
|
||||
|
||||
return (
|
||||
<div className="overflow-auto h-full">
|
||||
<Table className={classNames(className, "text-sm")}>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
{columnIndexes.map((columnIndex) => (
|
||||
<TableHeaderCell key={columnIndex}>{header[columnIndex] ?? ""}</TableHeaderCell>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{rows.map((row, i) => (
|
||||
// oxlint-disable-next-line react/no-array-index-key
|
||||
<TableRow key={i}>
|
||||
{row.map((cell, columnIndex) => (
|
||||
// oxlint-disable-next-line react/no-array-index-key
|
||||
<TableCell key={columnIndex}>{cell}</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import { extractSseValueAtPath, type ServerSentEvent } from "@yaakapp-internal/sse";
|
||||
import { HStack, Icon, InlineCode, SplitLayout, VStack } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import type { CSSProperties, ReactNode } from "react";
|
||||
import { Fragment, useMemo, useState } from "react";
|
||||
import { useKeyValue } from "../../hooks/useKeyValue";
|
||||
import { useFormatText } from "../../hooks/useFormatText";
|
||||
import { useResponseBodyEventSource } from "../../hooks/useResponseBodyEventSource";
|
||||
import { useResponseBodySseSummary } from "../../hooks/useResponseBodySseSummary";
|
||||
import {
|
||||
sseSummaryResultKeyPathAutocomplete,
|
||||
useSseSummaryResultKeyPath,
|
||||
} from "../../hooks/useSseSummaryResultKeyPath";
|
||||
import { isJSON } from "../../lib/contentType";
|
||||
import { EmptyStateText } from "../EmptyStateText";
|
||||
import { Markdown } from "../Markdown";
|
||||
import { Button } from "../core/Button";
|
||||
import type { DropdownItem } from "../core/Dropdown";
|
||||
import { Dropdown } from "../core/Dropdown";
|
||||
import type { EditorProps } from "../core/Editor/Editor";
|
||||
import { Editor } from "../core/Editor/LazyEditor";
|
||||
import { EventDetailHeader, EventViewer } from "../core/EventViewer";
|
||||
import { EventViewerRow } from "../core/EventViewerRow";
|
||||
import { IconButton } from "../core/IconButton";
|
||||
import { IconTooltip } from "../core/IconTooltip";
|
||||
import { Input } from "../core/Input";
|
||||
import { Select } from "../core/Select";
|
||||
|
||||
interface Props {
|
||||
response: HttpResponse;
|
||||
}
|
||||
|
||||
const DEFAULT_EXTRACTED_TEXT_RATIO = 0.28;
|
||||
|
||||
export function EventStreamViewer({ response }: Props) {
|
||||
return (
|
||||
<Fragment
|
||||
key={response.id} // force a refresh when the response changes
|
||||
>
|
||||
<ActualEventStreamViewer response={response} />
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
function ActualEventStreamViewer({ response }: Props) {
|
||||
const [showLarge, setShowLarge] = useState<boolean>(false);
|
||||
const [showingLarge, setShowingLarge] = useState<boolean>(false);
|
||||
const filterEventPreviewsSetting = useKeyValue<boolean>({
|
||||
namespace: "no_sync",
|
||||
key: ["sse_filter_event_previews", response.requestId],
|
||||
fallback: false,
|
||||
});
|
||||
const applyToDetailsSetting = useKeyValue<boolean>({
|
||||
namespace: "no_sync",
|
||||
key: ["sse_apply_to_details", response.requestId],
|
||||
fallback: false,
|
||||
});
|
||||
const renderMarkdownSetting = useKeyValue<boolean>({
|
||||
namespace: "no_sync",
|
||||
key: ["sse_render_markdown", response.requestId],
|
||||
fallback: false,
|
||||
});
|
||||
const summarySettings = useSseSummaryResultKeyPath({ response });
|
||||
const events = useResponseBodyEventSource(response);
|
||||
const summary = useResponseBodySseSummary(response, summarySettings.resultKeyPath);
|
||||
const showExtractedText = summarySettings.resultKeyPath != null;
|
||||
const showResultKeyPathWarning =
|
||||
showExtractedText &&
|
||||
summary.data != null &&
|
||||
summary.data.fragmentCount === 0 &&
|
||||
!summary.isFetching &&
|
||||
summary.error == null;
|
||||
|
||||
const filterEventPreviews = showExtractedText && filterEventPreviewsSetting.value === true;
|
||||
const applyToDetails = showExtractedText && applyToDetailsSetting.value === true;
|
||||
const renderMarkdown = showExtractedText && renderMarkdownSetting.value === true;
|
||||
const settingsItems = useMemo<DropdownItem[]>(
|
||||
() => [
|
||||
{
|
||||
label: "Apply to Previews",
|
||||
keepOpenOnSelect: true,
|
||||
onSelect: () => filterEventPreviewsSetting.set(filterEventPreviewsSetting.value !== true),
|
||||
leftSlot: (
|
||||
<Icon
|
||||
icon={
|
||||
filterEventPreviewsSetting.value === true
|
||||
? "check_square_checked"
|
||||
: "check_square_unchecked"
|
||||
}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
label: "Apply to Details",
|
||||
keepOpenOnSelect: true,
|
||||
onSelect: () => applyToDetailsSetting.set(applyToDetailsSetting.value !== true),
|
||||
leftSlot: (
|
||||
<Icon
|
||||
icon={
|
||||
applyToDetailsSetting.value === true
|
||||
? "check_square_checked"
|
||||
: "check_square_unchecked"
|
||||
}
|
||||
/>
|
||||
),
|
||||
},
|
||||
],
|
||||
[
|
||||
applyToDetailsSetting,
|
||||
filterEventPreviewsSetting,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="h-full min-h-0 grid grid-rows-[auto_minmax(0,1fr)]">
|
||||
<HStack space={2} alignItems="center" className="pt-1 pb-1 border-b border-border-subtle">
|
||||
<div className={classNames(summarySettings.enabled ? "w-44 shrink-0" : "min-w-40 flex-1")}>
|
||||
<Select
|
||||
name={`sse-summary-result-key-path-enabled::${response.requestId}`}
|
||||
label="Extracted text"
|
||||
hideLabel
|
||||
size="xs"
|
||||
value={summarySettings.enabled ? "jsonpath" : "off"}
|
||||
options={[
|
||||
{ label: "Full events", value: "off" },
|
||||
{ label: "JSONPath", value: "jsonpath" },
|
||||
]}
|
||||
onChange={(value) => summarySettings.setEnabled(value === "jsonpath")}
|
||||
/>
|
||||
</div>
|
||||
{summarySettings.enabled && (
|
||||
<>
|
||||
<div className="min-w-40 flex-1">
|
||||
<Input
|
||||
label="Result JSON path"
|
||||
hideLabel
|
||||
size="xs"
|
||||
autocomplete={sseSummaryResultKeyPathAutocomplete}
|
||||
defaultValue={summarySettings.resultKeyPathInputValue}
|
||||
forceUpdateKey={`${response.requestId}:${summarySettings.inferredResultKeyPath ?? ""}`}
|
||||
placeholder="$.choices[0].delta.content"
|
||||
rightSlot={
|
||||
showResultKeyPathWarning ? (
|
||||
<div className="flex items-center px-2">
|
||||
<IconTooltip
|
||||
tabIndex={-1}
|
||||
icon="alert_triangle"
|
||||
iconColor="notice"
|
||||
content="No text fragments matched this JSONPath."
|
||||
/>
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
stateKey={`sse-summary-result-key-path::${response.requestId}`}
|
||||
tint={showResultKeyPathWarning ? "notice" : undefined}
|
||||
onChange={summarySettings.setResultKeyPath}
|
||||
/>
|
||||
</div>
|
||||
<Dropdown items={settingsItems}>
|
||||
<IconButton
|
||||
size="xs"
|
||||
variant="border"
|
||||
icon="settings"
|
||||
title="Extracted text settings"
|
||||
/>
|
||||
</Dropdown>
|
||||
</>
|
||||
)}
|
||||
</HStack>
|
||||
<SplitLayout
|
||||
layout="vertical"
|
||||
storageKey={`sse_extracted_text::${response.requestId}`}
|
||||
defaultRatio={DEFAULT_EXTRACTED_TEXT_RATIO}
|
||||
minHeightPx={72}
|
||||
resizeHandleClassName="hover:bg-surface-highlight active:bg-surface-highlight"
|
||||
firstSlot={({ style }) => (
|
||||
<div style={style} className="min-h-0">
|
||||
<EventViewer
|
||||
events={events.data ?? []}
|
||||
getEventKey={(_, index) => String(index)}
|
||||
error={events.error ? String(events.error) : null}
|
||||
splitLayoutStorageKey="sse_events"
|
||||
defaultRatio={0.4}
|
||||
renderRow={({ event, index, isActive, onClick }) => (
|
||||
<EventViewerRow
|
||||
isActive={isActive}
|
||||
onClick={onClick}
|
||||
icon={<Icon color="info" title="Server Message" icon="arrow_big_down_dash" />}
|
||||
content={
|
||||
<HStack space={2} className="items-center">
|
||||
<EventLabels event={event} index={index} isActive={isActive} />
|
||||
<span className="truncate text-xs">
|
||||
{getEventPreview(event, summarySettings.resultKeyPath, filterEventPreviews)}
|
||||
</span>
|
||||
</HStack>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
renderDetail={({ event, index, onClose }) => (
|
||||
<EventDetail
|
||||
event={event}
|
||||
index={index}
|
||||
applyJsonPath={applyToDetails}
|
||||
resultKeyPath={summarySettings.resultKeyPath}
|
||||
showLarge={showLarge}
|
||||
showingLarge={showingLarge}
|
||||
setShowLarge={setShowLarge}
|
||||
setShowingLarge={setShowingLarge}
|
||||
onClose={onClose}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
secondSlot={
|
||||
showExtractedText
|
||||
? ({ style }) => (
|
||||
<SseSummaryFooter
|
||||
style={style}
|
||||
error={summary.error ? String(summary.error) : null}
|
||||
isLoading={summary.isLoading && summary.data == null}
|
||||
onRenderMarkdownChange={renderMarkdownSetting.set}
|
||||
renderMarkdown={renderMarkdown}
|
||||
resultKeyPath={summarySettings.resultKeyPath ?? ""}
|
||||
summary={summary.data?.summary ?? ""}
|
||||
fragmentCount={summary.data?.fragmentCount ?? 0}
|
||||
/>
|
||||
)
|
||||
: null
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SseSummaryFooter({
|
||||
error,
|
||||
fragmentCount,
|
||||
isLoading,
|
||||
onRenderMarkdownChange,
|
||||
renderMarkdown,
|
||||
resultKeyPath,
|
||||
style,
|
||||
summary,
|
||||
}: {
|
||||
error: string | null;
|
||||
fragmentCount: number;
|
||||
isLoading: boolean;
|
||||
onRenderMarkdownChange: (renderMarkdown: boolean) => void;
|
||||
renderMarkdown: boolean;
|
||||
resultKeyPath: string;
|
||||
style: CSSProperties;
|
||||
summary: string;
|
||||
}) {
|
||||
const hasSummary = fragmentCount > 0;
|
||||
const actions = useMemo(
|
||||
() => [
|
||||
{
|
||||
key: "sse-summary-format",
|
||||
label: "Extracted text format",
|
||||
type: "select" as const,
|
||||
value: renderMarkdown ? "markdown" : "text",
|
||||
options: [
|
||||
{ label: "Text", value: "text" },
|
||||
{ label: "Markdown", value: "markdown" },
|
||||
],
|
||||
onChange: (value: string) => onRenderMarkdownChange(value === "markdown"),
|
||||
},
|
||||
],
|
||||
[onRenderMarkdownChange, renderMarkdown],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={style}
|
||||
className="min-h-0 overflow-hidden border-t border-border-subtle bg-surface grid grid-rows-[auto_minmax(0,1fr)]"
|
||||
>
|
||||
<div className="pt-2">
|
||||
<EventDetailHeader
|
||||
actions={actions}
|
||||
title="Extracted Text"
|
||||
copyText={hasSummary ? summary : undefined}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"min-h-0 py-2 overflow-auto",
|
||||
(error != null || isLoading || (hasSummary && !renderMarkdown)) && "text-xs",
|
||||
)}
|
||||
>
|
||||
{error != null ? (
|
||||
<span className="text-danger">{error}</span>
|
||||
) : isLoading ? (
|
||||
<span className="italic text-text-subtlest">Loading extracted text...</span>
|
||||
) : hasSummary ? (
|
||||
renderMarkdown ? (
|
||||
<div className="min-h-0">
|
||||
<Markdown className="select-auto cursor-auto">{summary}</Markdown>
|
||||
</div>
|
||||
) : (
|
||||
<pre className="font-mono whitespace-pre-wrap wrap-break-word select-auto cursor-auto">
|
||||
{summary}
|
||||
</pre>
|
||||
)
|
||||
) : (
|
||||
<EmptyStateText className="gap-1.5">
|
||||
No fragments for <InlineCode className="py-0">{resultKeyPath}</InlineCode>
|
||||
</EmptyStateText>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getEventPreview(
|
||||
event: ServerSentEvent,
|
||||
resultKeyPath: string | null,
|
||||
filterEventPreview: boolean,
|
||||
): string {
|
||||
if (filterEventPreview && resultKeyPath != null) {
|
||||
return (extractSseValueAtPath(event.data, resultKeyPath) ?? event.data).slice(0, 1000);
|
||||
}
|
||||
|
||||
return event.data.slice(0, 1000);
|
||||
}
|
||||
|
||||
function EventDetail({
|
||||
applyJsonPath,
|
||||
event,
|
||||
index,
|
||||
resultKeyPath,
|
||||
showLarge,
|
||||
showingLarge,
|
||||
setShowLarge,
|
||||
setShowingLarge,
|
||||
onClose,
|
||||
}: {
|
||||
applyJsonPath: boolean;
|
||||
event: ServerSentEvent;
|
||||
index: number;
|
||||
resultKeyPath: string | null;
|
||||
showLarge: boolean;
|
||||
showingLarge: boolean;
|
||||
setShowLarge: (v: boolean) => void;
|
||||
setShowingLarge: (v: boolean) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const detailText = useMemo(
|
||||
() =>
|
||||
applyJsonPath && resultKeyPath != null
|
||||
? (extractSseValueAtPath(event.data, resultKeyPath) ?? event.data)
|
||||
: event.data,
|
||||
[applyJsonPath, event.data, resultKeyPath],
|
||||
);
|
||||
const language = useMemo<"text" | "json">(() => {
|
||||
if (!detailText) return "text";
|
||||
return isJSON(detailText) ? "json" : "text";
|
||||
}, [detailText]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<EventDetailHeader
|
||||
title="Message Received"
|
||||
prefix={<EventLabels event={event} index={index} />}
|
||||
onClose={onClose}
|
||||
/>
|
||||
{!showLarge && detailText.length > 1000 * 1000 ? (
|
||||
<VStack space={2} className="italic text-text-subtlest">
|
||||
Message previews larger than 1MB are hidden
|
||||
<div>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setShowingLarge(true);
|
||||
setTimeout(() => {
|
||||
setShowLarge(true);
|
||||
setShowingLarge(false);
|
||||
}, 500);
|
||||
}}
|
||||
isLoading={showingLarge}
|
||||
color="secondary"
|
||||
variant="border"
|
||||
size="xs"
|
||||
>
|
||||
Try Showing
|
||||
</Button>
|
||||
</div>
|
||||
</VStack>
|
||||
) : (
|
||||
<FormattedEditor language={language} text={detailText} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FormattedEditor({ text, language }: { text: string; language: EditorProps["language"] }) {
|
||||
const formatted = useFormatText({ text, language, pretty: true });
|
||||
if (formatted == null) return null;
|
||||
return <Editor readOnly defaultValue={formatted} language={language} stateKey={null} />;
|
||||
}
|
||||
|
||||
function EventLabels({
|
||||
className,
|
||||
event,
|
||||
index,
|
||||
isActive,
|
||||
}: {
|
||||
event: ServerSentEvent;
|
||||
index: number;
|
||||
className?: string;
|
||||
isActive?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<HStack space={1.5} alignItems="center" className={className}>
|
||||
<EventLabel isActive={isActive}>{event.id ?? index}</EventLabel>
|
||||
{event.eventType && <EventLabel isActive={isActive}>{event.eventType}</EventLabel>}
|
||||
</HStack>
|
||||
);
|
||||
}
|
||||
|
||||
function EventLabel({ children, isActive }: { children: ReactNode; isActive?: boolean }) {
|
||||
return (
|
||||
<InlineCode className={classNames("py-0", isActive && "relative overflow-hidden")}>
|
||||
{isActive && <span className="absolute inset-0 bg-text opacity-5 pointer-events-none" />}
|
||||
<span className="relative">{children}</span>
|
||||
</InlineCode>
|
||||
);
|
||||
}
|
||||
106
apps/yaak-client/components/responseViewers/HTMLOrTextViewer.tsx
Normal file
106
apps/yaak-client/components/responseViewers/HTMLOrTextViewer.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback } from "react";
|
||||
import { useCopyHttpResponse } from "../../hooks/useCopyHttpResponse";
|
||||
import { responseBodyTextQuery, useResponseBodyText } from "../../hooks/useResponseBodyText";
|
||||
import { useResponseFilter } from "../../hooks/useResponseFilter";
|
||||
import { useSaveResponse } from "../../hooks/useSaveResponse";
|
||||
import { languageFromContentType } from "../../lib/contentType";
|
||||
import { getContentTypeFromHeaders } from "../../lib/model_util";
|
||||
import type { EditorProps } from "../core/Editor/Editor";
|
||||
import { IconButton } from "../core/IconButton";
|
||||
import { EmptyStateText } from "../EmptyStateText";
|
||||
import { TextViewer } from "./TextViewer";
|
||||
import { WebPageViewer } from "./WebPageViewer";
|
||||
|
||||
interface Props {
|
||||
response: HttpResponse;
|
||||
pretty: boolean;
|
||||
textViewerClassName?: string;
|
||||
}
|
||||
|
||||
export function HTMLOrTextViewer({ response, pretty, textViewerClassName }: Props) {
|
||||
const rawTextBody = useResponseBodyText({ response, filter: null });
|
||||
const contentType = getContentTypeFromHeaders(response.headers);
|
||||
const language = languageFromContentType(contentType, rawTextBody.data ?? "");
|
||||
|
||||
if (rawTextBody.isLoading || response.state === "initialized") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (language === "html" && pretty) {
|
||||
return <WebPageViewer html={rawTextBody.data ?? ""} baseUrl={response.url} />;
|
||||
}
|
||||
if (rawTextBody.data == null) {
|
||||
return <EmptyStateText>Empty response</EmptyStateText>;
|
||||
}
|
||||
return (
|
||||
<HttpTextViewer
|
||||
response={response}
|
||||
text={rawTextBody.data}
|
||||
language={language}
|
||||
pretty={pretty}
|
||||
className={textViewerClassName}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface HttpTextViewerProps {
|
||||
response: HttpResponse;
|
||||
text: string;
|
||||
language: EditorProps["language"];
|
||||
pretty: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function HttpTextViewer({ response, text, language, pretty, className }: HttpTextViewerProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const filter = useResponseFilter({
|
||||
stateKey: `response.body.${response.requestId}`,
|
||||
// Shares the display query's cache entry, so the verdict costs no extra RPC
|
||||
runFilter: useCallback(
|
||||
(f: string) => queryClient.fetchQuery(responseBodyTextQuery({ response, filter: f })),
|
||||
[queryClient, response],
|
||||
),
|
||||
});
|
||||
const filteredBody = useResponseBodyText({ response, filter: filter.appliedFilter });
|
||||
const saveResponse = useSaveResponse(response);
|
||||
const copyResponse = useCopyHttpResponse(response);
|
||||
const actionsDisabled = response.state !== "closed" && response.status >= 100;
|
||||
|
||||
return (
|
||||
<TextViewer
|
||||
text={text}
|
||||
language={language}
|
||||
stateKey={`response.body.${response.id}`}
|
||||
pretty={pretty}
|
||||
className={className}
|
||||
footerActions={[
|
||||
<IconButton
|
||||
key="save"
|
||||
size="sm"
|
||||
icon="save"
|
||||
title="Save response to file"
|
||||
disabled={actionsDisabled}
|
||||
onClick={() => saveResponse.mutate()}
|
||||
className="border !border-border-subtle"
|
||||
/>,
|
||||
<IconButton
|
||||
key="copy"
|
||||
size="sm"
|
||||
icon="copy"
|
||||
title="Copy response body"
|
||||
disabled={actionsDisabled}
|
||||
onClick={() => copyResponse.mutate()}
|
||||
className="border !border-border-subtle"
|
||||
/>,
|
||||
]}
|
||||
filter={filter}
|
||||
filterResult={{
|
||||
data: filteredBody.data,
|
||||
isPending: filteredBody.isPending,
|
||||
error: !!filteredBody.error,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
39
apps/yaak-client/components/responseViewers/ImageViewer.tsx
Normal file
39
apps/yaak-client/components/responseViewers/ImageViewer.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import classNames from "classnames";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
type Props = { className?: string; mimeType?: string } & (
|
||||
| {
|
||||
/** A URL for the body the host already stored. */
|
||||
bodyUrl: string;
|
||||
}
|
||||
| {
|
||||
data: ArrayBuffer;
|
||||
}
|
||||
);
|
||||
|
||||
export function ImageViewer({ className, mimeType, ...props }: Props) {
|
||||
const [src, setSrc] = useState<string>();
|
||||
const bodyUrl = "bodyUrl" in props ? props.bodyUrl : null;
|
||||
const data = "data" in props ? props.data : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (bodyUrl != null) {
|
||||
setSrc(bodyUrl);
|
||||
} else if (data != null) {
|
||||
const blob = new Blob([data], { type: mimeType ?? "image/png" });
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
setSrc(objectUrl);
|
||||
return () => URL.revokeObjectURL(objectUrl);
|
||||
} else {
|
||||
setSrc(undefined);
|
||||
}
|
||||
}, [bodyUrl, data, mimeType]);
|
||||
|
||||
return (
|
||||
<img
|
||||
src={src}
|
||||
alt="Response preview"
|
||||
className={classNames(className, "max-w-full max-h-full")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
22
apps/yaak-client/components/responseViewers/JsonViewer.tsx
Normal file
22
apps/yaak-client/components/responseViewers/JsonViewer.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import classNames from "classnames";
|
||||
import { JsonAttributeTree } from "../core/JsonAttributeTree";
|
||||
|
||||
interface Props {
|
||||
text: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function JsonViewer({ text, className }: Props) {
|
||||
let parsed = {};
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch {
|
||||
// Nothing yet
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={classNames(className, "overflow-x-auto h-full")}>
|
||||
<JsonAttributeTree attrValue={parsed} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
136
apps/yaak-client/components/responseViewers/MultipartViewer.tsx
Normal file
136
apps/yaak-client/components/responseViewers/MultipartViewer.tsx
Normal file
@@ -0,0 +1,136 @@
|
||||
import { type MultipartPart, parseMultipart } from "@mjackson/multipart-parser";
|
||||
import { lazy, Suspense, useMemo } from "react";
|
||||
import { languageFromContentType } from "../../lib/contentType";
|
||||
import { Banner, Icon, LoadingIcon } from "@yaakapp-internal/ui";
|
||||
import { TabContent, Tabs } from "../core/Tabs/Tabs";
|
||||
import { AudioViewer } from "./AudioViewer";
|
||||
import { CsvViewer } from "./CsvViewer";
|
||||
import { ImageViewer } from "./ImageViewer";
|
||||
import { SvgViewer } from "./SvgViewer";
|
||||
import { TextViewer } from "./TextViewer";
|
||||
import { VideoViewer } from "./VideoViewer";
|
||||
import { WebPageViewer } from "./WebPageViewer";
|
||||
|
||||
const PdfViewer = lazy(() => import("./PdfViewer").then((m) => ({ default: m.PdfViewer })));
|
||||
|
||||
interface Props {
|
||||
data: Uint8Array;
|
||||
boundary: string;
|
||||
idPrefix?: string;
|
||||
}
|
||||
|
||||
export function MultipartViewer({ data, boundary, idPrefix = "multipart" }: Props) {
|
||||
const parseResult = useMemo(() => {
|
||||
try {
|
||||
const maxFileSize = 1024 * 1024 * 10; // 10MB
|
||||
const parsed = parseMultipart(data, { boundary, maxFileSize });
|
||||
const parts = Array.from(parsed);
|
||||
return { parts, error: null };
|
||||
} catch (err) {
|
||||
return { parts: [], error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}, [data, boundary]);
|
||||
|
||||
const { parts, error } = parseResult;
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Banner color="danger" className="m-3">
|
||||
Failed to parse multipart data: {error}
|
||||
</Banner>
|
||||
);
|
||||
}
|
||||
|
||||
if (parts.length === 0) {
|
||||
return (
|
||||
<Banner color="info" className="m-3">
|
||||
No multipart parts found
|
||||
</Banner>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
addBorders
|
||||
label="Multipart"
|
||||
layout="horizontal"
|
||||
tabListClassName="border-r border-r-border -ml-3"
|
||||
tabs={parts.map((part, i) => ({
|
||||
label: part.name ?? "",
|
||||
value: tabValue(part, i),
|
||||
rightSlot:
|
||||
part.filename && part.headers.contentType.mediaType?.startsWith("image/") ? (
|
||||
<div className="h-5 w-5 overflow-auto flex items-center justify-end">
|
||||
<ImageViewer
|
||||
data={part.arrayBuffer}
|
||||
className="ml-auto w-auto rounded-sm overflow-hidden"
|
||||
/>
|
||||
</div>
|
||||
) : part.filename ? (
|
||||
<Icon icon="file" />
|
||||
) : null,
|
||||
}))}
|
||||
>
|
||||
{parts.map((part, i) => (
|
||||
<TabContent
|
||||
// oxlint-disable-next-line react/no-array-index-key -- Nothing else to key on
|
||||
key={idPrefix + part.name + i}
|
||||
value={tabValue(part, i)}
|
||||
className="pl-3 pt-0!"
|
||||
>
|
||||
<Part part={part} />
|
||||
</TabContent>
|
||||
))}
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
||||
function Part({ part }: { part: MultipartPart }) {
|
||||
const mimeType = part.headers.contentType.mediaType ?? null;
|
||||
const contentTypeHeader = part.headers.get("content-type");
|
||||
|
||||
const { uint8Array, content, detectedLanguage } = useMemo(() => {
|
||||
const uint8Array = new Uint8Array(part.arrayBuffer);
|
||||
const content = new TextDecoder().decode(part.arrayBuffer);
|
||||
const detectedLanguage = languageFromContentType(contentTypeHeader, content);
|
||||
return { uint8Array, content, detectedLanguage };
|
||||
}, [part, contentTypeHeader]);
|
||||
|
||||
if (mimeType?.match(/^image\/svg/i)) {
|
||||
return <SvgViewer text={content} className="pb-2" />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/^image/i)) {
|
||||
return <ImageViewer data={part.arrayBuffer} className="pb-2" />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/^audio/i)) {
|
||||
return <AudioViewer data={uint8Array} />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/^video/i)) {
|
||||
return <VideoViewer data={uint8Array} />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/csv|tab-separated/i)) {
|
||||
return <CsvViewer text={content} className="bg-primary h-10 w-10" />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/^text\/html/i) || detectedLanguage === "html") {
|
||||
return <WebPageViewer html={content} />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/pdf/i)) {
|
||||
return (
|
||||
<Suspense fallback={<LoadingIcon />}>
|
||||
<PdfViewer data={uint8Array} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
return <TextViewer text={content} language={detectedLanguage} stateKey={null} />;
|
||||
}
|
||||
|
||||
function tabValue(part: MultipartPart, i: number) {
|
||||
return `${part.name ?? ""}::${i}`;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
.react-pdf__Document * {
|
||||
user-select: text;
|
||||
}
|
||||
81
apps/yaak-client/components/responseViewers/PdfViewer.tsx
Normal file
81
apps/yaak-client/components/responseViewers/PdfViewer.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
import "react-pdf/dist/Page/TextLayer.css";
|
||||
import "react-pdf/dist/Page/AnnotationLayer.css";
|
||||
import "./PdfViewer.css";
|
||||
import type { PDFDocumentProxy } from "pdfjs-dist";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { Document, Page } from "react-pdf";
|
||||
import { useContainerSize } from "@yaakapp-internal/ui";
|
||||
import { fireAndForget } from "../../lib/fireAndForget";
|
||||
|
||||
fireAndForget(
|
||||
import("react-pdf").then(({ pdfjs }) => {
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
|
||||
"pdfjs-dist/build/pdf.worker.min.mjs",
|
||||
import.meta.url,
|
||||
).toString();
|
||||
}),
|
||||
);
|
||||
|
||||
interface Props {
|
||||
/** A URL for the body the host already stored. */
|
||||
bodyUrl?: string;
|
||||
data?: Uint8Array;
|
||||
}
|
||||
|
||||
const options = {
|
||||
cMapUrl: "/cmaps/",
|
||||
standardFontDataUrl: "/standard_fonts/",
|
||||
};
|
||||
|
||||
export function PdfViewer({ bodyUrl, data }: Props) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [numPages, setNumPages] = useState<number>();
|
||||
|
||||
const { width: containerWidth } = useContainerSize(containerRef);
|
||||
|
||||
// During render, not in an effect: an effect leaves the first paint with no file, and
|
||||
// `Document` renders its "Failed to load PDF file" state for that frame before recovering
|
||||
const src = useMemo(() => {
|
||||
if (bodyUrl) {
|
||||
return bodyUrl;
|
||||
}
|
||||
if (data) {
|
||||
// Create a copy to avoid "Buffer is already detached" errors
|
||||
// This happens when the ArrayBuffer is transferred/detached elsewhere
|
||||
return { data: new Uint8Array(data) };
|
||||
}
|
||||
return undefined;
|
||||
}, [bodyUrl, data]);
|
||||
|
||||
const onDocumentLoadSuccess = ({ numPages: nextNumPages }: PDFDocumentProxy): void => {
|
||||
setNumPages(nextNumPages);
|
||||
};
|
||||
|
||||
// Nothing to show yet, rather than the failure state `Document` renders for an empty file
|
||||
if (src == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="w-full h-full overflow-y-auto">
|
||||
<Document
|
||||
file={src}
|
||||
options={options}
|
||||
onLoadSuccess={onDocumentLoadSuccess}
|
||||
externalLinkTarget="_blank"
|
||||
externalLinkRel="noopener noreferrer"
|
||||
>
|
||||
{Array.from({ length: numPages ?? 0 }, (_, index) => (
|
||||
<Page
|
||||
className="mb-6 select-all"
|
||||
renderTextLayer
|
||||
renderAnnotationLayer
|
||||
key={`page_${index + 1}`}
|
||||
pageNumber={index + 1}
|
||||
width={containerWidth}
|
||||
/>
|
||||
))}
|
||||
</Document>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { Icon } from "@yaakapp-internal/ui";
|
||||
import type { RecentFilter } from "../../hooks/useRecentFilters";
|
||||
import { Dropdown, type DropdownItem } from "../core/Dropdown";
|
||||
import { IconButton } from "../core/IconButton";
|
||||
|
||||
interface Props {
|
||||
recentFilters: RecentFilter[];
|
||||
activeFilter: string | null;
|
||||
onSelect: (value: string) => void;
|
||||
onRemove: (value: string) => void;
|
||||
onTogglePin: (value: string) => void;
|
||||
onClear: () => void;
|
||||
}
|
||||
|
||||
export function RecentFiltersDropdown({
|
||||
recentFilters,
|
||||
activeFilter,
|
||||
onSelect,
|
||||
onRemove,
|
||||
onTogglePin,
|
||||
onClear,
|
||||
}: Props) {
|
||||
const pinned = recentFilters.filter((f) => f.pinned);
|
||||
const unpinned = recentFilters.filter((f) => !f.pinned);
|
||||
|
||||
const toItem = (filter: RecentFilter): DropdownItem => ({
|
||||
label: (
|
||||
<div className="font-mono text-sm truncate max-w-sm" title={filter.value}>
|
||||
{filter.value}
|
||||
</div>
|
||||
),
|
||||
leftSlot: <Icon icon={filter.value === activeFilter ? "check" : "empty"} />,
|
||||
onSelect: () => onSelect(filter.value),
|
||||
submenuTrigger: "button",
|
||||
submenu: [
|
||||
{
|
||||
label: filter.pinned ? "Unpin" : "Pin",
|
||||
icon: filter.pinned ? "unpin" : "pin",
|
||||
keepOpenOnSelect: true,
|
||||
onSelect: () => onTogglePin(filter.value),
|
||||
},
|
||||
{
|
||||
label: "Remove",
|
||||
icon: "trash",
|
||||
color: "danger",
|
||||
keepOpenOnSelect: true,
|
||||
onSelect: () => onRemove(filter.value),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const items: DropdownItem[] = [];
|
||||
|
||||
if (recentFilters.length === 0) {
|
||||
items.push({
|
||||
type: "content",
|
||||
label: (
|
||||
<span className="block px-4 py-1 text-sm text-text-subtle">
|
||||
Filters you use are remembered here
|
||||
</span>
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
if (pinned.length > 0) {
|
||||
items.push({ type: "separator", label: "Pinned" }, ...pinned.map(toItem));
|
||||
}
|
||||
|
||||
if (unpinned.length > 0) {
|
||||
items.push({ type: "separator", label: "Recent" }, ...unpinned.map(toItem));
|
||||
}
|
||||
|
||||
if (recentFilters.length > 0) {
|
||||
items.push(
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Clear All",
|
||||
leftSlot: <Icon icon="trash" />,
|
||||
color: "danger",
|
||||
onSelect: onClear,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dropdown items={items}>
|
||||
<IconButton
|
||||
size="xs"
|
||||
icon="filter"
|
||||
title="Recent filters"
|
||||
iconColor="secondary"
|
||||
className="w-8 ml-0.5 mr-1 h-auto!"
|
||||
/>
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { Icon } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import type { JsonPathSegment } from "../core/Editor/json/jsonPath";
|
||||
import { IconButton } from "../core/IconButton";
|
||||
import { Tooltip } from "../core/Tooltip";
|
||||
|
||||
interface Props {
|
||||
segments: JsonPathSegment[];
|
||||
appliedFilter: string | null;
|
||||
/**
|
||||
* How many leading segments make up the applied filter. `null` when unfiltered, or
|
||||
* when the filter isn't a plain path and is shown as raw text instead.
|
||||
*/
|
||||
appliedDepth: number | null;
|
||||
filterError: boolean;
|
||||
/** Called with the number of leading segments to filter to. `0` clears the filter. */
|
||||
onSelect: (count: number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows where the cursor sits inside a response (`$ > sort > [0] > id`). An applied
|
||||
* plain-path filter is the start of the trail, so any crumb moves it. While filtered,
|
||||
* the bar is tinted so a lingering filter is hard to miss.
|
||||
*/
|
||||
export function ResponseBreadcrumbBar({
|
||||
segments,
|
||||
appliedFilter,
|
||||
appliedDepth,
|
||||
filterError,
|
||||
onSelect,
|
||||
}: Props) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [overflow, setOverflow] = useState({ left: false, right: false });
|
||||
|
||||
const measure = useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (el == null) return;
|
||||
const maxScroll = el.scrollWidth - el.clientWidth;
|
||||
setOverflow({
|
||||
left: el.scrollLeft > 1,
|
||||
right: el.scrollLeft < maxScroll - 1,
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Keep the deepest crumb (where the cursor is) in view as the path changes.
|
||||
useLayoutEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (el == null) return;
|
||||
el.scrollLeft = el.scrollWidth;
|
||||
measure();
|
||||
}, [segments, measure]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (el == null) return;
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, [measure]);
|
||||
|
||||
const scrollBy = useCallback((direction: -1 | 1) => {
|
||||
const el = scrollRef.current;
|
||||
if (el == null) return;
|
||||
el.scrollBy({ left: direction * Math.max(120, el.clientWidth * 0.6), behavior: "smooth" });
|
||||
}, []);
|
||||
|
||||
const isFiltered = appliedFilter != null;
|
||||
|
||||
return (
|
||||
<div className="rounded bg-surface shadow pointer-events-auto">
|
||||
<div
|
||||
className={classNames(
|
||||
"flex items-stretch h-6 rounded border overflow-hidden font-mono text-xs text-text-subtle select-none",
|
||||
!isFiltered && "border-border-subtle",
|
||||
isFiltered && !filterError && "border-primary/40 bg-primary/10",
|
||||
filterError && "border-danger/40 bg-danger/10",
|
||||
)}
|
||||
>
|
||||
{isFiltered && appliedDepth == null ? (
|
||||
<span
|
||||
className={classNames(
|
||||
"flex items-center min-w-0 truncate px-2",
|
||||
filterError ? "text-danger" : "text-primary",
|
||||
)}
|
||||
>
|
||||
{appliedFilter}
|
||||
</span>
|
||||
) : (
|
||||
<Crumb
|
||||
label="$"
|
||||
tooltip="Clear filter"
|
||||
isApplied={isFiltered}
|
||||
onClick={appliedDepth != null && appliedDepth > 0 ? () => onSelect(0) : null}
|
||||
/>
|
||||
)}
|
||||
{overflow.left && (
|
||||
<IconButton
|
||||
size="xs"
|
||||
icon="chevron_left"
|
||||
title="Scroll breadcrumbs left"
|
||||
iconColor="secondary"
|
||||
onClick={() => scrollBy(-1)}
|
||||
className="shrink-0 h-auto!"
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
ref={scrollRef}
|
||||
onScroll={measure}
|
||||
className="flex items-stretch min-w-0 overflow-x-auto hide-scrollbars whitespace-nowrap"
|
||||
>
|
||||
{segments.map((segment, i) => {
|
||||
const count = i + 1;
|
||||
const isApplied = appliedDepth != null && count <= appliedDepth;
|
||||
const isClickable = (!isFiltered || appliedDepth != null) && count !== appliedDepth;
|
||||
return (
|
||||
<div key={i} className="flex items-stretch shrink-0">
|
||||
<Icon
|
||||
icon="chevron_right"
|
||||
size="xs"
|
||||
className="text-text-subtlest shrink-0 self-center"
|
||||
/>
|
||||
<Crumb
|
||||
label={segment.kind === "index" ? `[${segment.index}]` : segment.key}
|
||||
tooltip={
|
||||
segment.kind === "index"
|
||||
? `Filter to element ${segment.index}`
|
||||
: `Filter to ${segment.key}`
|
||||
}
|
||||
isApplied={isApplied}
|
||||
onClick={isClickable ? () => onSelect(count) : null}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{overflow.right && (
|
||||
<IconButton
|
||||
size="xs"
|
||||
icon="chevron_right"
|
||||
title="Scroll breadcrumbs right"
|
||||
iconColor="secondary"
|
||||
onClick={() => scrollBy(1)}
|
||||
className="shrink-0 h-auto!"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Crumb({
|
||||
label,
|
||||
tooltip,
|
||||
isApplied,
|
||||
onClick,
|
||||
}: {
|
||||
label: string;
|
||||
tooltip: string;
|
||||
isApplied: boolean;
|
||||
onClick: (() => void) | null;
|
||||
}) {
|
||||
const outerClassName = classNames("flex items-center px-0.5 py-0.5", isApplied && "text-primary");
|
||||
const innerClassName = "flex items-center h-full px-1 rounded-sm";
|
||||
if (onClick == null) {
|
||||
return (
|
||||
<span className={classNames(outerClassName, "shrink-0")}>
|
||||
<span className={innerClassName}>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip content={tooltip} className="shrink-0 items-stretch!">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={classNames(outerClassName, "group/crumb focus-visible:outline-none")}
|
||||
>
|
||||
<span
|
||||
className={classNames(
|
||||
innerClassName,
|
||||
"transition-colors group-hover/crumb:text-text group-hover/crumb:bg-surface-highlight",
|
||||
"group-focus-visible/crumb:ring-1 group-focus-visible/crumb:ring-border-focus",
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
30
apps/yaak-client/components/responseViewers/SvgViewer.tsx
Normal file
30
apps/yaak-client/components/responseViewers/SvgViewer.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
interface Props {
|
||||
text: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function SvgViewer({ text, className }: Props) {
|
||||
const [src, setSrc] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!text) {
|
||||
return setSrc(null);
|
||||
}
|
||||
|
||||
const blob = new Blob([text], { type: "image/svg+xml;charset=utf-8" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
setSrc(url);
|
||||
|
||||
return () => URL.revokeObjectURL(url);
|
||||
}, [text]);
|
||||
|
||||
if (src == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<img src={src} alt="Response preview" className={className ?? "max-w-full max-h-full pb-2"} />
|
||||
);
|
||||
}
|
||||
222
apps/yaak-client/components/responseViewers/TextViewer.tsx
Normal file
222
apps/yaak-client/components/responseViewers/TextViewer.tsx
Normal file
@@ -0,0 +1,222 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Children, useCallback, useMemo, useState } from "react";
|
||||
import { useFormatText } from "../../hooks/useFormatText";
|
||||
import type { ResponseFilterApi } from "../../hooks/useResponseFilter";
|
||||
import type { EditorProps } from "../core/Editor/Editor";
|
||||
import { jsonBreadcrumbExtension } from "../core/Editor/json/breadcrumbExtension";
|
||||
import type { JsonPathSegment } from "../core/Editor/json/jsonPath";
|
||||
import { jsonPathToSegments, segmentsToJsonPath } from "../core/Editor/json/jsonPath";
|
||||
import { hyperlink } from "../core/Editor/hyperlink/extension";
|
||||
import { Editor } from "../core/Editor/LazyEditor";
|
||||
import { IconButton } from "../core/IconButton";
|
||||
import { Input } from "../core/Input";
|
||||
import { ResponseBreadcrumbBar } from "./ResponseBreadcrumbBar";
|
||||
import { RecentFiltersDropdown } from "./RecentFiltersDropdown";
|
||||
|
||||
interface Props {
|
||||
text: string;
|
||||
language: EditorProps["language"];
|
||||
stateKey: string | null;
|
||||
pretty?: boolean;
|
||||
className?: string;
|
||||
footerActions?: ReactNode;
|
||||
filter?: ResponseFilterApi;
|
||||
filterResult?: {
|
||||
data: string | null | undefined;
|
||||
isPending: boolean;
|
||||
error: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export function TextViewer({
|
||||
language,
|
||||
text,
|
||||
stateKey,
|
||||
pretty,
|
||||
className,
|
||||
footerActions,
|
||||
filter,
|
||||
filterResult,
|
||||
}: Props) {
|
||||
// Track the JSON path under the cursor to drive the breadcrumb bar. Selection
|
||||
// works even in this read-only editor, so it updates as the user clicks around.
|
||||
const [breadcrumbSegments, setBreadcrumbSegments] = useState<JsonPathSegment[]>([]);
|
||||
const handleBreadcrumbUpdate = useCallback(
|
||||
({ segments }: { segments: JsonPathSegment[] | null }) =>
|
||||
setBreadcrumbSegments((prev) => {
|
||||
const next = segments ?? [];
|
||||
return segmentsToJsonPath(prev) === segmentsToJsonPath(next) ? prev : next;
|
||||
}),
|
||||
[],
|
||||
);
|
||||
const extraExtensions = useMemo(
|
||||
() =>
|
||||
language === "json"
|
||||
? [hyperlink, jsonBreadcrumbExtension(handleBreadcrumbUpdate)]
|
||||
: [hyperlink],
|
||||
[language, handleBreadcrumbUpdate],
|
||||
);
|
||||
|
||||
const canFilter =
|
||||
filter != null && (language === "json" || language === "xml" || language === "html");
|
||||
const isSearching = filter?.isSearching ?? false;
|
||||
const appliedFilter = filter?.appliedFilter ?? null;
|
||||
const resultError = filterResult?.error ?? false;
|
||||
|
||||
// Filter output is always an array of matches, so under a plain-path filter the
|
||||
// cursor's leading index is that single match and the rest extends the filter.
|
||||
const appliedSegments =
|
||||
appliedFilter != null && language === "json" ? jsonPathToSegments(appliedFilter) : null;
|
||||
const pathSegments =
|
||||
appliedSegments != null
|
||||
? [...appliedSegments, ...breadcrumbSegments.slice(1)]
|
||||
: breadcrumbSegments;
|
||||
const showBreadcrumbs =
|
||||
filter != null &&
|
||||
(appliedFilter != null || (language === "json" && breadcrumbSegments.length > 0));
|
||||
|
||||
const handleFilterKeyDown = useCallback(
|
||||
(e: KeyboardEvent) => {
|
||||
if (filter == null) return;
|
||||
if (e.key === "Escape") {
|
||||
filter.toggleSearch();
|
||||
} else if (e.key === "Enter" && filter.filterText != null) {
|
||||
filter.applyFilter(filter.filterText);
|
||||
}
|
||||
},
|
||||
[filter],
|
||||
);
|
||||
|
||||
const actions = useMemo<ReactNode[]>(() => {
|
||||
const nodes: ReactNode[] = isSearching ? [] : Children.toArray(footerActions);
|
||||
|
||||
if (!canFilter) return nodes;
|
||||
|
||||
if (isSearching) {
|
||||
nodes.push(
|
||||
<div key="input" className="w-full opacity-100!">
|
||||
<Input
|
||||
key={filter.stateKey ?? "filter"}
|
||||
validate={!resultError}
|
||||
hideLabel
|
||||
autoFocus
|
||||
containerClassName="bg-surface"
|
||||
size="sm"
|
||||
placeholder={language === "json" ? "JSONPath expression" : "XPath expression"}
|
||||
label="Filter expression"
|
||||
name="filter"
|
||||
defaultValue={filter.filterText}
|
||||
forceUpdateKey={filter.filterUpdateKey}
|
||||
onKeyDown={handleFilterKeyDown}
|
||||
onChange={filter.setFilterText}
|
||||
stateKey={filter.stateKey ? `filter.${filter.stateKey}` : null}
|
||||
leftSlot={
|
||||
<div className="py-0.5 flex">
|
||||
<RecentFiltersDropdown
|
||||
recentFilters={filter.recentFilters}
|
||||
activeFilter={filter.appliedFilter}
|
||||
onSelect={filter.replaceFilter}
|
||||
onRemove={filter.removeRecentFilter}
|
||||
onTogglePin={filter.togglePinRecentFilter}
|
||||
onClear={filter.clearRecentFilters}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
rightSlot={
|
||||
<div className="py-0.5 flex">
|
||||
<IconButton
|
||||
size="xs"
|
||||
icon="x"
|
||||
title="Close filter"
|
||||
iconColor="secondary"
|
||||
onClick={filter.toggleSearch}
|
||||
className="w-8 mr-0.5 h-auto!"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>,
|
||||
);
|
||||
} else {
|
||||
nodes.push(
|
||||
<IconButton
|
||||
key="icon"
|
||||
size="sm"
|
||||
isLoading={filterResult?.isPending ?? false}
|
||||
icon="filter"
|
||||
title="Filter response"
|
||||
onClick={filter.toggleSearch}
|
||||
className="border border-border-subtle!"
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}, [
|
||||
canFilter,
|
||||
footerActions,
|
||||
filter,
|
||||
filterResult?.isPending,
|
||||
resultError,
|
||||
isSearching,
|
||||
language,
|
||||
handleFilterKeyDown,
|
||||
]);
|
||||
|
||||
const formattedBody = useFormatText({ text, language, pretty: pretty ?? false });
|
||||
if (formattedBody == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let body: string;
|
||||
if (appliedFilter) {
|
||||
if (resultError) {
|
||||
body = "";
|
||||
} else {
|
||||
body = filterResult?.data != null ? filterResult.data : "";
|
||||
}
|
||||
} else {
|
||||
body = formattedBody;
|
||||
}
|
||||
|
||||
// Decode unicode sequences in the text to readable characters
|
||||
if (language === "json" && pretty) {
|
||||
body = decodeUnicodeLiterals(body);
|
||||
body = body.replace(/\\\//g, "/"); // Hide unnecessary escaping of '/' by some older frameworks
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative h-full w-full">
|
||||
<Editor
|
||||
readOnly
|
||||
className={className}
|
||||
defaultValue={body}
|
||||
language={language}
|
||||
actions={actions}
|
||||
extraExtensions={extraExtensions}
|
||||
stateKey={stateKey}
|
||||
/>
|
||||
{showBreadcrumbs && (
|
||||
<div className="absolute top-0 right-3 max-w-[70%] pointer-events-none">
|
||||
<ResponseBreadcrumbBar
|
||||
segments={language === "json" ? pathSegments : []}
|
||||
appliedFilter={appliedFilter}
|
||||
appliedDepth={appliedSegments?.length ?? null}
|
||||
filterError={resultError}
|
||||
onSelect={(count) =>
|
||||
filter.replaceFilter(count === 0 ? "" : segmentsToJsonPath(pathSegments, count))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Convert \uXXXX to actual Unicode characters */
|
||||
function decodeUnicodeLiterals(text: string): string {
|
||||
return text.replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => {
|
||||
const charCode = Number.parseInt(hex, 16);
|
||||
return String.fromCharCode(charCode);
|
||||
});
|
||||
}
|
||||
29
apps/yaak-client/components/responseViewers/VideoViewer.tsx
Normal file
29
apps/yaak-client/components/responseViewers/VideoViewer.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
interface Props {
|
||||
/** A URL for the body the host already stored. */
|
||||
bodyUrl?: string;
|
||||
data?: Uint8Array;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
export function VideoViewer({ bodyUrl, data, mimeType }: Props) {
|
||||
const [src, setSrc] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
if (bodyUrl) {
|
||||
setSrc(bodyUrl);
|
||||
} else if (data) {
|
||||
// As in AudioViewer: a media element trusts the declared type instead of sniffing
|
||||
const blob = new Blob([new Uint8Array(data)], { type: mimeType ?? "video/mp4" });
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
setSrc(objectUrl);
|
||||
return () => URL.revokeObjectURL(objectUrl);
|
||||
} else {
|
||||
setSrc(undefined);
|
||||
}
|
||||
}, [bodyUrl, data, mimeType]);
|
||||
|
||||
// oxlint-disable-next-line jsx-a11y/media-has-caption
|
||||
return <video className="w-full" controls src={src} />;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
interface Props {
|
||||
html: string;
|
||||
baseUrl?: string;
|
||||
}
|
||||
|
||||
export function WebPageViewer({ html, baseUrl }: Props) {
|
||||
const contentForIframe: string | undefined = useMemo(() => {
|
||||
if (baseUrl && html.includes("<head>")) {
|
||||
return html.replace(/<head>/gi, `<head><base href="${baseUrl}"/>`);
|
||||
}
|
||||
return html;
|
||||
}, [baseUrl, html]);
|
||||
|
||||
return (
|
||||
<div className="h-full pb-3">
|
||||
<iframe
|
||||
key={html ? "has-body" : "no-body"}
|
||||
title="Yaak response preview"
|
||||
srcDoc={contentForIframe}
|
||||
sandbox="allow-scripts allow-forms"
|
||||
referrerPolicy="no-referrer"
|
||||
className="h-full w-full rounded-lg border border-border-subtle"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user