From 072574ee716c7608a5e2a3be39e5925eaffd3a18 Mon Sep 17 00:00:00 2001 From: Simon Backx Date: Tue, 12 Jul 2022 16:18:26 +0200 Subject: [PATCH] Fixed autofocus cursor position when editing comments --- apps/comments-ui/src/components/Form.js | 30 +++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/apps/comments-ui/src/components/Form.js b/apps/comments-ui/src/components/Form.js index cae96286ef..2992f5df8d 100644 --- a/apps/comments-ui/src/components/Form.js +++ b/apps/comments-ui/src/components/Form.js @@ -1,4 +1,4 @@ -import React, {useContext} from 'react'; +import React, {useContext, useEffect} from 'react'; import {Transition} from '@headlessui/react'; import AppContext from '../AppContext'; import Avatar from './Avatar'; @@ -17,7 +17,9 @@ const Form = (props) => { } else if (props.isEdit) { config = { placeholder: 'Edit this comment', - autofocus: true, + // warning: we cannot use autofocus on the edit field, because that sets + // the cursor position at the beginning of the text field instead of the end + autofocus: false, content: props.comment.html }; } else { @@ -31,6 +33,30 @@ const Form = (props) => { ...getEditorConfig(config) }); + // Set the cursor position at the end of the form, instead of the beginning (= when using autofocus) + useEffect(() => { + if (!editor) { + return; + } + + // Focus editor + jump to end + if (!props.isEdit) { + return; + } + + // jump to end + editor + .chain() + .focus() + .command(({tr, commands}) => { + return commands.setTextSelection({ + from: tr.doc.content.size, + to: tr.doc.content.size + }); + }) + .run(); + }, [editor, props.isEdit]); + const focused = editor?.isFocused || !editor?.isEmpty; const submitForm = async (event) => {