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