Skip to content

Commit 889cbb7

Browse files
author
Håkon Harnes
committed
fix: prevent Enter key from inserting newline before submit
1 parent aec3530 commit 889cbb7

File tree

1 file changed

+29
-23
lines changed

1 file changed

+29
-23
lines changed

src/components/mention-input.tsx

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,36 @@ export default function MentionInput({
184184
class:
185185
"w-full max-h-80 min-h-[2rem] break-words overflow-y-auto resize-none focus:outline-none px-2 py-1 prose prose-sm dark:prose-invert ",
186186
},
187+
handleKeyDown: (view, event) => {
188+
// Handle Enter key at ProseMirror level to prevent newline insertion before submit
189+
const isSubmit =
190+
!open &&
191+
event.key === "Enter" &&
192+
view.state.doc.textContent.trim().length > 0 &&
193+
!event.shiftKey &&
194+
!event.metaKey &&
195+
!event.isComposing;
196+
if (isSubmit) {
197+
event.preventDefault();
198+
onEnter?.();
199+
if (isMobile) {
200+
view.dom.blur();
201+
}
202+
return true; // Prevent ProseMirror from handling the key
203+
}
204+
return false; // Let ProseMirror handle other keys
205+
},
187206
},
188207
};
189-
}, [disabled, MentionItem, suggestionChar, onChange]);
208+
}, [
209+
disabled,
210+
MentionItem,
211+
suggestionChar,
212+
onChange,
213+
open,
214+
onEnter,
215+
isMobile,
216+
]);
190217

191218
const editor = useEditor(editorConfig);
192219

@@ -201,27 +228,6 @@ export default function MentionInput({
201228
editor?.setEditable(!disabled);
202229
}, [disabled]);
203230

204-
// Memoize handlers
205-
const handleKeyDown = useCallback(
206-
(e: React.KeyboardEvent) => {
207-
const isSubmit =
208-
!open &&
209-
e.key === "Enter" &&
210-
editor?.getText().trim().length &&
211-
!e.shiftKey &&
212-
!e.metaKey &&
213-
!e.nativeEvent.isComposing;
214-
if (isSubmit) {
215-
e.preventDefault();
216-
onEnter?.();
217-
if (isMobile) {
218-
editor?.commands.blur();
219-
}
220-
}
221-
},
222-
[editor, onEnter, open],
223-
);
224-
225231
// Memoize the DOM structure
226232
const suggestion = useMemo(() => {
227233
if (!open || disabledMention) return null;
@@ -303,7 +309,7 @@ export default function MentionInput({
303309
onClick={focus}
304310
className={cn("relative w-full", className)}
305311
>
306-
<EditorContent editor={editor} onKeyDown={handleKeyDown} />
312+
<EditorContent editor={editor} />
307313
{suggestion}
308314
{placeholderElement}
309315
</div>

0 commit comments

Comments
 (0)