Skip to content

Commit

Permalink
Return focus to textarea after clicking toggle
Browse files Browse the repository at this point in the history
  • Loading branch information
laymonage committed Nov 21, 2021
1 parent 32392f6 commit cd4c9f8
Showing 1 changed file with 13 additions and 12 deletions.
25 changes: 13 additions & 12 deletions components/CommentBox.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MarkdownIcon, MarkGithubIcon, TypographyIcon } from '@primer/octicons-react';
import { ChangeEvent, useCallback, useContext, useEffect, useState } from 'react';
import { ChangeEvent, useCallback, useContext, useEffect, useRef, useState } from 'react';
import { adaptComment, adaptReply, handleCommentClick, processCommentBody } from '../lib/adapter';
import { AuthContext } from '../lib/context';
import { useGiscusTranslation } from '../lib/i18n';
Expand Down Expand Up @@ -36,6 +36,7 @@ export default function CommentBox({
const [isReplyOpen, setIsReplyOpen] = useState(false);
const [isFixedWidth, setIsFixedWidth] = useState(false);
const { token, origin, getLoginUrl } = useContext(AuthContext);
const textarea = useRef<HTMLTextAreaElement>(null);
const loginUrl = getLoginUrl(origin);
const isReply = !!replyToId;

Expand Down Expand Up @@ -106,19 +107,16 @@ export default function CommentBox({
resizeTextArea(elem);
}, []);

const handleTextAreaRef = useCallback(
(textarea: HTMLTextAreaElement) => {
if (!textarea) return;
resizeTextArea(textarea);
if (isReply) setTimeout(() => textarea.focus());
},
[isReply],
);
useEffect(() => {
if (!textarea.current) return;
if (isReplyOpen) textarea.current.focus();
resizeTextArea(textarea.current);
}, [textarea, isReplyOpen]);

return !isReply || isReplyOpen ? (
<form
className={`color-bg-primary color-border-primary gsc-comment-box${
replyToId ? '' : ' border rounded'
isReply ? '' : ' border rounded'
}`}
onSubmit={(event) => {
event.preventDefault();
Expand Down Expand Up @@ -157,7 +155,10 @@ export default function CommentBox({
className="gsc-toolbar-item"
type="button"
title={isFixedWidth ? t('disableFixedWidth') : t('enableFixedWidth')}
onClick={() => setIsFixedWidth(!isFixedWidth)}
onClick={() => {
setIsFixedWidth(!isFixedWidth);
textarea.current.focus();
}}
tabIndex={-1}
>
<TypographyIcon />
Expand All @@ -184,7 +185,7 @@ export default function CommentBox({
onChange={handleTextAreaChange}
value={input}
disabled={!token || isSubmitting}
ref={handleTextAreaRef}
ref={textarea}
onKeyDown={(event) =>
(event.ctrlKey || event.metaKey) && event.key === 'Enter' && handleSubmit()
}
Expand Down

0 comments on commit cd4c9f8

Please sign in to comment.