Prevent sidebar re-render on every keypress (#152)

This commit is contained in:
Gregory Schier
2024-12-31 15:02:10 -08:00
committed by GitHub
parent 135c366e32
commit dfca17f9b7
32 changed files with 926 additions and 768 deletions

View File

@@ -1,4 +1,5 @@
import { useCallback, useMemo } from 'react';
import { generateId } from '../../lib/generateId';
import { Editor } from './Editor/Editor';
import type { PairEditorProps } from './PairEditor';
@@ -51,6 +52,7 @@ function lineToPair(line: string): PairEditorProps['pairs'][0] {
enabled: true,
name: (name ?? '').trim(),
value: (value ?? '').trim(),
id: generateId(),
};
return pair;
}

View File

@@ -57,7 +57,7 @@ export type DropdownItem = DropdownItemDefault | DropdownItemSeparator;
export interface DropdownProps {
children: ReactElement<HTMLAttributes<HTMLButtonElement>>;
items: DropdownItem[];
items: DropdownItem[] | (() => DropdownItem[]);
onOpen?: () => void;
onClose?: () => void;
fullWidth?: boolean;
@@ -75,7 +75,7 @@ export interface DropdownRef {
}
export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown(
{ children, items, onOpen, onClose, hotKeyAction, fullWidth }: DropdownProps,
{ children, items: itemsGetter, onOpen, onClose, hotKeyAction, fullWidth }: DropdownProps,
ref,
) {
const [isOpen, _setIsOpen] = useState<boolean>(false);
@@ -83,6 +83,8 @@ export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown
const buttonRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<Omit<DropdownRef, 'open'>>(null);
const [items, setItems] = useState<DropdownItem[]>([]);
const setIsOpen = useCallback(
(o: SetStateAction<boolean>) => {
_setIsOpen(o);
@@ -99,20 +101,24 @@ export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown
setDefaultSelectedIndex(undefined);
}, [setIsOpen]);
useImperativeHandle(ref, () => ({
...menuRef.current,
isOpen: isOpen,
toggle() {
if (!isOpen) this.open();
else this.close();
},
open() {
setIsOpen(true);
},
close() {
handleClose();
},
}), [handleClose, isOpen, setIsOpen]);
useImperativeHandle(
ref,
() => ({
...menuRef.current,
isOpen: isOpen,
toggle() {
if (!isOpen) this.open();
else this.close();
},
open() {
setIsOpen(true);
},
close() {
handleClose();
},
}),
[handleClose, isOpen, setIsOpen],
);
useHotKey(hotKeyAction ?? null, () => {
setDefaultSelectedIndex(0);
@@ -133,10 +139,11 @@ export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown
e.stopPropagation();
setDefaultSelectedIndex(undefined);
setIsOpen((o) => !o);
setItems(typeof itemsGetter === 'function' ? itemsGetter() : itemsGetter);
}),
};
return cloneElement(existingChild, props);
}, [children, setIsOpen]);
}, [children, itemsGetter, setIsOpen]);
useEffect(() => {
buttonRef.current?.setAttribute('aria-expanded', isOpen.toString());
@@ -169,7 +176,7 @@ export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown
interface ContextMenuProps {
triggerPosition: { x: number; y: number } | null;
className?: string;
items: DropdownProps['items'];
items: DropdownItem[];
onClose: () => void;
}
@@ -204,294 +211,299 @@ export const ContextMenu = forwardRef<DropdownRef, ContextMenuProps>(function Co
interface MenuProps {
className?: string;
defaultSelectedIndex?: number;
items: DropdownProps['items'];
triggerShape: Pick<DOMRect, 'top' | 'bottom' | 'left' | 'right'> | null;
onClose: () => void;
showTriangle?: boolean;
fullWidth?: boolean;
isOpen: boolean;
items: DropdownItem[];
}
const Menu = forwardRef<Omit<DropdownRef, 'open' | 'isOpen' | 'toggle'>, MenuProps>(function Menu(
{
className,
isOpen,
items,
fullWidth,
onClose,
triggerShape,
defaultSelectedIndex,
showTriangle,
}: MenuProps,
ref,
) {
const [selectedIndex, setSelectedIndex] = useStateWithDeps<number | null>(
defaultSelectedIndex ?? null,
[defaultSelectedIndex],
);
const [filter, setFilter] = useState<string>('');
const handleClose = useCallback(() => {
onClose();
setSelectedIndex(null);
setFilter('');
}, [onClose, setSelectedIndex]);
// Close menu on space bar
const handleMenuKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
const isCharacter = e.key.length === 1;
const isSpecial = e.ctrlKey || e.metaKey || e.altKey;
if (isCharacter && !isSpecial) {
e.preventDefault();
setFilter((f) => f + e.key);
setSelectedIndex(0);
} else if (e.key === 'Backspace' && !isSpecial) {
e.preventDefault();
setFilter((f) => f.slice(0, -1));
}
};
useKey(
'Escape',
() => {
if (!isOpen) return;
if (filter !== '') setFilter('');
else handleClose();
},
{},
[isOpen, filter, setFilter, handleClose],
);
const handlePrev = useCallback(() => {
setSelectedIndex((currIndex) => {
let nextIndex = (currIndex ?? 0) - 1;
const maxTries = items.length;
for (let i = 0; i < maxTries; i++) {
if (items[nextIndex]?.hidden || items[nextIndex]?.type === 'separator') {
nextIndex--;
} else if (nextIndex < 0) {
nextIndex = items.length - 1;
} else {
break;
}
}
return nextIndex;
});
}, [items, setSelectedIndex]);
const handleNext = useCallback(() => {
setSelectedIndex((currIndex) => {
let nextIndex = (currIndex ?? -1) + 1;
const maxTries = items.length;
for (let i = 0; i < maxTries; i++) {
if (items[nextIndex]?.hidden || items[nextIndex]?.type === 'separator') {
nextIndex++;
} else if (nextIndex >= items.length) {
nextIndex = 0;
} else {
break;
}
}
return nextIndex;
});
}, [items, setSelectedIndex]);
useKey(
'ArrowUp',
(e) => {
if (!isOpen) return;
e.preventDefault();
handlePrev();
},
{},
[isOpen],
);
useKey(
'ArrowDown',
(e) => {
if (!isOpen) return;
e.preventDefault();
handleNext();
},
{},
[isOpen],
);
const handleSelect = useCallback(
(i: DropdownItem) => {
if (i.type !== 'separator' && !i.keepOpen) {
handleClose();
}
setSelectedIndex(null);
if (i.type !== 'separator' && typeof i.onSelect === 'function') {
i.onSelect();
}
},
[handleClose, setSelectedIndex],
);
useImperativeHandle(
const Menu = forwardRef<Omit<DropdownRef, 'open' | 'isOpen' | 'toggle' | 'items'>, MenuProps>(
function Menu(
{
className,
isOpen,
items,
fullWidth,
onClose,
triggerShape,
defaultSelectedIndex,
showTriangle,
}: MenuProps,
ref,
() => ({
close: handleClose,
prev: handlePrev,
next: handleNext,
select: () => {
const item = items[selectedIndex ?? -1] ?? null;
if (!item) return;
handleSelect(item);
},
}),
[handleClose, handleNext, handlePrev, handleSelect, items, selectedIndex],
);
) {
const [selectedIndex, setSelectedIndex] = useStateWithDeps<number | null>(
defaultSelectedIndex ?? null,
[defaultSelectedIndex],
);
const [filter, setFilter] = useState<string>('');
const styles = useMemo<{
container: CSSProperties;
menu: CSSProperties;
triangle: CSSProperties;
upsideDown: boolean;
}>(() => {
if (triggerShape == null) return { container: {}, triangle: {}, menu: {}, upsideDown: false };
const handleClose = useCallback(() => {
onClose();
setSelectedIndex(null);
setFilter('');
}, [onClose, setSelectedIndex]);
const menuMarginY = 5;
const docRect = document.documentElement.getBoundingClientRect();
const width = triggerShape.right - triggerShape.left;
const heightAbove = triggerShape.top;
const heightBelow = docRect.height - triggerShape.bottom;
const horizontalSpaceRemaining = docRect.width - triggerShape.left;
const top = triggerShape.bottom;
const onRight = horizontalSpaceRemaining < 200;
const upsideDown = heightBelow < heightAbove && heightBelow < items.length * 25 + 20 + 200;
const triggerWidth = triggerShape.right - triggerShape.left;
return {
upsideDown,
container: {
top: !upsideDown ? top + menuMarginY : undefined,
bottom: upsideDown
? docRect.height - top - (triggerShape.top - triggerShape.bottom) + menuMarginY
: undefined,
right: onRight ? docRect.width - triggerShape.right : undefined,
left: !onRight ? triggerShape.left : undefined,
minWidth: fullWidth ? triggerWidth : undefined,
maxWidth: '40rem',
},
triangle: {
width: '0.4rem',
height: '0.4rem',
...(onRight
? { right: width / 2, marginRight: '-0.2rem' }
: { left: width / 2, marginLeft: '-0.2rem' }),
...(upsideDown
? { bottom: '-0.2rem', rotate: '225deg' }
: { top: '-0.2rem', rotate: '45deg' }),
},
menu: {
maxHeight: `${(upsideDown ? heightAbove : heightBelow) - 15}px`,
},
// Close menu on space bar
const handleMenuKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
const isCharacter = e.key.length === 1;
const isSpecial = e.ctrlKey || e.metaKey || e.altKey;
if (isCharacter && !isSpecial) {
e.preventDefault();
setFilter((f) => f + e.key);
setSelectedIndex(0);
} else if (e.key === 'Backspace' && !isSpecial) {
e.preventDefault();
setFilter((f) => f.slice(0, -1));
}
};
}, [fullWidth, items.length, triggerShape]);
const filteredItems = useMemo(
() => items.filter((i) => getNodeText(i.label).toLowerCase().includes(filter.toLowerCase())),
[items, filter],
);
useKey(
'Escape',
() => {
if (!isOpen) return;
if (filter !== '') setFilter('');
else handleClose();
},
{},
[isOpen, filter, setFilter, handleClose],
);
const handleFocus = useCallback(
(i: DropdownItem) => {
const index = filteredItems.findIndex((item) => item === i) ?? null;
setSelectedIndex(index);
},
[filteredItems, setSelectedIndex],
);
const handlePrev = useCallback(() => {
setSelectedIndex((currIndex) => {
let nextIndex = (currIndex ?? 0) - 1;
const maxTries = items.length;
for (let i = 0; i < maxTries; i++) {
if (items[nextIndex]?.hidden || items[nextIndex]?.type === 'separator') {
nextIndex--;
} else if (nextIndex < 0) {
nextIndex = items.length - 1;
} else {
break;
}
}
return nextIndex;
});
}, [items, setSelectedIndex]);
if (items.length === 0) return null;
const handleNext = useCallback(() => {
setSelectedIndex((currIndex) => {
let nextIndex = (currIndex ?? -1) + 1;
const maxTries = items.length;
for (let i = 0; i < maxTries; i++) {
if (items[nextIndex]?.hidden || items[nextIndex]?.type === 'separator') {
nextIndex++;
} else if (nextIndex >= items.length) {
nextIndex = 0;
} else {
break;
}
}
return nextIndex;
});
}, [items, setSelectedIndex]);
return (
<>
{filteredItems.map(
(item) =>
item.type !== 'separator' &&
!item.hotKeyLabelOnly && (
<MenuItemHotKey
key={item.key}
onSelect={handleSelect}
item={item}
action={item.hotKeyAction}
/>
),
)}
{isOpen && (
<Overlay open={true} variant="transparent" portalName="dropdown" zIndex={50}>
<div className="x-theme-menu">
<div tabIndex={-1} aria-hidden className="fixed inset-0 z-30" onClick={handleClose} />
<motion.div
tabIndex={0}
onKeyDown={handleMenuKeyDown}
initial={{ opacity: 0, y: (styles.upsideDown ? 1 : -1) * 5, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
role="menu"
aria-orientation="vertical"
dir="ltr"
style={styles.container}
className={classNames(className, 'outline-none my-1 pointer-events-auto fixed z-50')}
>
{showTriangle && (
<span
aria-hidden
style={styles.triangle}
className="bg-surface absolute border-border-subtle border-t border-l"
/>
)}
<VStack
style={styles.menu}
useKey(
'ArrowUp',
(e) => {
if (!isOpen) return;
e.preventDefault();
handlePrev();
},
{},
[isOpen],
);
useKey(
'ArrowDown',
(e) => {
if (!isOpen) return;
e.preventDefault();
handleNext();
},
{},
[isOpen],
);
const handleSelect = useCallback(
(i: DropdownItem) => {
if (i.type !== 'separator' && !i.keepOpen) {
handleClose();
}
setSelectedIndex(null);
if (i.type !== 'separator' && typeof i.onSelect === 'function') {
i.onSelect();
}
},
[handleClose, setSelectedIndex],
);
useImperativeHandle(
ref,
() => ({
close: handleClose,
prev: handlePrev,
next: handleNext,
select: () => {
const item = items[selectedIndex ?? -1] ?? null;
if (!item) return;
handleSelect(item);
},
}),
[handleClose, handleNext, handlePrev, handleSelect, items, selectedIndex],
);
const styles = useMemo<{
container: CSSProperties;
menu: CSSProperties;
triangle: CSSProperties;
upsideDown: boolean;
}>(() => {
if (triggerShape == null) return { container: {}, triangle: {}, menu: {}, upsideDown: false };
const menuMarginY = 5;
const docRect = document.documentElement.getBoundingClientRect();
const width = triggerShape.right - triggerShape.left;
const heightAbove = triggerShape.top;
const heightBelow = docRect.height - triggerShape.bottom;
const horizontalSpaceRemaining = docRect.width - triggerShape.left;
const top = triggerShape.bottom;
const onRight = horizontalSpaceRemaining < 200;
const upsideDown = heightBelow < heightAbove && heightBelow < items.length * 25 + 20 + 200;
const triggerWidth = triggerShape.right - triggerShape.left;
return {
upsideDown,
container: {
top: !upsideDown ? top + menuMarginY : undefined,
bottom: upsideDown
? docRect.height - top - (triggerShape.top - triggerShape.bottom) + menuMarginY
: undefined,
right: onRight ? docRect.width - triggerShape.right : undefined,
left: !onRight ? triggerShape.left : undefined,
minWidth: fullWidth ? triggerWidth : undefined,
maxWidth: '40rem',
},
triangle: {
width: '0.4rem',
height: '0.4rem',
...(onRight
? { right: width / 2, marginRight: '-0.2rem' }
: { left: width / 2, marginLeft: '-0.2rem' }),
...(upsideDown
? { bottom: '-0.2rem', rotate: '225deg' }
: { top: '-0.2rem', rotate: '45deg' }),
},
menu: {
maxHeight: `${(upsideDown ? heightAbove : heightBelow) - 15}px`,
},
};
}, [fullWidth, items.length, triggerShape]);
const filteredItems = useMemo(
() => items.filter((i) => getNodeText(i.label).toLowerCase().includes(filter.toLowerCase())),
[items, filter],
);
const handleFocus = useCallback(
(i: DropdownItem) => {
const index = filteredItems.findIndex((item) => item === i) ?? null;
setSelectedIndex(index);
},
[filteredItems, setSelectedIndex],
);
if (items.length === 0) return null;
return (
<>
{filteredItems.map(
(item) =>
item.type !== 'separator' &&
!item.hotKeyLabelOnly && (
<MenuItemHotKey
key={item.key}
onSelect={handleSelect}
item={item}
action={item.hotKeyAction}
/>
),
)}
{isOpen && (
<Overlay open={true} variant="transparent" portalName="dropdown" zIndex={50}>
<div className="x-theme-menu">
<div tabIndex={-1} aria-hidden className="fixed inset-0 z-30" onClick={handleClose} />
<motion.div
tabIndex={0}
onKeyDown={handleMenuKeyDown}
initial={{ opacity: 0, y: (styles.upsideDown ? 1 : -1) * 5, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
role="menu"
aria-orientation="vertical"
dir="ltr"
style={styles.container}
className={classNames(
className,
'h-auto bg-surface rounded-md shadow-lg py-1.5 border',
'border-border-subtle overflow-auto mx-0.5',
'outline-none my-1 pointer-events-auto fixed z-50',
)}
>
{filter && (
<HStack
space={2}
className="pb-0.5 px-1.5 mb-2 text-sm border border-border-subtle mx-2 rounded font-mono h-xs"
>
<Icon icon="search" size="xs" className="text-text-subtle" />
<div className="text">{filter}</div>
</HStack>
{showTriangle && (
<span
aria-hidden
style={styles.triangle}
className="bg-surface absolute border-border-subtle border-t border-l"
/>
)}
{filteredItems.length === 0 && (
<span className="text-text-subtlest text-center px-2 py-1">No matches</span>
)}
{filteredItems.map((item, i) => {
if (item.hidden) {
return null;
}
if (item.type === 'separator') {
<VStack
style={styles.menu}
className={classNames(
className,
'h-auto bg-surface rounded-md shadow-lg py-1.5 border',
'border-border-subtle overflow-auto mx-0.5',
)}
>
{filter && (
<HStack
space={2}
className="pb-0.5 px-1.5 mb-2 text-sm border border-border-subtle mx-2 rounded font-mono h-xs"
>
<Icon icon="search" size="xs" className="text-text-subtle" />
<div className="text">{filter}</div>
</HStack>
)}
{filteredItems.length === 0 && (
<span className="text-text-subtlest text-center px-2 py-1">No matches</span>
)}
{filteredItems.map((item, i) => {
if (item.hidden) {
return null;
}
if (item.type === 'separator') {
return (
<Separator key={i} className={classNames('my-1.5', item.label && 'ml-2')}>
{item.label}
</Separator>
);
}
return (
<Separator key={i} className={classNames('my-1.5', item.label && 'ml-2')}>
{item.label}
</Separator>
<MenuItem
focused={i === selectedIndex}
onFocus={handleFocus}
onSelect={handleSelect}
key={item.key}
item={item}
/>
);
}
return (
<MenuItem
focused={i === selectedIndex}
onFocus={handleFocus}
onSelect={handleSelect}
key={item.key}
item={item}
/>
);
})}
</VStack>
</motion.div>
</div>
</Overlay>
)}
</>
);
});
})}
</VStack>
</motion.div>
</div>
</Overlay>
)}
</>
);
},
);
interface MenuItemProps {
className?: string;

View File

@@ -1,5 +1,5 @@
import { defaultKeymap, historyField } from '@codemirror/commands';
import { foldState, forceParsing } from '@codemirror/language';
import { defaultKeymap } from '@codemirror/commands';
import { forceParsing } from '@codemirror/language';
import { Compartment, EditorState, type Extension } from '@codemirror/state';
import { keymap, placeholder as placeholderExt, tooltips } from '@codemirror/view';
import type { EnvironmentVariable } from '@yaakapp-internal/models';
@@ -8,12 +8,12 @@ import classNames from 'classnames';
import { EditorView } from 'codemirror';
import type { MutableRefObject, ReactNode } from 'react';
import {
useEffect,
Children,
cloneElement,
forwardRef,
isValidElement,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
@@ -31,7 +31,7 @@ import { HStack } from '../Stacks';
import './Editor.css';
import { baseExtensions, getLanguageExtension, multiLineExtensions } from './extensions';
import type { GenericCompletionConfig } from './genericCompletion';
import { singleLineExt } from './singleLine';
import { singleLineExtensions } from './singleLine';
export interface EditorProps {
id?: string;
@@ -122,7 +122,7 @@ export const Editor = forwardRef<EditorView | undefined, EditorProps>(function E
// Use ref so we can update the handler without re-initializing the editor
const handleChange = useRef<EditorProps['onChange']>(onChange);
useEffect(() => {
handleChange.current = onChange ? onChange : onChange;
handleChange.current = onChange;
}, [onChange]);
// Use ref so we can update the handler without re-initializing the editor
@@ -304,36 +304,35 @@ export const Editor = forwardRef<EditorView | undefined, EditorProps>(function E
onClickMissingVariable,
onClickPathParameter,
});
const extensions = [
languageCompartment.of(langExt),
placeholderCompartment.current.of(
placeholderExt(placeholderElFromText(placeholder ?? '')),
),
wrapLinesCompartment.current.of(wrapLines ? [EditorView.lineWrapping] : []),
...getExtensions({
container,
readOnly,
singleLine,
hideGutter,
stateKey,
onChange: handleChange,
onPaste: handlePaste,
onPasteOverwrite: handlePasteOverwrite,
onFocus: handleFocus,
onBlur: handleBlur,
onKeyDown: handleKeyDown,
}),
...(extraExtensions ?? []),
];
const cachedJsonState = getCachedEditorState(stateKey);
const state = cachedJsonState
? EditorState.fromJSON(
cachedJsonState,
{ extensions },
{ fold: foldState, history: historyField },
)
: EditorState.create({ doc: `${defaultValue ?? ''}`, extensions });
const cachedJsonState = getCachedEditorState(defaultValue ?? '', stateKey);
const state =
cachedJsonState ??
EditorState.create({
doc: `${defaultValue ?? ''}`,
extensions: [
languageCompartment.of(langExt),
placeholderCompartment.current.of(
placeholderExt(placeholderElFromText(placeholder ?? '')),
),
wrapLinesCompartment.current.of(wrapLines ? [EditorView.lineWrapping] : []),
...getExtensions({
container,
readOnly,
singleLine,
hideGutter,
stateKey,
onChange: handleChange,
onPaste: handlePaste,
onPasteOverwrite: handlePasteOverwrite,
onFocus: handleFocus,
onBlur: handleBlur,
onKeyDown: handleKeyDown,
}),
...(extraExtensions ?? []),
],
});
const view = new EditorView({ state, parent: container });
@@ -515,7 +514,7 @@ function getExtensions({
}),
tooltips({ parent }),
keymap.of(singleLine ? defaultKeymap.filter((k) => k.key !== 'Enter') : defaultKeymap),
...(singleLine ? [singleLineExt()] : []),
...(singleLine ? [singleLineExtensions()] : []),
...(!singleLine ? [multiLineExtensions({ hideGutter })] : []),
...(readOnly
? [EditorState.readOnly.of(true), EditorView.contentAttributes.of({ tabindex: '-1' })]
@@ -525,12 +524,17 @@ function getExtensions({
// Things that must be last //
// ------------------------ //
// Fire onChange event
EditorView.updateListener.of((update) => {
if (onChange && update.docChanged) {
onChange.current?.(update.state.doc.toString());
saveCachedEditorState(stateKey, update.state);
}
}),
// Cache editor state
EditorView.updateListener.of((update) => {
saveCachedEditorState(stateKey, update.state);
}),
];
}
@@ -540,20 +544,25 @@ const placeholderElFromText = (text: string) => {
return el;
};
function saveCachedEditorState(stateKey: string | null, state: EditorState | null) {
if (!stateKey || state == null) return;
const stateJson = state.toJSON({ history: historyField, folds: foldState });
sessionStorage.setItem(stateKey, JSON.stringify(stateJson));
}
function getCachedEditorState(stateKey: string | null) {
if (stateKey == null) return;
const serializedState = stateKey ? sessionStorage.getItem(stateKey) : null;
if (serializedState == null) return;
try {
return JSON.parse(serializedState);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (e) {
return null;
declare global {
interface Window {
editorStates: Record<string, EditorState>;
}
}
window.editorStates = window.editorStates ?? {};
function saveCachedEditorState(stateKey: string | null, state: EditorState | null) {
if (!stateKey || state == null) return;
window.editorStates[stateKey] = state;
}
function getCachedEditorState(doc: string, stateKey: string | null) {
if (stateKey == null) return;
const state = window.editorStates[stateKey] ?? null;
if (state == null) return null;
if (state.doc.toString() !== doc) return null;
console.log('CACHED STATE', stateKey, state);
return state;
}

View File

@@ -1,7 +1,7 @@
import type { Transaction, TransactionSpec } from '@codemirror/state';
import type {Extension, Transaction, TransactionSpec} from '@codemirror/state';
import { EditorSelection, EditorState } from '@codemirror/state';
export function singleLineExt() {
export function singleLineExtensions(): Extension {
return EditorState.transactionFilter.of(
(tr: Transaction): TransactionSpec | TransactionSpec[] => {
if (!tr.isUserEvent('input')) return tr;

View File

@@ -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(),
};
}

View File

@@ -18,7 +18,7 @@ export interface RadioDropdownProps<T = string | null> {
value: T;
onChange: (value: T) => void;
items: RadioDropdownItem<T>[];
extraItems?: DropdownProps['items'];
extraItems?: DropdownItem[];
children: DropdownProps['children'];
}
@@ -42,7 +42,7 @@ export function RadioDropdown<T = string | null>({
rightSlot: item.rightSlot,
onSelect: () => onChange(item.value),
leftSlot: <Icon icon={value === item.value ? 'check' : 'empty'} />,
} as DropdownProps['items'][0];
} as DropdownItem;
}
}),
...((extraItems ? [{ type: 'separator' }, ...extraItems] : []) as DropdownItem[]),

View File

@@ -10,11 +10,13 @@ import { HStack } from '../Stacks';
export type TabItem =
| {
value: string;
label: ReactNode;
label: string;
rightSlot?: ReactNode;
}
| {
value: string;
options: Omit<RadioDropdownProps, 'children'>;
rightSlot?: ReactNode;
};
interface Props {
@@ -63,7 +65,10 @@ export function Tabs({
return (
<div
ref={ref}
className={classNames(className, 'h-full grid grid-rows-[auto_minmax(0,1fr)] grid-cols-1 overflow-x-hidden')}
className={classNames(
className,
'h-full grid grid-rows-[auto_minmax(0,1fr)] grid-cols-1 overflow-x-hidden',
)}
>
<div
aria-label={label}
@@ -111,6 +116,7 @@ export function Tabs({
{option && 'shortLabel' in option
? option.shortLabel
: (option?.label ?? 'Unknown')}
{t.rightSlot}
<Icon
size="sm"
icon="chevron_down"
@@ -134,6 +140,7 @@ export function Tabs({
className={btnClassName}
>
{t.label}
{t.rightSlot}
</button>
);
}