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