-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAdvancedSearchDialog.tsx
More file actions
511 lines (471 loc) · 15 KB
/
Copy pathAdvancedSearchDialog.tsx
File metadata and controls
511 lines (471 loc) · 15 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
Button,
Dialog,
InputGroup,
NonIdealState,
Spinner,
SpinnerSize,
Tag,
} from "@blueprintjs/core";
import MiniSearch from "minisearch";
import posthog from "posthog-js";
import { render as renderToast } from "roamjs-components/components/Toast";
import getPageTitleByPageUid from "roamjs-components/queries/getPageTitleByPageUid";
import renderOverlay, {
RoamOverlayProps,
} from "roamjs-components/util/renderOverlay";
import {
insertPageRefAtRange,
snapshotInsertTarget,
type InsertTarget,
} from "~/utils/advancedSearchFooterUtils";
import { DiscourseNodeSortControl } from "~/components/DiscourseNodeSortControl";
import getDiscourseNodes, {
type DiscourseNode,
} from "~/utils/getDiscourseNodes";
import { getNodeTagStyles } from "~/utils/getDiscourseNodeColors";
import {
DEBOUNCE_MS,
DEFAULT_SORT_CONFIG,
type SearchResult,
type SortConfig,
buildSearchIndex,
formatMetadataDate,
searchIndexedNodes,
sortSearchResults,
splitWithHighlights,
stripTypePrefix,
} from "./utils";
import { DiscourseNodeTypeFilter } from "~/components/AdvancedNodeSearchDialog/DiscourseNodeTypeFilter";
import { RenderRoamBlock, RenderRoamPage } from "~/utils/roamReactComponents";
import { AdvancedSearchFooter } from "./AdvancedSearchFooter";
type Props = Record<string, unknown>;
const getNodeBadgeText = (node: DiscourseNode): string => {
const text = (node.tag?.trim() || node.text).replace(/^#/, "");
return text.slice(0, 3).toUpperCase();
};
const getTagStyle = (node: DiscourseNode | undefined): React.CSSProperties => {
const color = node?.canvasSettings?.color;
if (!color) return { flexShrink: 0 };
return { ...getNodeTagStyles(color), flexShrink: 0 };
};
const renderHighlightedText = (
text: string,
keywords: string[],
): React.ReactNode =>
splitWithHighlights(text, keywords).map((segment, index) =>
segment.isMatch ? (
<mark key={`${segment.text}-${index}`}>{segment.text}</mark>
) : (
<React.Fragment key={`${segment.text}-${index}`}>
{segment.text}
</React.Fragment>
),
);
const ResultRow = ({
active,
keywords,
nodeConfig,
onClick,
onMouseEnter,
result,
}: {
active: boolean;
keywords: string[];
nodeConfig: DiscourseNode | undefined;
onClick: () => void;
onMouseEnter: () => void;
result: SearchResult;
}) => (
<Button
alignText="left"
aria-selected={active}
className="flex-none !items-start gap-2 !px-3 !py-2"
fill
minimal
onClick={onClick}
onMouseEnter={onMouseEnter}
role="option"
style={{
background: active ? "rgba(95, 87, 192, 0.08)" : undefined,
boxShadow: active ? "inset 3px 0 0 #5f57c0" : undefined,
}}
>
<Tag minimal style={getTagStyle(nodeConfig)}>
{nodeConfig
? getNodeBadgeText(nodeConfig)
: result.nodeTypeLabel.replace(/^#/, "").slice(0, 3).toUpperCase()}
</Tag>
<span className="min-w-0 break-words text-sm leading-snug text-gray-900">
{renderHighlightedText(stripTypePrefix(result.title), keywords)}
</span>
</Button>
);
const PreviewPane = ({ result }: { result: SearchResult | null }) => {
if (!result) {
return (
<div className="flex min-h-0 flex-1 items-center justify-center overflow-hidden">
<NonIdealState
icon="search"
title="Search DG nodes"
description="Type a keyword to preview matching discourse graph nodes."
/>
</div>
);
}
const isPage = !!getPageTitleByPageUid(result.uid);
return (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
<div className="flex-none flex-row gap-2 border-b border-gray-200 px-5 py-3 text-xs text-gray-500">
Created: {formatMetadataDate(result.createdAt)} · Last modified:{" "}
{formatMetadataDate(result.lastModified)} · Author:{" "}
{result.authorName || "Unknown"}
</div>
<div
className="min-h-0 flex-1 overflow-y-auto border-t border-gray-200 px-5 py-3"
onMouseDown={(event) => event.preventDefault()}
>
<div className="pointer-events-none">
{isPage ? (
<RenderRoamPage hideMentions key={result.uid} uid={result.uid} />
) : (
<RenderRoamBlock key={result.uid} uid={result.uid} zoomPath />
)}
</div>
</div>
</div>
);
};
const AdvancedNodeSearchDialog = ({
isOpen,
onClose,
}: RoamOverlayProps<Props>) => {
const [searchTerm, setSearchTerm] = useState("");
const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");
const [isIndexLoading, setIsIndexLoading] = useState(false);
const [indexError, setIndexError] = useState(false);
const [activeIndex, setActiveIndex] = useState(0);
const [results, setResults] = useState<SearchResult[]>([]);
const [sort, setSort] = useState<SortConfig>(DEFAULT_SORT_CONFIG);
const [discourseNodes, setDiscourseNodes] = useState<DiscourseNode[]>([]);
const [selectedNodeTypeIds, setSelectedNodeTypeIds] = useState<string[]>([]);
const miniSearchRef = useRef<MiniSearch<
SearchResult & { id: string }
> | null>(null);
const allResultsRef = useRef<SearchResult[]>([]);
const resultsPanelRef = useRef<HTMLDivElement | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
const [insertTarget, setInsertTarget] = useState<InsertTarget | null>(null);
const nodeConfigByType = Object.fromEntries(
discourseNodes.map((node) => [node.type, node]),
);
const activeResult = results[activeIndex] ?? null;
const keywords = debouncedSearchTerm.split(/\s+/).filter(Boolean);
useEffect(() => {
if (!isOpen) return;
setInsertTarget(snapshotInsertTarget());
const focusInput = () => inputRef.current?.focus();
focusInput();
const rafId = requestAnimationFrame(focusInput);
const timeoutId = window.setTimeout(focusInput, 0);
return () => {
cancelAnimationFrame(rafId);
window.clearTimeout(timeoutId);
};
}, [isOpen]);
useEffect(() => {
if (!isOpen) {
setSearchTerm("");
setDebouncedSearchTerm("");
setActiveIndex(0);
setSort(DEFAULT_SORT_CONFIG);
setSelectedNodeTypeIds([]);
setResults([]);
setIndexError(false);
}
}, [isOpen]);
useEffect(() => {
if (
!isOpen ||
isIndexLoading ||
indexError ||
!debouncedSearchTerm ||
!miniSearchRef.current
) {
setResults([]);
return;
}
const scoredHits = searchIndexedNodes({
miniSearch: miniSearchRef.current,
allResults: allResultsRef.current,
searchTerm: debouncedSearchTerm,
typeFilter: selectedNodeTypeIds.length ? selectedNodeTypeIds : undefined,
});
setResults(sortSearchResults({ hits: scoredHits, sort }));
}, [
debouncedSearchTerm,
indexError,
isIndexLoading,
isOpen,
selectedNodeTypeIds,
sort,
]);
useEffect(() => {
let cancelled = false;
setIsIndexLoading(true);
setIndexError(false);
const discourseNodes = getDiscourseNodes().filter(
(node) => node.backedBy === "user",
);
setDiscourseNodes(discourseNodes);
void buildSearchIndex(discourseNodes)
.then(({ miniSearch, results: indexedResults }) => {
if (cancelled) return;
miniSearchRef.current = miniSearch;
allResultsRef.current = indexedResults;
})
.catch((error) => {
console.error("Error building advanced node search index:", error);
if (cancelled) return;
setIndexError(true);
renderToast({
id: "advanced-node-search-index-error",
content: "Failed to load discourse nodes for search.",
intent: "danger",
});
})
.finally(() => {
if (!cancelled) setIsIndexLoading(false);
});
return () => {
cancelled = true;
};
}, [isOpen]);
useEffect(() => {
const timeout = setTimeout(
() => setDebouncedSearchTerm(searchTerm.trim()),
DEBOUNCE_MS,
);
return () => clearTimeout(timeout);
}, [searchTerm]);
useEffect(() => {
setActiveIndex(0);
}, [debouncedSearchTerm, selectedNodeTypeIds, sort]);
useEffect(() => {
const panel = resultsPanelRef.current;
if (!panel) return;
const activeRow = panel.querySelector('[aria-selected="true"]');
activeRow?.scrollIntoView({ block: "nearest" });
}, [activeIndex, activeResult?.uid, debouncedSearchTerm]);
const onInsert = useCallback(async () => {
if (!activeResult || !insertTarget) return;
const pageTitle =
getPageTitleByPageUid(activeResult.uid) ??
stripTypePrefix(activeResult.title);
await insertPageRefAtRange({
blockUid: insertTarget.blockUid,
pageTitle,
selectionEnd: insertTarget.selectionEnd,
selectionStart: insertTarget.selectionStart,
windowId: insertTarget.windowId,
});
posthog.capture("Advanced Node Search: Insert", {
uid: activeResult.uid,
pageTitle,
});
onClose();
}, [activeResult, insertTarget, onClose]);
const contentState = indexError
? "error"
: isIndexLoading
? "indexing"
: !debouncedSearchTerm
? "initial"
: !results.length
? "empty"
: "results";
const handleSortChange = useCallback((nextSort: SortConfig): void => {
setSort(nextSort);
}, []);
const onOpen = useCallback(async () => {
if (!activeResult || contentState !== "results") return;
const uid = activeResult.uid;
if (getPageTitleByPageUid(uid)) {
await window.roamAlphaAPI.ui.mainWindow.openPage({ page: { uid } });
} else {
await window.roamAlphaAPI.ui.mainWindow.openBlock({ block: { uid } });
}
onClose();
}, [activeResult, contentState, onClose]);
const onOpenInSidebar = useCallback(async () => {
if (!activeResult || contentState !== "results") return;
await window.roamAlphaAPI.ui.rightSidebar.addWindow({
window: {
type: "outline",
// @ts-expect-error - block-uid is valid for outline sidebar windows
// eslint-disable-next-line @typescript-eslint/naming-convention
"block-uid": activeResult.uid,
},
});
onClose();
}, [activeResult, contentState, onClose]);
const onKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowDown" && results.length) {
event.preventDefault();
setActiveIndex((index) => Math.min(index + 1, results.length - 1));
} else if (event.key === "ArrowUp" && results.length) {
event.preventDefault();
setActiveIndex((index) => Math.max(index - 1, 0));
} else if (
event.key === "Enter" &&
!event.metaKey &&
!event.ctrlKey &&
contentState === "results" &&
activeResult
) {
event.preventDefault();
if (event.shiftKey) void onOpenInSidebar();
else void onOpen();
} else if (
event.key === "Enter" &&
(event.metaKey || event.ctrlKey) &&
contentState === "results" &&
activeResult &&
insertTarget
) {
event.preventDefault();
void onInsert();
} else if (event.key === "Escape") {
event.preventDefault();
onClose();
}
},
[
activeResult,
contentState,
insertTarget,
onClose,
onInsert,
onOpen,
onOpenInSidebar,
results.length,
],
);
const showSplitView = contentState === "results";
return (
<Dialog
autoFocus={false}
canEscapeKeyClose
canOutsideClickClose
className="flex max-w-4xl flex-col overflow-hidden bg-white p-0"
enforceFocus={false}
isOpen={isOpen}
onClose={onClose}
style={{
height: "72vh",
width: "min(56rem, calc(100vw - 64px))",
}}
>
<div
onClick={(event) => event.stopPropagation()}
onKeyDown={onKeyDown}
onMouseDown={(event) => event.stopPropagation()}
onMouseUp={(event) => event.stopPropagation()}
className="flex min-h-0 flex-1 flex-col overflow-hidden"
>
<div className="flex flex-none items-center gap-2 border-b border-gray-200 px-3 py-2">
<InputGroup
fill
inputRef={inputRef}
leftIcon="search"
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setSearchTerm(event.target.value)
}
placeholder="Search discourse nodes..."
value={searchTerm}
/>
<DiscourseNodeTypeFilter
nodeTypes={discourseNodes}
onSelectedTypeIdsChange={setSelectedNodeTypeIds}
selectedTypeIds={selectedNodeTypeIds}
/>
<DiscourseNodeSortControl
disabled={isIndexLoading || indexError}
onSortChange={handleSortChange}
sort={sort}
/>
<Button
className="shrink-0"
icon="cross"
minimal
onClick={onClose}
title="Close search"
/>
</div>
<div className="flex min-h-0 w-full flex-1 overflow-hidden">
{showSplitView ? (
<>
<div
aria-label="Search results"
className="w-1/3 shrink-0 overflow-y-auto border-r border-gray-200 py-1"
ref={resultsPanelRef}
role="listbox"
>
{results.map((result, index) => (
<ResultRow
active={index === activeIndex}
key={result.uid}
keywords={keywords}
nodeConfig={nodeConfigByType[result.type]}
onClick={() => setActiveIndex(index)}
onMouseEnter={() => setActiveIndex(index)}
result={result}
/>
))}
</div>
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
<PreviewPane result={activeResult} />
</div>
</>
) : (
<div className="flex min-h-0 w-full flex-1 items-center justify-center px-4 py-8 text-center text-sm text-gray-500">
{contentState === "indexing" && (
<Spinner size={SpinnerSize.SMALL} />
)}
{contentState === "empty" && (
<span>No matches. Try another keyword.</span>
)}
{contentState === "error" && (
<span>
Search unavailable. Reload the extension and try again.
</span>
)}
</div>
)}
</div>
<AdvancedSearchFooter
contentState={contentState}
hasActiveResult={!!activeResult}
insertTarget={insertTarget}
onInsert={() => void onInsert()}
onOpen={() => void onOpen()}
onOpenInSidebar={() => void onOpenInSidebar()}
/>
</div>
</Dialog>
);
};
export const renderAdvancedNodeSearchDialog = () =>
renderOverlay({
// eslint-disable-next-line @typescript-eslint/naming-convention
Overlay: AdvancedNodeSearchDialog,
props: {},
});