mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-04-23 09:08:32 +02:00
Prevent sidebar re-render on every keypress (#152)
This commit is contained in:
@@ -18,6 +18,7 @@ import { generateId } from '../../lib/generateId';
|
||||
import { DropMarker } from '../DropMarker';
|
||||
import { SelectFile } from '../SelectFile';
|
||||
import { Checkbox } from './Checkbox';
|
||||
import type { DropdownItem } from './Dropdown';
|
||||
import { Dropdown } from './Dropdown';
|
||||
import type { GenericCompletionConfig } from './Editor/genericCompletion';
|
||||
import { Icon } from './Icon';
|
||||
@@ -25,6 +26,7 @@ import { IconButton } from './IconButton';
|
||||
import type { InputProps } from './Input';
|
||||
import { Input } from './Input';
|
||||
import { PlainInput } from './PlainInput';
|
||||
import type { RadioDropdownItem } from './RadioDropdown';
|
||||
import { RadioDropdown } from './RadioDropdown';
|
||||
|
||||
export interface PairEditorRef {
|
||||
@@ -51,7 +53,7 @@ export type PairEditorProps = {
|
||||
};
|
||||
|
||||
export type Pair = {
|
||||
id?: string;
|
||||
id: string;
|
||||
enabled?: boolean;
|
||||
name: string;
|
||||
value: string;
|
||||
@@ -60,11 +62,6 @@ export type Pair = {
|
||||
readOnlyName?: boolean;
|
||||
};
|
||||
|
||||
type PairContainer = {
|
||||
pair: Pair;
|
||||
id: string;
|
||||
};
|
||||
|
||||
export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function PairEditor(
|
||||
{
|
||||
stateKey,
|
||||
@@ -89,11 +86,11 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
const [forceFocusNamePairId, setForceFocusNamePairId] = useState<string | null>(null);
|
||||
const [forceFocusValuePairId, setForceFocusValuePairId] = useState<string | null>(null);
|
||||
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
|
||||
const [pairs, setPairs] = useState<PairContainer[]>(() => {
|
||||
const [pairs, setPairs] = useState<Pair[]>(() => {
|
||||
// Remove empty headers on initial render
|
||||
const nonEmpty = originalPairs.filter((h) => !(h.name === '' && h.value === ''));
|
||||
const pairs = nonEmpty.map((pair) => newPairContainer(pair));
|
||||
return [...pairs, newPairContainer()];
|
||||
const pairs = nonEmpty.map((pair) => ensureValidPair(pair));
|
||||
return [...pairs, ensureValidPair()];
|
||||
});
|
||||
|
||||
useImperativeHandle(
|
||||
@@ -114,7 +111,7 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
const nonEmpty = originalPairs.filter(
|
||||
(h, i) => i !== originalPairs.length - 1 && !(h.name === '' && h.value === ''),
|
||||
);
|
||||
const newPairs = nonEmpty.map((pair) => newPairContainer(pair));
|
||||
const newPairs = nonEmpty.map((pair) => ensureValidPair(pair));
|
||||
if (!deepEqual(pairs, newPairs)) {
|
||||
setPairs(pairs);
|
||||
}
|
||||
@@ -123,11 +120,11 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
}, [forceUpdateKey]);
|
||||
|
||||
const setPairsAndSave = useCallback(
|
||||
(fn: (pairs: PairContainer[]) => PairContainer[]) => {
|
||||
(fn: (pairs: Pair[]) => Pair[]) => {
|
||||
setPairs((oldPairs) => {
|
||||
const pairs = fn(oldPairs).map((p) => p.pair);
|
||||
const pairs = fn(oldPairs);
|
||||
onChange(pairs);
|
||||
return fn(oldPairs);
|
||||
return pairs;
|
||||
});
|
||||
},
|
||||
[onChange],
|
||||
@@ -161,13 +158,12 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(pair: PairContainer) =>
|
||||
setPairsAndSave((pairs) => pairs.map((p) => (pair.id !== p.id ? p : pair))),
|
||||
(pair: Pair) => setPairsAndSave((pairs) => pairs.map((p) => (pair.id !== p.id ? p : pair))),
|
||||
[setPairsAndSave],
|
||||
);
|
||||
|
||||
const handleDelete = useCallback(
|
||||
(pair: PairContainer, focusPrevious: boolean) => {
|
||||
(pair: Pair, focusPrevious: boolean) => {
|
||||
if (focusPrevious) {
|
||||
const index = pairs.findIndex((p) => p.id === pair.id);
|
||||
const id = pairs[index - 1]?.id ?? null;
|
||||
@@ -179,13 +175,13 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
);
|
||||
|
||||
const handleFocus = useCallback(
|
||||
(pair: PairContainer) =>
|
||||
(pair: Pair) =>
|
||||
setPairs((pairs) => {
|
||||
setForceFocusNamePairId(null); // Remove focus override when something focused
|
||||
setForceFocusValuePairId(null); // Remove focus override when something focused
|
||||
const isLast = pair.id === pairs[pairs.length - 1]?.id;
|
||||
if (isLast) {
|
||||
const newPair = newPairContainer();
|
||||
const newPair = ensureValidPair();
|
||||
const prevPair = pairs[pairs.length - 1];
|
||||
setForceFocusNamePairId(prevPair?.id ?? null);
|
||||
return [...pairs, newPair];
|
||||
@@ -199,7 +195,7 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
// Ensure there's always at least one pair
|
||||
useEffect(() => {
|
||||
if (pairs.length === 0) {
|
||||
setPairs((pairs) => [...pairs, newPairContainer()]);
|
||||
setPairs((pairs) => [...pairs, ensureValidPair()]);
|
||||
}
|
||||
}, [pairs]);
|
||||
|
||||
@@ -238,7 +234,7 @@ export const PairEditor = forwardRef<PairEditorRef, PairEditorProps>(function Pa
|
||||
onEnd={handleEnd}
|
||||
onFocus={handleFocus}
|
||||
onMove={handleMove}
|
||||
pairContainer={p}
|
||||
pair={p}
|
||||
stateKey={stateKey}
|
||||
valueAutocomplete={valueAutocomplete}
|
||||
valueAutocompleteVariables={valueAutocompleteVariables}
|
||||
@@ -259,15 +255,15 @@ enum ItemTypes {
|
||||
|
||||
type PairEditorRowProps = {
|
||||
className?: string;
|
||||
pairContainer: PairContainer;
|
||||
pair: Pair;
|
||||
forceFocusNamePairId?: string | null;
|
||||
forceFocusValuePairId?: string | null;
|
||||
onMove: (id: string, side: 'above' | 'below') => void;
|
||||
onEnd: (id: string) => void;
|
||||
onChange: (pair: PairContainer) => void;
|
||||
onDelete?: (pair: PairContainer, focusPrevious: boolean) => void;
|
||||
onFocus?: (pair: PairContainer) => void;
|
||||
onSubmit?: (pair: PairContainer) => void;
|
||||
onChange: (pair: Pair) => void;
|
||||
onDelete?: (pair: Pair, focusPrevious: boolean) => void;
|
||||
onFocus?: (pair: Pair) => void;
|
||||
onSubmit?: (pair: Pair) => void;
|
||||
isLast?: boolean;
|
||||
index: number;
|
||||
} & Pick<
|
||||
@@ -303,7 +299,7 @@ function PairEditorRow({
|
||||
onEnd,
|
||||
onFocus,
|
||||
onMove,
|
||||
pairContainer,
|
||||
pair,
|
||||
stateKey,
|
||||
valueAutocomplete,
|
||||
valueAutocompleteVariables,
|
||||
@@ -311,62 +307,65 @@ function PairEditorRow({
|
||||
valueType,
|
||||
valueValidate,
|
||||
}: PairEditorRowProps) {
|
||||
const { id } = pairContainer;
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const prompt = usePrompt();
|
||||
const nameInputRef = useRef<EditorView>(null);
|
||||
const valueInputRef = useRef<EditorView>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (forceFocusNamePairId === pairContainer.id) {
|
||||
if (forceFocusNamePairId === pair.id) {
|
||||
nameInputRef.current?.focus();
|
||||
}
|
||||
}, [forceFocusNamePairId, pairContainer.id]);
|
||||
}, [forceFocusNamePairId, pair.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (forceFocusValuePairId === pairContainer.id) {
|
||||
if (forceFocusValuePairId === pair.id) {
|
||||
valueInputRef.current?.focus();
|
||||
}
|
||||
}, [forceFocusValuePairId, pairContainer.id]);
|
||||
}, [forceFocusValuePairId, pair.id]);
|
||||
|
||||
const handleFocus = useCallback(() => onFocus?.(pair), [onFocus, pair]);
|
||||
const handleDelete = useCallback(() => onDelete?.(pair, false), [onDelete, pair]);
|
||||
|
||||
const getDeleteItems = useCallback(
|
||||
(): DropdownItem[] => [
|
||||
{
|
||||
key: 'delete',
|
||||
label: 'Delete',
|
||||
onSelect: handleDelete,
|
||||
variant: 'danger',
|
||||
},
|
||||
],
|
||||
[handleDelete],
|
||||
);
|
||||
|
||||
const handleChangeEnabled = useMemo(
|
||||
() => (enabled: boolean) => onChange({ id, pair: { ...pairContainer.pair, enabled } }),
|
||||
[id, onChange, pairContainer.pair],
|
||||
() => (enabled: boolean) => onChange({ ...pair, enabled }),
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const handleChangeName = useMemo(
|
||||
() => (name: string) => onChange({ id, pair: { ...pairContainer.pair, name } }),
|
||||
[onChange, id, pairContainer.pair],
|
||||
() => (name: string) => onChange({ ...pair, name }),
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const handleChangeValueText = useMemo(
|
||||
() => (value: string) =>
|
||||
onChange({ id, pair: { ...pairContainer.pair, value, isFile: false } }),
|
||||
[onChange, id, pairContainer.pair],
|
||||
() => (value: string) => onChange({ ...pair, value, isFile: false }),
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const handleChangeValueFile = useMemo(
|
||||
() =>
|
||||
({ filePath }: { filePath: string | null }) =>
|
||||
onChange({
|
||||
id,
|
||||
pair: { ...pairContainer.pair, value: filePath ?? '', isFile: true },
|
||||
}),
|
||||
[onChange, id, pairContainer.pair],
|
||||
onChange({ ...pair, value: filePath ?? '', isFile: true }),
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const handleChangeValueContentType = useMemo(
|
||||
() => (contentType: string) => onChange({ id, pair: { ...pairContainer.pair, contentType } }),
|
||||
[onChange, id, pairContainer.pair],
|
||||
() => (contentType: string) => onChange({ ...pair, contentType }),
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const handleFocus = useCallback(() => onFocus?.(pairContainer), [onFocus, pairContainer]);
|
||||
const handleDelete = useCallback(
|
||||
() => onDelete?.(pairContainer, false),
|
||||
[onDelete, pairContainer],
|
||||
);
|
||||
|
||||
const [, connectDrop] = useDrop<PairContainer>(
|
||||
const [, connectDrop] = useDrop<Pair>(
|
||||
{
|
||||
accept: ItemTypes.ROW,
|
||||
hover: (_, monitor) => {
|
||||
@@ -375,7 +374,7 @@ function PairEditorRow({
|
||||
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
|
||||
const clientOffset = monitor.getClientOffset();
|
||||
const hoverClientY = (clientOffset as XYCoord).y - hoverBoundingRect.top;
|
||||
onMove(pairContainer.id, hoverClientY < hoverMiddleY ? 'above' : 'below');
|
||||
onMove(pair.id, hoverClientY < hoverMiddleY ? 'above' : 'below');
|
||||
},
|
||||
},
|
||||
[onMove],
|
||||
@@ -384,11 +383,11 @@ function PairEditorRow({
|
||||
const [, connectDrag] = useDrag(
|
||||
{
|
||||
type: ItemTypes.ROW,
|
||||
item: () => pairContainer,
|
||||
item: () => pair,
|
||||
collect: (m) => ({ isDragging: m.isDragging() }),
|
||||
end: () => onEnd(pairContainer.id),
|
||||
end: () => onEnd(pair.id),
|
||||
},
|
||||
[pairContainer, onEnd],
|
||||
[pair, onEnd],
|
||||
);
|
||||
|
||||
connectDrag(ref);
|
||||
@@ -401,7 +400,7 @@ function PairEditorRow({
|
||||
className,
|
||||
'group grid grid-cols-[auto_auto_minmax(0,1fr)_auto]',
|
||||
'grid-rows-1 items-center',
|
||||
!pairContainer.pair.enabled && 'opacity-60',
|
||||
!pair.enabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
{!isLast ? (
|
||||
@@ -418,9 +417,9 @@ function PairEditorRow({
|
||||
)}
|
||||
<Checkbox
|
||||
hideLabel
|
||||
title={pairContainer.pair.enabled ? 'Disable item' : 'Enable item'}
|
||||
title={pair.enabled ? 'Disable item' : 'Enable item'}
|
||||
disabled={isLast}
|
||||
checked={isLast ? false : !!pairContainer.pair.enabled}
|
||||
checked={isLast ? false : !!pair.enabled}
|
||||
className={classNames('pr-2', isLast && '!opacity-disabled')}
|
||||
onChange={handleChangeEnabled}
|
||||
/>
|
||||
@@ -448,15 +447,15 @@ function PairEditorRow({
|
||||
ref={nameInputRef}
|
||||
hideLabel
|
||||
useTemplating
|
||||
stateKey={`name.${pairContainer.id}.${stateKey}`}
|
||||
stateKey={`name.${pair.id}.${stateKey}`}
|
||||
wrapLines={false}
|
||||
readOnly={pairContainer.pair.readOnlyName}
|
||||
readOnly={pair.readOnlyName}
|
||||
size="sm"
|
||||
require={!isLast && !!pairContainer.pair.enabled && !!pairContainer.pair.value}
|
||||
require={!isLast && !!pair.enabled && !!pair.value}
|
||||
validate={nameValidate}
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
containerClassName={classNames(isLast && 'border-dashed')}
|
||||
defaultValue={pairContainer.pair.name}
|
||||
defaultValue={pair.name}
|
||||
label="Name"
|
||||
name={`name[${index}]`}
|
||||
onChange={handleChangeName}
|
||||
@@ -467,13 +466,8 @@ function PairEditorRow({
|
||||
/>
|
||||
)}
|
||||
<div className="w-full grid grid-cols-[minmax(0,1fr)_auto] gap-1 items-center">
|
||||
{pairContainer.pair.isFile ? (
|
||||
<SelectFile
|
||||
inline
|
||||
size="xs"
|
||||
filePath={pairContainer.pair.value}
|
||||
onChange={handleChangeValueFile}
|
||||
/>
|
||||
{pair.isFile ? (
|
||||
<SelectFile inline size="xs" filePath={pair.value} onChange={handleChangeValueFile} />
|
||||
) : isLast ? (
|
||||
// Use PlainInput for last ones because there's a unique bug where clicking below
|
||||
// the Codemirror input focuses it.
|
||||
@@ -491,93 +485,35 @@ function PairEditorRow({
|
||||
ref={valueInputRef}
|
||||
hideLabel
|
||||
useTemplating
|
||||
stateKey={`value.${pairContainer.id}.${stateKey}`}
|
||||
stateKey={`value.${pair.id}.${stateKey}`}
|
||||
wrapLines={false}
|
||||
size="sm"
|
||||
containerClassName={classNames(isLast && 'border-dashed')}
|
||||
validate={valueValidate}
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
defaultValue={pairContainer.pair.value}
|
||||
defaultValue={pair.value}
|
||||
label="Value"
|
||||
name={`value[${index}]`}
|
||||
onChange={handleChangeValueText}
|
||||
onFocus={handleFocus}
|
||||
type={isLast ? 'text' : valueType}
|
||||
placeholder={valuePlaceholder ?? 'value'}
|
||||
autocomplete={valueAutocomplete?.(pairContainer.pair.name)}
|
||||
autocomplete={valueAutocomplete?.(pair.name)}
|
||||
autocompleteVariables={valueAutocompleteVariables}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{allowFileValues ? (
|
||||
<RadioDropdown
|
||||
value={pairContainer.pair.isFile ? 'file' : 'text'}
|
||||
onChange={(v) => {
|
||||
if (v === 'file') handleChangeValueFile({ filePath: '' });
|
||||
else handleChangeValueText('');
|
||||
}}
|
||||
items={[
|
||||
{ label: 'Text', value: 'text' },
|
||||
{ label: 'File', value: 'file' },
|
||||
]}
|
||||
extraItems={[
|
||||
{
|
||||
key: 'mime',
|
||||
label: 'Set Content-Type',
|
||||
leftSlot: <Icon icon="pencil" />,
|
||||
hidden: !pairContainer.pair.isFile,
|
||||
onSelect: async () => {
|
||||
const contentType = await prompt({
|
||||
id: 'content-type',
|
||||
require: false,
|
||||
title: 'Override Content-Type',
|
||||
label: 'Content-Type',
|
||||
placeholder: 'text/plain',
|
||||
defaultValue: pairContainer.pair.contentType ?? '',
|
||||
confirmText: 'Set',
|
||||
description: 'Leave blank to auto-detect',
|
||||
});
|
||||
if (contentType == null) return;
|
||||
handleChangeValueContentType(contentType);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'clear-file',
|
||||
label: 'Unset File',
|
||||
leftSlot: <Icon icon="x" />,
|
||||
hidden: !pairContainer.pair.isFile,
|
||||
onSelect: async () => {
|
||||
handleChangeValueFile({ filePath: null });
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'delete',
|
||||
label: 'Delete',
|
||||
onSelect: handleDelete,
|
||||
variant: 'danger',
|
||||
leftSlot: <Icon icon="trash" />,
|
||||
},
|
||||
]}
|
||||
>
|
||||
<IconButton
|
||||
iconSize="sm"
|
||||
size="xs"
|
||||
icon={isLast ? 'empty' : 'chevron_down'}
|
||||
title="Select form data type"
|
||||
/>
|
||||
</RadioDropdown>
|
||||
<FileActionsDropdown
|
||||
pair={pair}
|
||||
onChangeFile={handleChangeValueFile}
|
||||
onChangeText={handleChangeValueText}
|
||||
onChangeContentType={handleChangeValueContentType}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
) : (
|
||||
<Dropdown
|
||||
items={[
|
||||
{
|
||||
key: 'delete',
|
||||
label: 'Delete',
|
||||
onSelect: handleDelete,
|
||||
variant: 'danger',
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Dropdown items={getDeleteItems}>
|
||||
<IconButton
|
||||
iconSize="sm"
|
||||
size="xs"
|
||||
@@ -590,8 +526,93 @@ function PairEditorRow({
|
||||
);
|
||||
}
|
||||
|
||||
const newPairContainer = (initialPair?: Pair): PairContainer => {
|
||||
const id = initialPair?.id ?? generateId();
|
||||
const pair = initialPair ?? { name: '', value: '', enabled: true, isFile: false };
|
||||
return { id, pair };
|
||||
};
|
||||
const fileItems: RadioDropdownItem<string>[] = [
|
||||
{ label: 'Text', value: 'text' },
|
||||
{ label: 'File', value: 'file' },
|
||||
];
|
||||
|
||||
function FileActionsDropdown({
|
||||
pair,
|
||||
onChangeFile,
|
||||
onChangeText,
|
||||
onChangeContentType,
|
||||
onDelete,
|
||||
}: {
|
||||
pair: Pair;
|
||||
onChangeFile: ({ filePath }: { filePath: string | null }) => void;
|
||||
onChangeText: (text: string) => void;
|
||||
onChangeContentType: (contentType: string) => void;
|
||||
onDelete: () => void;
|
||||
}) {
|
||||
const prompt = usePrompt();
|
||||
const onChange = useCallback(
|
||||
(v: string) => {
|
||||
if (v === 'file') onChangeFile({ filePath: '' });
|
||||
else onChangeText('');
|
||||
},
|
||||
[onChangeFile, onChangeText],
|
||||
);
|
||||
|
||||
const extraItems = useMemo<DropdownItem[]>(
|
||||
() => [
|
||||
{
|
||||
key: 'mime',
|
||||
label: 'Set Content-Type',
|
||||
leftSlot: <Icon icon="pencil" />,
|
||||
hidden: !pair.isFile,
|
||||
onSelect: async () => {
|
||||
const contentType = await prompt({
|
||||
id: 'content-type',
|
||||
require: false,
|
||||
title: 'Override Content-Type',
|
||||
label: 'Content-Type',
|
||||
placeholder: 'text/plain',
|
||||
defaultValue: pair.contentType ?? '',
|
||||
confirmText: 'Set',
|
||||
description: 'Leave blank to auto-detect',
|
||||
});
|
||||
if (contentType == null) return;
|
||||
onChangeContentType(contentType);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'clear-file',
|
||||
label: 'Unset File',
|
||||
leftSlot: <Icon icon="x" />,
|
||||
hidden: pair.isFile,
|
||||
onSelect: async () => {
|
||||
onChangeFile({ filePath: null });
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'delete',
|
||||
label: 'Delete',
|
||||
onSelect: onDelete,
|
||||
variant: 'danger',
|
||||
leftSlot: <Icon icon="trash" />,
|
||||
},
|
||||
],
|
||||
[onChangeContentType, onChangeFile, onDelete, pair.contentType, pair.isFile, prompt],
|
||||
);
|
||||
|
||||
return (
|
||||
<RadioDropdown
|
||||
value={pair.isFile ? 'file' : 'text'}
|
||||
onChange={onChange}
|
||||
items={fileItems}
|
||||
extraItems={extraItems}
|
||||
>
|
||||
<IconButton iconSize="sm" size="xs" icon="chevron_down" title="Select form data type" />
|
||||
</RadioDropdown>
|
||||
);
|
||||
}
|
||||
|
||||
function ensureValidPair(initialPair?: Pair): Pair {
|
||||
return {
|
||||
name: initialPair?.name ?? '',
|
||||
value: initialPair?.value ?? '',
|
||||
enabled: initialPair?.enabled ?? true,
|
||||
isFile: initialPair?.isFile ?? false,
|
||||
id: initialPair?.id || generateId(),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user