mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-03-21 00:49:17 +01:00
Better header editor and added completion data
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
import { formatSdl } from 'format-graphql';
|
||||
import { useMemo } from 'react';
|
||||
import { useUniqueKey } from '../../hooks/useUniqueKey';
|
||||
import { Divider } from '../core/Divider';
|
||||
import type { EditorProps } from '../core/Editor';
|
||||
import { Editor } from '../core/Editor';
|
||||
import { useUniqueKey } from '../hooks/useUniqueKey';
|
||||
import { Divider } from './core/Divider';
|
||||
import type { EditorProps } from './core/Editor';
|
||||
import { Editor } from './core/Editor';
|
||||
|
||||
type Props = Pick<EditorProps, 'heightMode' | 'onChange' | 'defaultValue' | 'className'>;
|
||||
|
||||
52
src-web/components/HeaderEditor.tsx
Normal file
52
src-web/components/HeaderEditor.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import { charsets } from '../lib/data/charsets';
|
||||
import { connections } from '../lib/data/connections';
|
||||
import { encodings } from '../lib/data/encodings';
|
||||
import { headerNames } from '../lib/data/headerNames';
|
||||
import { mimeTypes } from '../lib/data/mimetypes';
|
||||
import type { HttpRequest } from '../lib/models';
|
||||
import type { GenericCompletionConfig } from './core/Editor/genericCompletion';
|
||||
import type { PairEditorProps } from './core/PairEditor';
|
||||
import { PairEditor } from './core/PairEditor';
|
||||
|
||||
type Props = {
|
||||
headers: HttpRequest['headers'];
|
||||
onChange: (headers: HttpRequest['headers']) => void;
|
||||
};
|
||||
|
||||
export function HeaderEditor({ headers, onChange }: Props) {
|
||||
return (
|
||||
<PairEditor
|
||||
pairs={headers}
|
||||
onChange={onChange}
|
||||
nameAutocomplete={nameAutocomplete}
|
||||
valueAutocomplete={valueAutocomplete}
|
||||
namePlaceholder="Header-Name"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const MIN_MATCH = 3;
|
||||
|
||||
const headerOptionsMap: Record<string, string[]> = {
|
||||
'content-type': mimeTypes,
|
||||
accept: ['*/*', ...mimeTypes],
|
||||
'accept-encoding': encodings,
|
||||
connection: connections,
|
||||
'accept-charset': charsets,
|
||||
};
|
||||
|
||||
const valueAutocomplete = (headerName: string): GenericCompletionConfig | undefined => {
|
||||
const name = headerName.toLowerCase().trim();
|
||||
const options: GenericCompletionConfig['options'] =
|
||||
headerOptionsMap[name]?.map((o, i) => ({
|
||||
label: o,
|
||||
type: 'constant',
|
||||
boost: 99 - i, // Max boost is 99
|
||||
})) ?? [];
|
||||
return { minMatch: MIN_MATCH, options };
|
||||
};
|
||||
|
||||
const nameAutocomplete: PairEditorProps['nameAutocomplete'] = {
|
||||
minMatch: MIN_MATCH,
|
||||
options: headerNames.map((t, i) => ({ label: t, type: 'constant', boost: 99 - i })),
|
||||
};
|
||||
11
src-web/components/ParameterEditor.tsx
Normal file
11
src-web/components/ParameterEditor.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
import type { HttpRequest } from '../lib/models';
|
||||
import { PairEditor } from './core/PairEditor';
|
||||
|
||||
type Props = {
|
||||
parameters: { name: string; value: string }[];
|
||||
onChange: (headers: HttpRequest['headers']) => void;
|
||||
};
|
||||
|
||||
export function ParametersEditor({ parameters, onChange }: Props) {
|
||||
return <PairEditor pairs={parameters} onChange={onChange} namePlaceholder="param_name" />;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import classnames from 'classnames';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
import { useActiveRequest } from '../hooks/useActiveRequest';
|
||||
import { useKeyValue } from '../hooks/useKeyValue';
|
||||
import { useUpdateRequest } from '../hooks/useUpdateRequest';
|
||||
@@ -9,7 +10,9 @@ import { Editor } from './core/Editor';
|
||||
import { PairEditor } from './core/PairEditor';
|
||||
import type { TabItem } from './core/Tabs/Tabs';
|
||||
import { TabContent, Tabs } from './core/Tabs/Tabs';
|
||||
import { GraphQLEditor } from './editors/GraphQLEditor';
|
||||
import { GraphQLEditor } from './GraphQLEditor';
|
||||
import { HeaderEditor } from './HeaderEditor';
|
||||
import { ParametersEditor } from './ParameterEditor';
|
||||
import { UrlBar } from './UrlBar';
|
||||
|
||||
interface Props {
|
||||
@@ -67,12 +70,15 @@ export function RequestPane({ fullHeight, className }: Props) {
|
||||
label="Request body"
|
||||
>
|
||||
<TabContent value="headers">
|
||||
<PairEditor
|
||||
key={activeRequest.id}
|
||||
pairs={activeRequest.headers}
|
||||
<HeaderEditor
|
||||
key={activeRequestId}
|
||||
headers={activeRequest.headers}
|
||||
onChange={handleHeadersChange}
|
||||
/>
|
||||
</TabContent>
|
||||
<TabContent value="params">
|
||||
<ParametersEditor key={activeRequestId} parameters={[]} onChange={() => null} />
|
||||
</TabContent>
|
||||
<TabContent value="body">
|
||||
{activeRequest.bodyType === 'json' ? (
|
||||
<Editor
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useUnmount } from 'react-use';
|
||||
import { IconButton } from '../IconButton';
|
||||
import './Editor.css';
|
||||
import { baseExtensions, getLanguageExtension, multiLineExtensions } from './extensions';
|
||||
import type { GenericCompletionOption } from './genericCompletion';
|
||||
import type { GenericCompletionConfig } from './genericCompletion';
|
||||
import { singleLineExt } from './singleLine';
|
||||
|
||||
export interface _EditorProps {
|
||||
@@ -27,7 +27,7 @@ export interface _EditorProps {
|
||||
onFocus?: () => void;
|
||||
singleLine?: boolean;
|
||||
format?: (v: string) => string;
|
||||
autocompleteOptions?: GenericCompletionOption[];
|
||||
autocomplete?: GenericCompletionConfig;
|
||||
}
|
||||
|
||||
export function _Editor({
|
||||
@@ -43,7 +43,7 @@ export function _Editor({
|
||||
className,
|
||||
singleLine,
|
||||
format,
|
||||
autocompleteOptions,
|
||||
autocomplete,
|
||||
}: _EditorProps) {
|
||||
const cm = useRef<{ view: EditorView; languageCompartment: Compartment } | null>(null);
|
||||
const wrapperRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -80,16 +80,16 @@ export function _Editor({
|
||||
useEffect(() => {
|
||||
if (cm.current === null) return;
|
||||
const { view, languageCompartment } = cm.current;
|
||||
const ext = getLanguageExtension({ contentType, useTemplating, autocompleteOptions });
|
||||
const ext = getLanguageExtension({ contentType, useTemplating, autocomplete });
|
||||
view.dispatch({ effects: languageCompartment.reconfigure(ext) });
|
||||
}, [contentType, JSON.stringify(autocompleteOptions)]);
|
||||
}, [contentType, autocomplete]);
|
||||
|
||||
// Initialize the editor when ref mounts
|
||||
useEffect(() => {
|
||||
if (wrapperRef.current === null || cm.current !== null) return;
|
||||
try {
|
||||
const languageCompartment = new Compartment();
|
||||
const langExt = getLanguageExtension({ contentType, useTemplating, autocompleteOptions });
|
||||
const langExt = getLanguageExtension({ contentType, useTemplating, autocomplete });
|
||||
const state = EditorState.create({
|
||||
doc: `${defaultValue ?? ''}`,
|
||||
extensions: [
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
import { tags as t } from '@lezer/highlight';
|
||||
import { graphqlLanguageSupport } from 'cm6-graphql';
|
||||
import type { GenericCompletionOption } from './genericCompletion';
|
||||
import type { EditorProps } from './index';
|
||||
import { text } from './text/extension';
|
||||
import { twig } from './twig/extension';
|
||||
import { url } from './url/extension';
|
||||
@@ -95,19 +96,15 @@ const syntaxExtensions: Record<string, LanguageSupport> = {
|
||||
export function getLanguageExtension({
|
||||
contentType,
|
||||
useTemplating = false,
|
||||
autocompleteOptions,
|
||||
}: {
|
||||
contentType?: string;
|
||||
useTemplating?: boolean;
|
||||
autocompleteOptions?: GenericCompletionOption[];
|
||||
}) {
|
||||
autocomplete,
|
||||
}: Pick<EditorProps, 'contentType' | 'useTemplating' | 'autocomplete'>) {
|
||||
const justContentType = contentType?.split(';')[0] ?? contentType ?? '';
|
||||
const base = syntaxExtensions[justContentType] ?? text();
|
||||
if (!useTemplating) {
|
||||
return base ? base : [];
|
||||
}
|
||||
|
||||
return twig(base, autocompleteOptions);
|
||||
return twig(base, autocomplete);
|
||||
}
|
||||
|
||||
export const baseExtensions = [
|
||||
|
||||
@@ -3,17 +3,21 @@ import type { CompletionContext } from '@codemirror/autocomplete';
|
||||
export interface GenericCompletionOption {
|
||||
label: string;
|
||||
type: 'constant' | 'variable';
|
||||
/** When given, should be a number from -99 to 99 that adjusts
|
||||
* how this completion is ranked compared to other completions
|
||||
* that match the input as well as this one. A negative number
|
||||
* moves it down the list, a positive number moves it up. */
|
||||
boost?: number;
|
||||
}
|
||||
|
||||
export function genericCompletion({
|
||||
options,
|
||||
minMatch = 1,
|
||||
}: {
|
||||
options: GenericCompletionOption[];
|
||||
export interface GenericCompletionConfig {
|
||||
minMatch?: number;
|
||||
}) {
|
||||
options: GenericCompletionOption[];
|
||||
}
|
||||
|
||||
export function genericCompletion({ options, minMatch = 1 }: GenericCompletionConfig) {
|
||||
return function completions(context: CompletionContext) {
|
||||
const toMatch = context.matchBefore(/^[\w:/]*/);
|
||||
const toMatch = context.matchBefore(/^.*/);
|
||||
if (toMatch === null) return null;
|
||||
|
||||
const matchedMinimumLength = toMatch.to - toMatch.from >= minMatch;
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { LanguageSupport, LRLanguage } from '@codemirror/language';
|
||||
import { parseMixed } from '@lezer/common';
|
||||
import type { GenericCompletionOption } from '../genericCompletion';
|
||||
import type { GenericCompletionConfig } from '../genericCompletion';
|
||||
import { genericCompletion } from '../genericCompletion';
|
||||
import { placeholders } from '../widgets';
|
||||
import { completions } from './completion';
|
||||
import { parser as twigParser } from './twig';
|
||||
|
||||
export function twig(base?: LanguageSupport, autocompleteOptions?: GenericCompletionOption[]) {
|
||||
export function twig(base?: LanguageSupport, autocomplete?: GenericCompletionConfig) {
|
||||
const language = mixedOrPlainLanguage(base);
|
||||
const additionalCompletion =
|
||||
autocompleteOptions && base
|
||||
? [language.data.of({ autocomplete: genericCompletion({ options: autocompleteOptions }) })]
|
||||
autocomplete && base
|
||||
? [language.data.of({ autocomplete: genericCompletion(autocomplete) })]
|
||||
: [];
|
||||
const completion = language.data.of({
|
||||
autocomplete: completions,
|
||||
|
||||
@@ -12,7 +12,7 @@ type Props = Omit<HTMLAttributes<HTMLInputElement>, 'onChange' | 'onFocus'> & {
|
||||
containerClassName?: string;
|
||||
onChange?: (value: string) => void;
|
||||
onFocus?: () => void;
|
||||
useEditor?: Pick<EditorProps, 'contentType' | 'useTemplating' | 'autocompleteOptions'>;
|
||||
useEditor?: Pick<EditorProps, 'contentType' | 'useTemplating' | 'autocomplete'>;
|
||||
defaultValue?: string;
|
||||
leftSlot?: ReactNode;
|
||||
rightSlot?: ReactNode;
|
||||
|
||||
@@ -1,35 +1,39 @@
|
||||
import classnames from 'classnames';
|
||||
import { memo, useEffect, useMemo, useState } from 'react';
|
||||
import type { GenericCompletionOption } from './Editor/genericCompletion';
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import type { GenericCompletionConfig } from './Editor/genericCompletion';
|
||||
import { IconButton } from './IconButton';
|
||||
import { Input } from './Input';
|
||||
import { VStack } from './Stacks';
|
||||
|
||||
interface Props {
|
||||
export type PairEditorProps = {
|
||||
pairs: Pair[];
|
||||
onChange: (pairs: Pair[]) => void;
|
||||
className?: string;
|
||||
}
|
||||
namePlaceholder?: string;
|
||||
valuePlaceholder?: string;
|
||||
nameAutocomplete?: GenericCompletionConfig;
|
||||
valueAutocomplete?: (name: string) => GenericCompletionConfig | undefined;
|
||||
};
|
||||
|
||||
interface Pair {
|
||||
type Pair = {
|
||||
name: string;
|
||||
value: string;
|
||||
}
|
||||
};
|
||||
|
||||
interface PairContainer {
|
||||
type PairContainer = {
|
||||
pair: Pair;
|
||||
id: string;
|
||||
}
|
||||
};
|
||||
|
||||
export const PairEditor = memo(function PairEditor({
|
||||
pairs: originalPairs,
|
||||
nameAutocomplete,
|
||||
valueAutocomplete,
|
||||
namePlaceholder,
|
||||
valuePlaceholder,
|
||||
className,
|
||||
onChange,
|
||||
}: Props) {
|
||||
const newPairContainer = (): PairContainer => {
|
||||
return { pair: { name: '', value: '' }, id: Math.random().toString() };
|
||||
};
|
||||
|
||||
}: PairEditorProps) {
|
||||
const [pairs, setPairs] = useState<PairContainer[]>(() => {
|
||||
// Remove empty headers on initial render
|
||||
const nonEmpty = originalPairs.filter((h) => !(h.name === '' && h.value === ''));
|
||||
@@ -37,17 +41,20 @@ export const PairEditor = memo(function PairEditor({
|
||||
return [...pairs, newPairContainer()];
|
||||
});
|
||||
|
||||
const setPairsAndSave = (fn: (pairs: PairContainer[]) => PairContainer[]) => {
|
||||
setPairs((oldPairs) => {
|
||||
const pairs = fn(oldPairs).map((p) => p.pair);
|
||||
onChange(pairs);
|
||||
return fn(oldPairs);
|
||||
});
|
||||
};
|
||||
const setPairsAndSave = useCallback(
|
||||
(fn: (pairs: PairContainer[]) => PairContainer[]) => {
|
||||
setPairs((oldPairs) => {
|
||||
const pairs = fn(oldPairs).map((p) => p.pair);
|
||||
onChange(pairs);
|
||||
return fn(oldPairs);
|
||||
});
|
||||
},
|
||||
[onChange],
|
||||
);
|
||||
|
||||
const handleChangeHeader = (pair: PairContainer) => {
|
||||
const handleChangeHeader = useCallback((pair: PairContainer) => {
|
||||
setPairsAndSave((pairs) => pairs.map((p) => (pair.id !== p.id ? p : pair)));
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Ensure there's always at least one pair
|
||||
useEffect(() => {
|
||||
@@ -56,9 +63,19 @@ export const PairEditor = memo(function PairEditor({
|
||||
}
|
||||
}, [pairs]);
|
||||
|
||||
const handleDelete = (pair: PairContainer) => {
|
||||
const handleDelete = useCallback((pair: PairContainer) => {
|
||||
setPairsAndSave((oldPairs) => oldPairs.filter((p) => p.id !== pair.id));
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleFocus = useCallback(
|
||||
(pair: PairContainer) => {
|
||||
const isLast = pair.id === pairs[pairs.length - 1]?.id;
|
||||
if (isLast) {
|
||||
setPairs((pairs) => [...pairs, newPairContainer()]);
|
||||
}
|
||||
},
|
||||
[pairs],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={classnames(className, 'pb-6 grid')}>
|
||||
@@ -71,11 +88,11 @@ export const PairEditor = memo(function PairEditor({
|
||||
pairContainer={p}
|
||||
isLast={isLast}
|
||||
onChange={handleChangeHeader}
|
||||
onFocus={() => {
|
||||
if (isLast) {
|
||||
setPairs((pairs) => [...pairs, newPairContainer()]);
|
||||
}
|
||||
}}
|
||||
nameAutocomplete={nameAutocomplete}
|
||||
valueAutocomplete={valueAutocomplete}
|
||||
namePlaceholder={namePlaceholder}
|
||||
valuePlaceholder={valuePlaceholder}
|
||||
onFocus={handleFocus}
|
||||
onDelete={isLast ? undefined : handleDelete}
|
||||
/>
|
||||
);
|
||||
@@ -85,46 +102,65 @@ export const PairEditor = memo(function PairEditor({
|
||||
);
|
||||
});
|
||||
|
||||
type FormRowProps = {
|
||||
pairContainer: PairContainer;
|
||||
onChange: (pair: PairContainer) => void;
|
||||
onDelete?: (pair: PairContainer) => void;
|
||||
onFocus?: (pair: PairContainer) => void;
|
||||
isLast?: boolean;
|
||||
} & Pick<
|
||||
PairEditorProps,
|
||||
'nameAutocomplete' | 'valueAutocomplete' | 'namePlaceholder' | 'valuePlaceholder'
|
||||
>;
|
||||
|
||||
const FormRow = memo(function FormRow({
|
||||
pairContainer,
|
||||
onChange,
|
||||
onDelete,
|
||||
onFocus,
|
||||
isLast,
|
||||
}: {
|
||||
pairContainer: PairContainer;
|
||||
onChange: (pair: PairContainer) => void;
|
||||
onDelete?: (pair: PairContainer) => void;
|
||||
onFocus?: () => void;
|
||||
isLast?: boolean;
|
||||
}) {
|
||||
nameAutocomplete,
|
||||
valueAutocomplete,
|
||||
namePlaceholder,
|
||||
valuePlaceholder,
|
||||
}: FormRowProps) {
|
||||
const { id } = pairContainer;
|
||||
const valueOptions = useMemo<GenericCompletionOption[] | undefined>(() => {
|
||||
if (pairContainer.pair.name.toLowerCase() === 'content-type') {
|
||||
return [
|
||||
{ label: 'application/json', type: 'constant' },
|
||||
{ label: 'text/xml', type: 'constant' },
|
||||
{ label: 'text/html', type: 'constant' },
|
||||
];
|
||||
}
|
||||
return undefined;
|
||||
}, [pairContainer.pair.value]);
|
||||
|
||||
const handleChangeName = useMemo(
|
||||
() => (name: string) => onChange({ id, pair: { name, value: pairContainer.pair.value } }),
|
||||
[onChange, pairContainer.pair.value],
|
||||
);
|
||||
|
||||
const handleChangeValue = useMemo(
|
||||
() => (value: string) => onChange({ id, pair: { value, name: pairContainer.pair.name } }),
|
||||
[onChange, pairContainer.pair.name],
|
||||
);
|
||||
|
||||
const nameEditorConfig = useMemo(
|
||||
() => ({ useTemplating: true, autocomplete: nameAutocomplete }),
|
||||
[nameAutocomplete],
|
||||
);
|
||||
|
||||
const valueEditorConfig = useMemo(
|
||||
() => ({ useTemplating: true, autocomplete: valueAutocomplete?.(pairContainer.pair.name) }),
|
||||
[valueAutocomplete, pairContainer.pair.name],
|
||||
);
|
||||
|
||||
const handleFocus = useCallback(() => onFocus?.(pairContainer), [onFocus, pairContainer]);
|
||||
const handleDelete = useCallback(() => onDelete?.(pairContainer), [onDelete, pairContainer]);
|
||||
|
||||
return (
|
||||
<div className="group grid grid-cols-[1fr_1fr_auto] grid-rows-1 gap-2 items-center">
|
||||
<div className="group grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] grid-rows-1 gap-2 items-center">
|
||||
<Input
|
||||
hideLabel
|
||||
containerClassName={classnames(isLast && 'border-dashed')}
|
||||
defaultValue={pairContainer.pair.name}
|
||||
label="Name"
|
||||
name="name"
|
||||
onChange={(name) => onChange({ id, pair: { name, value: pairContainer.pair.value } })}
|
||||
onFocus={onFocus}
|
||||
placeholder={isLast ? 'new name' : 'name'}
|
||||
useEditor={{
|
||||
useTemplating: true,
|
||||
autocompleteOptions: [{ label: 'Content-Type', type: 'constant' }],
|
||||
}}
|
||||
onChange={handleChangeName}
|
||||
onFocus={handleFocus}
|
||||
placeholder={namePlaceholder ?? 'name'}
|
||||
useEditor={nameEditorConfig}
|
||||
/>
|
||||
<Input
|
||||
hideLabel
|
||||
@@ -132,16 +168,16 @@ const FormRow = memo(function FormRow({
|
||||
defaultValue={pairContainer.pair.value}
|
||||
label="Value"
|
||||
name="value"
|
||||
onChange={(value) => onChange({ id, pair: { name: pairContainer.pair.name, value } })}
|
||||
onFocus={onFocus}
|
||||
placeholder={isLast ? 'new value' : 'value'}
|
||||
useEditor={{ useTemplating: true, autocompleteOptions: valueOptions }}
|
||||
onChange={handleChangeValue}
|
||||
onFocus={handleFocus}
|
||||
placeholder={valuePlaceholder ?? 'value'}
|
||||
useEditor={valueEditorConfig}
|
||||
/>
|
||||
{onDelete ? (
|
||||
<IconButton
|
||||
icon="trash"
|
||||
title="Delete header"
|
||||
onClick={() => onDelete(pairContainer)}
|
||||
onClick={handleDelete}
|
||||
tabIndex={-1}
|
||||
className={classnames('opacity-0 group-hover:opacity-100')}
|
||||
/>
|
||||
@@ -151,3 +187,7 @@ const FormRow = memo(function FormRow({
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
const newPairContainer = (): PairContainer => {
|
||||
return { pair: { name: '', value: '' }, id: Math.random().toString() };
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user