Better header editor

This commit is contained in:
Gregory Schier
2023-03-15 07:54:04 -07:00
parent 34589f8b06
commit 3aaf365e4a
2 changed files with 36 additions and 26 deletions

View File

@@ -20,9 +20,12 @@ export function HeaderEditor({ request, className }: Props) {
return { header: { name: '', value: '' }, id: Math.random().toString() }; return { header: { name: '', value: '' }, id: Math.random().toString() };
}; };
const [pairs, setPairs] = useState<PairWithId[]>( const [pairs, setPairs] = useState<PairWithId[]>(() => {
request.headers.map((h) => ({ header: h, id: Math.random().toString() })), // Remove empty headers on initial render
); const nonEmpty = request.headers.filter((h) => !(h.name === '' && h.value === ''));
const pairs = nonEmpty.map((h) => ({ header: h, id: Math.random().toString() }));
return [...pairs, newPair()];
});
const setPairsAndSave = (fn: (pairs: PairWithId[]) => PairWithId[]) => { const setPairsAndSave = (fn: (pairs: PairWithId[]) => PairWithId[]) => {
setPairs((oldPairs) => { setPairs((oldPairs) => {
@@ -41,15 +44,10 @@ export function HeaderEditor({ request, className }: Props) {
); );
}; };
// Ensure there's always at least one pair
useEffect(() => { useEffect(() => {
const lastPair = pairs[pairs.length - 1]; if (pairs.length === 0) {
if (lastPair === undefined) { setPairs((pairs) => [...pairs, newPair()]);
setPairsAndSave((pairs) => [...pairs, newPair()]);
return;
}
if (lastPair.header.name !== '' || lastPair.header.value !== '') {
setPairsAndSave((pairs) => [...pairs, newPair()]);
} }
}, [pairs]); }, [pairs]);
@@ -68,6 +66,11 @@ export function HeaderEditor({ request, className }: Props) {
pair={p} pair={p}
isLast={isLast} isLast={isLast}
onChange={handleChangeHeader} onChange={handleChangeHeader}
onFocus={() => {
if (isLast) {
setPairs((pairs) => [...pairs, newPair()]);
}
}}
onDelete={isLast ? undefined : handleDelete} onDelete={isLast ? undefined : handleDelete}
/> />
); );
@@ -81,11 +84,13 @@ function FormRow({
pair, pair,
onChange, onChange,
onDelete, onDelete,
onFocus,
isLast, isLast,
}: { }: {
pair: PairWithId; pair: PairWithId;
onChange: (pair: PairWithId) => void; onChange: (pair: PairWithId) => void;
onDelete?: (pair: PairWithId) => void; onDelete?: (pair: PairWithId) => void;
onFocus?: () => void;
isLast?: boolean; isLast?: boolean;
}) { }) {
return ( return (
@@ -97,7 +102,8 @@ function FormRow({
label="Name" label="Name"
name="name" name="name"
onChange={(name) => onChange({ id: pair.id, header: { name } })} onChange={(name) => onChange({ id: pair.id, header: { name } })}
placeholder="name" onFocus={onFocus}
placeholder={isLast ? 'new name' : 'name'}
useEditor={{ useTemplating: true }} useEditor={{ useTemplating: true }}
/> />
<Input <Input
@@ -107,7 +113,8 @@ function FormRow({
label="Value" label="Value"
name="value" name="value"
onChange={(value) => onChange({ id: pair.id, header: { value } })} onChange={(value) => onChange({ id: pair.id, header: { value } })}
placeholder="value" onFocus={onFocus}
placeholder={isLast ? 'new value' : 'value'}
useEditor={{ useTemplating: true }} useEditor={{ useTemplating: true }}
/> />
{onDelete && ( {onDelete && (

View File

@@ -39,7 +39,7 @@ export function _Editor({
className, className,
singleLine, singleLine,
}: _EditorProps) { }: _EditorProps) {
const cm = useRef<{ view: EditorView; langHolder: Compartment } | null>(null); const cm = useRef<{ view: EditorView; languageCompartment: Compartment } | null>(null);
const wrapperRef = useRef<HTMLDivElement | null>(null); const wrapperRef = useRef<HTMLDivElement | null>(null);
// Unmount the editor // Unmount the editor
@@ -60,30 +60,38 @@ export function _Editor({
handleFocus.current = onFocus; handleFocus.current = onFocus;
}, [onFocus]); }, [onFocus]);
// Update placeholder
const placeholderCompartment = useRef(new Compartment());
useEffect(() => {
if (cm.current === null) return;
const effect = placeholderCompartment.current.reconfigure(placeholderExt(placeholder ?? ''));
cm.current?.view.dispatch({ effects: effect });
}, [placeholder]);
// Update language extension when contentType changes // Update language extension when contentType changes
useEffect(() => { useEffect(() => {
if (cm.current === null) return; if (cm.current === null) return;
const { view, langHolder } = cm.current; const { view, languageCompartment } = cm.current;
const ext = getLanguageExtension({ contentType, useTemplating }); const ext = getLanguageExtension({ contentType, useTemplating });
view.dispatch({ effects: langHolder.reconfigure(ext) }); view.dispatch({ effects: languageCompartment.reconfigure(ext) });
}, [contentType]); }, [contentType]);
// Initialize the editor when ref mounts // Initialize the editor when ref mounts
useEffect(() => { useEffect(() => {
if (wrapperRef.current === null || cm.current !== null) return; if (wrapperRef.current === null || cm.current !== null) return;
try { try {
const langHolder = new Compartment(); const languageCompartment = new Compartment();
const langExt = getLanguageExtension({ contentType, useTemplating }); const langExt = getLanguageExtension({ contentType, useTemplating });
const state = EditorState.create({ const state = EditorState.create({
doc: `${defaultValue ?? ''}`, doc: `${defaultValue ?? ''}`,
extensions: [ extensions: [
langHolder.of(langExt), languageCompartment.of(langExt),
placeholderCompartment.current.of(placeholderExt(placeholder ?? '')),
...getExtensions({ ...getExtensions({
container: wrapperRef.current, container: wrapperRef.current,
onChange: handleChange, onChange: handleChange,
onFocus: handleFocus, onFocus: handleFocus,
readOnly, readOnly,
placeholder,
singleLine, singleLine,
contentType, contentType,
useTemplating, useTemplating,
@@ -91,7 +99,7 @@ export function _Editor({
], ],
}); });
const view = new EditorView({ state, parent: wrapperRef.current }); const view = new EditorView({ state, parent: wrapperRef.current });
cm.current = { view, langHolder }; cm.current = { view, languageCompartment };
if (autoFocus) view.focus(); if (autoFocus) view.focus();
} catch (e) { } catch (e) {
console.log('Failed to initialize Codemirror', e); console.log('Failed to initialize Codemirror', e);
@@ -122,15 +130,11 @@ function getExtensions({
container, container,
readOnly, readOnly,
singleLine, singleLine,
placeholder,
onChange, onChange,
onFocus, onFocus,
contentType, contentType,
useTemplating, useTemplating,
}: Pick< }: Pick<_EditorProps, 'singleLine' | 'contentType' | 'useTemplating' | 'readOnly'> & {
_EditorProps,
'singleLine' | 'contentType' | 'useTemplating' | 'placeholder' | 'readOnly'
> & {
container: HTMLDivElement | null; container: HTMLDivElement | null;
onChange: MutableRefObject<_EditorProps['onChange']>; onChange: MutableRefObject<_EditorProps['onChange']>;
onFocus: MutableRefObject<_EditorProps['onFocus']>; onFocus: MutableRefObject<_EditorProps['onFocus']>;
@@ -151,7 +155,6 @@ function getExtensions({
...(!singleLine ? [multiLineExtensions] : []), ...(!singleLine ? [multiLineExtensions] : []),
...(ext ? [ext] : []), ...(ext ? [ext] : []),
...(readOnly ? [EditorState.readOnly.of(true)] : []), ...(readOnly ? [EditorState.readOnly.of(true)] : []),
...(placeholder ? [placeholderExt(placeholder)] : []),
...(singleLine ...(singleLine
? [ ? [
EditorView.domEventHandlers({ EditorView.domEventHandlers({