From 154a35c957880bd29f8b968012a201749f250813 Mon Sep 17 00:00:00 2001 From: Fedor Katurov Date: Fri, 5 Mar 2021 12:16:17 +0700 Subject: [PATCH] added hotkeys for textarea formatter --- .../CommentFormFormatButtons/index.tsx | 47 ++++++++++++++- src/utils/hooks/useFormatWrapper.ts | 60 +++++++++++-------- 2 files changed, 78 insertions(+), 29 deletions(-) diff --git a/src/components/comment/CommentFormFormatButtons/index.tsx b/src/components/comment/CommentFormFormatButtons/index.tsx index de39bbe0..be214c55 100644 --- a/src/components/comment/CommentFormFormatButtons/index.tsx +++ b/src/components/comment/CommentFormFormatButtons/index.tsx @@ -1,7 +1,7 @@ -import React, { FC, useCallback } from 'react'; +import React, { FC, useCallback, useEffect } from 'react'; import { ButtonGroup } from '~/components/input/ButtonGroup'; import { Button } from '~/components/input/Button'; -import { useFormatWrapper } from '~/utils/hooks/useFormatWrapper'; +import { useFormatWrapper, wrapTextInsideInput } from '~/utils/hooks/useFormatWrapper'; import styles from './styles.module.scss'; interface IProps { @@ -15,10 +15,51 @@ const CommentFormFormatButtons: FC = ({ element, handler }) => { [element, handler] ); + const wrapBold = useCallback( + event => { + event.preventDefault(); + wrapTextInsideInput(element, '**', '**', handler); + }, + [wrap, handler] + ); + + const wrapItalic = useCallback( + event => { + event.preventDefault(); + wrapTextInsideInput(element, '*', '*', handler); + }, + [wrap, handler] + ); + + const onKeyPress = useCallback( + (event: KeyboardEvent) => { + if (!event.ctrlKey) return; + + if (event.code === 'KeyB') { + wrapBold(event); + } + + if (event.code === 'KeyI') { + wrapItalic(event); + } + }, + [wrapBold, wrapItalic] + ); + + useEffect(() => { + if (!element) { + return; + } + + element.addEventListener('keypress', onKeyPress); + + return () => element.removeEventListener('keypress', onKeyPress); + }, [element, onKeyPress]); + return (