Skip to content

Commit

Permalink
Simulate GitHub's textarea behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
laymonage committed Nov 21, 2021
1 parent cd4c9f8 commit 5bdff56
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 deletions.
20 changes: 13 additions & 7 deletions components/CommentBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export default function CommentBox({
const [isSubmitting, setIsSubmitting] = useState(false);
const [isReplyOpen, setIsReplyOpen] = useState(false);
const [isFixedWidth, setIsFixedWidth] = useState(false);
const [lastHeight, setLastHeight] = useState('');
const { token, origin, getLoginUrl } = useContext(AuthContext);
const textarea = useRef<HTMLTextAreaElement>(null);
const loginUrl = getLoginUrl(origin);
Expand Down Expand Up @@ -101,17 +102,22 @@ export default function CommentBox({
setIsReplyOpen(true);
};

const handleTextAreaChange = useCallback((event: ChangeEvent<HTMLTextAreaElement>) => {
setInput(event.target.value);
const elem = event.target as HTMLTextAreaElement;
resizeTextArea(elem);
}, []);
const handleTextAreaChange = useCallback(
(event: ChangeEvent<HTMLTextAreaElement>) => {
setInput(event.target.value);
// Only resize if it hasn't been resized manually.
if (!lastHeight || lastHeight === textarea.current.style.height) {
resizeTextArea(textarea.current);
setLastHeight(textarea.current.style.height);
}
},
[lastHeight],
);

useEffect(() => {
if (!textarea.current) return;
if (isReplyOpen) textarea.current.focus();
resizeTextArea(textarea.current);
}, [textarea, isReplyOpen]);
}, [isReplyOpen]);

return !isReply || isReplyOpen ? (
<form
Expand Down
3 changes: 2 additions & 1 deletion lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ export function parseRepoWithOwner(repoWithOwner: string) {
}

export function resizeTextArea(textarea: HTMLTextAreaElement) {
const maxHeight = 270;
textarea.style.height = `0px`;
const height = textarea.scrollHeight <= 772 ? textarea.scrollHeight : 772;
const height = textarea.scrollHeight <= maxHeight ? textarea.scrollHeight : maxHeight;
textarea.style.height = `${height}px`;
}
2 changes: 1 addition & 1 deletion styles/base.css
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ img.emoji {
}

.gsc-comment-box-textarea {
@apply w-full p-2 border rounded min-h-[100px] disabled:cursor-not-allowed;
@apply w-full p-2 border rounded min-h-[100px] max-h-[500px] disabled:cursor-not-allowed;
}

.gsc-comment-box-bottom {
Expand Down

1 comment on commit 5bdff56

@vercel
Copy link

@vercel vercel bot commented on 5bdff56 Nov 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.