diff --git a/packages/ketcher-react/src/hooks/useClickOutside.ts b/packages/ketcher-react/src/hooks/useClickOutside.ts new file mode 100644 index 0000000000..a82fa87606 --- /dev/null +++ b/packages/ketcher-react/src/hooks/useClickOutside.ts @@ -0,0 +1,19 @@ +import { useEffect, RefObject } from 'react' + +export const useClickOutside = ( + targetRef: RefObject, + callback: () => void +): void => { + useEffect(() => { + document.addEventListener('click', onClickOutside) + return () => { + document.removeEventListener('click', onClickOutside) + } + }, []) + + const onClickOutside = (e: Event) => { + if (!targetRef.current?.contains(e.target as Node)) { + callback() + } + } +} diff --git a/packages/ketcher-react/src/script/ui/views/modal/components/Text/FontControl/FontControl.tsx b/packages/ketcher-react/src/script/ui/views/modal/components/Text/FontControl/FontControl.tsx index b75ee85f59..10c8c40ce5 100644 --- a/packages/ketcher-react/src/script/ui/views/modal/components/Text/FontControl/FontControl.tsx +++ b/packages/ketcher-react/src/script/ui/views/modal/components/Text/FontControl/FontControl.tsx @@ -14,7 +14,8 @@ * limitations under the License. ***************************************************************************/ -import { useEffect, useMemo, useState } from 'react' +import { useEffect, useMemo, useState, useRef } from 'react' +import { useClickOutside } from '../../../../../../../hooks/useClickOutside' import classes from './FontControl.module.less' @@ -24,6 +25,10 @@ export const FontControl = ({ editorState, setEditorState, styles }) => { const defaultFontSize = '13px' const [isShowingFontSizeMenu, setIsShowingFontSizeMenu] = useState(false) const [currentFontSize, setCurrentFontSize] = useState(defaultFontSize) + const wrapperRef = useRef(null) + const onClickOutsideCloseDrowndown = (): void => + setIsShowingFontSizeMenu(false) + useClickOutside(wrapperRef, onClickOutsideCloseDrowndown) const setFontSize = (e, value) => { e.preventDefault() @@ -58,7 +63,7 @@ export const FontControl = ({ editorState, setEditorState, styles }) => { ) return ( -
+