@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 468 lines 18.6 KB
Raw
1 'use client';
2
3 import { useState, useMemo, useEffect, type ReactNode } from 'react';
4 import Link from 'next/link';
5 import { Search, Copy, Check, ChevronDown, ChevronRight, ArrowLeft } from 'lucide-react';
6 import { TypeTable } from 'fumadocs-ui/components/type-table';
7 import type { Toolkit, Tool, Trigger, ParameterSchema } from '@/types/toolkit';
8 import { processSchema } from '@/lib/toolkit-schema';
9 import { descriptionLinks } from '@/lib/description-links';
10 import { instantDiscount, instantPricingDescription, toolkitSupportsInstant } from '@/lib/instant';
11 import { InstantBadge } from './instant-badge';
12 import { PageActions } from '@/components/page-actions';
13 import { EditOnGitHub } from '@/components/edit-on-github';
14 import { AuthDetailsSection } from '@/components/toolkits/auth-details-section';
15 import { FaqSection, type FaqItem } from '@/components/toolkits/faq-section';
16
17 interface ToolkitDetailProps {
18 toolkit: Toolkit;
19 tools: Tool[];
20 triggers: Trigger[];
21 path: string;
22 faq?: FaqItem[] | null;
23 }
24
25 function ToolkitIcon({ toolkit }: { toolkit: Toolkit }) {
26 const [imgFailed, setImgFailed] = useState(false);
27 const fallback = (toolkit.name?.trim() || toolkit.slug).charAt(0).toUpperCase();
28
29 return (
30 <div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-xl border border-fd-border bg-fd-card text-xl font-semibold text-fd-muted-foreground shadow-sm">
31 {toolkit.logo && !imgFailed ? (
32 <img
33 src={toolkit.logo}
34 alt=""
35 className="h-[60%] w-[60%] object-contain"
36 onError={() => setImgFailed(true)}
37 />
38 ) : (
39 fallback
40 )}
41 </div>
42 );
43 }
44
45 // Format default value for display
46 function formatDefault(value: unknown): string | undefined {
47 if (value === undefined || value === null) return undefined;
48 if (typeof value === 'object') return JSON.stringify(value);
49 return String(value);
50 }
51
52 // Format type with enum values if available
53 function formatType(param: ParameterSchema): string {
54 let typeStr = param.type || 'string';
55
56 // Show array item type
57 if (typeStr === 'array' && param.items) {
58 const itemType = param.items.type || 'unknown';
59 typeStr = `array<${itemType}>`;
60 }
61
62 // Include enum values in type display
63 if (param.enum && param.enum.length > 0) {
64 const enumValues = param.enum.map(v => `"${v}"`).join(' | ');
65 typeStr = `${typeStr} (${enumValues})`;
66 }
67
68 return typeStr;
69 }
70
71 // Get children from a param (object properties, array item properties, or additionalProperties)
72 function getChildren(param: ParameterSchema): Record<string, ParameterSchema> | null {
73 const props = param.properties || param.items?.properties;
74 const additionalProps = param.additionalProperties || param.items?.additionalProperties;
75
76 if ((!props || typeof props !== 'object') && (!additionalProps || typeof additionalProps !== 'object')) return null;
77
78 const requiredList: string[] = param.requiredFields || param.items?.requiredFields || [];
79 const result: Record<string, ParameterSchema> = {};
80
81 if (props && typeof props === 'object') {
82 for (const [key, value] of Object.entries(props)) {
83 if (typeof value === 'object' && value !== null) {
84 const raw = value as ParameterSchema & { required?: string[] | boolean };
85 result[key] = {
86 ...raw,
87 required: Array.isArray(requiredList) ? requiredList.includes(key) : false,
88 // Map the child's own JSON Schema required array to requiredFields
89 // so that deeper nesting levels preserve required info
90 ...(Array.isArray(raw.required) ? { requiredFields: raw.required } : {}),
91 };
92 }
93 }
94 }
95
96 // Include additionalProperties as a synthetic [key: string] entry
97 if (additionalProps && typeof additionalProps === 'object') {
98 const raw = additionalProps as ParameterSchema & { required?: string[] | boolean };
99 result['[key: string]'] = {
100 ...raw,
101 required: false,
102 ...(Array.isArray(raw.required) ? { requiredFields: raw.required } : {}),
103 };
104 }
105
106 return Object.keys(result).length > 0 ? result : null;
107 }
108
109 // Build a ReactNode description that includes text + nested TypeTable for children
110 function buildDescription(param: ParameterSchema): ReactNode {
111 const children = getChildren(param);
112 if (!children) return param.description || undefined;
113
114 return (
115 <div className="space-y-2">
116 {param.description && <p>{param.description}</p>}
117 <TypeTable type={paramsToTypeTable(children)} />
118 </div>
119 );
120 }
121
122 // Convert parameter schema to TypeTable format, recursively nesting child TypeTables in descriptions
123 function paramsToTypeTable(params: Record<string, ParameterSchema>): Record<string, {
124 type: string;
125 description?: ReactNode;
126 default?: string;
127 required?: boolean;
128 }> {
129 const result: Record<string, { type: string; description?: ReactNode; default?: string; required?: boolean }> = {};
130 for (const [name, param] of Object.entries(params)) {
131 result[name] = {
132 type: formatType(param),
133 description: buildDescription(param),
134 default: formatDefault(param.default),
135 required: param.required,
136 };
137 }
138 return result;
139 }
140
141
142 // Check if item is a Tool with parameters
143 function isTool(item: Tool | Trigger): item is Tool {
144 return 'input_parameters' in item || 'output_parameters' in item;
145 }
146
147 // Check if item is a Trigger with config/payload
148 function isTrigger(item: Tool | Trigger): item is Trigger {
149 return 'config' in item || 'payload' in item || 'type' in item;
150 }
151
152 function ToolItem({ item, toolkitVersion, instant }: { item: Tool | Trigger; toolkitVersion?: string | null; instant?: Tool['instant'] }) {
153 const [expanded, setExpanded] = useState(false);
154 const [copied, setCopied] = useState(false);
155 const [detailedParams, setDetailedParams] = useState<{
156 input?: Record<string, ParameterSchema>;
157 output?: Record<string, ParameterSchema>;
158 } | null>(null);
159 const [fetched, setFetched] = useState(false);
160
161 const copySlug = (e: React.MouseEvent) => {
162 e.stopPropagation();
163 navigator.clipboard.writeText(item.slug);
164 setCopied(true);
165 setTimeout(() => setCopied(false), 2000);
166 };
167
168 const tool = isTool(item) ? item : null;
169 const trigger = isTrigger(item) ? item : null;
170 const discount = instantDiscount(instant);
171
172 // Fetch detailed schema once when a tool is first expanded
173 useEffect(() => {
174 if (!expanded || !tool || fetched) return;
175 setFetched(true);
176 const versionParam = toolkitVersion ? `?version=${encodeURIComponent(toolkitVersion)}` : '';
177 fetch(`/api/tools/${item.slug}${versionParam}`)
178 .then((res) => (res.ok ? res.json() : null))
179 .then((data) => {
180 if (data) {
181 setDetailedParams({
182 input: processSchema(data.input_parameters),
183 output: processSchema(data.output_parameters),
184 });
185 }
186 })
187 .catch(() => {
188 // silently fall back to basic params
189 });
190 }, [expanded, tool, fetched, item.slug, toolkitVersion]);
191
192 const inputParams = detailedParams?.input || tool?.input_parameters;
193 const outputParams = detailedParams?.output || tool?.output_parameters;
194
195 const hasInputParams = inputParams && Object.keys(inputParams).length > 0;
196 const hasOutputParams = outputParams && Object.keys(outputParams).length > 0;
197 const hasConfig = trigger?.config && Object.keys(trigger.config).length > 0;
198 const hasPayload = trigger?.payload && Object.keys(trigger.payload).length > 0;
199
200 return (
201 <div className="border-b border-fd-border/50 last:border-0">
202 <button
203 onClick={() => setExpanded(!expanded)}
204 className="group flex w-full items-center gap-2 px-4 py-2.5 text-left transition-colors hover:bg-fd-accent/30"
205 >
206 <span className="shrink-0 text-fd-muted-foreground">
207 {expanded ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
208 </span>
209 <span className="flex min-w-0 flex-1 flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-2">
210 <span className="flex items-center gap-2">
211 <span className="truncate text-sm font-medium text-fd-foreground">{item.name}</span>
212 {instant?.supported === true && <InstantBadge />}
213 {trigger?.type && (
214 <span className={`shrink-0 rounded px-1.5 py-0.5 text-xs font-medium ${
215 trigger.type === 'webhook'
216 ? 'bg-green-500/10 text-green-600 dark:text-green-400'
217 : 'bg-blue-500/10 text-blue-600 dark:text-blue-400'
218 }`}>
219 {trigger.type}
220 </span>
221 )}
222 </span>
223 <span
224 role="button"
225 onClick={copySlug}
226 className="inline-flex w-fit shrink-0 items-center gap-1 rounded bg-fd-muted px-1.5 py-0.5 font-mono text-xs text-fd-muted-foreground transition-colors hover:text-fd-foreground"
227 >
228 <span className="max-w-[140px] truncate sm:max-w-[300px]">{item.slug}</span>
229 {copied ? <Check className="h-3 w-3 shrink-0 text-green-500" /> : <Copy className="h-3 w-3 shrink-0" />}
230 </span>
231 </span>
232 </button>
233 {expanded && (
234 <div className="space-y-4 bg-fd-muted/20 px-3 py-3 sm:px-4 sm:pl-10">
235 <p className="text-sm text-fd-muted-foreground">{item.description}</p>
236 {instant?.supported === true && (
237 <p className="text-sm text-fd-muted-foreground">Instant pricing, latest version. {instantPricingDescription(instant)}</p>
238 )}
239 {discount !== undefined && (
240 <p className="text-sm text-fd-muted-foreground">Discount: {discount}</p>
241 )}
242
243 {/* Tool parameters */}
244 {hasInputParams && (
245 <div className="space-y-2 overflow-x-auto">
246 <h4 className="text-xs font-semibold uppercase tracking-wide text-fd-muted-foreground">Input Parameters</h4>
247 <TypeTable type={paramsToTypeTable(inputParams!)} />
248 </div>
249 )}
250
251 {hasOutputParams && (
252 <div className="space-y-2 overflow-x-auto">
253 <h4 className="text-xs font-semibold uppercase tracking-wide text-fd-muted-foreground">Output</h4>
254 <TypeTable type={paramsToTypeTable(outputParams!)} />
255 </div>
256 )}
257
258 {/* Trigger config/payload */}
259 {hasConfig && (
260 <div className="space-y-2 overflow-x-auto">
261 <h4 className="text-xs font-semibold uppercase tracking-wide text-fd-muted-foreground">Configuration</h4>
262 <TypeTable type={paramsToTypeTable(trigger.config!)} />
263 </div>
264 )}
265
266 {hasPayload && (
267 <div className="space-y-2 overflow-x-auto">
268 <h4 className="text-xs font-semibold uppercase tracking-wide text-fd-muted-foreground">Payload</h4>
269 <TypeTable type={paramsToTypeTable(trigger.payload!)} />
270 </div>
271 )}
272 </div>
273 )}
274 </div>
275 );
276 }
277
278 export function ToolkitDetail({ toolkit, tools, triggers, path, faq }: ToolkitDetailProps) {
279 const instantSupported = toolkitSupportsInstant(toolkit.instant, tools);
280 const [copied, setCopied] = useState(false);
281 const [versionCopied, setVersionCopied] = useState(false);
282 const [toolSearch, setToolSearch] = useState('');
283 const [activeTab, setActiveTab] = useState<'tools' | 'triggers'>('tools');
284
285 const filteredTools = useMemo(() => {
286 const toolsArray = tools || [];
287 if (!toolSearch) return toolsArray;
288 const search = toolSearch.toLowerCase();
289 return toolsArray.filter(
290 (tool) =>
291 tool.name?.toLowerCase().includes(search) ||
292 tool.slug?.toLowerCase().includes(search)
293 );
294 }, [tools, toolSearch]);
295
296 const filteredTriggers = useMemo(() => {
297 const triggersArray = triggers || [];
298 if (!toolSearch) return triggersArray;
299 const search = toolSearch.toLowerCase();
300 return triggersArray.filter(
301 (trigger) =>
302 trigger.name?.toLowerCase().includes(search) ||
303 trigger.slug?.toLowerCase().includes(search)
304 );
305 }, [triggers, toolSearch]);
306
307 const copySlug = () => {
308 navigator.clipboard.writeText(toolkit.slug.toUpperCase());
309 setCopied(true);
310 setTimeout(() => setCopied(false), 2000);
311 };
312
313 const copyVersion = () => {
314 if (toolkit.version) {
315 navigator.clipboard.writeText(toolkit.version);
316 setVersionCopied(true);
317 setTimeout(() => setVersionCopied(false), 2000);
318 }
319 };
320
321 return (
322 <div className="space-y-5 sm:space-y-8">
323 {/* Back navigation */}
324 <Link
325 href="/toolkits"
326 className="inline-flex items-center gap-1.5 text-sm text-fd-muted-foreground transition-colors hover:text-fd-foreground"
327 >
328 <ArrowLeft className="h-4 w-4" />
329 All Toolkits
330 </Link>
331
332 {/* Header */}
333 <div className="flex flex-wrap items-start justify-between gap-4">
334 <div className="flex min-w-0 flex-1 gap-4">
335 <ToolkitIcon key={toolkit.slug} toolkit={toolkit} />
336 <div className="min-w-0 flex-1">
337 {/* Title row */}
338 <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
339 <h1 className="text-xl font-bold tracking-tight text-fd-foreground">{(toolkit.name?.trim() || toolkit.slug)}</h1>
340 {instantSupported && <InstantBadge />}
341 <button
342 onClick={copySlug}
343 className="inline-flex items-center gap-1 rounded bg-fd-muted px-1.5 py-0.5 font-mono text-xs text-fd-muted-foreground transition-colors hover:text-fd-foreground"
344 >
345 {toolkit.slug.toUpperCase()}
346 {copied ? <Check className="h-3 w-3 text-green-500" /> : <Copy className="h-3 w-3" />}
347 </button>
348 {toolkit.version && (
349 <span className="inline-flex items-center gap-1.5 text-xs text-fd-muted-foreground">
350 <span>Latest version</span>
351 <button
352 onClick={copyVersion}
353 className="inline-flex items-center gap-1 rounded bg-fd-muted px-1.5 py-0.5 font-mono text-xs text-fd-muted-foreground transition-colors hover:text-fd-foreground"
354 >
355 {toolkit.version}
356 {versionCopied ? <Check className="h-3 w-3 text-green-500" /> : <Copy className="h-3 w-3" />}
357 </button>
358 </span>
359 )}
360 </div>
361
362 {/* Description */}
363 <p className="mt-1.5 text-sm text-fd-muted-foreground">
364 {descriptionLinks(toolkit.description).map((part, index) => part.href ? (
365 <a key={index} href={part.href} className="underline hover:text-fd-foreground">{part.text}</a>
366 ) : part.text)}
367 </p>
368 {instantSupported && (
369 <p className="mt-1.5 text-sm text-fd-muted-foreground">
370 <Link href="/docs/instant-tools" className="underline">Instant</Link> is available on the latest version. Check each tool for support and pricing.
371 </p>
372 )}
373 </div>
374 </div>
375
376 {/* Page actions */}
377 <PageActions path={path} variant="inline" />
378 </div>
379
380 {/* Authentication Details */}
381 {toolkit.authConfigDetails && toolkit.authConfigDetails.length > 0 && (
382 <AuthDetailsSection authConfigDetails={toolkit.authConfigDetails} authSchemes={toolkit.authSchemes} composioManagedAuthSchemes={toolkit.composioManagedAuthSchemes} />
383 )}
384
385 {/* FAQ */}
386 {faq && faq.length > 0 && <FaqSection faq={faq} />}
387
388 {/* Tools & Triggers */}
389 {(tools.length > 0 || triggers.length > 0) && (
390 <div className="space-y-4">
391 {/* Tabs */}
392 <div className="flex items-center gap-6 border-b border-fd-border">
393 <button
394 onClick={() => setActiveTab('tools')}
395 className={`relative pb-2.5 text-sm font-medium transition-colors ${
396 activeTab === 'tools'
397 ? 'text-fd-foreground'
398 : 'text-fd-muted-foreground hover:text-fd-foreground'
399 }`}
400 >
401 Tools ({tools.length})
402 {activeTab === 'tools' && (
403 <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-500" />
404 )}
405 </button>
406 {triggers.length > 0 && (
407 <button
408 onClick={() => setActiveTab('triggers')}
409 className={`relative pb-2.5 text-sm font-medium transition-colors ${
410 activeTab === 'triggers'
411 ? 'text-fd-foreground'
412 : 'text-fd-muted-foreground hover:text-fd-foreground'
413 }`}
414 >
415 Triggers ({triggers.length})
416 {activeTab === 'triggers' && (
417 <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-500" />
418 )}
419 </button>
420 )}
421 </div>
422
423 {/* Search */}
424 <div className="relative">
425 <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-fd-muted-foreground" aria-hidden="true" />
426 <input
427 type="text"
428 name="tool-search"
429 aria-label={`Search ${activeTab}`}
430 placeholder={`Search ${activeTab}…`}
431 autoComplete="off"
432 value={toolSearch}
433 onChange={(e) => setToolSearch(e.target.value)}
434 className="h-9 w-full rounded-md border border-fd-border bg-fd-background pl-9 pr-4 text-sm text-fd-foreground placeholder:text-fd-muted-foreground focus:outline-none focus-visible:border-blue-500/50 focus-visible:ring-2 focus-visible:ring-blue-500/20"
435 />
436 </div>
437
438 {/* List */}
439 <div className="overflow-hidden rounded-md border border-fd-border">
440 {activeTab === 'tools' && (
441 filteredTools.length > 0 ? (
442 filteredTools.map((tool) => (
443 <ToolItem key={tool.slug} item={tool} toolkitVersion="latest" instant={tool.instant} />
444 ))
445 ) : (
446 <p className="px-4 py-8 text-center text-sm text-fd-muted-foreground">
447 No tools found
448 </p>
449 )
450 )}
451 {activeTab === 'triggers' && (
452 filteredTriggers.length > 0 ? (
453 filteredTriggers.map((trigger) => (
454 <ToolItem key={trigger.slug} item={trigger} toolkitVersion={toolkit.version} />
455 ))
456 ) : (
457 <p className="px-4 py-8 text-center text-sm text-fd-muted-foreground">
458 No triggers found
459 </p>
460 )
461 )}
462 </div>
463 </div>
464 )}
465 <EditOnGitHub path="docs/components/toolkits/toolkit-detail.tsx" />
466 </div>
467 );
468 }