mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-01-11 20:00:29 +01:00
Prevent sidebar re-render on every keypress (#152)
This commit is contained in:
7
package-lock.json
generated
7
package-lock.json
generated
@@ -1190,6 +1190,12 @@
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@gilbarbara/deep-equal": {
|
||||
"version": "0.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@gilbarbara/deep-equal/-/deep-equal-0.3.1.tgz",
|
||||
"integrity": "sha512-I7xWjLs2YSVMc5gGx1Z3ZG1lgFpITPndpi8Ku55GeEIKpACCPQNS/OTqQbxgTCfq0Ncvcc+CrFov96itVh6Qvw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@grpc/grpc-js": {
|
||||
"version": "1.12.1",
|
||||
"resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.12.1.tgz",
|
||||
@@ -15837,6 +15843,7 @@
|
||||
"@codemirror/lang-xml": "^6.0.2",
|
||||
"@codemirror/language": "^6.6.0",
|
||||
"@codemirror/search": "^6.2.3",
|
||||
"@gilbarbara/deep-equal": "^0.3.1",
|
||||
"@lezer/highlight": "^1.1.3",
|
||||
"@lezer/lr": "^1.3.3",
|
||||
"@react-hook/size": "^2.1.2",
|
||||
|
||||
@@ -12,7 +12,7 @@ export type CookieJar = { model: "cookie_jar", id: string, createdAt: string, up
|
||||
|
||||
export type Environment = { model: "environment", id: string, workspaceId: string, environmentId: string | null, createdAt: string, updatedAt: string, name: string, variables: Array<EnvironmentVariable>, };
|
||||
|
||||
export type EnvironmentVariable = { enabled?: boolean, name: string, value: string, };
|
||||
export type EnvironmentVariable = { enabled?: boolean, name: string, value: string, id: string, };
|
||||
|
||||
export type Folder = { model: "folder", id: string, createdAt: string, updatedAt: string, workspaceId: string, folderId: string | null, name: string, description: string, sortPriority: number, };
|
||||
|
||||
@@ -24,13 +24,13 @@ export type GrpcEvent = { model: "grpc_event", id: string, createdAt: string, up
|
||||
|
||||
export type GrpcEventType = "info" | "error" | "client_message" | "server_message" | "connection_start" | "connection_end";
|
||||
|
||||
export type GrpcMetadataEntry = { enabled?: boolean, name: string, value: string, };
|
||||
export type GrpcMetadataEntry = { enabled?: boolean, name: string, value: string, id: string, };
|
||||
|
||||
export type GrpcRequest = { model: "grpc_request", id: string, createdAt: string, updatedAt: string, workspaceId: string, folderId: string | null, authenticationType: string | null, authentication: Record<string, any>, description: string, message: string, metadata: Array<GrpcMetadataEntry>, method: string | null, name: string, service: string | null, sortPriority: number, url: string, };
|
||||
|
||||
export type HttpRequest = { model: "http_request", id: string, createdAt: string, updatedAt: string, workspaceId: string, folderId: string | null, authentication: Record<string, any>, authenticationType: string | null, body: Record<string, any>, bodyType: string | null, description: string, headers: Array<HttpRequestHeader>, method: string, name: string, sortPriority: number, url: string, urlParameters: Array<HttpUrlParameter>, };
|
||||
|
||||
export type HttpRequestHeader = { enabled?: boolean, name: string, value: string, };
|
||||
export type HttpRequestHeader = { enabled?: boolean, name: string, value: string, id: string, };
|
||||
|
||||
export type HttpResponse = { model: "http_response", id: string, createdAt: string, updatedAt: string, workspaceId: string, requestId: string, bodyPath: string | null, contentLength: number | null, elapsed: number, elapsedHeaders: number, error: string | null, headers: Array<HttpResponseHeader>, remoteAddr: string | null, status: number, statusReason: string | null, state: HttpResponseState, url: string, version: string | null, };
|
||||
|
||||
@@ -38,7 +38,7 @@ export type HttpResponseHeader = { name: string, value: string, };
|
||||
|
||||
export type HttpResponseState = "initialized" | "connected" | "closed";
|
||||
|
||||
export type HttpUrlParameter = { enabled?: boolean, name: string, value: string, };
|
||||
export type HttpUrlParameter = { enabled?: boolean, name: string, value: string, id: string, };
|
||||
|
||||
export type KeyValue = { model: "key_value", createdAt: string, updatedAt: string, key: string, namespace: string, value: string, };
|
||||
|
||||
|
||||
@@ -2,17 +2,17 @@
|
||||
|
||||
export type Environment = { model: "environment", id: string, workspaceId: string, environmentId: string | null, createdAt: string, updatedAt: string, name: string, variables: Array<EnvironmentVariable>, };
|
||||
|
||||
export type EnvironmentVariable = { enabled?: boolean, name: string, value: string, };
|
||||
export type EnvironmentVariable = { enabled?: boolean, name: string, value: string, id: string, };
|
||||
|
||||
export type Folder = { model: "folder", id: string, createdAt: string, updatedAt: string, workspaceId: string, folderId: string | null, name: string, description: string, sortPriority: number, };
|
||||
|
||||
export type GrpcMetadataEntry = { enabled?: boolean, name: string, value: string, };
|
||||
export type GrpcMetadataEntry = { enabled?: boolean, name: string, value: string, id: string, };
|
||||
|
||||
export type GrpcRequest = { model: "grpc_request", id: string, createdAt: string, updatedAt: string, workspaceId: string, folderId: string | null, authenticationType: string | null, authentication: Record<string, any>, description: string, message: string, metadata: Array<GrpcMetadataEntry>, method: string | null, name: string, service: string | null, sortPriority: number, url: string, };
|
||||
|
||||
export type HttpRequest = { model: "http_request", id: string, createdAt: string, updatedAt: string, workspaceId: string, folderId: string | null, authentication: Record<string, any>, authenticationType: string | null, body: Record<string, any>, bodyType: string | null, description: string, headers: Array<HttpRequestHeader>, method: string, name: string, sortPriority: number, url: string, urlParameters: Array<HttpUrlParameter>, };
|
||||
|
||||
export type HttpRequestHeader = { enabled?: boolean, name: string, value: string, };
|
||||
export type HttpRequestHeader = { enabled?: boolean, name: string, value: string, id: string, };
|
||||
|
||||
export type HttpResponse = { model: "http_response", id: string, createdAt: string, updatedAt: string, workspaceId: string, requestId: string, bodyPath: string | null, contentLength: number | null, elapsed: number, elapsedHeaders: number, error: string | null, headers: Array<HttpResponseHeader>, remoteAddr: string | null, status: number, statusReason: string | null, state: HttpResponseState, url: string, version: string | null, };
|
||||
|
||||
@@ -20,6 +20,6 @@ export type HttpResponseHeader = { name: string, value: string, };
|
||||
|
||||
export type HttpResponseState = "initialized" | "connected" | "closed";
|
||||
|
||||
export type HttpUrlParameter = { enabled?: boolean, name: string, value: string, };
|
||||
export type HttpUrlParameter = { enabled?: boolean, name: string, value: string, id: string, };
|
||||
|
||||
export type Workspace = { model: "workspace", id: string, createdAt: string, updatedAt: string, name: string, description: string, settingValidateCertificates: boolean, settingFollowRedirects: boolean, settingRequestTimeout: number, };
|
||||
|
||||
@@ -18,6 +18,7 @@ export function FormMultipartEditor({ request, forceUpdateKey, onChange }: Props
|
||||
value: p.file ?? p.value,
|
||||
contentType: p.contentType,
|
||||
isFile: !!p.file,
|
||||
id: p.id,
|
||||
})),
|
||||
[request.body.form],
|
||||
);
|
||||
@@ -31,6 +32,7 @@ export function FormMultipartEditor({ request, forceUpdateKey, onChange }: Props
|
||||
contentType: p.contentType,
|
||||
file: p.isFile ? p.value : undefined,
|
||||
value: p.isFile ? undefined : p.value,
|
||||
id: p.id,
|
||||
})),
|
||||
}),
|
||||
[onChange],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import type { HttpRequest } from '@yaakapp-internal/models';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import type { Pair, PairEditorProps } from './core/PairEditor';
|
||||
import { PairOrBulkEditor } from './core/PairOrBulkEditor';
|
||||
|
||||
@@ -16,6 +16,7 @@ export function FormUrlencodedEditor({ request, forceUpdateKey, onChange }: Prop
|
||||
enabled: !!p.enabled,
|
||||
name: p.name || '',
|
||||
value: p.value || '',
|
||||
id: p.id,
|
||||
})),
|
||||
[request.body.form],
|
||||
);
|
||||
|
||||
@@ -136,12 +136,8 @@ export function GrpcConnectionSetupPane({
|
||||
() => [
|
||||
{
|
||||
value: TAB_DESCRIPTION,
|
||||
label: (
|
||||
<div className="flex items-center">
|
||||
Info
|
||||
{activeRequest.description && <CountBadge count={true} />}
|
||||
</div>
|
||||
),
|
||||
label: 'Info',
|
||||
rightSlot: activeRequest.description && <CountBadge count={true} />,
|
||||
},
|
||||
{ value: TAB_MESSAGE, label: 'Message' },
|
||||
{
|
||||
@@ -187,10 +183,10 @@ export function GrpcConnectionSetupPane({
|
||||
|
||||
const activeTab = activeTabs?.[activeRequest.id];
|
||||
const setActiveTab = useCallback(
|
||||
(tab: string) => {
|
||||
setActiveTabs((r) => ({ ...r, [activeRequest.id]: tab }));
|
||||
},
|
||||
[activeRequest.id, setActiveTabs],
|
||||
(tab: string) => {
|
||||
setActiveTabs((r) => ({ ...r, [activeRequest.id]: tab }));
|
||||
},
|
||||
[activeRequest.id, setActiveTabs],
|
||||
);
|
||||
|
||||
const handleMetadataChange = useCallback(
|
||||
@@ -224,7 +220,7 @@ export function GrpcConnectionSetupPane({
|
||||
onUrlChange={handleChangeUrl}
|
||||
onCancel={onCancel}
|
||||
isLoading={isStreaming}
|
||||
stateKey={'grpc_url.'+activeRequest.id}
|
||||
stateKey={'grpc_url.' + activeRequest.id}
|
||||
/>
|
||||
<HStack space={1.5}>
|
||||
<RadioDropdown
|
||||
|
||||
@@ -23,7 +23,7 @@ export function HttpRequestLayout({ activeRequest, style }: Props) {
|
||||
fullHeight={orientation === 'horizontal'}
|
||||
/>
|
||||
)}
|
||||
secondSlot={({ style }) => <ResponsePane activeRequest={activeRequest} style={style} />}
|
||||
secondSlot={({ style }) => <ResponsePane activeRequestId={activeRequest.id} style={style} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,26 +1,29 @@
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import classNames from 'classnames';
|
||||
import { useMemo, useRef } from 'react';
|
||||
import { useCallback, useMemo, useRef } from 'react';
|
||||
import { useKeyPressEvent } from 'react-use';
|
||||
import { useActiveRequest } from '../hooks/useActiveRequest';
|
||||
import { useActiveWorkspace } from '../hooks/useActiveWorkspace';
|
||||
import { getActiveWorkspaceId } from '../hooks/useActiveWorkspace';
|
||||
import { grpcRequestsAtom } from '../hooks/useGrpcRequests';
|
||||
import { useHotKey } from '../hooks/useHotKey';
|
||||
import { httpRequestsAtom } from '../hooks/useHttpRequests';
|
||||
import { useRecentRequests } from '../hooks/useRecentRequests';
|
||||
import { useRequests } from '../hooks/useRequests';
|
||||
import { fallbackRequestName } from '../lib/fallbackRequestName';
|
||||
import type { ButtonProps } from './core/Button';
|
||||
import { jotaiStore } from '../lib/jotai';
|
||||
import { Button } from './core/Button';
|
||||
import type { DropdownItem, DropdownRef } from './core/Dropdown';
|
||||
import { Dropdown } from './core/Dropdown';
|
||||
import { HttpMethodTag } from './core/HttpMethodTag';
|
||||
|
||||
export function RecentRequestsDropdown({ className }: Pick<ButtonProps, 'className'>) {
|
||||
interface Props {
|
||||
activeRequestId: string | null;
|
||||
activeRequestName: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RecentRequestsDropdown({ className, activeRequestId, activeRequestName }: Props) {
|
||||
const dropdownRef = useRef<DropdownRef>(null);
|
||||
const activeRequest = useActiveRequest();
|
||||
const activeWorkspace = useActiveWorkspace();
|
||||
const [allRecentRequestIds] = useRecentRequests();
|
||||
const recentRequestIds = useMemo(() => allRecentRequestIds.slice(1), [allRecentRequestIds]);
|
||||
const requests = useRequests();
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Handle key-up
|
||||
@@ -39,9 +42,11 @@ export function RecentRequestsDropdown({ className }: Pick<ButtonProps, 'classNa
|
||||
dropdownRef.current?.prev?.();
|
||||
});
|
||||
|
||||
const items = useMemo<DropdownItem[]>(() => {
|
||||
if (activeWorkspace === null) return [];
|
||||
const getItems = useCallback(() => {
|
||||
const activeWorkspaceId = getActiveWorkspaceId();
|
||||
if (activeWorkspaceId === null) return [];
|
||||
|
||||
const requests = [...jotaiStore.get(httpRequestsAtom), ...jotaiStore.get(grpcRequestsAtom)];
|
||||
const recentRequestItems: DropdownItem[] = [];
|
||||
for (const id of recentRequestIds) {
|
||||
const request = requests.find((r) => r.id === id);
|
||||
@@ -57,7 +62,7 @@ export function RecentRequestsDropdown({ className }: Pick<ButtonProps, 'classNa
|
||||
to: '/workspaces/$workspaceId/requests/$requestId',
|
||||
params: {
|
||||
requestId: request.id,
|
||||
workspaceId: activeWorkspace.id,
|
||||
workspaceId: activeWorkspaceId,
|
||||
},
|
||||
search: (prev) => ({ ...prev }),
|
||||
});
|
||||
@@ -77,10 +82,10 @@ export function RecentRequestsDropdown({ className }: Pick<ButtonProps, 'classNa
|
||||
}
|
||||
|
||||
return recentRequestItems.slice(0, 20);
|
||||
}, [activeWorkspace, navigate, recentRequestIds, requests]);
|
||||
}, [navigate, recentRequestIds]);
|
||||
|
||||
return (
|
||||
<Dropdown ref={dropdownRef} items={items}>
|
||||
<Dropdown ref={dropdownRef} items={getItems}>
|
||||
<Button
|
||||
data-tauri-drag-region
|
||||
size="sm"
|
||||
@@ -88,10 +93,10 @@ export function RecentRequestsDropdown({ className }: Pick<ButtonProps, 'classNa
|
||||
className={classNames(
|
||||
className,
|
||||
'truncate pointer-events-auto',
|
||||
activeRequest === null && 'text-text-subtlest italic',
|
||||
activeRequestId === null && 'text-text-subtlest italic',
|
||||
)}
|
||||
>
|
||||
{fallbackRequestName(activeRequest)}
|
||||
{activeRequestName}
|
||||
</Button>
|
||||
</Dropdown>
|
||||
);
|
||||
|
||||
@@ -17,6 +17,7 @@ import { useToast } from '../hooks/useToast';
|
||||
import { useUpdateAnyHttpRequest } from '../hooks/useUpdateAnyHttpRequest';
|
||||
import { languageFromContentType } from '../lib/contentType';
|
||||
import { tryFormatJson } from '../lib/formatters';
|
||||
import { generateId } from '../lib/generateId';
|
||||
import {
|
||||
AUTH_TYPE_BASIC,
|
||||
AUTH_TYPE_BEARER,
|
||||
@@ -86,6 +87,11 @@ export const RequestPane = memo(function RequestPane({
|
||||
|
||||
const handleContentTypeChange = useCallback(
|
||||
async (contentType: string | null) => {
|
||||
if (activeRequest == null || activeRequest.model !== 'http_request') {
|
||||
console.error('Failed to get active request to update', activeRequest);
|
||||
return;
|
||||
}
|
||||
|
||||
const headers = activeRequest.headers.filter((h) => h.name.toLowerCase() !== 'content-type');
|
||||
|
||||
if (contentType != null) {
|
||||
@@ -93,14 +99,15 @@ export const RequestPane = memo(function RequestPane({
|
||||
name: 'Content-Type',
|
||||
value: contentType,
|
||||
enabled: true,
|
||||
id: generateId(),
|
||||
});
|
||||
}
|
||||
await updateRequest.mutateAsync({ id: activeRequestId, update: { headers } });
|
||||
await updateRequest.mutateAsync({ id: activeRequest.id, update: { headers } });
|
||||
|
||||
// Force update header editor so any changed headers are reflected
|
||||
setTimeout(() => setForceUpdateHeaderEditorKey((u) => u + 1), 100);
|
||||
},
|
||||
[activeRequest.headers, activeRequestId, updateRequest],
|
||||
[activeRequest, updateRequest],
|
||||
);
|
||||
|
||||
const toast = useToast();
|
||||
@@ -116,51 +123,39 @@ export const RequestPane = memo(function RequestPane({
|
||||
if (index >= 0) {
|
||||
items[index]!.readOnlyName = true;
|
||||
} else {
|
||||
items.push({ name, value: '', enabled: true, readOnlyName: true });
|
||||
items.push({ name, value: '', enabled: true, readOnlyName: true, id: generateId() });
|
||||
}
|
||||
}
|
||||
return { urlParameterPairs: items, urlParametersKey: placeholderNames.join(',') };
|
||||
}, [activeRequest.url, activeRequest.urlParameters]);
|
||||
|
||||
const tabs: TabItem[] = useMemo(
|
||||
let numParams = 0;
|
||||
if (
|
||||
activeRequest.bodyType === BODY_TYPE_FORM_URLENCODED ||
|
||||
activeRequest.bodyType === BODY_TYPE_FORM_MULTIPART
|
||||
) {
|
||||
const n = Array.isArray(activeRequest.body?.form)
|
||||
? activeRequest.body.form.filter((p) => p.name).length
|
||||
: 0;
|
||||
numParams = n;
|
||||
}
|
||||
|
||||
const tabs = useMemo<TabItem[]>(
|
||||
() => [
|
||||
{
|
||||
value: TAB_DESCRIPTION,
|
||||
label: (
|
||||
<div className="flex items-center">
|
||||
Info
|
||||
{activeRequest.description && <CountBadge count={true} />}
|
||||
</div>
|
||||
),
|
||||
label: 'Info',
|
||||
rightSlot: activeRequest.description ? <CountBadge count={true} /> : null,
|
||||
},
|
||||
{
|
||||
value: TAB_BODY,
|
||||
rightSlot: numParams > 0 ? <CountBadge count={numParams} /> : null,
|
||||
options: {
|
||||
value: activeRequest.bodyType,
|
||||
items: [
|
||||
{ type: 'separator', label: 'Form Data' },
|
||||
{
|
||||
label: (
|
||||
<>
|
||||
Url Encoded
|
||||
<CountBadge
|
||||
count={'form' in activeRequest.body && activeRequest.body.form.length}
|
||||
/>
|
||||
</>
|
||||
),
|
||||
value: BODY_TYPE_FORM_URLENCODED,
|
||||
},
|
||||
{
|
||||
label: (
|
||||
<>
|
||||
Url Encoded
|
||||
<CountBadge
|
||||
count={'form' in activeRequest.body && activeRequest.body.form.length}
|
||||
/>
|
||||
</>
|
||||
),
|
||||
value: BODY_TYPE_FORM_MULTIPART,
|
||||
},
|
||||
{ label: 'Url Encoded', value: BODY_TYPE_FORM_URLENCODED },
|
||||
{ label: 'Multi-Part', value: BODY_TYPE_FORM_MULTIPART },
|
||||
{ type: 'separator', label: 'Text Content' },
|
||||
{ label: 'GraphQL', value: BODY_TYPE_GRAPHQL },
|
||||
{ label: 'JSON', value: BODY_TYPE_JSON },
|
||||
@@ -221,21 +216,13 @@ export const RequestPane = memo(function RequestPane({
|
||||
},
|
||||
{
|
||||
value: TAB_PARAMS,
|
||||
label: (
|
||||
<div className="flex items-center">
|
||||
Params
|
||||
<CountBadge count={urlParameterPairs.length} />
|
||||
</div>
|
||||
),
|
||||
rightSlot: <CountBadge count={urlParameterPairs.length} />,
|
||||
label: 'Params',
|
||||
},
|
||||
{
|
||||
value: TAB_HEADERS,
|
||||
label: (
|
||||
<div className="flex items-center">
|
||||
Headers
|
||||
<CountBadge count={activeRequest.headers.filter((h) => h.name).length} />
|
||||
</div>
|
||||
),
|
||||
label: 'Headers',
|
||||
rightSlot: <CountBadge count={activeRequest.headers.filter((h) => h.name).length} />,
|
||||
},
|
||||
{
|
||||
value: TAB_AUTH,
|
||||
@@ -271,13 +258,13 @@ export const RequestPane = memo(function RequestPane({
|
||||
[
|
||||
activeRequest.authentication,
|
||||
activeRequest.authenticationType,
|
||||
activeRequest.body,
|
||||
activeRequest.bodyType,
|
||||
activeRequest.description,
|
||||
activeRequest.headers,
|
||||
activeRequest.method,
|
||||
activeRequestId,
|
||||
handleContentTypeChange,
|
||||
numParams,
|
||||
toast,
|
||||
updateRequest,
|
||||
urlParameterPairs.length,
|
||||
@@ -285,7 +272,7 @@ export const RequestPane = memo(function RequestPane({
|
||||
);
|
||||
|
||||
const sendRequest = useSendAnyHttpRequest();
|
||||
const { activeResponse } = usePinnedHttpResponse(activeRequest);
|
||||
const { activeResponse } = usePinnedHttpResponse(activeRequestId);
|
||||
const cancelResponse = useCancelHttpResponse(activeResponse?.id ?? null);
|
||||
const isLoading = useIsResponseLoading(activeRequestId);
|
||||
const { updateKey } = useRequestUpdateKey(activeRequestId);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { HttpRequest, HttpResponse } from '@yaakapp-internal/models';
|
||||
import type { HttpResponse } from '@yaakapp-internal/models';
|
||||
import classNames from 'classnames';
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
import React, { memo, useCallback, useMemo } from 'react';
|
||||
@@ -32,15 +32,19 @@ import { VideoViewer } from './responseViewers/VideoViewer';
|
||||
interface Props {
|
||||
style?: CSSProperties;
|
||||
className?: string;
|
||||
activeRequest: HttpRequest;
|
||||
activeRequestId: string;
|
||||
}
|
||||
|
||||
const TAB_BODY = 'body';
|
||||
const TAB_HEADERS = 'headers';
|
||||
const TAB_INFO = 'info';
|
||||
|
||||
export const ResponsePane = memo(function ResponsePane({ style, className, activeRequest }: Props) {
|
||||
const { activeResponse, setPinnedResponseId, responses } = usePinnedHttpResponse(activeRequest);
|
||||
export const ResponsePane = memo(function ResponsePane({
|
||||
style,
|
||||
className,
|
||||
activeRequestId,
|
||||
}: Props) {
|
||||
const { activeResponse, setPinnedResponseId, responses } = usePinnedHttpResponse(activeRequestId);
|
||||
const [viewMode, setViewMode] = useResponseViewMode(activeResponse?.requestId);
|
||||
const [activeTabs, setActiveTabs] = useLocalStorage<Record<string, string>>(
|
||||
'responsePaneActiveTabs',
|
||||
@@ -64,13 +68,11 @@ export const ResponsePane = memo(function ResponsePane({ style, className, activ
|
||||
},
|
||||
{
|
||||
value: TAB_HEADERS,
|
||||
label: (
|
||||
<div className="flex items-center">
|
||||
Headers
|
||||
<CountBadge
|
||||
count={activeResponse?.headers.filter((h) => h.name && h.value).length ?? 0}
|
||||
/>
|
||||
</div>
|
||||
label: 'Headers',
|
||||
rightSlot: (
|
||||
<CountBadge
|
||||
count={activeResponse?.headers.filter((h) => h.name && h.value).length ?? 0}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -80,12 +82,12 @@ export const ResponsePane = memo(function ResponsePane({ style, className, activ
|
||||
],
|
||||
[activeResponse?.headers, contentType, setViewMode, viewMode],
|
||||
);
|
||||
const activeTab = activeTabs?.[activeRequest.id];
|
||||
const activeTab = activeTabs?.[activeRequestId];
|
||||
const setActiveTab = useCallback(
|
||||
(tab: string) => {
|
||||
setActiveTabs((r) => ({ ...r, [activeRequest.id]: tab }));
|
||||
},
|
||||
[activeRequest.id, setActiveTabs],
|
||||
(tab: string) => {
|
||||
setActiveTabs((r) => ({ ...r, [activeRequestId]: tab }));
|
||||
},
|
||||
[activeRequestId, setActiveTabs],
|
||||
);
|
||||
|
||||
const isLoading = isResponseLoading(activeResponse);
|
||||
@@ -150,7 +152,7 @@ export const ResponsePane = memo(function ResponsePane({ style, className, activ
|
||||
</Banner>
|
||||
) : (
|
||||
<Tabs
|
||||
key={activeRequest.id} // Freshen tabs on request change
|
||||
key={activeRequestId} // Freshen tabs on request change
|
||||
value={activeTab}
|
||||
onChangeValue={setActiveTab}
|
||||
tabs={tabs}
|
||||
|
||||
@@ -1,24 +1,22 @@
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import type { Folder, GrpcRequest, HttpRequest, Workspace } from '@yaakapp-internal/models';
|
||||
import type { AnyModel, Folder, GrpcRequest, HttpRequest } from '@yaakapp-internal/models';
|
||||
import classNames from 'classnames';
|
||||
import { useAtom } from 'jotai';
|
||||
import React, { memo, useCallback, useMemo, useRef, useState } from 'react';
|
||||
import { useAtom, useAtomValue } from 'jotai';
|
||||
import React, { useCallback, useRef, useState } from 'react';
|
||||
import { useKey, useKeyPressEvent } from 'react-use';
|
||||
import { getActiveRequest } from '../hooks/useActiveRequest';
|
||||
import { useActiveWorkspace } from '../hooks/useActiveWorkspace';
|
||||
import { useCreateDropdownItems } from '../hooks/useCreateDropdownItems';
|
||||
import { useFolders } from '../hooks/useFolders';
|
||||
import { useGrpcConnections } from '../hooks/useGrpcConnections';
|
||||
import { useHotKey } from '../hooks/useHotKey';
|
||||
import { useHttpResponses } from '../hooks/useHttpResponses';
|
||||
import { useRequests } from '../hooks/useRequests';
|
||||
import { useSidebarHidden } from '../hooks/useSidebarHidden';
|
||||
import { getSidebarCollapsedMap } from '../hooks/useSidebarItemCollapsed';
|
||||
import { useUpdateAnyFolder } from '../hooks/useUpdateAnyFolder';
|
||||
import { useUpdateAnyGrpcRequest } from '../hooks/useUpdateAnyGrpcRequest';
|
||||
import { useUpdateAnyHttpRequest } from '../hooks/useUpdateAnyHttpRequest';
|
||||
import { ContextMenu } from './core/Dropdown';
|
||||
import { sidebarSelectedIdAtom } from './SidebarAtoms';
|
||||
import { sidebarSelectedIdAtom, sidebarTreeAtom } from './SidebarAtoms';
|
||||
import type { SidebarItemProps } from './SidebarItem';
|
||||
import { SidebarItems } from './SidebarItems';
|
||||
|
||||
@@ -27,16 +25,21 @@ interface Props {
|
||||
}
|
||||
|
||||
export interface SidebarTreeNode {
|
||||
item: Workspace | Folder | HttpRequest | GrpcRequest;
|
||||
id: string;
|
||||
name: string;
|
||||
model: AnyModel['model'];
|
||||
sortPriority?: number;
|
||||
workspaceId?: string;
|
||||
folderId?: string | null;
|
||||
children: SidebarTreeNode[];
|
||||
depth: number;
|
||||
}
|
||||
|
||||
export const Sidebar = memo(function Sidebar({ className }: Props) {
|
||||
export type SidebarModel = Folder | GrpcRequest | HttpRequest;
|
||||
|
||||
export function Sidebar({ className }: Props) {
|
||||
const [hidden, setHidden] = useSidebarHidden();
|
||||
const sidebarRef = useRef<HTMLLIElement>(null);
|
||||
const folders = useFolders();
|
||||
const requests = useRequests();
|
||||
const activeWorkspace = useActiveWorkspace();
|
||||
const httpResponses = useHttpResponses();
|
||||
const grpcConnections = useGrpcConnections();
|
||||
@@ -51,64 +54,7 @@ export const Sidebar = memo(function Sidebar({ className }: Props) {
|
||||
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { tree, treeParentMap, selectableRequests } = useMemo<{
|
||||
tree: SidebarTreeNode | null;
|
||||
treeParentMap: Record<string, SidebarTreeNode>;
|
||||
selectableRequests: {
|
||||
id: string;
|
||||
index: number;
|
||||
tree: SidebarTreeNode;
|
||||
}[];
|
||||
}>(() => {
|
||||
const childrenMap: Record<string, (HttpRequest | GrpcRequest | Folder)[]> = {};
|
||||
for (const item of [...requests, ...folders]) {
|
||||
if (item.folderId == null) {
|
||||
childrenMap[item.workspaceId] = childrenMap[item.workspaceId] ?? [];
|
||||
childrenMap[item.workspaceId]!.push(item);
|
||||
} else {
|
||||
childrenMap[item.folderId] = childrenMap[item.folderId] ?? [];
|
||||
childrenMap[item.folderId]!.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
const treeParentMap: Record<string, SidebarTreeNode> = {};
|
||||
const selectableRequests: {
|
||||
id: string;
|
||||
index: number;
|
||||
tree: SidebarTreeNode;
|
||||
}[] = [];
|
||||
|
||||
if (activeWorkspace == null) {
|
||||
return { tree: null, treeParentMap, selectableRequests };
|
||||
}
|
||||
|
||||
const selectedRequest: HttpRequest | GrpcRequest | null = null;
|
||||
let selectableRequestIndex = 0;
|
||||
|
||||
// Put requests and folders into a tree structure
|
||||
const next = (node: SidebarTreeNode): SidebarTreeNode => {
|
||||
const childItems = childrenMap[node.item.id] ?? [];
|
||||
|
||||
// Recurse to children
|
||||
const depth = node.depth + 1;
|
||||
childItems.sort((a, b) => a.sortPriority - b.sortPriority);
|
||||
for (const item of childItems) {
|
||||
treeParentMap[item.id] = node;
|
||||
// Add to children
|
||||
node.children.push(next({ item, children: [], depth }));
|
||||
// Add to selectable requests
|
||||
if (item.model !== 'folder') {
|
||||
selectableRequests.push({ id: item.id, index: selectableRequestIndex++, tree: node });
|
||||
}
|
||||
}
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
const tree = next({ item: activeWorkspace, children: [], depth: 0 });
|
||||
|
||||
return { tree, treeParentMap, selectableRequests, selectedRequest };
|
||||
}, [activeWorkspace, requests, folders]);
|
||||
const { tree, treeParentMap, selectableRequests } = useAtomValue(sidebarTreeAtom);
|
||||
|
||||
const focusActiveRequest = useCallback(
|
||||
(
|
||||
@@ -124,8 +70,7 @@ export const Sidebar = memo(function Sidebar({ className }: Props) {
|
||||
const { forced, noFocusSidebar } = args;
|
||||
const tree = forced?.tree ?? treeParentMap[activeRequest?.id ?? 'n/a'] ?? null;
|
||||
const children = tree?.children ?? [];
|
||||
const id =
|
||||
forced?.id ?? children.find((m) => m.item.id === activeRequest?.id)?.item.id ?? null;
|
||||
const id = forced?.id ?? children.find((m) => m.id === activeRequest?.id)?.id ?? null;
|
||||
|
||||
setHasFocus(true);
|
||||
setSelectedId(id);
|
||||
@@ -145,19 +90,17 @@ export const Sidebar = memo(function Sidebar({ className }: Props) {
|
||||
async (id: string) => {
|
||||
const tree = treeParentMap[id ?? 'n/a'] ?? null;
|
||||
const children = tree?.children ?? [];
|
||||
const node = children.find((m) => m.item.id === id) ?? null;
|
||||
if (node == null || tree == null || node.item.model === 'workspace') {
|
||||
const node = children.find((m) => m.id === id) ?? null;
|
||||
if (node == null || tree == null || node.model === 'workspace') {
|
||||
return;
|
||||
}
|
||||
|
||||
const { item } = node;
|
||||
|
||||
if (item.model === 'http_request' || item.model === 'grpc_request') {
|
||||
if (node.model === 'http_request' || node.model === 'grpc_request') {
|
||||
await navigate({
|
||||
to: '/workspaces/$workspaceId/requests/$requestId',
|
||||
params: {
|
||||
requestId: id,
|
||||
workspaceId: item.workspaceId,
|
||||
workspaceId: node.workspaceId ?? 'n/a',
|
||||
},
|
||||
search: (prev) => ({ ...prev }),
|
||||
});
|
||||
@@ -259,14 +202,15 @@ export const Sidebar = memo(function Sidebar({ className }: Props) {
|
||||
const handleMove = useCallback<SidebarItemProps['onMove']>(
|
||||
async (id, side) => {
|
||||
let hoveredTree = treeParentMap[id] ?? null;
|
||||
const dragIndex = hoveredTree?.children.findIndex((n) => n.item.id === id) ?? -99;
|
||||
const hoveredItem = hoveredTree?.children[dragIndex]?.item ?? null;
|
||||
const dragIndex = hoveredTree?.children.findIndex((n) => n.id === id) ?? -99;
|
||||
const hoveredItem = hoveredTree?.children[dragIndex] ?? null;
|
||||
let hoveredIndex = dragIndex + (side === 'above' ? 0 : 1);
|
||||
|
||||
const isHoveredItemCollapsed = hoveredItem != null ? getSidebarCollapsedMap()[hoveredItem.id] : false;
|
||||
const isHoveredItemCollapsed =
|
||||
hoveredItem != null ? getSidebarCollapsedMap()[hoveredItem.id] : false;
|
||||
if (hoveredItem?.model === 'folder' && side === 'below' && !isHoveredItemCollapsed) {
|
||||
// Move into the folder if it's open and we're moving below it
|
||||
hoveredTree = hoveredTree?.children.find((n) => n.item.id === id) ?? null;
|
||||
hoveredTree = hoveredTree?.children.find((n) => n.id === id) ?? null;
|
||||
hoveredIndex = 0;
|
||||
}
|
||||
|
||||
@@ -290,19 +234,19 @@ export const Sidebar = memo(function Sidebar({ className }: Props) {
|
||||
}
|
||||
|
||||
// Block dragging folder into itself
|
||||
if (hoveredTree.item.id === itemId) {
|
||||
if (hoveredTree.id === itemId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parentTree = treeParentMap[itemId] ?? null;
|
||||
const index = parentTree?.children.findIndex((n) => n.item.id === itemId) ?? -1;
|
||||
const index = parentTree?.children.findIndex((n) => n.id === itemId) ?? -1;
|
||||
const child = parentTree?.children[index ?? -1];
|
||||
if (child == null || parentTree == null) return;
|
||||
|
||||
const movedToDifferentTree = hoveredTree.item.id !== parentTree.item.id;
|
||||
const movedToDifferentTree = hoveredTree.id !== parentTree.id;
|
||||
const movedUpInSameTree = !movedToDifferentTree && hoveredIndex < index;
|
||||
|
||||
const newChildren = hoveredTree.children.filter((c) => c.item.id !== itemId);
|
||||
const newChildren = hoveredTree.children.filter((c) => c.id !== itemId);
|
||||
if (movedToDifferentTree || movedUpInSameTree) {
|
||||
// Moving up or into a new tree is simply inserting before the hovered item
|
||||
newChildren.splice(hoveredIndex, 0, child);
|
||||
@@ -311,42 +255,42 @@ export const Sidebar = memo(function Sidebar({ className }: Props) {
|
||||
newChildren.splice(hoveredIndex - 1, 0, child);
|
||||
}
|
||||
|
||||
const insertedIndex = newChildren.findIndex((c) => c.item === child.item);
|
||||
const prev = newChildren[insertedIndex - 1]?.item;
|
||||
const next = newChildren[insertedIndex + 1]?.item;
|
||||
const beforePriority = prev == null || prev.model === 'workspace' ? 0 : prev.sortPriority;
|
||||
const afterPriority = next == null || next.model === 'workspace' ? 0 : next.sortPriority;
|
||||
const insertedIndex = newChildren.findIndex((c) => c.id === child.id);
|
||||
const prev = newChildren[insertedIndex - 1];
|
||||
const next = newChildren[insertedIndex + 1];
|
||||
const beforePriority = prev?.sortPriority ?? 0;
|
||||
const afterPriority = next?.sortPriority ?? 0;
|
||||
|
||||
const folderId = hoveredTree.item.model === 'folder' ? hoveredTree.item.id : null;
|
||||
const folderId = hoveredTree.model === 'folder' ? hoveredTree.id : null;
|
||||
const shouldUpdateAll = afterPriority - beforePriority < 1;
|
||||
|
||||
if (shouldUpdateAll) {
|
||||
await Promise.all(
|
||||
newChildren.map((child, i) => {
|
||||
const sortPriority = i * 1000;
|
||||
if (child.item.model === 'folder') {
|
||||
if (child.model === 'folder') {
|
||||
const updateFolder = (f: Folder) => ({ ...f, sortPriority, folderId });
|
||||
return updateAnyFolder({ id: child.item.id, update: updateFolder });
|
||||
} else if (child.item.model === 'grpc_request') {
|
||||
return updateAnyFolder({ id: child.id, update: updateFolder });
|
||||
} else if (child.model === 'grpc_request') {
|
||||
const updateRequest = (r: GrpcRequest) => ({ ...r, sortPriority, folderId });
|
||||
return updateAnyGrpcRequest({ id: child.item.id, update: updateRequest });
|
||||
} else if (child.item.model === 'http_request') {
|
||||
return updateAnyGrpcRequest({ id: child.id, update: updateRequest });
|
||||
} else if (child.model === 'http_request') {
|
||||
const updateRequest = (r: HttpRequest) => ({ ...r, sortPriority, folderId });
|
||||
return updateAnyHttpRequest({ id: child.item.id, update: updateRequest });
|
||||
return updateAnyHttpRequest({ id: child.id, update: updateRequest });
|
||||
}
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
const sortPriority = afterPriority - (afterPriority - beforePriority) / 2;
|
||||
if (child.item.model === 'folder') {
|
||||
if (child.model === 'folder') {
|
||||
const updateFolder = (f: Folder) => ({ ...f, sortPriority, folderId });
|
||||
await updateAnyFolder({ id: child.item.id, update: updateFolder });
|
||||
} else if (child.item.model === 'grpc_request') {
|
||||
await updateAnyFolder({ id: child.id, update: updateFolder });
|
||||
} else if (child.model === 'grpc_request') {
|
||||
const updateRequest = (r: GrpcRequest) => ({ ...r, sortPriority, folderId });
|
||||
await updateAnyGrpcRequest({ id: child.item.id, update: updateRequest });
|
||||
} else if (child.item.model === 'http_request') {
|
||||
await updateAnyGrpcRequest({ id: child.id, update: updateRequest });
|
||||
} else if (child.model === 'http_request') {
|
||||
const updateRequest = (r: HttpRequest) => ({ ...r, sortPriority, folderId });
|
||||
await updateAnyHttpRequest({ id: child.item.id, update: updateRequest });
|
||||
await updateAnyHttpRequest({ id: child.id, update: updateRequest });
|
||||
}
|
||||
}
|
||||
setDraggingId(null);
|
||||
@@ -420,4 +364,4 @@ export const Sidebar = memo(function Sidebar({ className }: Props) {
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,125 @@
|
||||
import deepEqual from '@gilbarbara/deep-equal';
|
||||
import type { Folder, GrpcRequest, HttpRequest } from '@yaakapp-internal/models';
|
||||
|
||||
// This is an atom so we can use it in the child items to avoid re-rendering the entire list
|
||||
import {atom} from "jotai/index";
|
||||
import { atom } from 'jotai';
|
||||
import { selectAtom } from 'jotai/utils';
|
||||
import { activeWorkspaceAtom } from '../hooks/useActiveWorkspace';
|
||||
import { foldersAtom } from '../hooks/useFolders';
|
||||
import { grpcRequestsAtom } from '../hooks/useGrpcRequests';
|
||||
import { httpRequestsAtom } from '../hooks/useHttpRequests';
|
||||
import { fallbackRequestName } from '../lib/fallbackRequestName';
|
||||
import type { SidebarTreeNode } from './Sidebar';
|
||||
|
||||
export const sidebarSelectedIdAtom = atom<string | null>(null);
|
||||
|
||||
const allPotentialChildrenAtom = atom((get) => {
|
||||
const httpRequests = get(httpRequestsAtom);
|
||||
const grpcRequests = get(grpcRequestsAtom);
|
||||
const folders = get(foldersAtom);
|
||||
return [...httpRequests, ...folders, ...grpcRequests].map((v) => ({
|
||||
id: v.id,
|
||||
model: v.model,
|
||||
folderId: v.folderId,
|
||||
name: fallbackRequestName(v),
|
||||
workspaceId: v.workspaceId,
|
||||
sortPriority: v.sortPriority,
|
||||
}));
|
||||
});
|
||||
|
||||
const memoAllPotentialChildrenAtom = selectAtom(
|
||||
allPotentialChildrenAtom,
|
||||
(v) => v,
|
||||
(a, b) => deepEqual(a, b),
|
||||
);
|
||||
|
||||
export const sidebarTreeAtom = atom<{
|
||||
tree: SidebarTreeNode | null;
|
||||
treeParentMap: Record<string, SidebarTreeNode>;
|
||||
selectableRequests: {
|
||||
id: string;
|
||||
index: number;
|
||||
tree: SidebarTreeNode;
|
||||
}[];
|
||||
}>((get) => {
|
||||
const allModels = get(memoAllPotentialChildrenAtom);
|
||||
const activeWorkspace = get(activeWorkspaceAtom);
|
||||
|
||||
const childrenMap: Record<string, typeof allModels> = {};
|
||||
for (const item of allModels) {
|
||||
if ('folderId' in item && item.folderId == null) {
|
||||
childrenMap[item.workspaceId] = childrenMap[item.workspaceId] ?? [];
|
||||
childrenMap[item.workspaceId]!.push(item);
|
||||
} else if ('folderId' in item && item.folderId != null) {
|
||||
childrenMap[item.folderId] = childrenMap[item.folderId] ?? [];
|
||||
childrenMap[item.folderId]!.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
const treeParentMap: Record<string, SidebarTreeNode> = {};
|
||||
const selectableRequests: {
|
||||
id: string;
|
||||
index: number;
|
||||
tree: SidebarTreeNode;
|
||||
}[] = [];
|
||||
|
||||
if (activeWorkspace == null) {
|
||||
return { tree: null, treeParentMap, selectableRequests };
|
||||
}
|
||||
|
||||
const selectedRequest: HttpRequest | GrpcRequest | null = null;
|
||||
let selectableRequestIndex = 0;
|
||||
|
||||
// Put requests and folders into a tree structure
|
||||
const next = (node: SidebarTreeNode): SidebarTreeNode => {
|
||||
const childItems = childrenMap[node.id] ?? [];
|
||||
|
||||
// Recurse to children
|
||||
const depth = node.depth + 1;
|
||||
childItems.sort((a, b) => a.sortPriority - b.sortPriority);
|
||||
for (const childItem of childItems) {
|
||||
treeParentMap[childItem.id] = node;
|
||||
// Add to children
|
||||
node.children.push(next(itemFromModel(childItem, depth)));
|
||||
// Add to selectable requests
|
||||
if (childItem.model !== 'folder') {
|
||||
selectableRequests.push({
|
||||
id: childItem.id,
|
||||
index: selectableRequestIndex++,
|
||||
tree: node,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
const tree = next({
|
||||
id: activeWorkspace.id,
|
||||
name: activeWorkspace.name,
|
||||
model: activeWorkspace.model,
|
||||
children: [],
|
||||
depth: 0,
|
||||
});
|
||||
|
||||
return { tree, treeParentMap, selectableRequests, selectedRequest };
|
||||
});
|
||||
|
||||
function itemFromModel(
|
||||
item: Pick<
|
||||
Folder | HttpRequest | GrpcRequest,
|
||||
'folderId' | 'model' | 'workspaceId' | 'id' | 'name' | 'sortPriority'
|
||||
>,
|
||||
depth = 0,
|
||||
): SidebarTreeNode {
|
||||
return {
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
model: item.model,
|
||||
sortPriority: 'sortPriority' in item ? item.sortPriority : -1,
|
||||
workspaceId: item.workspaceId,
|
||||
folderId: item.folderId,
|
||||
depth,
|
||||
children: [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import type { AnyModel, GrpcConnection, HttpResponse } from '@yaakapp-internal/models';
|
||||
import classNames from 'classnames';
|
||||
import { atom, useAtomValue } from 'jotai';
|
||||
import type { ReactNode } from 'react';
|
||||
import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { XYCoord } from 'react-dnd';
|
||||
import { useDrag, useDrop } from 'react-dnd';
|
||||
import { activeRequestAtom } from '../hooks/useActiveRequest';
|
||||
import { foldersAtom } from '../hooks/useFolders';
|
||||
import { grpcRequestsAtom } from '../hooks/useGrpcRequests';
|
||||
import { httpRequestsAtom } from '../hooks/useHttpRequests';
|
||||
import { useScrollIntoView } from '../hooks/useScrollIntoView';
|
||||
import { useSidebarItemCollapsed } from '../hooks/useSidebarItemCollapsed';
|
||||
import { useUpdateAnyGrpcRequest } from '../hooks/useUpdateAnyGrpcRequest';
|
||||
@@ -14,9 +18,9 @@ import { isResponseLoading } from '../lib/model_util';
|
||||
import { HttpMethodTag } from './core/HttpMethodTag';
|
||||
import { Icon } from './core/Icon';
|
||||
import { StatusTag } from './core/StatusTag';
|
||||
import { RequestContextMenu } from './RequestContextMenu';
|
||||
import type { SidebarTreeNode } from './Sidebar';
|
||||
import { sidebarSelectedIdAtom } from './SidebarAtoms';
|
||||
import { SidebarItemContextMenu } from './SidebarItemContextMenu';
|
||||
import type { SidebarItemsProps } from './SidebarItems';
|
||||
|
||||
enum ItemTypes {
|
||||
@@ -194,10 +198,29 @@ export const SidebarItem = memo(function SidebarItem({
|
||||
|
||||
const handleCloseContextMenu = useCallback(() => setShowContextMenu(null), []);
|
||||
|
||||
const itemPrefix = (child.item.model === 'http_request' ||
|
||||
child.item.model === 'grpc_request') && (
|
||||
const itemAtom = useMemo(() => {
|
||||
return atom((get) => {
|
||||
if (itemModel === 'http_request') {
|
||||
return get(httpRequestsAtom).find((v) => v.id === itemId);
|
||||
} else if (itemModel === 'grpc_request') {
|
||||
return get(grpcRequestsAtom).find((v) => v.id === itemId);
|
||||
} else if (itemModel === 'folder') {
|
||||
return get(foldersAtom).find((v) => v.id === itemId);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}, [itemId, itemModel])
|
||||
|
||||
const item = useAtomValue(itemAtom);
|
||||
|
||||
if (item == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const itemPrefix = (item.model === 'http_request' || item.model === 'grpc_request') && (
|
||||
<HttpMethodTag
|
||||
request={child.item}
|
||||
request={item}
|
||||
className={classNames(!(active || selected) && 'text-text-subtlest')}
|
||||
/>
|
||||
);
|
||||
@@ -205,7 +228,11 @@ export const SidebarItem = memo(function SidebarItem({
|
||||
return (
|
||||
<li ref={ref} draggable>
|
||||
<div className={classNames(className, 'block relative group/item px-1.5 pb-0.5')}>
|
||||
<RequestContextMenu child={child} show={showContextMenu} close={handleCloseContextMenu} />
|
||||
<SidebarItemContextMenu
|
||||
child={child}
|
||||
show={showContextMenu}
|
||||
close={handleCloseContextMenu}
|
||||
/>
|
||||
<button
|
||||
// tabIndex={-1} // Will prevent drag-n-drop
|
||||
disabled={editing}
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react';
|
||||
import { useCreateDropdownItems } from '../hooks/useCreateDropdownItems';
|
||||
import { useDeleteFolder } from '../hooks/useDeleteFolder';
|
||||
import { useDeleteRequest } from '../hooks/useDeleteRequest';
|
||||
import { useDialog } from '../hooks/useDialog';
|
||||
import { useDuplicateFolder } from '../hooks/useDuplicateFolder';
|
||||
import { useDuplicateGrpcRequest } from '../hooks/useDuplicateGrpcRequest';
|
||||
import { useDuplicateHttpRequest } from '../hooks/useDuplicateHttpRequest';
|
||||
@@ -15,7 +16,6 @@ import { getHttpRequest } from '../lib/store';
|
||||
import type { DropdownItem } from './core/Dropdown';
|
||||
import { ContextMenu } from './core/Dropdown';
|
||||
import { Icon } from './core/Icon';
|
||||
import { useDialog } from '../hooks/useDialog';
|
||||
import { FolderSettingsDialog } from './FolderSettingsDialog';
|
||||
import type { SidebarTreeNode } from './Sidebar';
|
||||
|
||||
@@ -25,31 +25,31 @@ interface Props {
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
export function RequestContextMenu({ child, show, close }: Props) {
|
||||
export function SidebarItemContextMenu({ child, show, close }: Props) {
|
||||
const sendManyRequests = useSendManyRequests();
|
||||
const duplicateFolder = useDuplicateFolder(child.item.id);
|
||||
const deleteFolder = useDeleteFolder(child.item.id);
|
||||
const duplicateFolder = useDuplicateFolder(child.id);
|
||||
const deleteFolder = useDeleteFolder(child.id);
|
||||
const httpRequestActions = useHttpRequestActions();
|
||||
const sendRequest = useSendAnyHttpRequest();
|
||||
const workspaces = useWorkspaces();
|
||||
const dialog = useDialog();
|
||||
const deleteRequest = useDeleteRequest(child.item.id);
|
||||
const renameRequest = useRenameRequest(child.item.id);
|
||||
const duplicateHttpRequest = useDuplicateHttpRequest({ id: child.item.id, navigateAfter: true });
|
||||
const duplicateGrpcRequest = useDuplicateGrpcRequest({ id: child.item.id, navigateAfter: true });
|
||||
const moveToWorkspace = useMoveToWorkspace(child.item.id);
|
||||
const deleteRequest = useDeleteRequest(child.id);
|
||||
const renameRequest = useRenameRequest(child.id);
|
||||
const duplicateHttpRequest = useDuplicateHttpRequest({ id: child.id, navigateAfter: true });
|
||||
const duplicateGrpcRequest = useDuplicateGrpcRequest({ id: child.id, navigateAfter: true });
|
||||
const moveToWorkspace = useMoveToWorkspace(child.id);
|
||||
const createDropdownItems = useCreateDropdownItems({
|
||||
folderId: child.item.model === 'folder' ? child.item.id : null,
|
||||
folderId: child.model === 'folder' ? child.id : null,
|
||||
});
|
||||
|
||||
const items = useMemo<DropdownItem[]>(() => {
|
||||
if (child.item.model === 'folder') {
|
||||
if (child.model === 'folder') {
|
||||
return [
|
||||
{
|
||||
key: 'send-all',
|
||||
label: 'Send All',
|
||||
leftSlot: <Icon icon="send_horizontal" />,
|
||||
onSelect: () => sendManyRequests.mutate(child.children.map((c) => c.item.id)),
|
||||
onSelect: () => sendManyRequests.mutate(child.children.map((c) => c.id)),
|
||||
},
|
||||
{
|
||||
key: 'folder-settings',
|
||||
@@ -60,7 +60,7 @@ export function RequestContextMenu({ child, show, close }: Props) {
|
||||
id: 'folder-settings',
|
||||
title: 'Folder Settings',
|
||||
size: 'md',
|
||||
render: () => <FolderSettingsDialog folderId={child.item.id} />,
|
||||
render: () => <FolderSettingsDialog folderId={child.id} />,
|
||||
}),
|
||||
},
|
||||
{
|
||||
@@ -81,7 +81,7 @@ export function RequestContextMenu({ child, show, close }: Props) {
|
||||
];
|
||||
} else {
|
||||
const requestItems: DropdownItem[] =
|
||||
child.item.model === 'http_request'
|
||||
child.model === 'http_request'
|
||||
? [
|
||||
{
|
||||
key: 'send-request',
|
||||
@@ -89,7 +89,7 @@ export function RequestContextMenu({ child, show, close }: Props) {
|
||||
hotKeyAction: 'http_request.send',
|
||||
hotKeyLabelOnly: true, // Already bound in URL bar
|
||||
leftSlot: <Icon icon="send_horizontal" />,
|
||||
onSelect: () => sendRequest.mutate(child.item.id),
|
||||
onSelect: () => sendRequest.mutate(child.id),
|
||||
},
|
||||
...httpRequestActions.map((a) => ({
|
||||
key: a.key,
|
||||
@@ -97,7 +97,7 @@ export function RequestContextMenu({ child, show, close }: Props) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
leftSlot: <Icon icon={(a.icon as any) ?? 'empty'} />,
|
||||
onSelect: async () => {
|
||||
const request = await getHttpRequest(child.item.id);
|
||||
const request = await getHttpRequest(child.id);
|
||||
if (request != null) await a.call(request);
|
||||
},
|
||||
})),
|
||||
@@ -119,7 +119,7 @@ export function RequestContextMenu({ child, show, close }: Props) {
|
||||
hotKeyLabelOnly: true, // Would trigger for every request (bad)
|
||||
leftSlot: <Icon icon="copy" />,
|
||||
onSelect: () =>
|
||||
child.item.model === 'http_request'
|
||||
child.model === 'http_request'
|
||||
? duplicateHttpRequest.mutate()
|
||||
: duplicateGrpcRequest.mutate(),
|
||||
},
|
||||
@@ -141,8 +141,8 @@ export function RequestContextMenu({ child, show, close }: Props) {
|
||||
}
|
||||
}, [
|
||||
child.children,
|
||||
child.item.id,
|
||||
child.item.model,
|
||||
child.id,
|
||||
child.model,
|
||||
createDropdownItems,
|
||||
deleteFolder,
|
||||
deleteRequest,
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { GrpcConnection, HttpResponse } from '@yaakapp-internal/models';
|
||||
import classNames from 'classnames';
|
||||
import React, { Fragment, memo } from 'react';
|
||||
import { fallbackRequestName } from '../lib/fallbackRequestName';
|
||||
import { VStack } from './core/Stacks';
|
||||
import { DropMarker } from './DropMarker';
|
||||
import type { SidebarTreeNode } from './Sidebar';
|
||||
@@ -50,20 +49,16 @@ export const SidebarItems = memo(function SidebarItems({
|
||||
>
|
||||
{tree.children.map((child, i) => {
|
||||
return (
|
||||
<Fragment key={child.item.id}>
|
||||
{hoveredIndex === i && hoveredTree?.item.id === tree.item.id && <DropMarker />}
|
||||
<Fragment key={child.id}>
|
||||
{hoveredIndex === i && hoveredTree?.id === tree.id && <DropMarker />}
|
||||
<SidebarItem
|
||||
itemId={child.item.id}
|
||||
itemName={child.item.name}
|
||||
itemFallbackName={
|
||||
child.item.model === 'http_request' || child.item.model === 'grpc_request'
|
||||
? fallbackRequestName(child.item)
|
||||
: 'New Folder'
|
||||
}
|
||||
itemModel={child.item.model}
|
||||
latestHttpResponse={httpResponses.find((r) => r.requestId === child.item.id) ?? null}
|
||||
itemId={child.id}
|
||||
itemName={child.name}
|
||||
itemFallbackName="TODO"
|
||||
itemModel={child.model}
|
||||
latestHttpResponse={httpResponses.find((r) => r.requestId === child.id) ?? null}
|
||||
latestGrpcConnection={
|
||||
grpcConnections.find((c) => c.requestId === child.item.id) ?? null
|
||||
grpcConnections.find((c) => c.requestId === child.id) ?? null
|
||||
}
|
||||
onMove={handleMove}
|
||||
onEnd={handleEnd}
|
||||
@@ -71,30 +66,29 @@ export const SidebarItems = memo(function SidebarItems({
|
||||
onDragStart={handleDragStart}
|
||||
child={child}
|
||||
>
|
||||
{child.item.model === 'folder' &&
|
||||
draggingId !== child.item.id && (
|
||||
<SidebarItems
|
||||
draggingId={draggingId}
|
||||
handleDragStart={handleDragStart}
|
||||
handleEnd={handleEnd}
|
||||
handleMove={handleMove}
|
||||
hoveredIndex={hoveredIndex}
|
||||
hoveredTree={hoveredTree}
|
||||
httpResponses={httpResponses}
|
||||
grpcConnections={grpcConnections}
|
||||
onSelect={onSelect}
|
||||
selectedTree={selectedTree}
|
||||
tree={child}
|
||||
treeParentMap={treeParentMap}
|
||||
/>
|
||||
)}
|
||||
{child.model === 'folder' && draggingId !== child.id && (
|
||||
<SidebarItems
|
||||
draggingId={draggingId}
|
||||
handleDragStart={handleDragStart}
|
||||
handleEnd={handleEnd}
|
||||
handleMove={handleMove}
|
||||
hoveredIndex={hoveredIndex}
|
||||
hoveredTree={hoveredTree}
|
||||
httpResponses={httpResponses}
|
||||
grpcConnections={grpcConnections}
|
||||
onSelect={onSelect}
|
||||
selectedTree={selectedTree}
|
||||
tree={child}
|
||||
treeParentMap={treeParentMap}
|
||||
/>
|
||||
)}
|
||||
</SidebarItem>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
{hoveredIndex === tree.children.length && hoveredTree?.item.id === tree.item.id && (
|
||||
{hoveredIndex === tree.children.length && hoveredTree?.id === tree.id && (
|
||||
<DropMarker />
|
||||
)}
|
||||
</VStack>
|
||||
);
|
||||
})
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import classNames from 'classnames';
|
||||
import React, { memo } from 'react';
|
||||
import { useActiveRequest } from '../hooks/useActiveRequest';
|
||||
import { useToggleCommandPalette } from '../hooks/useToggleCommandPalette';
|
||||
import { fallbackRequestName } from '../lib/fallbackRequestName';
|
||||
import { CookieDropdown } from './CookieDropdown';
|
||||
import { Icon } from './core/Icon';
|
||||
import { IconButton } from './core/IconButton';
|
||||
@@ -19,6 +21,8 @@ interface Props {
|
||||
|
||||
export const WorkspaceHeader = memo(function WorkspaceHeader({ className }: Props) {
|
||||
const togglePalette = useToggleCommandPalette();
|
||||
const activeRequest = useActiveRequest();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
@@ -36,7 +40,10 @@ export const WorkspaceHeader = memo(function WorkspaceHeader({ className }: Prop
|
||||
</HStack>
|
||||
</HStack>
|
||||
<div className="pointer-events-none w-full max-w-[30vw] mx-auto flex justify-center">
|
||||
<RecentRequestsDropdown />
|
||||
<RecentRequestsDropdown
|
||||
activeRequestId={activeRequest?.id ?? null}
|
||||
activeRequestName={fallbackRequestName(activeRequest)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 flex gap-1 items-center h-full justify-end pointer-events-none pr-1">
|
||||
<LicenseBadge />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { generateId } from '../../lib/generateId';
|
||||
import { Editor } from './Editor/Editor';
|
||||
import type { PairEditorProps } from './PairEditor';
|
||||
|
||||
@@ -51,6 +52,7 @@ function lineToPair(line: string): PairEditorProps['pairs'][0] {
|
||||
enabled: true,
|
||||
name: (name ?? '').trim(),
|
||||
value: (value ?? '').trim(),
|
||||
id: generateId(),
|
||||
};
|
||||
return pair;
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ export type DropdownItem = DropdownItemDefault | DropdownItemSeparator;
|
||||
|
||||
export interface DropdownProps {
|
||||
children: ReactElement<HTMLAttributes<HTMLButtonElement>>;
|
||||
items: DropdownItem[];
|
||||
items: DropdownItem[] | (() => DropdownItem[]);
|
||||
onOpen?: () => void;
|
||||
onClose?: () => void;
|
||||
fullWidth?: boolean;
|
||||
@@ -75,7 +75,7 @@ export interface DropdownRef {
|
||||
}
|
||||
|
||||
export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown(
|
||||
{ children, items, onOpen, onClose, hotKeyAction, fullWidth }: DropdownProps,
|
||||
{ children, items: itemsGetter, onOpen, onClose, hotKeyAction, fullWidth }: DropdownProps,
|
||||
ref,
|
||||
) {
|
||||
const [isOpen, _setIsOpen] = useState<boolean>(false);
|
||||
@@ -83,6 +83,8 @@ export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
const menuRef = useRef<Omit<DropdownRef, 'open'>>(null);
|
||||
|
||||
const [items, setItems] = useState<DropdownItem[]>([]);
|
||||
|
||||
const setIsOpen = useCallback(
|
||||
(o: SetStateAction<boolean>) => {
|
||||
_setIsOpen(o);
|
||||
@@ -99,20 +101,24 @@ export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown
|
||||
setDefaultSelectedIndex(undefined);
|
||||
}, [setIsOpen]);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
...menuRef.current,
|
||||
isOpen: isOpen,
|
||||
toggle() {
|
||||
if (!isOpen) this.open();
|
||||
else this.close();
|
||||
},
|
||||
open() {
|
||||
setIsOpen(true);
|
||||
},
|
||||
close() {
|
||||
handleClose();
|
||||
},
|
||||
}), [handleClose, isOpen, setIsOpen]);
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
...menuRef.current,
|
||||
isOpen: isOpen,
|
||||
toggle() {
|
||||
if (!isOpen) this.open();
|
||||
else this.close();
|
||||
},
|
||||
open() {
|
||||
setIsOpen(true);
|
||||
},
|
||||
close() {
|
||||
handleClose();
|
||||
},
|
||||
}),
|
||||
[handleClose, isOpen, setIsOpen],
|
||||
);
|
||||
|
||||
useHotKey(hotKeyAction ?? null, () => {
|
||||
setDefaultSelectedIndex(0);
|
||||
@@ -133,10 +139,11 @@ export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown
|
||||
e.stopPropagation();
|
||||
setDefaultSelectedIndex(undefined);
|
||||
setIsOpen((o) => !o);
|
||||
setItems(typeof itemsGetter === 'function' ? itemsGetter() : itemsGetter);
|
||||
}),
|
||||
};
|
||||
return cloneElement(existingChild, props);
|
||||
}, [children, setIsOpen]);
|
||||
}, [children, itemsGetter, setIsOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
buttonRef.current?.setAttribute('aria-expanded', isOpen.toString());
|
||||
@@ -169,7 +176,7 @@ export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown
|
||||
interface ContextMenuProps {
|
||||
triggerPosition: { x: number; y: number } | null;
|
||||
className?: string;
|
||||
items: DropdownProps['items'];
|
||||
items: DropdownItem[];
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -204,294 +211,299 @@ export const ContextMenu = forwardRef<DropdownRef, ContextMenuProps>(function Co
|
||||
interface MenuProps {
|
||||
className?: string;
|
||||
defaultSelectedIndex?: number;
|
||||
items: DropdownProps['items'];
|
||||
triggerShape: Pick<DOMRect, 'top' | 'bottom' | 'left' | 'right'> | null;
|
||||
onClose: () => void;
|
||||
showTriangle?: boolean;
|
||||
fullWidth?: boolean;
|
||||
isOpen: boolean;
|
||||
items: DropdownItem[];
|
||||
}
|
||||
|
||||
const Menu = forwardRef<Omit<DropdownRef, 'open' | 'isOpen' | 'toggle'>, MenuProps>(function Menu(
|
||||
{
|
||||
className,
|
||||
isOpen,
|
||||
items,
|
||||
fullWidth,
|
||||
onClose,
|
||||
triggerShape,
|
||||
defaultSelectedIndex,
|
||||
showTriangle,
|
||||
}: MenuProps,
|
||||
ref,
|
||||
) {
|
||||
const [selectedIndex, setSelectedIndex] = useStateWithDeps<number | null>(
|
||||
defaultSelectedIndex ?? null,
|
||||
[defaultSelectedIndex],
|
||||
);
|
||||
const [filter, setFilter] = useState<string>('');
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
onClose();
|
||||
setSelectedIndex(null);
|
||||
setFilter('');
|
||||
}, [onClose, setSelectedIndex]);
|
||||
|
||||
// Close menu on space bar
|
||||
const handleMenuKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
const isCharacter = e.key.length === 1;
|
||||
const isSpecial = e.ctrlKey || e.metaKey || e.altKey;
|
||||
if (isCharacter && !isSpecial) {
|
||||
e.preventDefault();
|
||||
setFilter((f) => f + e.key);
|
||||
setSelectedIndex(0);
|
||||
} else if (e.key === 'Backspace' && !isSpecial) {
|
||||
e.preventDefault();
|
||||
setFilter((f) => f.slice(0, -1));
|
||||
}
|
||||
};
|
||||
|
||||
useKey(
|
||||
'Escape',
|
||||
() => {
|
||||
if (!isOpen) return;
|
||||
if (filter !== '') setFilter('');
|
||||
else handleClose();
|
||||
},
|
||||
{},
|
||||
[isOpen, filter, setFilter, handleClose],
|
||||
);
|
||||
|
||||
const handlePrev = useCallback(() => {
|
||||
setSelectedIndex((currIndex) => {
|
||||
let nextIndex = (currIndex ?? 0) - 1;
|
||||
const maxTries = items.length;
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
if (items[nextIndex]?.hidden || items[nextIndex]?.type === 'separator') {
|
||||
nextIndex--;
|
||||
} else if (nextIndex < 0) {
|
||||
nextIndex = items.length - 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return nextIndex;
|
||||
});
|
||||
}, [items, setSelectedIndex]);
|
||||
|
||||
const handleNext = useCallback(() => {
|
||||
setSelectedIndex((currIndex) => {
|
||||
let nextIndex = (currIndex ?? -1) + 1;
|
||||
const maxTries = items.length;
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
if (items[nextIndex]?.hidden || items[nextIndex]?.type === 'separator') {
|
||||
nextIndex++;
|
||||
} else if (nextIndex >= items.length) {
|
||||
nextIndex = 0;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return nextIndex;
|
||||
});
|
||||
}, [items, setSelectedIndex]);
|
||||
|
||||
useKey(
|
||||
'ArrowUp',
|
||||
(e) => {
|
||||
if (!isOpen) return;
|
||||
e.preventDefault();
|
||||
handlePrev();
|
||||
},
|
||||
{},
|
||||
[isOpen],
|
||||
);
|
||||
|
||||
useKey(
|
||||
'ArrowDown',
|
||||
(e) => {
|
||||
if (!isOpen) return;
|
||||
e.preventDefault();
|
||||
handleNext();
|
||||
},
|
||||
{},
|
||||
[isOpen],
|
||||
);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(i: DropdownItem) => {
|
||||
if (i.type !== 'separator' && !i.keepOpen) {
|
||||
handleClose();
|
||||
}
|
||||
setSelectedIndex(null);
|
||||
if (i.type !== 'separator' && typeof i.onSelect === 'function') {
|
||||
i.onSelect();
|
||||
}
|
||||
},
|
||||
[handleClose, setSelectedIndex],
|
||||
);
|
||||
|
||||
useImperativeHandle(
|
||||
const Menu = forwardRef<Omit<DropdownRef, 'open' | 'isOpen' | 'toggle' | 'items'>, MenuProps>(
|
||||
function Menu(
|
||||
{
|
||||
className,
|
||||
isOpen,
|
||||
items,
|
||||
fullWidth,
|
||||
onClose,
|
||||
triggerShape,
|
||||
defaultSelectedIndex,
|
||||
showTriangle,
|
||||
}: MenuProps,
|
||||
ref,
|
||||
() => ({
|
||||
close: handleClose,
|
||||
prev: handlePrev,
|
||||
next: handleNext,
|
||||
select: () => {
|
||||
const item = items[selectedIndex ?? -1] ?? null;
|
||||
if (!item) return;
|
||||
handleSelect(item);
|
||||
},
|
||||
}),
|
||||
[handleClose, handleNext, handlePrev, handleSelect, items, selectedIndex],
|
||||
);
|
||||
) {
|
||||
const [selectedIndex, setSelectedIndex] = useStateWithDeps<number | null>(
|
||||
defaultSelectedIndex ?? null,
|
||||
[defaultSelectedIndex],
|
||||
);
|
||||
const [filter, setFilter] = useState<string>('');
|
||||
|
||||
const styles = useMemo<{
|
||||
container: CSSProperties;
|
||||
menu: CSSProperties;
|
||||
triangle: CSSProperties;
|
||||
upsideDown: boolean;
|
||||
}>(() => {
|
||||
if (triggerShape == null) return { container: {}, triangle: {}, menu: {}, upsideDown: false };
|
||||
const handleClose = useCallback(() => {
|
||||
onClose();
|
||||
setSelectedIndex(null);
|
||||
setFilter('');
|
||||
}, [onClose, setSelectedIndex]);
|
||||
|
||||
const menuMarginY = 5;
|
||||
const docRect = document.documentElement.getBoundingClientRect();
|
||||
const width = triggerShape.right - triggerShape.left;
|
||||
const heightAbove = triggerShape.top;
|
||||
const heightBelow = docRect.height - triggerShape.bottom;
|
||||
const horizontalSpaceRemaining = docRect.width - triggerShape.left;
|
||||
const top = triggerShape.bottom;
|
||||
const onRight = horizontalSpaceRemaining < 200;
|
||||
const upsideDown = heightBelow < heightAbove && heightBelow < items.length * 25 + 20 + 200;
|
||||
const triggerWidth = triggerShape.right - triggerShape.left;
|
||||
return {
|
||||
upsideDown,
|
||||
container: {
|
||||
top: !upsideDown ? top + menuMarginY : undefined,
|
||||
bottom: upsideDown
|
||||
? docRect.height - top - (triggerShape.top - triggerShape.bottom) + menuMarginY
|
||||
: undefined,
|
||||
right: onRight ? docRect.width - triggerShape.right : undefined,
|
||||
left: !onRight ? triggerShape.left : undefined,
|
||||
minWidth: fullWidth ? triggerWidth : undefined,
|
||||
maxWidth: '40rem',
|
||||
},
|
||||
triangle: {
|
||||
width: '0.4rem',
|
||||
height: '0.4rem',
|
||||
...(onRight
|
||||
? { right: width / 2, marginRight: '-0.2rem' }
|
||||
: { left: width / 2, marginLeft: '-0.2rem' }),
|
||||
...(upsideDown
|
||||
? { bottom: '-0.2rem', rotate: '225deg' }
|
||||
: { top: '-0.2rem', rotate: '45deg' }),
|
||||
},
|
||||
menu: {
|
||||
maxHeight: `${(upsideDown ? heightAbove : heightBelow) - 15}px`,
|
||||
},
|
||||
// Close menu on space bar
|
||||
const handleMenuKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
const isCharacter = e.key.length === 1;
|
||||
const isSpecial = e.ctrlKey || e.metaKey || e.altKey;
|
||||
if (isCharacter && !isSpecial) {
|
||||
e.preventDefault();
|
||||
setFilter((f) => f + e.key);
|
||||
setSelectedIndex(0);
|
||||
} else if (e.key === 'Backspace' && !isSpecial) {
|
||||
e.preventDefault();
|
||||
setFilter((f) => f.slice(0, -1));
|
||||
}
|
||||
};
|
||||
}, [fullWidth, items.length, triggerShape]);
|
||||
|
||||
const filteredItems = useMemo(
|
||||
() => items.filter((i) => getNodeText(i.label).toLowerCase().includes(filter.toLowerCase())),
|
||||
[items, filter],
|
||||
);
|
||||
useKey(
|
||||
'Escape',
|
||||
() => {
|
||||
if (!isOpen) return;
|
||||
if (filter !== '') setFilter('');
|
||||
else handleClose();
|
||||
},
|
||||
{},
|
||||
[isOpen, filter, setFilter, handleClose],
|
||||
);
|
||||
|
||||
const handleFocus = useCallback(
|
||||
(i: DropdownItem) => {
|
||||
const index = filteredItems.findIndex((item) => item === i) ?? null;
|
||||
setSelectedIndex(index);
|
||||
},
|
||||
[filteredItems, setSelectedIndex],
|
||||
);
|
||||
const handlePrev = useCallback(() => {
|
||||
setSelectedIndex((currIndex) => {
|
||||
let nextIndex = (currIndex ?? 0) - 1;
|
||||
const maxTries = items.length;
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
if (items[nextIndex]?.hidden || items[nextIndex]?.type === 'separator') {
|
||||
nextIndex--;
|
||||
} else if (nextIndex < 0) {
|
||||
nextIndex = items.length - 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return nextIndex;
|
||||
});
|
||||
}, [items, setSelectedIndex]);
|
||||
|
||||
if (items.length === 0) return null;
|
||||
const handleNext = useCallback(() => {
|
||||
setSelectedIndex((currIndex) => {
|
||||
let nextIndex = (currIndex ?? -1) + 1;
|
||||
const maxTries = items.length;
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
if (items[nextIndex]?.hidden || items[nextIndex]?.type === 'separator') {
|
||||
nextIndex++;
|
||||
} else if (nextIndex >= items.length) {
|
||||
nextIndex = 0;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return nextIndex;
|
||||
});
|
||||
}, [items, setSelectedIndex]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{filteredItems.map(
|
||||
(item) =>
|
||||
item.type !== 'separator' &&
|
||||
!item.hotKeyLabelOnly && (
|
||||
<MenuItemHotKey
|
||||
key={item.key}
|
||||
onSelect={handleSelect}
|
||||
item={item}
|
||||
action={item.hotKeyAction}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
{isOpen && (
|
||||
<Overlay open={true} variant="transparent" portalName="dropdown" zIndex={50}>
|
||||
<div className="x-theme-menu">
|
||||
<div tabIndex={-1} aria-hidden className="fixed inset-0 z-30" onClick={handleClose} />
|
||||
<motion.div
|
||||
tabIndex={0}
|
||||
onKeyDown={handleMenuKeyDown}
|
||||
initial={{ opacity: 0, y: (styles.upsideDown ? 1 : -1) * 5, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
role="menu"
|
||||
aria-orientation="vertical"
|
||||
dir="ltr"
|
||||
style={styles.container}
|
||||
className={classNames(className, 'outline-none my-1 pointer-events-auto fixed z-50')}
|
||||
>
|
||||
{showTriangle && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={styles.triangle}
|
||||
className="bg-surface absolute border-border-subtle border-t border-l"
|
||||
/>
|
||||
)}
|
||||
<VStack
|
||||
style={styles.menu}
|
||||
useKey(
|
||||
'ArrowUp',
|
||||
(e) => {
|
||||
if (!isOpen) return;
|
||||
e.preventDefault();
|
||||
handlePrev();
|
||||
},
|
||||
{},
|
||||
[isOpen],
|
||||
);
|
||||
|
||||
useKey(
|
||||
'ArrowDown',
|
||||
(e) => {
|
||||
if (!isOpen) return;
|
||||
e.preventDefault();
|
||||
handleNext();
|
||||
},
|
||||
{},
|
||||
[isOpen],
|
||||
);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(i: DropdownItem) => {
|
||||
if (i.type !== 'separator' && !i.keepOpen) {
|
||||
handleClose();
|
||||
}
|
||||
setSelectedIndex(null);
|
||||
if (i.type !== 'separator' && typeof i.onSelect === 'function') {
|
||||
i.onSelect();
|
||||
}
|
||||
},
|
||||
[handleClose, setSelectedIndex],
|
||||
);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
close: handleClose,
|
||||
prev: handlePrev,
|
||||
next: handleNext,
|
||||
select: () => {
|
||||
const item = items[selectedIndex ?? -1] ?? null;
|
||||
if (!item) return;
|
||||
handleSelect(item);
|
||||
},
|
||||
}),
|
||||
[handleClose, handleNext, handlePrev, handleSelect, items, selectedIndex],
|
||||
);
|
||||
|
||||
const styles = useMemo<{
|
||||
container: CSSProperties;
|
||||
menu: CSSProperties;
|
||||
triangle: CSSProperties;
|
||||
upsideDown: boolean;
|
||||
}>(() => {
|
||||
if (triggerShape == null) return { container: {}, triangle: {}, menu: {}, upsideDown: false };
|
||||
|
||||
const menuMarginY = 5;
|
||||
const docRect = document.documentElement.getBoundingClientRect();
|
||||
const width = triggerShape.right - triggerShape.left;
|
||||
const heightAbove = triggerShape.top;
|
||||
const heightBelow = docRect.height - triggerShape.bottom;
|
||||
const horizontalSpaceRemaining = docRect.width - triggerShape.left;
|
||||
const top = triggerShape.bottom;
|
||||
const onRight = horizontalSpaceRemaining < 200;
|
||||
const upsideDown = heightBelow < heightAbove && heightBelow < items.length * 25 + 20 + 200;
|
||||
const triggerWidth = triggerShape.right - triggerShape.left;
|
||||
return {
|
||||
upsideDown,
|
||||
container: {
|
||||
top: !upsideDown ? top + menuMarginY : undefined,
|
||||
bottom: upsideDown
|
||||
? docRect.height - top - (triggerShape.top - triggerShape.bottom) + menuMarginY
|
||||
: undefined,
|
||||
right: onRight ? docRect.width - triggerShape.right : undefined,
|
||||
left: !onRight ? triggerShape.left : undefined,
|
||||
minWidth: fullWidth ? triggerWidth : undefined,
|
||||
maxWidth: '40rem',
|
||||
},
|
||||
triangle: {
|
||||
width: '0.4rem',
|
||||
height: '0.4rem',
|
||||
...(onRight
|
||||
? { right: width / 2, marginRight: '-0.2rem' }
|
||||
: { left: width / 2, marginLeft: '-0.2rem' }),
|
||||
...(upsideDown
|
||||
? { bottom: '-0.2rem', rotate: '225deg' }
|
||||
: { top: '-0.2rem', rotate: '45deg' }),
|
||||
},
|
||||
menu: {
|
||||
maxHeight: `${(upsideDown ? heightAbove : heightBelow) - 15}px`,
|
||||
},
|
||||
};
|
||||
}, [fullWidth, items.length, triggerShape]);
|
||||
|
||||
const filteredItems = useMemo(
|
||||
() => items.filter((i) => getNodeText(i.label).toLowerCase().includes(filter.toLowerCase())),
|
||||
[items, filter],
|
||||
);
|
||||
|
||||
const handleFocus = useCallback(
|
||||
(i: DropdownItem) => {
|
||||
const index = filteredItems.findIndex((item) => item === i) ?? null;
|
||||
setSelectedIndex(index);
|
||||
},
|
||||
[filteredItems, setSelectedIndex],
|
||||
);
|
||||
|
||||
if (items.length === 0) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{filteredItems.map(
|
||||
(item) =>
|
||||
item.type !== 'separator' &&
|
||||
!item.hotKeyLabelOnly && (
|
||||
<MenuItemHotKey
|
||||
key={item.key}
|
||||
onSelect={handleSelect}
|
||||
item={item}
|
||||
action={item.hotKeyAction}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
{isOpen && (
|
||||
<Overlay open={true} variant="transparent" portalName="dropdown" zIndex={50}>
|
||||
<div className="x-theme-menu">
|
||||
<div tabIndex={-1} aria-hidden className="fixed inset-0 z-30" onClick={handleClose} />
|
||||
<motion.div
|
||||
tabIndex={0}
|
||||
onKeyDown={handleMenuKeyDown}
|
||||
initial={{ opacity: 0, y: (styles.upsideDown ? 1 : -1) * 5, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
role="menu"
|
||||
aria-orientation="vertical"
|
||||
dir="ltr"
|
||||
style={styles.container}
|
||||
className={classNames(
|
||||
className,
|
||||
'h-auto bg-surface rounded-md shadow-lg py-1.5 border',
|
||||
'border-border-subtle overflow-auto mx-0.5',
|
||||
'outline-none my-1 pointer-events-auto fixed z-50',
|
||||
)}
|
||||
>
|
||||
{filter && (
|
||||
<HStack
|
||||
space={2}
|
||||
className="pb-0.5 px-1.5 mb-2 text-sm border border-border-subtle mx-2 rounded font-mono h-xs"
|
||||
>
|
||||
<Icon icon="search" size="xs" className="text-text-subtle" />
|
||||
<div className="text">{filter}</div>
|
||||
</HStack>
|
||||
{showTriangle && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={styles.triangle}
|
||||
className="bg-surface absolute border-border-subtle border-t border-l"
|
||||
/>
|
||||
)}
|
||||
{filteredItems.length === 0 && (
|
||||
<span className="text-text-subtlest text-center px-2 py-1">No matches</span>
|
||||
)}
|
||||
{filteredItems.map((item, i) => {
|
||||
if (item.hidden) {
|
||||
return null;
|
||||
}
|
||||
if (item.type === 'separator') {
|
||||
<VStack
|
||||
style={styles.menu}
|
||||
className={classNames(
|
||||
className,
|
||||
'h-auto bg-surface rounded-md shadow-lg py-1.5 border',
|
||||
'border-border-subtle overflow-auto mx-0.5',
|
||||
)}
|
||||
>
|
||||
{filter && (
|
||||
<HStack
|
||||
space={2}
|
||||
className="pb-0.5 px-1.5 mb-2 text-sm border border-border-subtle mx-2 rounded font-mono h-xs"
|
||||
>
|
||||
<Icon icon="search" size="xs" className="text-text-subtle" />
|
||||
<div className="text">{filter}</div>
|
||||
</HStack>
|
||||
)}
|
||||
{filteredItems.length === 0 && (
|
||||
<span className="text-text-subtlest text-center px-2 py-1">No matches</span>
|
||||
)}
|
||||
{filteredItems.map((item, i) => {
|
||||
if (item.hidden) {
|
||||
return null;
|
||||
}
|
||||
if (item.type === 'separator') {
|
||||
return (
|
||||
<Separator key={i} className={classNames('my-1.5', item.label && 'ml-2')}>
|
||||
{item.label}
|
||||
</Separator>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Separator key={i} className={classNames('my-1.5', item.label && 'ml-2')}>
|
||||
{item.label}
|
||||
</Separator>
|
||||
<MenuItem
|
||||
focused={i === selectedIndex}
|
||||
onFocus={handleFocus}
|
||||
onSelect={handleSelect}
|
||||
key={item.key}
|
||||
item={item}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<MenuItem
|
||||
focused={i === selectedIndex}
|
||||
onFocus={handleFocus}
|
||||
onSelect={handleSelect}
|
||||
key={item.key}
|
||||
item={item}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</VStack>
|
||||
</motion.div>
|
||||
</div>
|
||||
</Overlay>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
});
|
||||
})}
|
||||
</VStack>
|
||||
</motion.div>
|
||||
</div>
|
||||
</Overlay>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
interface MenuItemProps {
|
||||
className?: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { defaultKeymap, historyField } from '@codemirror/commands';
|
||||
import { foldState, forceParsing } from '@codemirror/language';
|
||||
import { defaultKeymap } from '@codemirror/commands';
|
||||
import { forceParsing } from '@codemirror/language';
|
||||
import { Compartment, EditorState, type Extension } from '@codemirror/state';
|
||||
import { keymap, placeholder as placeholderExt, tooltips } from '@codemirror/view';
|
||||
import type { EnvironmentVariable } from '@yaakapp-internal/models';
|
||||
@@ -8,12 +8,12 @@ import classNames from 'classnames';
|
||||
import { EditorView } from 'codemirror';
|
||||
import type { MutableRefObject, ReactNode } from 'react';
|
||||
import {
|
||||
useEffect,
|
||||
Children,
|
||||
cloneElement,
|
||||
forwardRef,
|
||||
isValidElement,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
@@ -31,7 +31,7 @@ import { HStack } from '../Stacks';
|
||||
import './Editor.css';
|
||||
import { baseExtensions, getLanguageExtension, multiLineExtensions } from './extensions';
|
||||
import type { GenericCompletionConfig } from './genericCompletion';
|
||||
import { singleLineExt } from './singleLine';
|
||||
import { singleLineExtensions } from './singleLine';
|
||||
|
||||
export interface EditorProps {
|
||||
id?: string;
|
||||
@@ -122,7 +122,7 @@ export const Editor = forwardRef<EditorView | undefined, EditorProps>(function E
|
||||
// Use ref so we can update the handler without re-initializing the editor
|
||||
const handleChange = useRef<EditorProps['onChange']>(onChange);
|
||||
useEffect(() => {
|
||||
handleChange.current = onChange ? onChange : onChange;
|
||||
handleChange.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
// Use ref so we can update the handler without re-initializing the editor
|
||||
@@ -304,36 +304,35 @@ export const Editor = forwardRef<EditorView | undefined, EditorProps>(function E
|
||||
onClickMissingVariable,
|
||||
onClickPathParameter,
|
||||
});
|
||||
const extensions = [
|
||||
languageCompartment.of(langExt),
|
||||
placeholderCompartment.current.of(
|
||||
placeholderExt(placeholderElFromText(placeholder ?? '')),
|
||||
),
|
||||
wrapLinesCompartment.current.of(wrapLines ? [EditorView.lineWrapping] : []),
|
||||
...getExtensions({
|
||||
container,
|
||||
readOnly,
|
||||
singleLine,
|
||||
hideGutter,
|
||||
stateKey,
|
||||
onChange: handleChange,
|
||||
onPaste: handlePaste,
|
||||
onPasteOverwrite: handlePasteOverwrite,
|
||||
onFocus: handleFocus,
|
||||
onBlur: handleBlur,
|
||||
onKeyDown: handleKeyDown,
|
||||
}),
|
||||
...(extraExtensions ?? []),
|
||||
];
|
||||
|
||||
const cachedJsonState = getCachedEditorState(stateKey);
|
||||
const state = cachedJsonState
|
||||
? EditorState.fromJSON(
|
||||
cachedJsonState,
|
||||
{ extensions },
|
||||
{ fold: foldState, history: historyField },
|
||||
)
|
||||
: EditorState.create({ doc: `${defaultValue ?? ''}`, extensions });
|
||||
const cachedJsonState = getCachedEditorState(defaultValue ?? '', stateKey);
|
||||
|
||||
const state =
|
||||
cachedJsonState ??
|
||||
EditorState.create({
|
||||
doc: `${defaultValue ?? ''}`,
|
||||
extensions: [
|
||||
languageCompartment.of(langExt),
|
||||
placeholderCompartment.current.of(
|
||||
placeholderExt(placeholderElFromText(placeholder ?? '')),
|
||||
),
|
||||
wrapLinesCompartment.current.of(wrapLines ? [EditorView.lineWrapping] : []),
|
||||
...getExtensions({
|
||||
container,
|
||||
readOnly,
|
||||
singleLine,
|
||||
hideGutter,
|
||||
stateKey,
|
||||
onChange: handleChange,
|
||||
onPaste: handlePaste,
|
||||
onPasteOverwrite: handlePasteOverwrite,
|
||||
onFocus: handleFocus,
|
||||
onBlur: handleBlur,
|
||||
onKeyDown: handleKeyDown,
|
||||
}),
|
||||
...(extraExtensions ?? []),
|
||||
],
|
||||
});
|
||||
|
||||
const view = new EditorView({ state, parent: container });
|
||||
|
||||
@@ -515,7 +514,7 @@ function getExtensions({
|
||||
}),
|
||||
tooltips({ parent }),
|
||||
keymap.of(singleLine ? defaultKeymap.filter((k) => k.key !== 'Enter') : defaultKeymap),
|
||||
...(singleLine ? [singleLineExt()] : []),
|
||||
...(singleLine ? [singleLineExtensions()] : []),
|
||||
...(!singleLine ? [multiLineExtensions({ hideGutter })] : []),
|
||||
...(readOnly
|
||||
? [EditorState.readOnly.of(true), EditorView.contentAttributes.of({ tabindex: '-1' })]
|
||||
@@ -525,12 +524,17 @@ function getExtensions({
|
||||
// Things that must be last //
|
||||
// ------------------------ //
|
||||
|
||||
// Fire onChange event
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (onChange && update.docChanged) {
|
||||
onChange.current?.(update.state.doc.toString());
|
||||
saveCachedEditorState(stateKey, update.state);
|
||||
}
|
||||
}),
|
||||
|
||||
// Cache editor state
|
||||
EditorView.updateListener.of((update) => {
|
||||
saveCachedEditorState(stateKey, update.state);
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -540,20 +544,25 @@ const placeholderElFromText = (text: string) => {
|
||||
return el;
|
||||
};
|
||||
|
||||
function saveCachedEditorState(stateKey: string | null, state: EditorState | null) {
|
||||
if (!stateKey || state == null) return;
|
||||
const stateJson = state.toJSON({ history: historyField, folds: foldState });
|
||||
sessionStorage.setItem(stateKey, JSON.stringify(stateJson));
|
||||
}
|
||||
|
||||
function getCachedEditorState(stateKey: string | null) {
|
||||
if (stateKey == null) return;
|
||||
const serializedState = stateKey ? sessionStorage.getItem(stateKey) : null;
|
||||
if (serializedState == null) return;
|
||||
try {
|
||||
return JSON.parse(serializedState);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
} catch (e) {
|
||||
return null;
|
||||
declare global {
|
||||
interface Window {
|
||||
editorStates: Record<string, EditorState>;
|
||||
}
|
||||
}
|
||||
window.editorStates = window.editorStates ?? {};
|
||||
|
||||
function saveCachedEditorState(stateKey: string | null, state: EditorState | null) {
|
||||
if (!stateKey || state == null) return;
|
||||
window.editorStates[stateKey] = state;
|
||||
}
|
||||
|
||||
function getCachedEditorState(doc: string, stateKey: string | null) {
|
||||
if (stateKey == null) return;
|
||||
|
||||
const state = window.editorStates[stateKey] ?? null;
|
||||
if (state == null) return null;
|
||||
if (state.doc.toString() !== doc) return null;
|
||||
|
||||
console.log('CACHED STATE', stateKey, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Transaction, TransactionSpec } from '@codemirror/state';
|
||||
import type {Extension, Transaction, TransactionSpec} from '@codemirror/state';
|
||||
import { EditorSelection, EditorState } from '@codemirror/state';
|
||||
|
||||
export function singleLineExt() {
|
||||
export function singleLineExtensions(): Extension {
|
||||
return EditorState.transactionFilter.of(
|
||||
(tr: Transaction): TransactionSpec | TransactionSpec[] => {
|
||||
if (!tr.isUserEvent('input')) return tr;
|
||||
|
||||
@@ -18,6 +18,7 @@ import { generateId } from '../../lib/generateId';
|
||||
import { DropMarker } from '../DropMarker';
|
||||
import { SelectFile } from '../SelectFile';
|
||||
import { Checkbox } from './Checkbox';
|
||||
import type { DropdownItem } from './Dropdown';
|
||||
import { Dropdown } from './Dropdown';
|
||||
import type { GenericCompletionConfig } from './Editor/genericCompletion';
|
||||
import { Icon } from './Icon';
|
||||
@@ -25,6 +26,7 @@ import { IconButton } from './IconButton';
|
||||
import type { InputProps } from './Input';
|
||||
import { Input } from './Input';
|
||||
import { PlainInput } from './PlainInput';
|
||||
import type { RadioDropdownItem } from './RadioDropdown';
|
||||
import { RadioDropdown } from './RadioDropdown';
|
||||
|
||||
export interface PairEditorRef {
|
||||
@@ -51,7 +53,7 @@ export type PairEditorProps = {
|
||||
};
|
||||
|
||||
export type Pair = {
|
||||
id?: string;
|
||||
id: string;
|
||||
enabled?: boolean;
|
||||
name: string;
|
||||
value: string;
|
||||
@@ -60,11 +62,6 @@ export type Pair = {
|
||||
readOnlyName?: boolean;
|
||||
};
|
||||
|
||||
type PairContainer = {
|
||||
pair: Pair;
|
||||
id: string;
|
||||
};
|
||||
|
||||
export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function PairEditor(
|
||||
{
|
||||
stateKey,
|
||||
@@ -89,11 +86,11 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
const [forceFocusNamePairId, setForceFocusNamePairId] = useState<string | null>(null);
|
||||
const [forceFocusValuePairId, setForceFocusValuePairId] = useState<string | null>(null);
|
||||
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
|
||||
const [pairs, setPairs] = useState<PairContainer[]>(() => {
|
||||
const [pairs, setPairs] = useState<Pair[]>(() => {
|
||||
// Remove empty headers on initial render
|
||||
const nonEmpty = originalPairs.filter((h) => !(h.name === '' && h.value === ''));
|
||||
const pairs = nonEmpty.map((pair) => newPairContainer(pair));
|
||||
return [...pairs, newPairContainer()];
|
||||
const pairs = nonEmpty.map((pair) => ensureValidPair(pair));
|
||||
return [...pairs, ensureValidPair()];
|
||||
});
|
||||
|
||||
useImperativeHandle(
|
||||
@@ -114,7 +111,7 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
const nonEmpty = originalPairs.filter(
|
||||
(h, i) => i !== originalPairs.length - 1 && !(h.name === '' && h.value === ''),
|
||||
);
|
||||
const newPairs = nonEmpty.map((pair) => newPairContainer(pair));
|
||||
const newPairs = nonEmpty.map((pair) => ensureValidPair(pair));
|
||||
if (!deepEqual(pairs, newPairs)) {
|
||||
setPairs(pairs);
|
||||
}
|
||||
@@ -123,11 +120,11 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
}, [forceUpdateKey]);
|
||||
|
||||
const setPairsAndSave = useCallback(
|
||||
(fn: (pairs: PairContainer[]) => PairContainer[]) => {
|
||||
(fn: (pairs: Pair[]) => Pair[]) => {
|
||||
setPairs((oldPairs) => {
|
||||
const pairs = fn(oldPairs).map((p) => p.pair);
|
||||
const pairs = fn(oldPairs);
|
||||
onChange(pairs);
|
||||
return fn(oldPairs);
|
||||
return pairs;
|
||||
});
|
||||
},
|
||||
[onChange],
|
||||
@@ -161,13 +158,12 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(pair: PairContainer) =>
|
||||
setPairsAndSave((pairs) => pairs.map((p) => (pair.id !== p.id ? p : pair))),
|
||||
(pair: Pair) => setPairsAndSave((pairs) => pairs.map((p) => (pair.id !== p.id ? p : pair))),
|
||||
[setPairsAndSave],
|
||||
);
|
||||
|
||||
const handleDelete = useCallback(
|
||||
(pair: PairContainer, focusPrevious: boolean) => {
|
||||
(pair: Pair, focusPrevious: boolean) => {
|
||||
if (focusPrevious) {
|
||||
const index = pairs.findIndex((p) => p.id === pair.id);
|
||||
const id = pairs[index - 1]?.id ?? null;
|
||||
@@ -179,13 +175,13 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
);
|
||||
|
||||
const handleFocus = useCallback(
|
||||
(pair: PairContainer) =>
|
||||
(pair: Pair) =>
|
||||
setPairs((pairs) => {
|
||||
setForceFocusNamePairId(null); // Remove focus override when something focused
|
||||
setForceFocusValuePairId(null); // Remove focus override when something focused
|
||||
const isLast = pair.id === pairs[pairs.length - 1]?.id;
|
||||
if (isLast) {
|
||||
const newPair = newPairContainer();
|
||||
const newPair = ensureValidPair();
|
||||
const prevPair = pairs[pairs.length - 1];
|
||||
setForceFocusNamePairId(prevPair?.id ?? null);
|
||||
return [...pairs, newPair];
|
||||
@@ -199,7 +195,7 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
// Ensure there's always at least one pair
|
||||
useEffect(() => {
|
||||
if (pairs.length === 0) {
|
||||
setPairs((pairs) => [...pairs, newPairContainer()]);
|
||||
setPairs((pairs) => [...pairs, ensureValidPair()]);
|
||||
}
|
||||
}, [pairs]);
|
||||
|
||||
@@ -238,7 +234,7 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
onEnd={handleEnd}
|
||||
onFocus={handleFocus}
|
||||
onMove={handleMove}
|
||||
pairContainer={p}
|
||||
pair={p}
|
||||
stateKey={stateKey}
|
||||
valueAutocomplete={valueAutocomplete}
|
||||
valueAutocompleteVariables={valueAutocompleteVariables}
|
||||
@@ -259,15 +255,15 @@ enum ItemTypes {
|
||||
|
||||
type PairEditorRowProps = {
|
||||
className?: string;
|
||||
pairContainer: PairContainer;
|
||||
pair: Pair;
|
||||
forceFocusNamePairId?: string | null;
|
||||
forceFocusValuePairId?: string | null;
|
||||
onMove: (id: string, side: 'above' | 'below') => void;
|
||||
onEnd: (id: string) => void;
|
||||
onChange: (pair: PairContainer) => void;
|
||||
onDelete?: (pair: PairContainer, focusPrevious: boolean) => void;
|
||||
onFocus?: (pair: PairContainer) => void;
|
||||
onSubmit?: (pair: PairContainer) => void;
|
||||
onChange: (pair: Pair) => void;
|
||||
onDelete?: (pair: Pair, focusPrevious: boolean) => void;
|
||||
onFocus?: (pair: Pair) => void;
|
||||
onSubmit?: (pair: Pair) => void;
|
||||
isLast?: boolean;
|
||||
index: number;
|
||||
} & Pick<
|
||||
@@ -303,7 +299,7 @@ function PairEditorRow({
|
||||
onEnd,
|
||||
onFocus,
|
||||
onMove,
|
||||
pairContainer,
|
||||
pair,
|
||||
stateKey,
|
||||
valueAutocomplete,
|
||||
valueAutocompleteVariables,
|
||||
@@ -311,62 +307,65 @@ function PairEditorRow({
|
||||
valueType,
|
||||
valueValidate,
|
||||
}: PairEditorRowProps) {
|
||||
const { id } = pairContainer;
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const prompt = usePrompt();
|
||||
const nameInputRef = useRef<EditorView>(null);
|
||||
const valueInputRef = useRef<EditorView>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (forceFocusNamePairId === pairContainer.id) {
|
||||
if (forceFocusNamePairId === pair.id) {
|
||||
nameInputRef.current?.focus();
|
||||
}
|
||||
}, [forceFocusNamePairId, pairContainer.id]);
|
||||
}, [forceFocusNamePairId, pair.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (forceFocusValuePairId === pairContainer.id) {
|
||||
if (forceFocusValuePairId === pair.id) {
|
||||
valueInputRef.current?.focus();
|
||||
}
|
||||
}, [forceFocusValuePairId, pairContainer.id]);
|
||||
}, [forceFocusValuePairId, pair.id]);
|
||||
|
||||
const handleFocus = useCallback(() => onFocus?.(pair), [onFocus, pair]);
|
||||
const handleDelete = useCallback(() => onDelete?.(pair, false), [onDelete, pair]);
|
||||
|
||||
const getDeleteItems = useCallback(
|
||||
(): DropdownItem[] => [
|
||||
{
|
||||
key: 'delete',
|
||||
label: 'Delete',
|
||||
onSelect: handleDelete,
|
||||
variant: 'danger',
|
||||
},
|
||||
],
|
||||
[handleDelete],
|
||||
);
|
||||
|
||||
const handleChangeEnabled = useMemo(
|
||||
() => (enabled: boolean) => onChange({ id, pair: { ...pairContainer.pair, enabled } }),
|
||||
[id, onChange, pairContainer.pair],
|
||||
() => (enabled: boolean) => onChange({ ...pair, enabled }),
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const handleChangeName = useMemo(
|
||||
() => (name: string) => onChange({ id, pair: { ...pairContainer.pair, name } }),
|
||||
[onChange, id, pairContainer.pair],
|
||||
() => (name: string) => onChange({ ...pair, name }),
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const handleChangeValueText = useMemo(
|
||||
() => (value: string) =>
|
||||
onChange({ id, pair: { ...pairContainer.pair, value, isFile: false } }),
|
||||
[onChange, id, pairContainer.pair],
|
||||
() => (value: string) => onChange({ ...pair, value, isFile: false }),
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const handleChangeValueFile = useMemo(
|
||||
() =>
|
||||
({ filePath }: { filePath: string | null }) =>
|
||||
onChange({
|
||||
id,
|
||||
pair: { ...pairContainer.pair, value: filePath ?? '', isFile: true },
|
||||
}),
|
||||
[onChange, id, pairContainer.pair],
|
||||
onChange({ ...pair, value: filePath ?? '', isFile: true }),
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const handleChangeValueContentType = useMemo(
|
||||
() => (contentType: string) => onChange({ id, pair: { ...pairContainer.pair, contentType } }),
|
||||
[onChange, id, pairContainer.pair],
|
||||
() => (contentType: string) => onChange({ ...pair, contentType }),
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const handleFocus = useCallback(() => onFocus?.(pairContainer), [onFocus, pairContainer]);
|
||||
const handleDelete = useCallback(
|
||||
() => onDelete?.(pairContainer, false),
|
||||
[onDelete, pairContainer],
|
||||
);
|
||||
|
||||
const [, connectDrop] = useDrop<PairContainer>(
|
||||
const [, connectDrop] = useDrop<Pair>(
|
||||
{
|
||||
accept: ItemTypes.ROW,
|
||||
hover: (_, monitor) => {
|
||||
@@ -375,7 +374,7 @@ function PairEditorRow({
|
||||
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
|
||||
const clientOffset = monitor.getClientOffset();
|
||||
const hoverClientY = (clientOffset as XYCoord).y - hoverBoundingRect.top;
|
||||
onMove(pairContainer.id, hoverClientY < hoverMiddleY ? 'above' : 'below');
|
||||
onMove(pair.id, hoverClientY < hoverMiddleY ? 'above' : 'below');
|
||||
},
|
||||
},
|
||||
[onMove],
|
||||
@@ -384,11 +383,11 @@ function PairEditorRow({
|
||||
const [, connectDrag] = useDrag(
|
||||
{
|
||||
type: ItemTypes.ROW,
|
||||
item: () => pairContainer,
|
||||
item: () => pair,
|
||||
collect: (m) => ({ isDragging: m.isDragging() }),
|
||||
end: () => onEnd(pairContainer.id),
|
||||
end: () => onEnd(pair.id),
|
||||
},
|
||||
[pairContainer, onEnd],
|
||||
[pair, onEnd],
|
||||
);
|
||||
|
||||
connectDrag(ref);
|
||||
@@ -401,7 +400,7 @@ function PairEditorRow({
|
||||
className,
|
||||
'group grid grid-cols-[auto_auto_minmax(0,1fr)_auto]',
|
||||
'grid-rows-1 items-center',
|
||||
!pairContainer.pair.enabled && 'opacity-60',
|
||||
!pair.enabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
{!isLast ? (
|
||||
@@ -418,9 +417,9 @@ function PairEditorRow({
|
||||
)}
|
||||
<Checkbox
|
||||
hideLabel
|
||||
title={pairContainer.pair.enabled ? 'Disable item' : 'Enable item'}
|
||||
title={pair.enabled ? 'Disable item' : 'Enable item'}
|
||||
disabled={isLast}
|
||||
checked={isLast ? false : !!pairContainer.pair.enabled}
|
||||
checked={isLast ? false : !!pair.enabled}
|
||||
className={classNames('pr-2', isLast && '!opacity-disabled')}
|
||||
onChange={handleChangeEnabled}
|
||||
/>
|
||||
@@ -448,15 +447,15 @@ function PairEditorRow({
|
||||
ref={nameInputRef}
|
||||
hideLabel
|
||||
useTemplating
|
||||
stateKey={`name.${pairContainer.id}.${stateKey}`}
|
||||
stateKey={`name.${pair.id}.${stateKey}`}
|
||||
wrapLines={false}
|
||||
readOnly={pairContainer.pair.readOnlyName}
|
||||
readOnly={pair.readOnlyName}
|
||||
size="sm"
|
||||
require={!isLast && !!pairContainer.pair.enabled && !!pairContainer.pair.value}
|
||||
require={!isLast && !!pair.enabled && !!pair.value}
|
||||
validate={nameValidate}
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
containerClassName={classNames(isLast && 'border-dashed')}
|
||||
defaultValue={pairContainer.pair.name}
|
||||
defaultValue={pair.name}
|
||||
label="Name"
|
||||
name={`name[${index}]`}
|
||||
onChange={handleChangeName}
|
||||
@@ -467,13 +466,8 @@ function PairEditorRow({
|
||||
/>
|
||||
)}
|
||||
<div className="w-full grid grid-cols-[minmax(0,1fr)_auto] gap-1 items-center">
|
||||
{pairContainer.pair.isFile ? (
|
||||
<SelectFile
|
||||
inline
|
||||
size="xs"
|
||||
filePath={pairContainer.pair.value}
|
||||
onChange={handleChangeValueFile}
|
||||
/>
|
||||
{pair.isFile ? (
|
||||
<SelectFile inline size="xs" filePath={pair.value} onChange={handleChangeValueFile} />
|
||||
) : isLast ? (
|
||||
// Use PlainInput for last ones because there's a unique bug where clicking below
|
||||
// the Codemirror input focuses it.
|
||||
@@ -491,93 +485,35 @@ function PairEditorRow({
|
||||
ref={valueInputRef}
|
||||
hideLabel
|
||||
useTemplating
|
||||
stateKey={`value.${pairContainer.id}.${stateKey}`}
|
||||
stateKey={`value.${pair.id}.${stateKey}`}
|
||||
wrapLines={false}
|
||||
size="sm"
|
||||
containerClassName={classNames(isLast && 'border-dashed')}
|
||||
validate={valueValidate}
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
defaultValue={pairContainer.pair.value}
|
||||
defaultValue={pair.value}
|
||||
label="Value"
|
||||
name={`value[${index}]`}
|
||||
onChange={handleChangeValueText}
|
||||
onFocus={handleFocus}
|
||||
type={isLast ? 'text' : valueType}
|
||||
placeholder={valuePlaceholder ?? 'value'}
|
||||
autocomplete={valueAutocomplete?.(pairContainer.pair.name)}
|
||||
autocomplete={valueAutocomplete?.(pair.name)}
|
||||
autocompleteVariables={valueAutocompleteVariables}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{allowFileValues ? (
|
||||
<RadioDropdown
|
||||
value={pairContainer.pair.isFile ? 'file' : 'text'}
|
||||
onChange={(v) => {
|
||||
if (v === 'file') handleChangeValueFile({ filePath: '' });
|
||||
else handleChangeValueText('');
|
||||
}}
|
||||
items={[
|
||||
{ label: 'Text', value: 'text' },
|
||||
{ label: 'File', value: 'file' },
|
||||
]}
|
||||
extraItems={[
|
||||
{
|
||||
key: 'mime',
|
||||
label: 'Set Content-Type',
|
||||
leftSlot: <Icon icon="pencil" />,
|
||||
hidden: !pairContainer.pair.isFile,
|
||||
onSelect: async () => {
|
||||
const contentType = await prompt({
|
||||
id: 'content-type',
|
||||
require: false,
|
||||
title: 'Override Content-Type',
|
||||
label: 'Content-Type',
|
||||
placeholder: 'text/plain',
|
||||
defaultValue: pairContainer.pair.contentType ?? '',
|
||||
confirmText: 'Set',
|
||||
description: 'Leave blank to auto-detect',
|
||||
});
|
||||
if (contentType == null) return;
|
||||
handleChangeValueContentType(contentType);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'clear-file',
|
||||
label: 'Unset File',
|
||||
leftSlot: <Icon icon="x" />,
|
||||
hidden: !pairContainer.pair.isFile,
|
||||
onSelect: async () => {
|
||||
handleChangeValueFile({ filePath: null });
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'delete',
|
||||
label: 'Delete',
|
||||
onSelect: handleDelete,
|
||||
variant: 'danger',
|
||||
leftSlot: <Icon icon="trash" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<IconButton
|
||||
iconSize="sm"
|
||||
size="xs"
|
||||
icon={isLast ? 'empty' : 'chevron_down'}
|
||||
title="Select form data type"
|
||||
/>
|
||||
</RadioDropdown>
|
||||
<FileActionsDropdown
|
||||
pair={pair}
|
||||
onChangeFile={handleChangeValueFile}
|
||||
onChangeText={handleChangeValueText}
|
||||
onChangeContentType={handleChangeValueContentType}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
) : (
|
||||
<Dropdown
|
||||
items={[
|
||||
{
|
||||
key: 'delete',
|
||||
label: 'Delete',
|
||||
onSelect: handleDelete,
|
||||
variant: 'danger',
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Dropdown items={getDeleteItems}>
|
||||
<IconButton
|
||||
iconSize="sm"
|
||||
size="xs"
|
||||
@@ -590,8 +526,93 @@ function PairEditorRow({
|
||||
);
|
||||
}
|
||||
|
||||
const newPairContainer = (initialPair?: Pair): PairContainer => {
|
||||
const id = initialPair?.id ?? generateId();
|
||||
const pair = initialPair ?? { name: '', value: '', enabled: true, isFile: false };
|
||||
return { id, pair };
|
||||
};
|
||||
const fileItems: RadioDropdownItem<string>[] = [
|
||||
{ label: 'Text', value: 'text' },
|
||||
{ label: 'File', value: 'file' },
|
||||
];
|
||||
|
||||
function FileActionsDropdown({
|
||||
pair,
|
||||
onChangeFile,
|
||||
onChangeText,
|
||||
onChangeContentType,
|
||||
onDelete,
|
||||
}: {
|
||||
pair: Pair;
|
||||
onChangeFile: ({ filePath }: { filePath: string | null }) => void;
|
||||
onChangeText: (text: string) => void;
|
||||
onChangeContentType: (contentType: string) => void;
|
||||
onDelete: () => void;
|
||||
}) {
|
||||
const prompt = usePrompt();
|
||||
const onChange = useCallback(
|
||||
(v: string) => {
|
||||
if (v === 'file') onChangeFile({ filePath: '' });
|
||||
else onChangeText('');
|
||||
},
|
||||
[onChangeFile, onChangeText],
|
||||
);
|
||||
|
||||
const extraItems = useMemo<DropdownItem[]>(
|
||||
() => [
|
||||
{
|
||||
key: 'mime',
|
||||
label: 'Set Content-Type',
|
||||
leftSlot: <Icon icon="pencil" />,
|
||||
hidden: !pair.isFile,
|
||||
onSelect: async () => {
|
||||
const contentType = await prompt({
|
||||
id: 'content-type',
|
||||
require: false,
|
||||
title: 'Override Content-Type',
|
||||
label: 'Content-Type',
|
||||
placeholder: 'text/plain',
|
||||
defaultValue: pair.contentType ?? '',
|
||||
confirmText: 'Set',
|
||||
description: 'Leave blank to auto-detect',
|
||||
});
|
||||
if (contentType == null) return;
|
||||
onChangeContentType(contentType);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'clear-file',
|
||||
label: 'Unset File',
|
||||
leftSlot: <Icon icon="x" />,
|
||||
hidden: pair.isFile,
|
||||
onSelect: async () => {
|
||||
onChangeFile({ filePath: null });
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'delete',
|
||||
label: 'Delete',
|
||||
onSelect: onDelete,
|
||||
variant: 'danger',
|
||||
leftSlot: <Icon icon="trash" />,
|
||||
},
|
||||
],
|
||||
[onChangeContentType, onChangeFile, onDelete, pair.contentType, pair.isFile, prompt],
|
||||
);
|
||||
|
||||
return (
|
||||
<RadioDropdown
|
||||
value={pair.isFile ? 'file' : 'text'}
|
||||
onChange={onChange}
|
||||
items={fileItems}
|
||||
extraItems={extraItems}
|
||||
>
|
||||
<IconButton iconSize="sm" size="xs" icon="chevron_down" title="Select form data type" />
|
||||
</RadioDropdown>
|
||||
);
|
||||
}
|
||||
|
||||
function ensureValidPair(initialPair?: Pair): Pair {
|
||||
return {
|
||||
name: initialPair?.name ?? '',
|
||||
value: initialPair?.value ?? '',
|
||||
enabled: initialPair?.enabled ?? true,
|
||||
isFile: initialPair?.isFile ?? false,
|
||||
id: initialPair?.id || generateId(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export interface RadioDropdownProps<T = string | null> {
|
||||
value: T;
|
||||
onChange: (value: T) => void;
|
||||
items: RadioDropdownItem<T>[];
|
||||
extraItems?: DropdownProps['items'];
|
||||
extraItems?: DropdownItem[];
|
||||
children: DropdownProps['children'];
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ export function RadioDropdown<T = string | null>({
|
||||
rightSlot: item.rightSlot,
|
||||
onSelect: () => onChange(item.value),
|
||||
leftSlot: <Icon icon={value === item.value ? 'check' : 'empty'} />,
|
||||
} as DropdownProps['items'][0];
|
||||
} as DropdownItem;
|
||||
}
|
||||
}),
|
||||
...((extraItems ? [{ type: 'separator' }, ...extraItems] : []) as DropdownItem[]),
|
||||
|
||||
@@ -10,11 +10,13 @@ import { HStack } from '../Stacks';
|
||||
export type TabItem =
|
||||
| {
|
||||
value: string;
|
||||
label: ReactNode;
|
||||
label: string;
|
||||
rightSlot?: ReactNode;
|
||||
}
|
||||
| {
|
||||
value: string;
|
||||
options: Omit<RadioDropdownProps, 'children'>;
|
||||
rightSlot?: ReactNode;
|
||||
};
|
||||
|
||||
interface Props {
|
||||
@@ -63,7 +65,10 @@ export function Tabs({
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={classNames(className, 'h-full grid grid-rows-[auto_minmax(0,1fr)] grid-cols-1 overflow-x-hidden')}
|
||||
className={classNames(
|
||||
className,
|
||||
'h-full grid grid-rows-[auto_minmax(0,1fr)] grid-cols-1 overflow-x-hidden',
|
||||
)}
|
||||
>
|
||||
<div
|
||||
aria-label={label}
|
||||
@@ -111,6 +116,7 @@ export function Tabs({
|
||||
{option && 'shortLabel' in option
|
||||
? option.shortLabel
|
||||
: (option?.label ?? 'Unknown')}
|
||||
{t.rightSlot}
|
||||
<Icon
|
||||
size="sm"
|
||||
icon="chevron_down"
|
||||
@@ -134,6 +140,7 @@ export function Tabs({
|
||||
className={btnClassName}
|
||||
>
|
||||
{t.label}
|
||||
{t.rightSlot}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@ export function TextViewer({
|
||||
language={language}
|
||||
actions={actions}
|
||||
extraExtensions={extraExtensions}
|
||||
stateKey={null}
|
||||
stateKey={`response_text.${responseId}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { GrpcRequest, HttpRequest } from '@yaakapp-internal/models';
|
||||
import { atom, useAtomValue } from 'jotai';
|
||||
import {fallbackRequestName} from "../lib/fallbackRequestName";
|
||||
import {jotaiStore} from "../lib/jotai";
|
||||
import { activeRequestIdAtom } from './useActiveRequestId';
|
||||
import { grpcRequestsAtom } from './useGrpcRequests';
|
||||
@@ -20,6 +21,11 @@ export function getActiveRequest() {
|
||||
return jotaiStore.get(activeRequestAtom);
|
||||
}
|
||||
|
||||
export const activeRequestNameAtom = atom(get => {
|
||||
const activeRequest = get(activeRequestAtom);
|
||||
return fallbackRequestName(activeRequest);
|
||||
});
|
||||
|
||||
export function useActiveRequest<T extends keyof TypeMap>(
|
||||
model?: T | undefined,
|
||||
): TypeMap[T] | null {
|
||||
|
||||
@@ -3,18 +3,18 @@ import type { Workspace } from '@yaakapp-internal/models';
|
||||
import { atom, useAtomValue } from 'jotai/index';
|
||||
import { useEffect } from 'react';
|
||||
import { jotaiStore } from '../lib/jotai';
|
||||
import { useWorkspaces } from './useWorkspaces';
|
||||
import { workspacesAtom } from './useWorkspaces';
|
||||
|
||||
export const activeWorkspaceIdAtom = atom<string>();
|
||||
|
||||
export function useActiveWorkspace(): Workspace | null {
|
||||
const workspaceId = useActiveWorkspaceId();
|
||||
const workspaces = useWorkspaces();
|
||||
return workspaces.find((w) => w.id === workspaceId) ?? null;
|
||||
}
|
||||
export const activeWorkspaceAtom = atom<Workspace | null>((get) => {
|
||||
const activeWorkspaceId = get(activeWorkspaceIdAtom);
|
||||
const workspaces = get(workspacesAtom);
|
||||
return workspaces.find((w) => w.id === activeWorkspaceId) ?? null;
|
||||
});
|
||||
|
||||
function useActiveWorkspaceId(): string | null {
|
||||
return useAtomValue(activeWorkspaceIdAtom) ?? null;
|
||||
export function useActiveWorkspace(): Workspace | null {
|
||||
return useAtomValue(activeWorkspaceAtom);
|
||||
}
|
||||
|
||||
export function getActiveWorkspaceId() {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useMemo } from 'react';
|
||||
import type { DropdownItem } from '../components/core/Dropdown';
|
||||
import { Icon } from '../components/core/Icon';
|
||||
import { generateId } from '../lib/generateId';
|
||||
import { BODY_TYPE_GRAPHQL } from '../lib/model_util';
|
||||
import { useCreateFolder } from './useCreateFolder';
|
||||
import { useCreateGrpcRequest } from './useCreateGrpcRequest';
|
||||
@@ -36,7 +37,7 @@ export function useCreateDropdownItems({
|
||||
folderId,
|
||||
bodyType: BODY_TYPE_GRAPHQL,
|
||||
method: 'POST',
|
||||
headers: [{ name: 'Content-Type', value: 'application/json' }],
|
||||
headers: [{ name: 'Content-Type', value: 'application/json', id: generateId() }],
|
||||
}),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -2,15 +2,15 @@ import { useNavigate } from '@tanstack/react-router';
|
||||
import type { GrpcRequest } from '@yaakapp-internal/models';
|
||||
import { useSetAtom } from 'jotai';
|
||||
import { trackEvent } from '../lib/analytics';
|
||||
import { jotaiStore } from '../lib/jotai';
|
||||
import { invokeCmd } from '../lib/tauri';
|
||||
import { getActiveRequest } from './useActiveRequest';
|
||||
import { useActiveWorkspace } from './useActiveWorkspace';
|
||||
import { activeWorkspaceAtom } from './useActiveWorkspace';
|
||||
import { useFastMutation } from './useFastMutation';
|
||||
import { grpcRequestsAtom } from './useGrpcRequests';
|
||||
import { updateModelList } from './useSyncModelStores';
|
||||
|
||||
export function useCreateGrpcRequest() {
|
||||
const workspace = useActiveWorkspace();
|
||||
const setGrpcRequests = useSetAtom(grpcRequestsAtom);
|
||||
const navigate = useNavigate();
|
||||
|
||||
@@ -21,6 +21,7 @@ export function useCreateGrpcRequest() {
|
||||
>({
|
||||
mutationKey: ['create_grpc_request'],
|
||||
mutationFn: async (patch) => {
|
||||
const workspace = jotaiStore.get(activeWorkspaceAtom);
|
||||
if (workspace === null) {
|
||||
throw new Error("Cannot create grpc request when there's no active workspace");
|
||||
}
|
||||
@@ -46,7 +47,7 @@ export function useCreateGrpcRequest() {
|
||||
// Optimistic update
|
||||
setGrpcRequests(updateModelList(request));
|
||||
|
||||
navigate({
|
||||
await navigate({
|
||||
to: '/workspaces/$workspaceId/requests/$requestId',
|
||||
params: {
|
||||
workspaceId: request.workspaceId,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import {generateId} from "../lib/generateId";
|
||||
import { useFastMutation } from './useFastMutation';
|
||||
import type { HttpUrlParameter } from '@yaakapp-internal/models';
|
||||
import { useToast } from './useToast';
|
||||
@@ -27,6 +28,7 @@ export function useImportQuerystring(requestId: string) {
|
||||
name,
|
||||
value,
|
||||
enabled: true,
|
||||
id: generateId(),
|
||||
}));
|
||||
|
||||
await updateRequest.mutateAsync({
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { HttpRequest, HttpResponse } from '@yaakapp-internal/models';
|
||||
import type { HttpResponse } from '@yaakapp-internal/models';
|
||||
import { useHttpResponses } from './useHttpResponses';
|
||||
import { useKeyValue } from './useKeyValue';
|
||||
import { useLatestHttpResponse } from './useLatestHttpResponse';
|
||||
|
||||
export function usePinnedHttpResponse(activeRequest: HttpRequest) {
|
||||
const latestResponse = useLatestHttpResponse(activeRequest.id);
|
||||
export function usePinnedHttpResponse(activeRequestId: string) {
|
||||
const latestResponse = useLatestHttpResponse(activeRequestId);
|
||||
const { set, value: pinnedResponseId } = useKeyValue<string | null>({
|
||||
// Key on the latest response instead of activeRequest because responses change out of band of active request
|
||||
key: ['pinned_http_response_id', latestResponse?.id ?? 'n/a'],
|
||||
@@ -12,7 +12,7 @@ export function usePinnedHttpResponse(activeRequest: HttpRequest) {
|
||||
namespace: 'global',
|
||||
});
|
||||
const allResponses = useHttpResponses();
|
||||
const responses = allResponses.filter((r) => r.requestId === activeRequest.id);
|
||||
const responses = allResponses.filter((r) => r.requestId === activeRequestId);
|
||||
const activeResponse: HttpResponse | null =
|
||||
responses.find((r) => r.id === pinnedResponseId) ?? latestResponse;
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import type { GrpcRequest, HttpRequest } from '@yaakapp-internal/models';
|
||||
import type {AnyModel, GrpcRequest, HttpRequest} from '@yaakapp-internal/models';
|
||||
|
||||
export function fallbackRequestName(r: HttpRequest | GrpcRequest | null): string {
|
||||
export function fallbackRequestName(r: HttpRequest | GrpcRequest | AnyModel | null): string {
|
||||
if (r == null) return '';
|
||||
|
||||
// Return name if it has one
|
||||
if (r.name) {
|
||||
if ('name' in r && r.name) {
|
||||
return r.name;
|
||||
}
|
||||
|
||||
if (r.model !== 'http_request' && r.model !== 'grpc_request') {
|
||||
return 'No Name';
|
||||
}
|
||||
|
||||
// Replace variable syntax with variable name
|
||||
const withoutVariables = r.url.replace(/\$\{\[\s*([^\]\s]+)\s*]}/g, '$1');
|
||||
if (withoutVariables.trim() === '') {
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"@codemirror/lang-xml": "^6.0.2",
|
||||
"@codemirror/language": "^6.6.0",
|
||||
"@codemirror/search": "^6.2.3",
|
||||
"@gilbarbara/deep-equal": "^0.3.1",
|
||||
"@lezer/highlight": "^1.1.3",
|
||||
"@lezer/lr": "^1.3.3",
|
||||
"@react-hook/size": "^2.1.2",
|
||||
|
||||
Reference in New Issue
Block a user