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

next
tsx 179 lines 6.66 KB
Raw
1 'use client';
2
3 import { useEffect, useRef, useState } from 'react';
4 import { createPortal } from 'react-dom';
5 import { Check, Clipboard } from 'lucide-react';
6 import { CodeBlock, Pre } from 'fumadocs-ui/components/codeblock';
7 import { cn } from '@/lib/utils';
8
9 import { PACKAGE_MANAGERS } from '@/lib/package-install';
10
11 type Ecosystem = keyof typeof PACKAGE_MANAGERS;
12
13 /**
14 * Install-command code block whose copy button is a package-manager picker.
15 *
16 * Renders the first manager's command by default (`npm install …` for node,
17 * `uv add …` for python). The copy button opens a menu of managers; selecting
18 * one rewrites the displayed command for that manager and copies it. Comment
19 * lines are display-only and never copied.
20 *
21 * The menu is portaled to `document.body`: ancestors (fumadocs `Tabs`, the
22 * `CodeBlock` figure) clip overflow, and the actions container's
23 * `backdrop-blur` would make it the containing block for `position: fixed`.
24 */
25 export function PackageInstall({
26 packages,
27 comment,
28 ecosystem = 'node',
29 }: {
30 /** Space-separated package names, e.g. "@composio/core @openai/agents" */
31 packages: string;
32 /** Display-only `#` comment line(s) shown below the command; excluded from copy */
33 comment?: string | string[];
34 /** Which package managers to offer; defaults to node (npm/pnpm/bun/yarn) */
35 ecosystem?: Ecosystem;
36 }) {
37 const managers = PACKAGE_MANAGERS[ecosystem];
38 const [manager, setManager] = useState<string>(managers[0].id);
39 const [open, setOpen] = useState(false);
40 const [position, setPosition] = useState<{ top: number; left: number } | null>(null);
41 const [copied, setCopied] = useState(false);
42 const triggerRef = useRef<HTMLButtonElement>(null);
43 const menuRef = useRef<HTMLDivElement>(null);
44 const anchorRect = useRef<DOMRect | null>(null);
45 const resetTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
46
47 const toggle = () => {
48 if (open) {
49 setOpen(false);
50 return;
51 }
52 const rect = triggerRef.current?.getBoundingClientRect();
53 if (!rect) return;
54 anchorRect.current = rect;
55 // Page coordinates; the menu is right-aligned to the trigger via -translate-x-full.
56 setPosition({ top: rect.bottom + window.scrollY + 4, left: rect.right + window.scrollX });
57 setOpen(true);
58 };
59
60 useEffect(() => {
61 if (!open) return;
62 const onPointerDown = (event: PointerEvent) => {
63 const target = event.target as Node;
64 if (!triggerRef.current?.contains(target) && !menuRef.current?.contains(target)) {
65 setOpen(false);
66 }
67 };
68 const onKeyDown = (event: KeyboardEvent) => {
69 if (event.key === 'Escape') setOpen(false);
70 };
71 // Close only when the trigger actually moved in the viewport (the menu is
72 // positioned in page coordinates); ignore spurious scroll events.
73 const onScrollOrResize = () => {
74 const rect = triggerRef.current?.getBoundingClientRect();
75 const anchor = anchorRect.current;
76 if (!rect || !anchor) return setOpen(false);
77 if (Math.abs(rect.top - anchor.top) > 1 || Math.abs(rect.left - anchor.left) > 1) {
78 setOpen(false);
79 }
80 };
81 document.addEventListener('pointerdown', onPointerDown);
82 document.addEventListener('keydown', onKeyDown);
83 window.addEventListener('scroll', onScrollOrResize, true);
84 window.addEventListener('resize', onScrollOrResize);
85 return () => {
86 document.removeEventListener('pointerdown', onPointerDown);
87 document.removeEventListener('keydown', onKeyDown);
88 window.removeEventListener('scroll', onScrollOrResize, true);
89 window.removeEventListener('resize', onScrollOrResize);
90 };
91 }, [open]);
92
93 useEffect(() => () => clearTimeout(resetTimer.current), []);
94
95 const commandFor = (id: string) =>
96 `${managers.find((m) => m.id === id)?.install ?? managers[0].install} ${packages}`;
97
98 const select = async (id: string) => {
99 setManager(id);
100 setOpen(false);
101 try {
102 await navigator.clipboard.writeText(commandFor(id));
103 setCopied(true);
104 clearTimeout(resetTimer.current);
105 resetTimer.current = setTimeout(() => setCopied(false), 1600);
106 } catch {
107 // clipboard unavailable (e.g. insecure context); selection still applies
108 }
109 };
110
111 const comments = comment == null ? [] : Array.isArray(comment) ? comment : [comment];
112
113 return (
114 <CodeBlock
115 allowCopy={false}
116 Actions={({ className }) => (
117 <div className={className}>
118 <button
119 ref={triggerRef}
120 type="button"
121 aria-haspopup="menu"
122 aria-expanded={open}
123 aria-label={copied ? 'Copied install command' : 'Copy install command'}
124 data-checked={copied || undefined}
125 className="inline-flex items-center justify-center rounded-lg p-1.5 transition-colors hover:text-fd-accent-foreground data-checked:text-fd-accent-foreground [&_svg]:size-3.5"
126 onClick={toggle}
127 >
128 {copied ? <Check /> : <Clipboard />}
129 </button>
130 {open &&
131 position &&
132 createPortal(
133 <div
134 ref={menuRef}
135 role="menu"
136 style={{ top: position.top, left: position.left }}
137 className="absolute z-50 min-w-24 -translate-x-full rounded-lg border bg-fd-popover p-1 text-sm shadow-md"
138 >
139 {managers.map((m) => (
140 <button
141 key={m.id}
142 type="button"
143 role="menuitemradio"
144 aria-checked={manager === m.id}
145 className={cn(
146 'flex w-full items-center rounded-md px-3 py-1.5 text-fd-popover-foreground transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground',
147 manager === m.id && 'font-medium text-fd-primary',
148 )}
149 onClick={() => void select(m.id)}
150 >
151 {m.id}
152 </button>
153 ))}
154 </div>,
155 document.body,
156 )}
157 </div>
158 )}
159 >
160 {/* No horizontal padding here: `.line` spans already carry it via shiki.css */}
161 <Pre>
162 <code>
163 <span className="line">{commandFor(manager)}</span>
164 {comments.map((line) => (
165 <span
166 key={line}
167 className="line"
168 // Inline style: fumadocs' `.shiki code span { color: var(--shiki-light) }`
169 // out-specifies Tailwind utilities, so `text-fd-muted-foreground` loses.
170 style={{ color: 'var(--color-fd-muted-foreground)' }}
171 >
172 {`# ${line}`}
173 </span>
174 ))}
175 </code>
176 </Pre>
177 </CodeBlock>
178 );
179 }