-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathNodeSelectionMenu.tsx
More file actions
92 lines (86 loc) · 2.85 KB
/
NodeSelectionMenu.tsx
File metadata and controls
92 lines (86 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { useEffect, useState } from "react";
import Menu, { OptionItem } from "./Menu";
import { useFilteredItems } from "./Menu/useFilteredItems";
import { COMMAND_PRIORITY_HIGH, KEY_DOWN_COMMAND } from "lexical";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import LexicalMenuNavigation from "./LexicalMenuNavigation";
interface NodeSelectionMenuProps {
options: Array<OptionItem>;
onSelectOption?: (option: OptionItem) => void;
onClose?: () => void;
inverse?: boolean;
query?: string;
}
export function NodeSelectionMenu({
options,
onSelectOption,
onClose,
inverse,
query: controlledQuery,
}: NodeSelectionMenuProps) {
const [editor] = useLexicalComposerContext();
const isControlled = controlledQuery !== undefined;
const [query, setQuery] = useState("");
const localQuery = isControlled ? controlledQuery : query;
const filteredOptions = useFilteredItems({ query: localQuery, items: options, filterBy: "name" });
const handleOptionSelection = (option: OptionItem) => {
onClose?.();
if (onSelectOption) onSelectOption(option);
else option.action({ editor });
};
useEffect(() => {
return editor.registerCommand(
KEY_DOWN_COMMAND,
(event) => {
if (isControlled) return false;
const actions: { [key: string]: () => void } = {
Escape: () => onClose?.(),
Backspace: () => {
if (localQuery.length === 0) {
onClose?.();
} else {
setQuery((prev) => prev.slice(0, -1));
}
},
};
const action = actions[event.key];
if (action) {
event.stopPropagation();
event.preventDefault();
action();
return true;
} else {
if (event.key.length === 1) {
event.stopPropagation();
event.preventDefault();
setQuery((prev) => prev + event.key);
return true;
}
}
return false;
},
COMMAND_PRIORITY_HIGH,
);
}, [editor, onClose, localQuery]);
return (
<Menu.Root
className={`autocomplete-menu-container ${inverse ? "inverse" : ""}`}
menuItems={filteredOptions}
onSelectOption={(item) => handleOptionSelection(item)}
>
{!isControlled && <input value={localQuery} type="text" disabled />}
<LexicalMenuNavigation />
<Menu.Options className="autocomplete-menu-options" autoIndex={false}>
{(options) => {
const mappedOptions = options.map((option, index) => (
<Menu.Option index={index} key={option.name}>
<span className="label">{option.label ?? option.name}</span>
<span className="description">{option.description}</span>
</Menu.Option>
));
return mappedOptions;
}}
</Menu.Options>
</Menu.Root>
);
}