aboutsummaryrefslogtreecommitdiff
path: root/apps/web/components/new/text-editor/slash-command.tsx
blob: 3b6f3a3381660224c7718d877735086e585b259f (plain) (blame)
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
"use client"

import { Extension, type Editor, type Range } from "@tiptap/core"
import Suggestion, { type SuggestionOptions } from "@tiptap/suggestion"
import { useEffect, useLayoutEffect, useState, useRef } from "react"
import { createPortal } from "react-dom"
import { createRoot, type Root } from "react-dom/client"
import {
	useFloating,
	offset,
	flip,
	shift,
	autoUpdate,
} from "@floating-ui/react"
import { cn } from "@lib/utils"

export interface SuggestionItem {
	title: string
	description: string
	searchTerms?: string[]
	icon: React.ReactNode
	command: (props: { editor: Editor; range: Range }) => void
}

interface CommandListProps {
	items: SuggestionItem[]
	command: (item: SuggestionItem) => void
	selectedIndex: number
}

function CommandList({ items, command, selectedIndex }: CommandListProps) {
	const containerRef = useRef<HTMLDivElement>(null)

	useEffect(() => {
		const selectedElement = containerRef.current?.querySelector(
			`[data-index="${selectedIndex}"]`,
		)
		selectedElement?.scrollIntoView({ block: "nearest" })
	}, [selectedIndex])

	if (items.length === 0) {
		return (
			<div className="z-50 h-auto max-h-[330px] overflow-y-auto rounded-[8px] bg-[#1b1f24] p-2 shadow-[0px_4px_20px_0px_rgba(0,0,0,0.25),inset_1px_1px_1px_0px_rgba(255,255,255,0.1)]">
				<div className="px-2 text-muted-foreground">No results</div>
			</div>
		)
	}

	return (
		<div
			ref={containerRef}
			className="z-50 h-auto max-h-[330px] overflow-y-auto rounded-[8px] bg-[#1b1f24] p-2 shadow-[0px_4px_20px_0px_rgba(0,0,0,0.25),inset_1px_1px_1px_0px_rgba(255,255,255,0.1)]"
		>
			{items.map((item, index) => (
				<button
					type="button"
					key={item.title}
					data-index={index}
					onClick={() => command(item)}
					className={cn(
						"flex w-full items-center gap-2 rounded-[4px] px-3 py-2 text-left hover:bg-[#2e353d]",
						index === selectedIndex && "bg-[#2e353d]",
					)}
				>
					<div className="flex size-[20px] shrink-0 items-center justify-center text-[#fafafa]">
						{item.icon}
					</div>
					<p className="font-medium text-[16px] leading-[1.35] tracking-[-0.16px] text-[#fafafa]">
						{item.title}
					</p>
				</button>
			))}
		</div>
	)
}

interface CommandMenuProps {
	items: SuggestionItem[]
	command: (item: SuggestionItem) => void
	clientRect: (() => DOMRect | null) | null
	selectedIndex: number
}

function CommandMenu({
	items,
	command,
	clientRect,
	selectedIndex,
}: CommandMenuProps) {
	const [mounted, setMounted] = useState(false)

	const { refs, floatingStyles } = useFloating({
		placement: "bottom-start",
		middleware: [offset(8), flip(), shift()],
		whileElementsMounted: autoUpdate,
	})

	useLayoutEffect(() => {
		setMounted(true)
	}, [])

	useEffect(() => {
		const rect = clientRect?.()
		if (rect) {
			refs.setReference({
				getBoundingClientRect: () => rect,
			})
		}
	}, [clientRect, refs])

	if (!mounted) return null

	return createPortal(
		<div ref={refs.setFloating} style={floatingStyles} className="z-50">
			<CommandList
				items={items}
				command={command}
				selectedIndex={selectedIndex}
			/>
		</div>,
		document.body,
	)
}

