@devries-cameron20 / composio Mirror · read-only
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 03:37 UTC

next
tsx 337 lines 10 KB
Raw
1 'use client';
2
3 import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4 import Link from 'next/link';
5 import { liteClient } from 'algoliasearch/lite';
6 import aa from 'search-insights';
7 import {
8 SearchDialog,
9 SearchDialogClose,
10 SearchDialogContent,
11 SearchDialogHeader,
12 SearchDialogIcon,
13 SearchDialogInput,
14 SearchDialogList,
15 SearchDialogOverlay,
16 type SharedProps,
17 } from 'fumadocs-ui/components/dialog/search';
18 import { useI18n } from 'fumadocs-ui/contexts/i18n';
19 import { useDocsSearch } from 'fumadocs-core/search/client';
20 import type { BaseIndex } from 'fumadocs-core/search/algolia';
21 import { BotMessageSquare } from 'lucide-react';
22 import {
23 KNOWLEDGE_SOURCE_LABELS,
24 type KnowledgeSourceType,
25 } from '@/lib/knowledge/types';
26 import { getKnowledgeDisplayDescription } from '@/lib/knowledge/display';
27 import { detectMac } from './ask-ai-button';
28 import { toggleEveChat } from './eve-chat-store';
29
30 function MetaKey() {
31 const [key, setKey] = useState('⌘');
32
33 useEffect(() => {
34 if (detectMac()) return;
35
36 const id = window.setTimeout(() => setKey('Ctrl'), 0);
37 return () => window.clearTimeout(id);
38 }, []);
39
40 return key;
41 }
42
43 export interface DefaultLink {
44 title: string;
45 description: string;
46 href: string;
47 }
48
49 interface CustomSearchDialogProps extends SharedProps {
50 defaultLinks?: DefaultLink[];
51 api?: string;
52 }
53
54 type AlgoliaHit = BaseIndex & {
55 canonical_url?: string;
56 source_type?: KnowledgeSourceType;
57 };
58
59 type AlgoliaSearchResponse = {
60 hits: AlgoliaHit[];
61 queryID?: string;
62 };
63
64 type AlgoliaHitMeta = {
65 objectID: string;
66 position: number;
67 queryID?: string;
68 };
69
70 export function buildAlgoliaHitMetadata(
71 hits: Array<{ objectID: string; url?: string }>,
72 queryID?: string,
73 ): Map<string, AlgoliaHitMeta> {
74 const metadata = new Map<string, AlgoliaHitMeta>();
75 hits.forEach((hit, index) => {
76 if (!hit.url || metadata.has(hit.url)) return;
77 metadata.set(hit.url, {
78 objectID: hit.objectID,
79 position: index + 1,
80 queryID,
81 });
82 });
83 return metadata;
84 }
85
86 type SearchResultItem = {
87 content: unknown;
88 breadcrumbs?: unknown[];
89 };
90
91 const SEARCH_BREADCRUMB_LABELS: Record<string, string> = {
92 toolkits: 'Toolkit',
93 toolkit: 'Toolkit',
94 examples: 'Example',
95 example: 'Example',
96 docs: 'Docs',
97 kb: 'Knowledge Base',
98 guide: 'Knowledge Base',
99 auth: 'OAuth',
100 oauth: 'OAuth',
101 'oauth-guide': 'OAuth',
102 reference: 'Reference',
103 'api-reference': 'API Reference',
104 changelog: 'Changelog',
105 };
106
107 function normalizeSearchBreadcrumb(value: string): string {
108 return SEARCH_BREADCRUMB_LABELS[value.toLowerCase()] ?? value;
109 }
110
111 function normalizeSearchResult<T extends SearchResultItem>(result: T): T {
112 const content = typeof result.content === 'string'
113 ? getKnowledgeDisplayDescription(result.content)
114 : result.content;
115 if (!result.breadcrumbs) return { ...result, content };
116
117 const breadcrumbs = result.breadcrumbs.map((breadcrumb) =>
118 typeof breadcrumb === 'string' ? normalizeSearchBreadcrumb(breadcrumb) : breadcrumb,
119 );
120
121 const normalizedContent = typeof content === 'string' ? content.toLowerCase() : null;
122 const dedupedBreadcrumbs = breadcrumbs.filter((breadcrumb, index) => {
123 if (index !== breadcrumbs.length - 1 || normalizedContent === null || typeof breadcrumb !== 'string') {
124 return true;
125 }
126
127 return breadcrumb.toLowerCase() !== normalizedContent;
128 });
129
130 return {
131 ...result,
132 content,
133 breadcrumbs: dedupedBreadcrumbs,
134 };
135 }
136
137 export default function CustomSearchDialog({
138 defaultLinks = [],
139 api = '/api/search',
140 ...props
141 }: CustomSearchDialogProps) {
142 const { locale } = useI18n();
143 const algoliaHitMetaRef = useRef(new Map<string, AlgoliaHitMeta>());
144 const insightsInitializedRef = useRef(false);
145
146 const ensureAlgoliaInsights = useCallback((appId: string, searchApiKey: string) => {
147 if (insightsInitializedRef.current) return;
148
149 aa('init', {
150 appId,
151 apiKey: searchApiKey,
152 useCookie: true,
153 });
154 insightsInitializedRef.current = true;
155 }, []);
156
157 const clientOptions = useMemo(() => {
158 const appId = process.env.NEXT_PUBLIC_ALGOLIA_APP_ID ?? '62HI9PQZ1L';
159 const searchApiKey = process.env.NEXT_PUBLIC_ALGOLIA_SEARCH_API_KEY;
160 const indexName = process.env.NEXT_PUBLIC_ALGOLIA_INDEX_NAME ?? 'docs_composio';
161
162 if (appId && searchApiKey) {
163 const client = liteClient(appId, searchApiKey);
164
165 return {
166 type: 'algolia' as const,
167 client,
168 indexName,
169 locale,
170 onSearch: async (query: string, tag?: string) => {
171 ensureAlgoliaInsights(appId, searchApiKey);
172
173 const result = await client.searchForHits<AlgoliaHit>({
174 requests: [
175 {
176 type: 'default',
177 indexName,
178 query,
179 distinct: true,
180 hitsPerPage: 10,
181 filters: tag ? `tag:${tag}` : undefined,
182 clickAnalytics: true,
183 },
184 ],
185 });
186 const response = result.results[0] as AlgoliaSearchResponse;
187 response.hits = response.hits.map((hit) => {
188 const canonicalUrl = hit.canonical_url || hit.url;
189 const sourceLabel = hit.source_type
190 ? KNOWLEDGE_SOURCE_LABELS[hit.source_type]
191 : null;
192 const breadcrumbs = sourceLabel
193 ? [
194 sourceLabel,
195 ...(hit.breadcrumbs ?? []).filter(
196 (breadcrumb) => breadcrumb.toLowerCase() !== sourceLabel.toLowerCase(),
197 ),
198 ]
199 : hit.breadcrumbs;
200 return { ...hit, url: canonicalUrl, breadcrumbs };
201 });
202
203 const metadata = buildAlgoliaHitMetadata(response.hits, response.queryID);
204
205 algoliaHitMetaRef.current = metadata;
206
207 const viewedObjectIDs = Array.from(metadata.values())
208 .slice(0, 20)
209 .map((hit) => hit.objectID);
210
211 if (viewedObjectIDs.length > 0) {
212 aa('viewedObjectIDs', {
213 index: indexName,
214 eventName: 'Docs Search Results Viewed',
215 objectIDs: viewedObjectIDs,
216 });
217 }
218
219 return result;
220 },
221 };
222 }
223
224 return {
225 type: 'fetch' as const,
226 locale,
227 api,
228 };
229 }, [api, ensureAlgoliaInsights, locale]);
230
231 const { search, setSearch, query } = useDocsSearch(clientOptions);
232 const searchResults = useMemo(() => {
233 if (query.data === 'empty' || !query.data) return query.data;
234 return query.data.map(normalizeSearchResult);
235 }, [query.data]);
236
237 const trackAlgoliaClick = useCallback((href: string) => {
238 const url = new URL(href, window.location.origin);
239 const path = `${url.pathname}${url.hash}`;
240 const hit = algoliaHitMetaRef.current.get(href) ??
241 algoliaHitMetaRef.current.get(url.href) ??
242 algoliaHitMetaRef.current.get(path) ??
243 algoliaHitMetaRef.current.get(url.pathname);
244 const indexName = process.env.NEXT_PUBLIC_ALGOLIA_INDEX_NAME ?? 'docs_composio';
245
246 if (!hit) return;
247
248 if (hit.queryID) {
249 aa('clickedObjectIDsAfterSearch', {
250 index: indexName,
251 eventName: 'Docs Search Result Clicked',
252 queryID: hit.queryID,
253 objectIDs: [hit.objectID],
254 positions: [hit.position],
255 });
256 return;
257 }
258
259 aa('clickedObjectIDs', {
260 index: indexName,
261 eventName: 'Docs Search Result Clicked',
262 objectIDs: [hit.objectID],
263 });
264 }, []);
265
266 return (
267 <SearchDialog
268 search={search}
269 onSearchChange={setSearch}
270 isLoading={query.isLoading}
271 {...props}
272 >
273 <SearchDialogOverlay />
274 <SearchDialogContent className="max-md:max-h-[calc(100dvh-2rem)] max-md:flex max-md:flex-col">
275 <SearchDialogHeader>
276 <SearchDialogIcon />
277 <SearchDialogInput />
278 <SearchDialogClose />
279 </SearchDialogHeader>
280 <div
281 className="search-scroll-container max-md:min-h-0 max-md:flex-1 max-md:overflow-y-auto"
282 onClickCapture={(event) => {
283 const target = event.target;
284 if (!(target instanceof Element)) return;
285
286 const anchor = target.closest('a[href]');
287 const href = anchor?.getAttribute('href');
288 if (!href) return;
289
290 trackAlgoliaClick(href);
291 }}
292 >
293 {query.data === 'empty' && defaultLinks.length > 0 ? (
294 <div className="flex flex-col p-2">
295 {defaultLinks.map((link) => (
296 <Link
297 key={link.href}
298 href={link.href}
299 onClick={() => props.onOpenChange(false)}
300 className="rounded-lg px-2.5 py-2 text-start text-sm transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground"
301 >
302 <p className="font-medium">{link.title}</p>
303 <p className="text-xs text-fd-muted-foreground">
304 {getKnowledgeDisplayDescription(link.description)}
305 </p>
306 </Link>
307 ))}
308 </div>
309 ) : (
310 <SearchDialogList items={searchResults === 'empty' ? null : searchResults} />
311 )}
312 </div>
313 <div className="flex items-center justify-between border-t px-3 py-2">
314 <button
315 type="button"
316 className="inline-flex items-center gap-1.5 text-xs text-[var(--composio-orange)] hover:text-[var(--composio-orange)]/80 transition-colors"
317 onClick={() => {
318 props.onOpenChange(false);
319 toggleEveChat();
320 }}
321 >
322 <BotMessageSquare className="size-3.5" />
323 You can also Ask AI
324 </button>
325 <div className="hidden sm:inline-flex gap-0.5">
326 <kbd className="rounded-md border bg-fd-background px-1.5 text-xs text-fd-muted-foreground">
327 <MetaKey />
328 </kbd>
329 <kbd className="rounded-md border bg-fd-background px-1.5 text-xs text-fd-muted-foreground">
330 I
331 </kbd>
332 </div>
333 </div>
334 </SearchDialogContent>
335 </SearchDialog>
336 );
337 }