-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathAutocomplete.tsx
More file actions
842 lines (788 loc) · 27.1 KB
/
Autocomplete.tsx
File metadata and controls
842 lines (788 loc) · 27.1 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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
import {
AutocompleteState,
BaseItem,
createAutocomplete,
} from "@algolia/autocomplete-core";
import {
getAlgoliaResults,
parseAlgoliaHitHighlight,
} from "@algolia/autocomplete-preset-algolia";
import algoliasearch from "algoliasearch/lite";
import { ScrollerBottomGradient } from "./Page/ScrollerBottomGradient";
import Link from "next/link";
import { useRouter } from "next/router";
import React, {
RefObject,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { useHotkeys } from "react-hotkeys-hook";
import "@algolia/autocomplete-theme-classic";
import {
AIChatFunctions,
type InkeepModalSearchAndChat,
} from "@inkeep/cxkit-react";
import { Input } from "@telegraph/input";
import { Box, Stack } from "@telegraph/layout";
import { Tag } from "@telegraph/tag";
import { Search, Sparkles, X } from "lucide-react";
const InKeepTrigger = dynamic(
() =>
import("@inkeep/cxkit-react").then((mod) => mod.InkeepModalSearchAndChat),
{
ssr: false,
},
) as typeof InkeepModalSearchAndChat;
import { DocsSearchItem, EndpointSearchItem, EnhancedDocsSearchItem } from "@/types";
import { Button } from "@telegraph/button";
import { Icon } from "@telegraph/icon";
import { MenuItem } from "@telegraph/menu";
import { Code, Text } from "@telegraph/typography";
import dynamic from "next/dynamic";
import useInkeepSettings from "../../hooks/useInKeepSettings";
import { usePageContext } from "./Page";
import { highlightResource } from "./Page/helpers";
// This Autocomplete component was created following:
// https://www.algolia.com/doc/ui-libraries/autocomplete/api-reference/autocomplete-core/createAutocomplete/
//
// It has a few customizations when compared with algolia's autocomplete, but it already
// support customizations in case we want to implement future enhancements.
//
// This component is inspired heavily on https://github.com/algolia/autocomplete/blob/next/packages/autocomplete-js/src/components/Highlight.ts#L5.
// It's not exposed publicly for import, that's why we keep our version here.
const highlightingStyles = {
color: "#485CC7",
fontWeight: 600,
background: "transparent",
};
// These are the number of hits we want to show for each section
const NUM_DOCS_HITS = 12;
const NUM_ENDPOINT_HITS = 5;
type ResultItem = (EnhancedDocsSearchItem & BaseItem) | (EndpointSearchItem & BaseItem);
const algoliaAppId = process.env.NEXT_PUBLIC_ALGOLIA_APP_ID || "";
const algoliaSearchApiKey =
process.env.NEXT_PUBLIC_ALGOLIA_SEARCH_API_KEY || "";
const algoliaIndex = process.env.NEXT_PUBLIC_ALGOLIA_INDEX_NAME || "";
const algoliaEndpointIndex =
process.env.NEXT_PUBLIC_ALGOLIA_ENDPOINT_INDEX_NAME || "";
// We do some delayed rendering below to avoid hydration errors
// Instead of returning null when the component isn't ready, we return a static version
// This makes sure the server renders the same element and client will do a hot-swap with the real thing
// Prevents loading jank
const StaticSearch = () => {
return (
<Box as="form">
<Input
placeholder="Search the docs..."
size="2"
className="aa-Input"
LeadingComponent={
<Icon icon={Search} alt="Search" color="gray" size="1" mr="2" />
}
TrailingComponent={
<Stack
bg="gray-1"
borderRadius="1"
border="px"
borderColor="gray-3"
justifyContent="center"
alignItems="center"
width="5"
height="5"
>
<Text
as="span"
size="1"
color="black"
weight="medium"
style={{ lineHeight: "1", transform: "translateY(-1px)" }}
>
/
</Text>
</Stack>
}
/>
</Box>
);
};
const handleSearchNavigation = (
e: React.MouseEvent<HTMLAnchorElement> | React.KeyboardEvent<HTMLFormElement>,
router,
itemUrl,
onSearch: () => void,
) => {
e.preventDefault();
const pathname = router.asPath;
const isMapiReference =
itemUrl.startsWith("mapi-reference") &&
pathname.startsWith("/mapi-reference");
const isApiReference =
itemUrl.startsWith("api-reference") &&
pathname.startsWith("/api-reference");
const isSamePageReferenceResult = isMapiReference || isApiReference;
// If the item is in the same reference, highlight the item, don't navigate
if (isSamePageReferenceResult) {
highlightResource(`/${itemUrl}`, { moveToItem: true });
} else {
// Handle regular navigation
router.push(`/${itemUrl}`);
}
onSearch();
};
const DocsSearchResult = ({
item,
onClick,
}: {
item: ResultItem;
onClick: () => void;
}) => {
const router = useRouter();
return (
<Link
href={`/${item.path}`}
onClick={(e) => handleSearchNavigation(e, router, item.path, onClick)}
>
<Box w="full" h="full" px="2" py="2">
<Text as="p" size="2" color="black" weight="regular">
{/* @ts-expect-error not sure about these algolia types */}
{parseAlgoliaHitHighlight({ hit: item, attribute: "title" }).map(
(x, index) => {
if (x.isHighlighted) {
return (
<mark key={index} style={highlightingStyles}>
{x.value}
</mark>
);
}
return x.value;
},
)}
</Text>
<Text as="span" size="1" color="gray" weight="regular">
{item.pageTitle ? `${item.pageTitle as string} •` : ""} {item.section}
</Text>
</Box>
</Link>
);
};
const EndpointSearchResult = ({
item,
onClick,
}: {
item: EndpointSearchItem;
onClick: () => void;
}) => {
const router = useRouter();
const colors = {
get: "blue",
post: "green",
put: "yellow",
delete: "red",
patch: "purple",
} as const;
return (
<Link
href={`/${item.path}`}
onClick={(e) => handleSearchNavigation(e, router, item.path, onClick)}
>
<Stack w="full" h="full" px="1" py="2" gap="2" alignItems="center">
<Tag size="0" color={colors[item.method as keyof typeof colors]}>
{item.method?.toUpperCase()}
</Tag>
<Code as="p" size="1" color="black" weight="regular">
{/* @ts-expect-error not sure about these algolia types */}
{parseAlgoliaHitHighlight({ hit: item, attribute: "endpoint" }).map(
(x, index) => {
if (x.isHighlighted) {
return (
<mark key={index} style={highlightingStyles}>
{x.value}
</mark>
);
}
return x.value;
},
)}
</Code>
<Text
as="span"
size="1"
color="gray"
weight="regular"
style={{
textOverflow: "ellipsis",
overflow: "hidden",
whiteSpace: "nowrap",
maxWidth: "100%",
}}
>
{item.title}
</Text>
</Stack>
</Link>
);
};
const Autocomplete = () => {
const { setIsSearchOpen } = usePageContext();
const [autocompleteState, setAutocompleteState] =
useState<AutocompleteState<BaseItem> | null>(null);
const scrollerRef = useRef<HTMLDivElement>(null);
// Add state for the AI chat
const [isAiChatOpen, setIsAiChatOpen] = useState(false);
const [aiSearchTerm, setAiSearchTerm] = useState("");
const chatFunctionsRef = useRef<AIChatFunctions | null>(null);
const { baseSettings, aiChatSettings, searchSettings, modalSettings } =
useInkeepSettings();
const inputRef = useRef(null);
const router = useRouter();
const searchClient = useMemo(
() => algoliasearch(algoliaAppId, algoliaSearchApiKey),
[],
);
// Function to handle opening the AI chat
const handleOpenAiChat = useCallback((searchTerm: string) => {
setAiSearchTerm(searchTerm);
setIsAiChatOpen(true);
}, []);
// Function to handle closing the AI chat
const handleCloseAiChat = useCallback(() => {
setIsAiChatOpen(false);
}, []);
// Add this effect to update the chat input when aiSearchTerm changes
useEffect(() => {
if (isAiChatOpen && chatFunctionsRef.current && aiSearchTerm) {
// Update the input message with the search term
chatFunctionsRef.current.updateInputMessage(aiSearchTerm);
// Use a small timeout to ensure the chat is fully loaded before submitting
setTimeout(() => {
if (chatFunctionsRef.current) {
chatFunctionsRef.current.submitMessage();
}
}, 500);
}
}, [isAiChatOpen, aiSearchTerm]);
const autocomplete = useMemo(
() =>
createAutocomplete({
onStateChange({ state }) {
setIsSearchOpen(state.isOpen);
setAutocompleteState(state);
},
getSources() {
return [
{
sourceId: "docSearchResults",
getItemInputValue({
item,
state,
}: {
item: BaseItem;
state: AutocompleteState<BaseItem>;
}): string {
return state.query;
},
getItems({ query }) {
if (!query) {
return [];
}
// Create our custom "Ask AI" item
const askAiItem = {
objectID: "ask-ai",
path: "#",
title: `Can you tell me about ${query}`,
section: "Use AI to answer your question",
__isAskAiItem: true,
};
// Get the Algolia results and add the "Ask AI" item at the top
return getAlgoliaResults({
searchClient,
queries: [
{
indexName: algoliaIndex,
query,
params: {
hitsPerPage: NUM_DOCS_HITS,
},
},
{
indexName: algoliaEndpointIndex,
query,
params: {
hitsPerPage: NUM_ENDPOINT_HITS,
},
},
],
transformResponse({ hits: hitsArray }) {
const hits = hitsArray as (
| DocsSearchItem[]
| EndpointSearchItem[]
)[];
// Add the "Ask AI" item at the top of the results
// Filter out any items that don't have required properties or have invalid paths
const filteredHits = hits.map((hitsArr) =>
hitsArr.filter((hit) => {
if (!hit?.objectID || !hit?.path) return false;
// Ensure the path is not empty and doesn't contain any malformed segments
const path = hit.path as string;
return (
path.length > 0 &&
!path.includes("//") &&
!path.startsWith("/") &&
!path.endsWith("/")
);
}),
);
const endpointHits =
filteredHits.length > 1 ? filteredHits[1] : [];
const docsHits =
filteredHits.length > 0 ? filteredHits[0] : [];
// Sort docs hits to put endpoints at the back of the results
const sortedDocsHits = docsHits.sort((a, b) => {
if (
a.contentType === "api-reference" &&
b.contentType !== "api-reference"
)
return 1;
if (
a.contentType !== "api-reference" &&
b.contentType === "api-reference"
)
return -1;
return 0;
});
// Quick hack to lift items in the "Concepts" section to the top of results
docsHits.sort((a, b) => {
const aIsConcepts =
a.section && a.section.toLowerCase() === "concepts";
const bIsConcepts =
b.section && b.section.toLowerCase() === "concepts";
if (aIsConcepts && !bIsConcepts) return -1;
if (!aIsConcepts && bIsConcepts) return 1;
return 0;
});
return [askAiItem, ...endpointHits, ...sortedDocsHits];
},
});
},
getItemUrl({ item }: { item: BaseItem }): string {
return (item as ResultItem).path;
},
},
];
},
shouldPanelOpen({ state }) {
return !!state.query;
},
navigator: {
navigate({ itemUrl, item, state }) {
// Check if this is our Ask AI item
if ((item as any).__isAskAiItem) {
handleOpenAiChat(state.query);
return;
}
// Handle regular navigation
router.push(`/${itemUrl}`);
// Clear the query when navigating
if (state.query) {
autocomplete.setQuery("");
}
},
},
}),
[router, searchClient, handleOpenAiChat, setIsSearchOpen],
);
useHotkeys("/, cmd+k", (e) => {
// adding small timeout so event doesn't get to the focused input resulting
// in "/" being displayed on the input
e.preventDefault();
setTimeout(() => {
const ref = inputRef.current;
if (ref) {
(ref as HTMLElement).focus();
}
}, 20);
});
// Fix hydration error by hiding autocomplete during ssr
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
// Add a ref for the root element
const rootRef = useRef<HTMLDivElement>(null);
// Add click outside handler
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
rootRef.current &&
!rootRef.current.contains(event.target as Node) &&
autocompleteState?.isOpen
) {
// Reset the autocomplete state
autocomplete.setIsOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [autocomplete, autocompleteState?.isOpen]);
if (!mounted) {
return <StaticSearch />;
}
type FormProps = {
action: string;
noValidate: boolean;
role: string;
onSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
onReset: (e: React.FormEvent<HTMLFormElement>) => void;
};
const hasResults =
autocompleteState?.collections?.some(
(collection) => collection.items.length > 1,
) ?? false;
const handleKeyDown = (e: React.KeyboardEvent<HTMLFormElement>) => {
if (e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
// Open the AI chat
if (autocompleteState?.query && !hasResults) {
handleOpenAiChat(autocompleteState.query);
return;
} else {
// Navigate to the first item that is not the "Ask AI" item
const firstItem = autocompleteState?.collections[0]?.items[1];
if (firstItem) {
handleSearchNavigation(e, router, firstItem?.path, () => {});
}
return;
}
}
};
const formProps: unknown = autocomplete.getFormProps({
inputElement: inputRef.current,
});
const inputProps: unknown = autocomplete.getInputProps({
inputElement: inputRef.current,
placeholder: "Search the docs...",
});
return (
<Box {...autocomplete.getRootProps()} w="full" tgphRef={rootRef}>
<Box
as="form"
className="aa-Form"
onKeyDown={handleKeyDown}
{...(formProps as FormProps)}
>
<Input
tgphRef={inputRef}
placeholder="Search the docs.."
className="aa-Input"
{...(inputProps as React.DetailedHTMLProps<
React.InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>)}
size="2"
w="full"
LeadingComponent={
<Icon icon={Search} alt="Search" color="gray" size="1" mr="2" />
}
TrailingComponent={
<>
{autocompleteState?.query ? (
<Button
variant="outline"
size="1"
weight="regular"
bg="gray-1"
color="gray"
icon={{
icon: X,
"aria-hidden": true,
color: "black",
}}
onClick={() => {
autocomplete.setQuery("");
if (inputRef.current) {
(inputRef.current as HTMLInputElement).focus();
}
}}
py="2"
px="1"
ml="2"
style={{
height: "20px",
}}
>
Clear
</Button>
) : (
<>
<Stack
bg="gray-1"
borderRadius="1"
border="px"
borderColor="gray-3"
justifyContent="center"
alignItems="center"
width="5"
height="5"
className="md-hidden"
>
<Text
as="span"
size="1"
color="black"
weight="medium"
style={{
lineHeight: "1",
transform: "translateY(-1px)",
}}
>
/
</Text>
</Stack>
<Box
borderRadius="1"
width="5"
height="5"
className="md-visible"
></Box>
</>
)}
</>
}
/>
</Box>
{autocompleteState?.isOpen && (
<Box
data-search-results-container
position="absolute"
bg="white"
w="96"
border="px"
borderColor="gray-6"
mt="2"
shadow="1"
borderRadius="2"
p="2"
style={{
overscrollBehavior: "none",
zIndex: 50,
overflow: "hidden",
transition: "opacity 0.15s ease-in-out",
width: "clamp(200px, 500px, 90vw)",
left: "clamp(5%, auto, 5%)",
}}
>
{/* Adds a white shadow to the bottom of the autocomplete when items below scroll */}
<ScrollerBottomGradient
scrollerRef={scrollerRef as RefObject<HTMLDivElement>}
gradientProps={{
height: "20",
}}
managePadding={false}
/>
<Box
w="full"
h="full"
style={{
overflowY: "auto",
maxHeight: "80dvh",
paddingBottom: "0",
}}
tgphRef={scrollerRef}
>
{autocompleteState?.collections.map((collection, index) => {
const { source, items } = collection;
return (
<Box key={`source-${index}`}>
{items.length > 0 ? (
<Box>
<Box
as="ul"
className="aa-List"
pb={items.length > 1 ? "2" : "0"}
{...autocomplete.getListProps()}
>
<MenuItem
as="li"
className="aa-Item"
w="full"
h="full"
key={(items[0] as ResultItem).objectID}
style={{
cursor: "pointer",
transition: "all 0.15s ease-in-out",
gridTemplateColumns: "1fr",
}}
{...(autocomplete.getItemProps({
item: items[0],
source,
}) as unknown as React.LiHTMLAttributes<HTMLLIElement>)}
color="default"
onClick={() =>
handleOpenAiChat((inputProps as any).value)
}
>
<Stack
py="3"
px="2"
justifyContent="space-between"
alignItems="center"
w="full"
>
<Box>
<Text
as="p"
size="2"
color="black"
weight="regular"
>
{(items[0] as ResultItem).title}
</Text>
<Text
as="span"
size="1"
color="gray"
weight="regular"
>
{(items[0] as ResultItem).section}
</Text>
</Box>
<Icon
icon={Sparkles}
alt="Sparkles"
color="black"
size="4"
/>
</Stack>
</MenuItem>
{items.map((item, index) => {
// Skip the first item, it's rendered above
if (index === 0) return null;
const isEndpoint =
(item as ResultItem).index === "endpoints";
const previousItem = items[index - 1] as ResultItem;
const prevIsEndpoint =
previousItem?.index === "endpoints";
// Show divider after the first AskAI item and between endpoints and docs sections
const showDivider =
index === 1 || (!isEndpoint && prevIsEndpoint);
const key = (item as ResultItem).objectID;
return (
<React.Fragment key={key}>
{showDivider && (
<Box
borderTop="px"
borderColor="gray-4"
marginY="2"
w="full"
/>
)}
<MenuItem
as="li"
w="full"
h="full"
className="aa-Item"
style={{
cursor: "pointer",
transition: "all 0.15s ease-in-out",
gridTemplateColumns: "1fr",
}}
{...(autocomplete.getItemProps({
item,
source,
}) as unknown as React.LiHTMLAttributes<HTMLLIElement>)}
color="default"
>
{isEndpoint ? (
<EndpointSearchResult
item={item as EndpointSearchItem}
onClick={() => autocomplete.setQuery("")}
/>
) : (
<DocsSearchResult
item={item as EnhancedDocsSearchItem}
onClick={() => autocomplete.setQuery("")}
/>
)}
</MenuItem>
</React.Fragment>
);
})}
</Box>
</Box>
) : (
<Box
p="4"
className="p-4 text-[14px] text-gray-400 dark:text-gray-200 font-medium "
>
<Text as="span" size="1" color="gray" weight="regular">
No matching results.
</Text>{" "}
<Link
href="javascript:void(0)"
className="text-brand"
onClick={() =>
handleOpenAiChat((inputProps as any).value)
}
>
Ask AI ✨
</Link>
</Box>
)}
</Box>
);
})}
</Box>
</Box>
)}
{/* Add the InKeep trigger component directly in the Autocomplete component */}
<InKeepTrigger
defaultView="chat"
baseSettings={{
...baseSettings,
theme: {
styles: [
{
key: "knock-autocomplete-style",
type: "style",
// InkeepModalSearchAndChat does not accept a canToggleView prop,
// so we apply a custom style to hide the header. Without this style,
// the AI chat displays a header that allows the user to toggle between
// a normal search and an AI chat.
value: `
.ikp-ai-chat-header {
display: none;
}
`,
},
],
},
}}
aiChatSettings={{
...aiChatSettings,
chatFunctionsRef,
placeholder: "Ask a question...",
}}
modalSettings={{
...modalSettings,
isOpen: isAiChatOpen,
onOpenChange: (open) => {
if (!open) {
handleCloseAiChat();
}
},
}}
searchSettings={{
...searchSettings,
defaultQuery: aiSearchTerm,
}}
/>
</Box>
);
};
export default Autocomplete;