Skip to content

Commit

Permalink
Prevent newlines in firefox and add an optional onSubmit handler that…
Browse files Browse the repository at this point in the history
… is triggered by Mod-Enter
  • Loading branch information
brettimus committed Sep 19, 2024
1 parent 89806ec commit cd2a46e
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions studio/src/components/CodeMirrorEditor/CodeMirrorInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,19 @@ type CodeMirrorEditorProps = {
value?: string;
onChange: (value?: string) => void;
placeholder?: string;
onSubmit?: () => void;
};

const preventNewlineInFirefox = keymap.of([
{
key: "Enter",
run: (_view) => {
// Do nothingggg and don't bubble up the event
return true;
},
},
]);

// Extension that blurs the editor when the user presses "Escape"
const escapeKeymap = keymap.of([
{
Expand All @@ -112,8 +123,21 @@ const escapeKeymap = keymap.of([
},
]);

const submitKeymap = (onSubmit: (() => void) | undefined) =>
keymap.of([
{
key: "Mod-Enter",
run: (_view) => {
if (onSubmit) {
onSubmit();
}
return true;
},
},
]);

export function CodeMirrorInput(props: CodeMirrorEditorProps) {
const { value, onChange, placeholder, width, readOnly } = props;
const { value, onChange, placeholder, width, readOnly, onSubmit } = props;

const [isFocused, setIsFocused] = useState(false);

Expand All @@ -135,6 +159,7 @@ export function CodeMirrorInput(props: CodeMirrorEditorProps) {

const extensions = useMemo(() => {
return [
preventNewlineInFirefox,
escapeKeymap,
hiddenGutterExtension,
inputBaseStylesExtension,
Expand All @@ -153,8 +178,9 @@ export function CodeMirrorInput(props: CodeMirrorEditorProps) {
EditorView.lineWrapping,
readOnly ? readonlyExtension : noopExtension,
isFocused ? noopExtension : inputTrucateExtension,
submitKeymap(onSubmit),
];
}, [isFocused, readOnly]);
}, [isFocused, readOnly, onSubmit]);

return (
<div
Expand Down

0 comments on commit cd2a46e

Please sign in to comment.