-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathslash-command-plugin.tsx
More file actions
321 lines (308 loc) · 10.3 KB
/
slash-command-plugin.tsx
File metadata and controls
321 lines (308 loc) · 10.3 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
"use client";
import { useCallback, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import {
LexicalTypeaheadMenuPlugin,
MenuOption,
useBasicTypeaheadTriggerMatch,
} from "@lexical/react/LexicalTypeaheadMenuPlugin";
import { $createHeadingNode } from "@lexical/rich-text";
import { $createQuoteNode } from "@lexical/rich-text";
import {
INSERT_ORDERED_LIST_COMMAND,
INSERT_UNORDERED_LIST_COMMAND,
INSERT_CHECK_LIST_COMMAND,
} from "@lexical/list";
import { $createCodeNode } from "@lexical/code";
import { INSERT_HORIZONTAL_RULE_COMMAND } from "@lexical/react/LexicalHorizontalRuleNode";
import {
$createParagraphNode,
$getSelection,
$isRangeSelection,
type TextNode,
} from "lexical";
import {
Heading1,
Heading2,
Heading3,
List,
ListOrdered,
CheckSquare,
Code,
Quote,
Minus,
Type,
ImageIcon,
MessageSquare,
ChevronRight,
} from "lucide-react";
import type { JSX, ReactElement } from "react";
import { openImagePicker } from "@/components/editor/image-plugin";
import { INSERT_CALLOUT_COMMAND } from "@/components/editor/callout-plugin";
import { INSERT_COLLAPSIBLE_COMMAND } from "@/components/editor/collapsible-plugin";
class SlashCommandOption extends MenuOption {
title: string;
description: string;
icon: ReactElement;
onSelect: (queryString: string) => void;
constructor(
title: string,
options: {
description: string;
icon: ReactElement;
onSelect: (queryString: string) => void;
}
) {
super(title);
this.title = title;
this.description = options.description;
this.icon = options.icon;
this.onSelect = options.onSelect;
}
}
export function SlashCommandPlugin(): JSX.Element | null {
const [editor] = useLexicalComposerContext();
const [queryString, setQueryString] = useState<string | null>(null);
const menuRef = useRef<HTMLDivElement>(null);
const triggerFn = useBasicTypeaheadTriggerMatch("/", {
minLength: 0,
});
// Create base options once per editor instance so MenuOption refs stay
// stable across query changes. Recreating options on every keystroke
// discards the DOM refs that Lexical uses for scroll-into-view, causing
// the highlighted index to appear to jump back to the top.
const baseOptions = useMemo(
() => [
new SlashCommandOption("Paragraph", {
description: "Plain text block",
icon: <Type className="h-5 w-5" />,
onSelect: () => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const node = $createParagraphNode();
selection.insertNodes([node]);
}
});
},
}),
new SlashCommandOption("Heading 1", {
description: "Large section heading",
icon: <Heading1 className="h-5 w-5" />,
onSelect: () => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const node = $createHeadingNode("h1");
selection.insertNodes([node]);
}
});
},
}),
new SlashCommandOption("Heading 2", {
description: "Medium section heading",
icon: <Heading2 className="h-5 w-5" />,
onSelect: () => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const node = $createHeadingNode("h2");
selection.insertNodes([node]);
}
});
},
}),
new SlashCommandOption("Heading 3", {
description: "Small section heading",
icon: <Heading3 className="h-5 w-5" />,
onSelect: () => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const node = $createHeadingNode("h3");
selection.insertNodes([node]);
}
});
},
}),
new SlashCommandOption("Bullet List", {
description: "Unordered list",
icon: <List className="h-5 w-5" />,
onSelect: () => {
editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, undefined);
},
}),
new SlashCommandOption("Numbered List", {
description: "Ordered list",
icon: <ListOrdered className="h-5 w-5" />,
onSelect: () => {
editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, undefined);
},
}),
new SlashCommandOption("To-do List", {
description: "Checklist with checkboxes",
icon: <CheckSquare className="h-5 w-5" />,
onSelect: () => {
editor.dispatchCommand(INSERT_CHECK_LIST_COMMAND, undefined);
},
}),
new SlashCommandOption("Code Block", {
description: "Code with syntax highlighting",
icon: <Code className="h-5 w-5" />,
onSelect: () => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const node = $createCodeNode();
selection.insertNodes([node]);
}
});
},
}),
new SlashCommandOption("Quote", {
description: "Blockquote",
icon: <Quote className="h-5 w-5" />,
onSelect: () => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
const node = $createQuoteNode();
selection.insertNodes([node]);
}
});
},
}),
new SlashCommandOption("Divider", {
description: "Horizontal rule",
icon: <Minus className="h-5 w-5" />,
onSelect: () => {
editor.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND, undefined);
},
}),
new SlashCommandOption("Image", {
description: "Upload an image",
icon: <ImageIcon className="h-5 w-5" />,
onSelect: () => {
openImagePicker(editor);
},
}),
new SlashCommandOption("Callout", {
description: "Highlighted info block",
icon: <MessageSquare className="h-5 w-5" />,
onSelect: () => {
editor.dispatchCommand(INSERT_CALLOUT_COMMAND, {});
},
}),
new SlashCommandOption("Toggle", {
description: "Collapsible section",
icon: <ChevronRight className="h-5 w-5" />,
onSelect: () => {
editor.dispatchCommand(INSERT_COLLAPSIBLE_COMMAND, undefined);
},
}),
],
[editor]
);
// Filter separately so base option objects (and their refs) persist.
const options = useMemo(() => {
if (queryString) {
const lower = queryString.toLowerCase();
return baseOptions.filter((option) =>
option.title.toLowerCase().includes(lower)
);
}
return baseOptions;
}, [baseOptions, queryString]);
const onSelectOption = useCallback(
(
selectedOption: SlashCommandOption,
nodeToReplace: TextNode | null,
closeMenu: () => void,
matchingString: string
) => {
editor.update(() => {
if (nodeToReplace) {
nodeToReplace.remove();
}
});
selectedOption.onSelect(matchingString);
closeMenu();
},
[editor]
);
// Scroll the highlighted item into view within the menu's scrollable
// container. Lexical's built-in SCROLL_TYPEAHEAD_OPTION_INTO_VIEW_COMMAND
// targets the #typeahead-menu anchor div, not the overflow-y-auto menu
// div we render, so it cannot scroll items within our container.
const scrollHighlightedIntoView = useCallback((index: number) => {
const container = menuRef.current;
if (!container) return;
const item = container.children[index];
if (item instanceof HTMLElement) {
item.scrollIntoView({ block: "nearest" });
}
}, []);
const lastScrolledIndex = useRef<number | null>(null);
return (
<LexicalTypeaheadMenuPlugin<SlashCommandOption>
onQueryChange={setQueryString}
onSelectOption={onSelectOption}
triggerFn={triggerFn}
options={options}
menuRenderFn={(
anchorElementRef,
{ selectedIndex, selectOptionAndCleanUp, setHighlightedIndex, options: items }
) => {
if (items.length === 0 || !anchorElementRef.current) {
return null;
}
// Scroll the newly highlighted item into view when the index changes.
// We track the last scrolled index to avoid redundant calls.
if (
selectedIndex !== null &&
selectedIndex !== lastScrolledIndex.current
) {
lastScrolledIndex.current = selectedIndex;
// Defer to after React has committed the DOM update
requestAnimationFrame(() => scrollHighlightedIntoView(selectedIndex));
}
return createPortal(
<div
ref={menuRef}
className="fixed z-50 max-h-[300px] w-64 overflow-y-auto rounded-sm border border-white/[0.06] bg-popover p-1 shadow-md"
>
{items.map((option, index) => (
<button
key={option.key}
ref={(el) => option.setRefElement(el)}
className={`flex w-full items-center gap-2 px-2 py-1.5 text-left text-sm outline-none ${
selectedIndex === index
? "bg-white/[0.08] text-foreground"
: "text-muted-foreground hover:bg-white/[0.04]"
}`}
onClick={() => selectOptionAndCleanUp(option)}
onMouseEnter={() => setHighlightedIndex(index)}
role="option"
aria-selected={selectedIndex === index}
>
<span className="flex h-8 w-8 shrink-0 items-center justify-center text-muted-foreground">
{option.icon}
</span>
<span className="flex flex-col">
<span className="text-sm font-medium text-foreground">
{option.title}
</span>
<span className="text-xs text-muted-foreground">
{option.description}
</span>
</span>
</button>
))}
</div>,
anchorElementRef.current
);
}}
/>
);
}