mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-08-15 16:12:05 +02:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5fc719491b | ||
|
|
85ed7ba170 | ||
|
|
d75396c3f3 |
@@ -36,7 +36,6 @@ import { fireAndForget } from "../../lib/fireAndForget";
|
||||
import { ErrorBoundary } from "../ErrorBoundary";
|
||||
import { Button } from "./Button";
|
||||
import { Hotkey } from "./Hotkey";
|
||||
import { IconButton } from "./IconButton";
|
||||
import { Separator } from "./Separator";
|
||||
|
||||
export type DropdownItemSeparator = {
|
||||
@@ -67,12 +66,6 @@ export type DropdownItemDefault = {
|
||||
submenu?: DropdownItem[];
|
||||
/** If true, submenu opens on click instead of hover */
|
||||
submenuOpenOnClick?: boolean;
|
||||
/**
|
||||
* How the submenu opens. "row" (default) opens it from the row itself (hover, or click
|
||||
* with submenuOpenOnClick). "button" keeps the row selectable via onSelect and renders
|
||||
* a dedicated button on the right that opens the submenu.
|
||||
*/
|
||||
submenuTrigger?: "row" | "button";
|
||||
icon?: IconProps["icon"];
|
||||
};
|
||||
|
||||
@@ -509,15 +502,9 @@ const Menu = forwardRef<Omit<DropdownRef, "open" | "isOpen" | "toggle" | "items"
|
||||
}
|
||||
}
|
||||
|
||||
if (!item.keepOpenOnSelect) {
|
||||
handleCloseAll();
|
||||
} else if (isSubmenu) {
|
||||
// Keep the parent menu open, but close this submenu — its items may no
|
||||
// longer describe the row after the action (e.g. Pin → Unpin, Remove)
|
||||
handleClose();
|
||||
}
|
||||
if (!item.keepOpenOnSelect) handleCloseAll();
|
||||
},
|
||||
[handleCloseAll, handleClose, isSubmenu, setSelectedIndex],
|
||||
[handleCloseAll, setSelectedIndex],
|
||||
);
|
||||
|
||||
useImperativeHandle(ref, () => {
|
||||
@@ -642,7 +629,7 @@ const Menu = forwardRef<Omit<DropdownRef, "open" | "isOpen" | "toggle" | "items"
|
||||
const item = filteredItems[selectedIndex ?? -1];
|
||||
if (!item || item.type === "separator" || item.type === "content") return;
|
||||
e.preventDefault();
|
||||
if (item.submenu && item.submenuTrigger !== "button") {
|
||||
if (item.submenu) {
|
||||
const parent = document.activeElement as HTMLButtonElement;
|
||||
if (parent) {
|
||||
setActiveSubmenu({ item, parent, viaKeyboard: true });
|
||||
@@ -661,11 +648,9 @@ const Menu = forwardRef<Omit<DropdownRef, "open" | "isOpen" | "toggle" | "items"
|
||||
clearTimeout(submenuTimeoutRef.current);
|
||||
}
|
||||
|
||||
if (item.submenu && !item.submenuOpenOnClick && item.submenuTrigger !== "button") {
|
||||
if (item.submenu && !item.submenuOpenOnClick) {
|
||||
setActiveSubmenu({ item, parent });
|
||||
} else if (activeSubmenu && activeSubmenu.item !== item) {
|
||||
// Hovering the row that owns the open submenu must not dismiss it — the
|
||||
// pointer travels across the row on its way to a button-triggered submenu
|
||||
} else if (activeSubmenu) {
|
||||
submenuTimeoutRef.current = window.setTimeout(() => {
|
||||
const submenuEl = submenuRef.current;
|
||||
if (!submenuEl || !activeSubmenu) {
|
||||
@@ -812,7 +797,6 @@ const Menu = forwardRef<Omit<DropdownRef, "open" | "isOpen" | "toggle" | "items"
|
||||
onFocus={handleFocus}
|
||||
onSelect={handleSelect}
|
||||
onHover={handleItemHover}
|
||||
onOpenSubmenu={(item, el) => setActiveSubmenu({ item, parent: el })}
|
||||
// oxlint-disable-next-line no-array-index-key -- It's fine
|
||||
key={i}
|
||||
item={item}
|
||||
@@ -884,7 +868,6 @@ interface MenuItemProps {
|
||||
onSelect: (item: DropdownItemDefault, el?: HTMLButtonElement) => Promise<void>;
|
||||
onFocus: (item: DropdownItemDefault) => void;
|
||||
onHover: (item: DropdownItemDefault, el: HTMLButtonElement) => void;
|
||||
onOpenSubmenu: (item: DropdownItemDefault, el: HTMLButtonElement) => void;
|
||||
focused: boolean;
|
||||
isParentOfActiveSubmenu?: boolean;
|
||||
}
|
||||
@@ -896,7 +879,6 @@ function MenuItem({
|
||||
onHover,
|
||||
item,
|
||||
onSelect,
|
||||
onOpenSubmenu,
|
||||
isParentOfActiveSubmenu,
|
||||
...props
|
||||
}: MenuItemProps) {
|
||||
@@ -932,22 +914,19 @@ function MenuItem({
|
||||
e.currentTarget.focus();
|
||||
};
|
||||
|
||||
const hasButtonSubmenu = item.submenu != null && item.submenuTrigger === "button";
|
||||
const rightSlot = item.submenu ? (
|
||||
<Icon icon="chevron_right" color="secondary" />
|
||||
) : (
|
||||
(item.rightSlot ?? <Hotkey variant="text" action={item.hotKeyAction ?? null} />)
|
||||
);
|
||||
|
||||
const rightSlot =
|
||||
item.submenu && !hasButtonSubmenu ? (
|
||||
<Icon icon="chevron_right" color="secondary" />
|
||||
) : (
|
||||
(item.rightSlot ?? <Hotkey variant="text" action={item.hotKeyAction ?? null} />)
|
||||
);
|
||||
|
||||
const button = (
|
||||
return (
|
||||
<Button
|
||||
ref={initRef}
|
||||
size="sm"
|
||||
tabIndex={-1}
|
||||
onMouseEnter={hasButtonSubmenu ? undefined : handleMouseEnter}
|
||||
onMouseLeave={hasButtonSubmenu ? undefined : (e) => e.currentTarget.blur()}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={(e) => e.currentTarget.blur()}
|
||||
disabled={item.disabled}
|
||||
onFocus={handleFocus}
|
||||
onClick={handleClick}
|
||||
@@ -968,7 +947,6 @@ function MenuItem({
|
||||
"min-w-32 outline-hidden px-2 mx-1.5 flex whitespace-nowrap",
|
||||
"focus:bg-surface-highlight focus:text rounded-sm focus:outline-hidden focus-visible:outline-1",
|
||||
isParentOfActiveSubmenu && "bg-surface-highlight text rounded-sm",
|
||||
hasButtonSubmenu && "pr-8",
|
||||
item.color === "danger" && "text-danger!",
|
||||
item.color === "primary" && "text-primary!",
|
||||
item.color === "success" && "text-success!",
|
||||
@@ -981,52 +959,6 @@ function MenuItem({
|
||||
<div className={classNames("truncate min-w-20")}>{item.label}</div>
|
||||
</Button>
|
||||
);
|
||||
|
||||
if (!hasButtonSubmenu) {
|
||||
return button;
|
||||
}
|
||||
|
||||
// The submenu trigger overlays the row as a sibling (not a child) because the row is
|
||||
// itself a button and buttons cannot nest. Hover handling lives on this wrapper so the
|
||||
// row keeps its focus highlight while the mouse is over the trigger.
|
||||
return (
|
||||
<div
|
||||
className="relative grid group/menuitem"
|
||||
onMouseEnter={() => {
|
||||
const el = buttonRef.current;
|
||||
if (el == null) return;
|
||||
onHover(item, el);
|
||||
el.focus();
|
||||
}}
|
||||
onMouseLeave={() => buttonRef.current?.blur()}
|
||||
>
|
||||
{button}
|
||||
<div
|
||||
className={classNames(
|
||||
"absolute right-1.5 inset-y-0 flex items-center",
|
||||
"opacity-0 group-hover/menuitem:opacity-100 group-focus-within/menuitem:opacity-100",
|
||||
)}
|
||||
>
|
||||
<IconButton
|
||||
color="custom"
|
||||
size="2xs"
|
||||
tabIndex={-1}
|
||||
icon="ellipsis_vertical"
|
||||
iconColor="secondary"
|
||||
title="More actions"
|
||||
className="h-full! w-7!"
|
||||
onMouseDown={(e) => {
|
||||
// Prevent the trigger from stealing focus, which would unhighlight the row
|
||||
e.preventDefault();
|
||||
}}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onOpenSubmenu(item, e.currentTarget);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface MenuItemHotKeyProps {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useCopyHttpResponse } from "../../hooks/useCopyHttpResponse";
|
||||
import { responseBodyTextQuery, useResponseBodyText } from "../../hooks/useResponseBodyText";
|
||||
import { useResponseFilter } from "../../hooks/useResponseFilter";
|
||||
import { useResponseBodyText } from "../../hooks/useResponseBodyText";
|
||||
import { useSaveResponse } from "../../hooks/useSaveResponse";
|
||||
import { languageFromContentType } from "../../lib/contentType";
|
||||
import { getContentTypeFromHeaders } from "../../lib/model_util";
|
||||
@@ -54,25 +52,30 @@ interface HttpTextViewerProps {
|
||||
}
|
||||
|
||||
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 [currentFilter, setCurrentFilter] = useState<string | null>(null);
|
||||
const filteredBody = useResponseBodyText({ response, filter: currentFilter });
|
||||
const saveResponse = useSaveResponse(response);
|
||||
const copyResponse = useCopyHttpResponse(response);
|
||||
const actionsDisabled = response.state !== "closed" && response.status >= 100;
|
||||
|
||||
const filterCallback = useMemo(
|
||||
() => (filter: string) => {
|
||||
setCurrentFilter(filter);
|
||||
return {
|
||||
data: filteredBody.data,
|
||||
isPending: filteredBody.isPending,
|
||||
error: !!filteredBody.error,
|
||||
};
|
||||
},
|
||||
[filteredBody],
|
||||
);
|
||||
|
||||
return (
|
||||
<TextViewer
|
||||
text={text}
|
||||
language={language}
|
||||
stateKey={`response.body.${response.id}`}
|
||||
filterStateKey={`response.body.${response.requestId}`}
|
||||
pretty={pretty}
|
||||
className={className}
|
||||
footerActions={[
|
||||
@@ -95,12 +98,7 @@ function HttpTextViewer({ response, text, language, pretty, className }: HttpTex
|
||||
className="border !border-border-subtle"
|
||||
/>,
|
||||
]}
|
||||
filter={filter}
|
||||
filterResult={{
|
||||
data: filteredBody.data,
|
||||
isPending: filteredBody.isPending,
|
||||
error: !!filteredBody.error,
|
||||
}}
|
||||
onFilter={filterCallback}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,14 @@
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode } from "react";
|
||||
import { Children, useCallback, useMemo } from "react";
|
||||
import { Banner, HStack, Icon, InlineCode } from "@yaakapp-internal/ui";
|
||||
import { createGlobalState } from "react-use";
|
||||
import { useDebouncedValue } from "@yaakapp-internal/ui";
|
||||
import { useFormatText } from "../../hooks/useFormatText";
|
||||
import type { ResponseFilterApi } from "../../hooks/useResponseFilter";
|
||||
import { Button } from "../core/Button";
|
||||
import type { EditorProps } from "../core/Editor/Editor";
|
||||
import { hyperlink } from "../core/Editor/hyperlink/extension";
|
||||
import { Editor } from "../core/Editor/LazyEditor";
|
||||
import { IconButton } from "../core/IconButton";
|
||||
import { Input } from "../core/Input";
|
||||
import { RecentFiltersDropdown } from "./RecentFiltersDropdown";
|
||||
|
||||
const extraExtensions = [hyperlink];
|
||||
|
||||
@@ -17,45 +16,57 @@ interface Props {
|
||||
text: string;
|
||||
language: EditorProps["language"];
|
||||
stateKey: string | null;
|
||||
filterStateKey?: string | null;
|
||||
pretty?: boolean;
|
||||
className?: string;
|
||||
footerActions?: ReactNode;
|
||||
filter?: ResponseFilterApi;
|
||||
filterResult?: {
|
||||
onFilter?: (filter: string) => {
|
||||
data: string | null | undefined;
|
||||
isPending: boolean;
|
||||
error: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
const useFilterText = createGlobalState<Record<string, string | null>>({});
|
||||
|
||||
export function TextViewer({
|
||||
language,
|
||||
text,
|
||||
stateKey,
|
||||
filterStateKey,
|
||||
pretty,
|
||||
className,
|
||||
footerActions,
|
||||
filter,
|
||||
filterResult,
|
||||
onFilter,
|
||||
}: Props) {
|
||||
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;
|
||||
|
||||
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);
|
||||
}
|
||||
const filterKey = filterStateKey ?? stateKey;
|
||||
const [filterTextMap, setFilterTextMap] = useFilterText();
|
||||
const filterText = filterKey ? (filterTextMap[filterKey] ?? null) : null;
|
||||
const debouncedFilterText = useDebouncedValue(filterText);
|
||||
const setFilterText = useCallback(
|
||||
(v: string | null) => {
|
||||
if (!filterKey) return;
|
||||
setFilterTextMap((m) => ({ ...m, [filterKey]: v }));
|
||||
},
|
||||
[filter],
|
||||
[filterKey, setFilterTextMap],
|
||||
);
|
||||
|
||||
const isSearching = filterText != null;
|
||||
const filteredResponse =
|
||||
onFilter && debouncedFilterText
|
||||
? onFilter(debouncedFilterText)
|
||||
: { data: null, isPending: false, error: false };
|
||||
|
||||
const toggleSearch = useCallback(() => {
|
||||
if (isSearching) {
|
||||
setFilterText(null);
|
||||
} else {
|
||||
setFilterText("");
|
||||
}
|
||||
}, [isSearching, setFilterText]);
|
||||
|
||||
const canFilter = onFilter && (language === "json" || language === "xml" || language === "html");
|
||||
|
||||
const actions = useMemo<ReactNode[]>(() => {
|
||||
const nodes: ReactNode[] = isSearching ? [] : Children.toArray(footerActions);
|
||||
|
||||
@@ -65,8 +76,8 @@ export function TextViewer({
|
||||
nodes.push(
|
||||
<div key="input" className="w-full opacity-100!">
|
||||
<Input
|
||||
key={filter.stateKey ?? "filter"}
|
||||
validate={!resultError}
|
||||
key={filterKey ?? "filter"}
|
||||
validate={!filteredResponse.error}
|
||||
hideLabel
|
||||
autoFocus
|
||||
containerClassName="bg-surface"
|
||||
@@ -74,62 +85,39 @@ export function TextViewer({
|
||||
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>
|
||||
}
|
||||
defaultValue={filterText}
|
||||
onKeyDown={(e) => e.key === "Escape" && toggleSearch()}
|
||||
onChange={setFilterText}
|
||||
stateKey={filterKey ? `filter.${filterKey}` : null}
|
||||
/>
|
||||
</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!"
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
nodes.push(
|
||||
<IconButton
|
||||
key="icon"
|
||||
size="sm"
|
||||
isLoading={filteredResponse.isPending}
|
||||
icon={isSearching ? "x" : "filter"}
|
||||
title={isSearching ? "Close filter" : "Filter response"}
|
||||
onClick={toggleSearch}
|
||||
className={classNames("border border-border-subtle!", isSearching && "opacity-100!")}
|
||||
/>,
|
||||
);
|
||||
|
||||
return nodes;
|
||||
}, [
|
||||
canFilter,
|
||||
footerActions,
|
||||
filter,
|
||||
filterResult?.isPending,
|
||||
resultError,
|
||||
filterKey,
|
||||
filterText,
|
||||
filteredResponse.error,
|
||||
filteredResponse.isPending,
|
||||
isSearching,
|
||||
language,
|
||||
handleFilterKeyDown,
|
||||
setFilterText,
|
||||
toggleSearch,
|
||||
]);
|
||||
|
||||
const formattedBody = useFormatText({ text, language, pretty: pretty ?? false });
|
||||
@@ -138,11 +126,11 @@ export function TextViewer({
|
||||
}
|
||||
|
||||
let body: string;
|
||||
if (appliedFilter) {
|
||||
if (resultError) {
|
||||
if (isSearching && filterText?.length > 0) {
|
||||
if (filteredResponse.error) {
|
||||
body = "";
|
||||
} else {
|
||||
body = filterResult?.data != null ? filterResult.data : "";
|
||||
body = filteredResponse.data != null ? filteredResponse.data : "";
|
||||
}
|
||||
} else {
|
||||
body = formattedBody;
|
||||
@@ -155,61 +143,15 @@ export function TextViewer({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-rows-[auto_minmax(0,1fr)] h-full w-full">
|
||||
{appliedFilter && filter != null ? (
|
||||
<AppliedFilterBar
|
||||
filter={appliedFilter}
|
||||
error={resultError}
|
||||
onClear={() => filter.replaceFilter("")}
|
||||
/>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<Editor
|
||||
readOnly
|
||||
className={className}
|
||||
defaultValue={body}
|
||||
language={language}
|
||||
actions={actions}
|
||||
extraExtensions={extraExtensions}
|
||||
stateKey={stateKey}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows what's actually filtering the body, which the filter box below can't convey
|
||||
* once it holds an edited expression that hasn't been applied yet.
|
||||
*/
|
||||
function AppliedFilterBar({
|
||||
filter,
|
||||
error,
|
||||
onClear,
|
||||
}: {
|
||||
filter: string;
|
||||
error: boolean;
|
||||
onClear: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Banner color={error ? "danger" : "info"} className="py-1! mb-2! text-sm">
|
||||
<HStack space={2} className="min-w-0">
|
||||
<Icon icon="filter" size="xs" className="shrink-0 opacity-70" />
|
||||
<span className="truncate min-w-0" title={filter}>
|
||||
Response filtered by <InlineCode>{filter}</InlineCode>
|
||||
{error && " (invalid expression)"}
|
||||
</span>
|
||||
<Button
|
||||
size="2xs"
|
||||
variant="border"
|
||||
color={error ? "danger" : "info"}
|
||||
className="ml-auto shrink-0"
|
||||
onClick={onClear}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</HStack>
|
||||
</Banner>
|
||||
<Editor
|
||||
readOnly
|
||||
className={className}
|
||||
defaultValue={body}
|
||||
language={language}
|
||||
actions={actions}
|
||||
extraExtensions={extraExtensions}
|
||||
stateKey={stateKey}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import { useCallback } from "react";
|
||||
import { useKeyValue } from "./useKeyValue";
|
||||
|
||||
export interface RecentFilter {
|
||||
value: string;
|
||||
pinned?: boolean;
|
||||
}
|
||||
|
||||
const MAX_RECENT_FILTERS = 20;
|
||||
const kvKey = (filterStateKey: string) => `recent_filters::${filterStateKey}`;
|
||||
const namespace = "global";
|
||||
const fallback: RecentFilter[] = [];
|
||||
|
||||
export function useRecentFilters(filterStateKey: string | null) {
|
||||
const { value, set } = useKeyValue<RecentFilter[]>({
|
||||
key: kvKey(filterStateKey ?? "n/a"),
|
||||
namespace,
|
||||
fallback,
|
||||
});
|
||||
|
||||
const addFilter = useCallback(
|
||||
async (rawValue: string) => {
|
||||
const value = rawValue.trim();
|
||||
if (filterStateKey == null || value === "") return;
|
||||
await set((prev) => {
|
||||
// Returning the same reference skips the write, so re-committing the
|
||||
// expression already at the top (on every blur) costs nothing
|
||||
if (prev[0]?.value === value) return prev;
|
||||
const existing = prev.find((f) => f.value === value);
|
||||
const rest = prev.filter((f) => f.value !== value);
|
||||
return trim([{ value, pinned: existing?.pinned }, ...rest]);
|
||||
});
|
||||
},
|
||||
[filterStateKey, set],
|
||||
);
|
||||
|
||||
const removeFilter = useCallback(
|
||||
async (value: string) => set((prev) => prev.filter((f) => f.value !== value)),
|
||||
[set],
|
||||
);
|
||||
|
||||
const togglePin = useCallback(
|
||||
async (value: string) =>
|
||||
set((prev) => prev.map((f) => (f.value === value ? { ...f, pinned: !f.pinned } : f))),
|
||||
[set],
|
||||
);
|
||||
|
||||
const clearFilters = useCallback(async () => set([]), [set]);
|
||||
|
||||
return { recentFilters: value ?? fallback, addFilter, removeFilter, togglePin, clearFilters };
|
||||
}
|
||||
|
||||
/** Bound the list, evicting the oldest unpinned entries before any pinned ones */
|
||||
function trim(filters: RecentFilter[]): RecentFilter[] {
|
||||
const excess = filters.length - MAX_RECENT_FILTERS;
|
||||
if (excess <= 0) return filters;
|
||||
|
||||
const evicted = new Set<number>();
|
||||
for (let i = filters.length - 1; i >= 0 && evicted.size < excess; i--) {
|
||||
if (!filters[i]?.pinned) evicted.add(i);
|
||||
}
|
||||
for (let i = filters.length - 1; i >= 0 && evicted.size < excess; i--) {
|
||||
evicted.add(i);
|
||||
}
|
||||
|
||||
return filters.filter((_, i) => !evicted.has(i));
|
||||
}
|
||||
@@ -2,25 +2,6 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import { getResponseBodyBytes, getResponseBodyText } from "../lib/responseBody";
|
||||
|
||||
export function responseBodyTextQuery({
|
||||
response,
|
||||
filter,
|
||||
}: {
|
||||
response: HttpResponse;
|
||||
filter: string | null;
|
||||
}) {
|
||||
return {
|
||||
queryKey: [
|
||||
"response_body_text",
|
||||
response.id,
|
||||
response.updatedAt,
|
||||
response.contentLength,
|
||||
filter ?? "",
|
||||
],
|
||||
queryFn: () => getResponseBodyText({ response, filter }),
|
||||
};
|
||||
}
|
||||
|
||||
export function useResponseBodyText({
|
||||
response,
|
||||
filter,
|
||||
@@ -30,7 +11,14 @@ export function useResponseBodyText({
|
||||
}) {
|
||||
return useQuery({
|
||||
placeholderData: (prev) => prev, // Keep previous data on refetch
|
||||
...responseBodyTextQuery({ response, filter }),
|
||||
queryKey: [
|
||||
"response_body_text",
|
||||
response.id,
|
||||
response.updatedAt,
|
||||
response.contentLength,
|
||||
filter ?? "",
|
||||
],
|
||||
queryFn: () => getResponseBodyText({ response, filter }),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { createGlobalState } from "react-use";
|
||||
import type { RecentFilter } from "./useRecentFilters";
|
||||
import { useRecentFilters } from "./useRecentFilters";
|
||||
|
||||
/** What's typed in the filter box. `null` means the filter box is closed */
|
||||
const useFilterTextMap = createGlobalState<Record<string, string | null>>({});
|
||||
|
||||
/** What's actually applied to the response. Only changes on an explicit apply */
|
||||
const useAppliedFilterMap = createGlobalState<Record<string, string | null>>({});
|
||||
|
||||
export interface ResponseFilterApi {
|
||||
stateKey: string | null;
|
||||
/** Draft text in the filter box, or `null` when the box is closed */
|
||||
filterText: string | null;
|
||||
/** The expression currently filtering the response */
|
||||
appliedFilter: string | null;
|
||||
isSearching: boolean;
|
||||
/** The box holds an expression that isn't the one currently applied */
|
||||
isDirty: boolean;
|
||||
/** Bumped when the (uncontrolled) filter input must re-read its defaultValue */
|
||||
filterUpdateKey: number;
|
||||
setFilterText: (value: string | null) => void;
|
||||
/** Apply the expression to the response, recording it if the filter accepts it */
|
||||
applyFilter: (value: string) => void;
|
||||
/** Like applyFilter, but also replaces what's shown in the filter box */
|
||||
replaceFilter: (value: string) => void;
|
||||
toggleSearch: () => void;
|
||||
recentFilters: RecentFilter[];
|
||||
removeRecentFilter: (value: string) => void;
|
||||
togglePinRecentFilter: (value: string) => void;
|
||||
clearRecentFilters: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draft/applied state and history for a response filter (JSONPath/XPath).
|
||||
*
|
||||
* History records at most one entry per apply gesture, and only after `runFilter`
|
||||
* confirms the plugin accepts the expression — the plugin is the sole judge of
|
||||
* validity. Because nothing but the gesture ever writes, refetches can't resurrect
|
||||
* deleted entries and a gesture can't record into another request's history.
|
||||
*/
|
||||
export function useResponseFilter({
|
||||
stateKey,
|
||||
runFilter,
|
||||
}: {
|
||||
stateKey: string | null;
|
||||
/** Evaluate an expression, rejecting if the filter plugin reports an error */
|
||||
runFilter: (filter: string) => Promise<unknown>;
|
||||
}): ResponseFilterApi {
|
||||
const [filterTextMap, setFilterTextMap] = useFilterTextMap();
|
||||
const [appliedFilterMap, setAppliedFilterMap] = useAppliedFilterMap();
|
||||
const filterText = stateKey ? (filterTextMap[stateKey] ?? null) : null;
|
||||
const appliedFilter = stateKey ? (appliedFilterMap[stateKey] ?? null) : null;
|
||||
|
||||
const setFilterText = useCallback(
|
||||
(v: string | null) => {
|
||||
if (!stateKey) return;
|
||||
setFilterTextMap((m) => ({ ...m, [stateKey]: v }));
|
||||
},
|
||||
[stateKey, setFilterTextMap],
|
||||
);
|
||||
|
||||
const setAppliedFilter = useCallback(
|
||||
(v: string | null) => {
|
||||
if (!stateKey) return;
|
||||
setAppliedFilterMap((m) => ({ ...m, [stateKey]: v }));
|
||||
},
|
||||
[stateKey, setAppliedFilterMap],
|
||||
);
|
||||
|
||||
const {
|
||||
recentFilters,
|
||||
addFilter,
|
||||
removeFilter: removeRecentFilter,
|
||||
togglePin: togglePinRecentFilter,
|
||||
clearFilters: clearRecentFilters,
|
||||
} = useRecentFilters(stateKey);
|
||||
|
||||
const applyFilter = useCallback(
|
||||
(value: string) => {
|
||||
setFilterText(value);
|
||||
const applied = value.trim() === "" ? null : value.trim();
|
||||
setAppliedFilter(applied);
|
||||
if (applied == null) return;
|
||||
runFilter(applied).then(
|
||||
() => addFilter(applied),
|
||||
() => {}, // Rejected by the filter plugin — don't record
|
||||
);
|
||||
},
|
||||
[setFilterText, setAppliedFilter, runFilter, addFilter],
|
||||
);
|
||||
|
||||
const [filterUpdateKey, setFilterUpdateKey] = useState(0);
|
||||
const replaceFilter = useCallback(
|
||||
(value: string) => {
|
||||
applyFilter(value);
|
||||
setFilterUpdateKey((k) => k + 1);
|
||||
},
|
||||
[applyFilter],
|
||||
);
|
||||
|
||||
const isSearching = filterText != null;
|
||||
const toggleSearch = useCallback(() => {
|
||||
if (isSearching) {
|
||||
setFilterText(null);
|
||||
setAppliedFilter(null);
|
||||
} else {
|
||||
setFilterText("");
|
||||
}
|
||||
}, [isSearching, setFilterText, setAppliedFilter]);
|
||||
|
||||
return {
|
||||
stateKey,
|
||||
filterText,
|
||||
appliedFilter,
|
||||
isSearching,
|
||||
isDirty: filterText != null && filterText.trim() !== (appliedFilter ?? ""),
|
||||
filterUpdateKey,
|
||||
setFilterText,
|
||||
applyFilter,
|
||||
replaceFilter,
|
||||
toggleSearch,
|
||||
recentFilters,
|
||||
removeRecentFilter,
|
||||
togglePinRecentFilter,
|
||||
clearRecentFilters,
|
||||
};
|
||||
}
|
||||
@@ -593,7 +593,7 @@ impl UpsertModelInfo for WorkspaceMeta {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq)]
|
||||
#[ts(export, export_to = "gen_models.ts")]
|
||||
pub enum CookieDomain {
|
||||
HostOnly(String),
|
||||
@@ -602,14 +602,14 @@ pub enum CookieDomain {
|
||||
Empty,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq)]
|
||||
#[ts(export, export_to = "gen_models.ts")]
|
||||
pub enum CookieExpires {
|
||||
AtUtc(String),
|
||||
SessionEnd,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, TS, PartialEq)]
|
||||
#[ts(export, export_to = "gen_models.ts")]
|
||||
pub enum CookieSameSite {
|
||||
Strict,
|
||||
@@ -617,7 +617,7 @@ pub enum CookieSameSite {
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, TS)]
|
||||
#[derive(Debug, Clone, Serialize, TS, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export, export_to = "gen_models.ts")]
|
||||
pub struct Cookie {
|
||||
|
||||
@@ -21,3 +21,4 @@ yaak-tls = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
|
||||
|
||||
+512
-207
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user