export function createSlashCommand(items: SuggestionItem[]) {
	let component: {
		updateProps: (props: CommandMenuProps) => void
		destroy: () => void
		element: HTMLElement
	} | null = null
	let root: Root | null = null
	let selectedIndex = 0
	let currentItems: SuggestionItem[] = []

	const renderMenu = (props: {
		items: SuggestionItem[]
		command: (item: SuggestionItem) => void
		clientRect: (() => DOMRect | null) | null
	}) => {
		root?.render(
			<CommandMenu
				items={props.items}
				command={props.command}
				clientRect={props.clientRect}
				selectedIndex={selectedIndex}
			/>,
		)
	}

	const suggestion: Omit<SuggestionOptions<SuggestionItem>, "editor"> = {
		char: "/",
		items: ({ query }) => {
			return items.filter(
				(item) =>
					item.title.toLowerCase().includes(query.toLowerCase()) ||
					item.searchTerms?.some((term) =>
						term.toLowerCase().includes(query.toLowerCase()),
					),
			)
		},
		command: ({ editor, range, props }) => {
			props.command({ editor, range })
		},
		render: () => {
			let currentCommand: ((item: SuggestionItem) => void) | null = null
			let currentClientRect: (() => DOMRect | null) | null = null

			return {
				onStart: (props) => {
					selectedIndex = 0
					currentItems = props.items as SuggestionItem[]
					currentCommand = props.command as (item: SuggestionItem) => void
					currentClientRect = props.clientRect ?? null

					const element = document.createElement("div")
					document.body.appendChild(element)

					root = createRoot(element)
					if (currentCommand) {
						renderMenu({
							items: currentItems,
							command: currentCommand,
							clientRect: currentClientRect,
						})
					}

					component = {
						element,
						updateProps: (newProps: CommandMenuProps) => {
							root?.render(
								<CommandMenu
									items={newProps.items}
									command={newProps.command}
									clientRect={newProps.clientRect}
									selectedIndex={newProps.selectedIndex}
								/>,
							)
						},
						destroy: () => {
							root?.unmount()
							element.remove()
							root = null
						},
					}
				},

				onUpdate: (props) => {
					currentItems = props.items as SuggestionItem[]
					currentCommand = props.command as (item: SuggestionItem) => void
					currentClientRect = props.clientRect ?? null

					if (selectedIndex >= currentItems.length) {
						selectedIndex = Math.max(0, currentItems.length - 1)
					}

					if (currentCommand) {
						component?.updateProps({
							items: currentItems,
							command: currentCommand,
							clientRect: currentClientRect,
							selectedIndex,
						})
					}
				},

				onKeyDown: (props) => {
					const { event } = props

					if (event.key === "Escape") {
						component?.destroy()
						component = null
						return true
					}

					if (event.key === "ArrowUp") {
						selectedIndex =
							selectedIndex <= 0 ? currentItems.length - 1 : selectedIndex - 1
						if (currentCommand) {
							component?.updateProps({
								items: currentItems,
								command: currentCommand,
								clientRect: currentClientRect,
								selectedIndex,
							})
						}
						return true
					}

					if (event.key === "ArrowDown") {
						selectedIndex =
							selectedIndex >= currentItems.length - 1 ? 0 : selectedIndex + 1
						if (currentCommand) {
							component?.updateProps({
								items: currentItems,
								command: currentCommand,
								clientRect: currentClientRect,
								selectedIndex,
							})
						}
						return true
					}

					if (event.key === "Enter") {
						const item = currentItems[selectedIndex]
						if (item && currentCommand) {
							currentCommand(item)
						}
						return true
					}

					return false
				},

				onExit: () => {
					component?.destroy()
					component = null
				},
			}
		},
	}

	return Extension.create({
		name: "slashCommand",

		addOptions() {
			return {
				suggestion,
			}
		},

		addProseMirrorPlugins() {
			return [
				Suggestion({
					editor: this.editor,
					...this.options.suggestion,
				}),
			]
		},
	})
}