-
-
Notifications
You must be signed in to change notification settings - Fork 921
Expand file tree
/
Copy pathsuggestion.tsx
More file actions
351 lines (326 loc) · 12.9 KB
/
suggestion.tsx
File metadata and controls
351 lines (326 loc) · 12.9 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright 2026, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
import { atoms } from "@/app/store/global";
import { isBlank, makeIconClass } from "@/util/util";
import { offset, useFloating } from "@floating-ui/react";
import clsx from "clsx";
import { Atom, useAtomValue } from "jotai";
import React, { ReactNode, useEffect, useId, useRef, useState } from "react";
interface SuggestionControlProps {
anchorRef: React.RefObject<HTMLElement>;
isOpen: boolean;
onClose: () => void;
onSelect: (item: SuggestionType, queryStr: string) => boolean;
onTab?: (item: SuggestionType, queryStr: string) => string;
fetchSuggestions: SuggestionsFnType;
className?: string;
placeholderText?: string;
children?: React.ReactNode;
}
type BlockHeaderSuggestionControlProps = Omit<SuggestionControlProps, "anchorRef" | "isOpen"> & {
blockRef: React.RefObject<HTMLElement>;
openAtom: Atom<boolean>;
};
function SuggestionControl({
anchorRef,
isOpen,
onClose,
onSelect,
onTab,
fetchSuggestions,
className,
placeholderText,
children,
}: SuggestionControlProps) {
if (!isOpen || !anchorRef.current || !fetchSuggestions) return null;
return (
<SuggestionControlInner
{...{ anchorRef, onClose, onSelect, onTab, fetchSuggestions, className, placeholderText, children }}
/>
);
}
function highlightPositions(target: string, positions: number[]): ReactNode[] {
if (target == null) {
return [];
}
if (positions == null) {
return [target];
}
const result: ReactNode[] = [];
let targetIndex = 0;
let posIndex = 0;
while (targetIndex < target.length) {
if (posIndex < positions.length && targetIndex === positions[posIndex]) {
result.push(
<span key={`h-${targetIndex}`} className="text-blue-500 font-bold">
{target[targetIndex]}
</span>
);
posIndex++;
} else {
result.push(target[targetIndex]);
}
targetIndex++;
}
return result;
}
function getMimeTypeIconAndColor(fullConfig: FullConfigType, mimeType: string): [string, string] {
if (mimeType == null) {
return [null, null];
}
while (mimeType.length > 0) {
const icon = fullConfig.mimetypes?.[mimeType]?.icon ?? null;
const iconColor = fullConfig.mimetypes?.[mimeType]?.color ?? null;
if (icon != null) {
return [icon, iconColor];
}
mimeType = mimeType.slice(0, -1);
}
return [null, null];
}
function SuggestionIcon({ suggestion }: { suggestion: SuggestionType }) {
if (suggestion.iconsrc) {
return <img src={suggestion.iconsrc} alt="favicon" className="w-4 h-4 object-contain" />;
}
if (suggestion.icon) {
const iconClass = makeIconClass(suggestion.icon, true);
const iconColor = suggestion.iconcolor;
return <i className={iconClass} style={{ color: iconColor }} />;
}
if (suggestion.type === "url") {
const iconClass = makeIconClass("globe", true);
const iconColor = suggestion.iconcolor;
return <i className={iconClass} style={{ color: iconColor }} />;
} else if (suggestion.type === "file") {
// For file suggestions, use the existing logic.
const fullConfig = useAtomValue(atoms.fullConfigAtom);
let icon: string = null;
let iconColor: string = null;
if (icon == null && suggestion["file:mimetype"] != null) {
[icon, iconColor] = getMimeTypeIconAndColor(fullConfig, suggestion["file:mimetype"]);
}
const iconClass = makeIconClass(icon, true, { defaultIcon: "file" });
return <i className={iconClass} style={{ color: iconColor }} />;
}
const iconClass = makeIconClass("file", true);
return <i className={iconClass} />;
}
function SuggestionContent({ suggestion }: { suggestion: SuggestionType }) {
if (!isBlank(suggestion.subtext)) {
return (
<div className="flex flex-col">
{/* Title on the first line, with highlighting */}
<div className="truncate text-white">{highlightPositions(suggestion.display, suggestion.matchpos)}</div>
{/* Subtext on the second line in a smaller, grey style */}
<div className="truncate text-sm text-secondary">
{highlightPositions(suggestion.subtext, suggestion.submatchpos)}
</div>
</div>
);
}
return <span className="truncate">{highlightPositions(suggestion.display, suggestion.matchpos)}</span>;
}
function BlockHeaderSuggestionControl(props: BlockHeaderSuggestionControlProps) {
const [headerElem, setHeaderElem] = useState<HTMLElement>(null);
const isOpen = useAtomValue(props.openAtom);
useEffect(() => {
if (props.blockRef.current == null) {
setHeaderElem(null);
return;
}
const headerElem = props.blockRef.current.querySelector("[data-role='block-header']");
setHeaderElem(headerElem as HTMLElement);
}, [props.blockRef.current]);
const newClass = clsx(props.className, "rounded-t-none");
return <SuggestionControl {...props} anchorRef={{ current: headerElem }} isOpen={isOpen} className={newClass} />;
}
/**
* The empty state component that can be used as a child of SuggestionControl.
* If no children are provided to SuggestionControl, this default empty state will be used.
*/
function SuggestionControlNoResults({ children }: { children?: React.ReactNode }) {
return (
<div className="flex items-center justify-center min-h-[120px] p-4">
{children ?? <span className="text-gray-500">No Suggestions</span>}
</div>
);
}
function SuggestionControlNoData({ children }: { children?: React.ReactNode }) {
return (
<div className="flex items-center justify-center min-h-[120px] p-4">
{children ?? <span className="text-gray-500">No Suggestions</span>}
</div>
);
}
type SuggestionControlInnerProps = Omit<SuggestionControlProps, "isOpen">;
function SuggestionControlInner({
anchorRef,
onClose,
onSelect,
onTab,
fetchSuggestions,
className,
placeholderText,
children,
}: SuggestionControlInnerProps) {
const widgetId = useId();
const [query, setQuery] = useState("");
const reqNumRef = useRef(0);
let [suggestions, setSuggestions] = useState<SuggestionType[]>([]);
const [selectedIndex, setSelectedIndex] = useState(0);
const [fetched, setFetched] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
const { refs, floatingStyles, middlewareData } = useFloating({
placement: "bottom",
strategy: "absolute",
middleware: [offset(-1)],
});
const emptyStateChild = React.Children.toArray(children).find(
(child) => React.isValidElement(child) && child.type === SuggestionControlNoResults
);
const noDataChild = React.Children.toArray(children).find(
(child) => React.isValidElement(child) && child.type === SuggestionControlNoData
);
useEffect(() => {
refs.setReference(anchorRef.current);
}, [anchorRef.current]);
useEffect(() => {
reqNumRef.current++;
fetchSuggestions(query, { widgetid: widgetId, reqnum: reqNumRef.current }).then((results) => {
if (results.reqnum !== reqNumRef.current) {
return;
}
setSuggestions(results.suggestions ?? []);
setFetched(true);
});
}, [query, fetchSuggestions]);
useEffect(() => {
return () => {
reqNumRef.current++;
fetchSuggestions("", { widgetid: widgetId, reqnum: reqNumRef.current, dispose: true });
};
}, []);
useEffect(() => {
inputRef.current?.focus();
}, []);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
onClose();
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, [onClose, anchorRef]);
useEffect(() => {
if (dropdownRef.current) {
const children = dropdownRef.current.children;
if (children[selectedIndex]) {
(children[selectedIndex] as HTMLElement).scrollIntoView({
behavior: "auto",
block: "nearest",
});
}
}
}, [selectedIndex]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "ArrowDown") {
e.preventDefault();
e.stopPropagation();
setSelectedIndex((prev) => Math.min(prev + 1, suggestions.length - 1));
} else if (e.key === "ArrowUp") {
e.preventDefault();
e.stopPropagation();
setSelectedIndex((prev) => Math.max(prev - 1, 0));
} else if (e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
let suggestion: SuggestionType = null;
if (selectedIndex >= 0 && selectedIndex < suggestions.length) {
suggestion = suggestions[selectedIndex];
}
if (onSelect(suggestion, query)) {
onClose();
}
} else if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
onClose();
} else if (e.key === "Tab") {
e.preventDefault();
e.stopPropagation();
const suggestion = suggestions[selectedIndex];
if (suggestion != null) {
const tabResult = onTab?.(suggestion, query);
if (tabResult != null) {
setQuery(tabResult);
}
}
} else if (e.key === "PageDown") {
e.preventDefault();
e.stopPropagation();
setSelectedIndex((prev) => Math.min(prev + 10, suggestions.length - 1));
} else if (e.key === "PageUp") {
e.preventDefault();
e.stopPropagation();
setSelectedIndex((prev) => Math.max(prev - 10, 0));
}
};
return (
<div
className={clsx(
"w-96 rounded-lg bg-modalbg shadow-lg border border-gray-700 z-[var(--zindex-typeahead-modal)] absolute",
middlewareData?.offset == null ? "opacity-0" : null,
className
)}
ref={refs.setFloating}
style={floatingStyles}
>
<div className="p-2">
<input
ref={inputRef}
type="text"
value={query}
onChange={(e) => {
setQuery(e.target.value);
setSelectedIndex(0);
}}
onKeyDown={handleKeyDown}
className="w-full bg-zinc-900 text-gray-100 px-4 py-2 rounded-md border border-gray-700 focus:outline-none focus:border-accent placeholder-secondary"
placeholder={placeholderText}
/>
</div>
{fetched &&
(suggestions.length > 0 ? (
<div ref={dropdownRef} className="max-h-96 overflow-y-auto divide-y divide-gray-700">
{suggestions.map((suggestion, index) => (
<div
key={suggestion.suggestionid}
className={clsx(
"flex items-center gap-3 px-4 py-2 cursor-pointer",
index === selectedIndex ? "bg-accentbg" : "hover:bg-hoverbg",
"text-gray-100"
)}
onClick={() => {
onSelect(suggestion, query);
onClose();
}}
>
<SuggestionIcon suggestion={suggestion} />
<SuggestionContent suggestion={suggestion} />
</div>
))}
</div>
) : (
// Render the empty state (either a provided child or the default)
<div key="empty" className="flex items-center justify-center min-h-[120px] p-4">
{query === ""
? (noDataChild ?? <SuggestionControlNoData />)
: (emptyStateChild ?? <SuggestionControlNoResults />)}
</div>
))}
</div>
);
}
export { BlockHeaderSuggestionControl, SuggestionControl, SuggestionControlNoData, SuggestionControlNoResults };