Lexical: Hide AutosuggestPlugin when clicking outside

Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
This commit is contained in:
marcin mikołajczak 2023-05-17 00:40:36 +02:00
parent e76c3cc231
commit 4557fb98b6

View file

@ -7,11 +7,14 @@
*/ */
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { mergeRegister } from '@lexical/utils';
import clsx from 'clsx'; import clsx from 'clsx';
import { import {
$getSelection, $getSelection,
$isRangeSelection, $isRangeSelection,
$isTextNode, $isTextNode,
COMMAND_PRIORITY_LOW,
KEY_ESCAPE_COMMAND,
LexicalEditor, LexicalEditor,
RangeSelection, RangeSelection,
} from 'lexical'; } from 'lexical';
@ -358,8 +361,8 @@ const AutosuggestPlugin = ({
}; };
const renderSuggestion = (suggestion: AutoSuggestion, i: number) => { const renderSuggestion = (suggestion: AutoSuggestion, i: number) => {
let inner; let inner: string | JSX.Element;
let key; let key: React.Key;
if (typeof suggestion === 'object') { if (typeof suggestion === 'object') {
inner = <AutosuggestEmoji emoji={suggestion} />; inner = <AutosuggestEmoji emoji={suggestion} />;
@ -447,6 +450,35 @@ const AutosuggestPlugin = ({
if (suggestions && suggestions.size > 0) setSuggestionsHidden(false); if (suggestions && suggestions.size > 0) setSuggestionsHidden(false);
}, [suggestions]); }, [suggestions]);
useEffect(() => {
if (resolution !== null && !suggestionsHidden && !suggestions.isEmpty()) {
const handleClick = (event: MouseEvent) => {
const target = event.target as HTMLElement;
if (!editor._rootElement?.contains(target) && !anchorElementRef.current.contains(target)) {
setResolution(null);
}
};
document.addEventListener('click', handleClick);
return () => document.removeEventListener('click', handleClick);
}
}, [resolution, suggestionsHidden, suggestions.isEmpty()]);
useEffect(() => mergeRegister(
editor.registerCommand<KeyboardEvent>(
KEY_ESCAPE_COMMAND,
(payload) => {
const event = payload;
event.preventDefault();
event.stopImmediatePropagation();
setResolution(null);
return true;
},
COMMAND_PRIORITY_LOW,
),
), [editor]);
return resolution === null || editor === null ? null : ( return resolution === null || editor === null ? null : (
<LexicalPopoverMenu <LexicalPopoverMenu
anchorElementRef={anchorElementRef} anchorElementRef={anchorElementRef}