Skip to content

Commit

Permalink
Add EnterSubmitExtension to handle 'Enter' key press in Tiptap editor
Browse files Browse the repository at this point in the history
  • Loading branch information
khakimov committed Nov 6, 2023
1 parent c8cd778 commit 2de6bd3
Showing 1 changed file with 33 additions and 18 deletions.
51 changes: 33 additions & 18 deletions src/renderer/pages/Pile/Editor/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,32 @@ export default function Editor({
const { ai, prompt } = useAIContext();

const isNew = !postPath;

const EnterSubmitExtension = Extension.create({
name: 'customExtension',

addCommands() {
return {
triggerSubmit: () => ({ state, dispatch }) => {
// This will trigger a 'submit' event on the editor
const event = new CustomEvent('submit');
document.dispatchEvent(event);

return true;
},
};
},

addKeyboardShortcuts() {
return {
'Enter': ({ editor }) => {
editor.commands.triggerSubmit();
return true;
},
};
},
});

const editor = useEditor({
extensions: [
StarterKit,
Expand All @@ -54,6 +80,7 @@ export default function Editor({
CharacterCount.configure({
limit: 100000,
}),
EnterSubmitExtension,
],
editorProps: {
handlePaste: function(view, event, slice) {
Expand Down Expand Up @@ -90,7 +117,6 @@ export default function Editor({
const [isDragging, setIsDragging] = useState(false);
const [isAIResponding, setIsAiResponding] = useState(false);
const [prevDragPos, setPrevDragPos] = useState(0);
const [isActive, setIsActive] = useState(false);

const handleMouseDown = (e) => {
setIsDragging(true);
Expand Down Expand Up @@ -126,29 +152,20 @@ export default function Editor({
setEditable(false);
}, [editor, isNew, post]);

// Listen for the 'submit' event and call handleSubmit when it's triggered
useEffect(() => {
if (!editor || !editable) return;

const handleKeyDown = (event) => {
if (isActive && editable && (event.metaKey || event.ctrlKey) && event.key === 'Enter') {
const handleEvent = () => {
if (editor?.isFocused) {
handleSubmit();
}
};

document.addEventListener('keydown', handleKeyDown);
document.addEventListener('submit', handleEvent);

return () => {
document.removeEventListener('keydown', handleKeyDown);
document.removeEventListener('submit', handleEvent);
};
}, [isActive, editable, handleSubmit]);

const handleFocus = () => {
setIsActive(true);
};

const handleBlur = () => {
setIsActive(false);
};
}, [handleSubmit, editor]);

const generateAiResponse = useCallback(async () => {
if (!editor) return;
Expand Down Expand Up @@ -234,8 +251,6 @@ export default function Editor({
<div className={`${styles.frame} ${isNew && styles.isNew}`}>
{editable ? (
<EditorContent
onFocus={handleFocus}
onBlur={handleBlur}
key={'new'}
className={`${styles.editor} ${isBig() && styles.editorBig} ${
isAIResponding && styles.responding
Expand Down

0 comments on commit 2de6bd3

Please sign in to comment.