import { EditorState, RichUtils } from 'draft-js'; import { useLayoutEffect, useState } from 'react'; import getSelectionRange from '../utils/getSelectionRange.js'; interface Rect { top: number; left: number; width: number; height: number; } interface UseStyleToolbarPropsRes { trigger: Rect; visible: boolean; } /** * Updates the visibility of the style toolbar */ const useStyleToolbarProps = (value: EditorState): UseStyleToolbarPropsRes => { const [trigger, setTrigger] = useState({ top: 0, left: 0, width: 0, height: 0, }); const [visible, setVisible] = useState(false); useLayoutEffect(() => { if (!value) return; const selectionRange = getSelectionRange(); // Do not show the panel if either there is no selected text, // or the selection range is collapsed, // or the selected text is in an atomic block. if ( !selectionRange || value.getSelection().isCollapsed() || RichUtils.getCurrentBlockType(value).startsWith('atomic') ) { // eslint-disable-next-line react-hooks/set-state-in-effect setVisible(false); return; } // Otherwise, set the rect of the selection range setTrigger(selectionRange.getBoundingClientRect()); setVisible(true); }, [value]); return { trigger, visible }; }; export default useStyleToolbarProps;