A terminal component from Aceternity UI.
From Aceternity UI
1"use client";
2import React, { useEffect, useMemo, useRef, useState } from "react";
3import { cn } from "@/lib/utils";
4
5const KEY_SOUNDS_DOWN: Record<string, [number, number]> = {
6 A: [31542, 85],
7 B: [40621, 107],
8 C: [39632, 95],
9 D: [32492, 85],
10 E: [23317, 83],
11 F: [32973, 87],
12 G: [33453, 94],
13 H: [33986, 93],
14 I: [25795, 91],
15 J: [34425, 88],
16 K: [34932, 90],
17 L: [35410, 95],
18 M: [41610, 93],
19 N: [41103, 90],
20 O: [26309, 84],
21 P: [26804, 83],
22 Q: [22245, 95],
23 R: [23817, 92],
24 S: [32031, 88],
25 T: [24297, 92],
26 U: [25313, 95],
27 V: [40136, 94],
28 W: [22790, 89],
29 X: [39148, 76],
30 Y: [24811, 93],
31 Z: [38694, 80],
32 " ": [51541, 144],
33 "-": [42594, 90],
34 "@": [23317, 83],
35 "/": [42594, 90],
36 ".": [42594, 90],
37 ":": [42594, 90],
38 "0": [26309, 84],
39 "1": [25313, 95],
40 "2": [23317, 83],
41 "3": [23817, 92],
42 "4": [24297, 92],
43 "5": [24811, 93],
44 "6": [25313, 95],
45 "7": [25795, 91],
46 "8": [26309, 84],
47 "9": [26804, 83],
48 Enter: [19065, 110],
49};
50
51const KEY_SOUNDS_UP: Record<string, [number, number]> = {
52 A: [31632, 80],
53 B: [40736, 95],
54 C: [39732, 85],
55 D: [32577, 80],
56 E: [23402, 80],
57 F: [33063, 80],
58 G: [33553, 85],
59 H: [34081, 85],
60 I: [25890, 85],
61 J: [34515, 85],
62 K: [35027, 85],
63 L: [35510, 85],
64 M: [41710, 85],
65 N: [41198, 85],
66 O: [26394, 80],
67 P: [26889, 80],
68 Q: [22345, 85],
69 R: [23912, 85],
70 S: [32121, 80],
71 T: [24392, 85],
72 U: [25413, 85],
73 V: [40236, 85],
74 W: [22880, 85],
75 X: [39228, 70],
76 Y: [24911, 85],
77 Z: [38779, 75],
78 " ": [51691, 130],
79 "-": [42689, 85],
80 "@": [23402, 80],
81 "/": [42689, 85],
82 ".": [42689, 85],
83 ":": [42689, 85],
84 "0": [26394, 80],
85 "1": [25413, 85],
86 "2": [23402, 80],
87 "3": [23912, 85],
88 "4": [24392, 85],
89 "5": [24911, 85],
90 "6": [25413, 85],
91 "7": [25890, 85],
92 "8": [26394, 80],
93 "9": [26889, 80],
94 Enter: [19180, 100],
95};
96
97function useAudio(enabled: boolean) {
98 const ctxRef = useRef<AudioContext | null>(null);
99 const bufferRef = useRef<AudioBuffer | null>(null);
100 const readyRef = useRef(false);
101
102 useEffect(() => {
103 if (!enabled) return;
104 const init = async () => {
105 try {
106 ctxRef.current = new AudioContext();
107 const res = await fetch("/sounds/sound.ogg");
108 if (!res.ok) return;
109 bufferRef.current = await ctxRef.current.decodeAudioData(
110 await res.arrayBuffer(),
111 );
112 readyRef.current = true;
113 } catch {}
114 };
115 init();
116 return () => {
117 ctxRef.current?.close();
118 };
119 }, [enabled]);
120
121 const playSound = (sound: [number, number] | undefined) => {
122 if (!readyRef.current || !ctxRef.current || !bufferRef.current || !sound)
123 return;
124 if (ctxRef.current.state === "suspended") ctxRef.current.resume();
125 const src = ctxRef.current.createBufferSource();
126 src.buffer = bufferRef.current;
127 src.connect(ctxRef.current.destination);
128 src.start(0, sound[0] / 1000, sound[1] / 1000);
129 };
130
131 const down = (key: string) =>
132 playSound(KEY_SOUNDS_DOWN[key.toUpperCase()] || KEY_SOUNDS_DOWN[key]);
133 const up = (key: string) =>
134 playSound(KEY_SOUNDS_UP[key.toUpperCase()] || KEY_SOUNDS_UP[key]);
135
136 return { down, up };
137}
138
139function useInView(ref: React.RefObject<HTMLElement | null>, once = true) {
140 const [inView, setInView] = useState(false);
141 const triggered = useRef(false);
142
143 useEffect(() => {
144 const el = ref.current;
145 if (!el || (once && triggered.current)) return;
146
147 const observer = new IntersectionObserver(
148 ([entry]) => {
149 if (entry.isIntersecting && !triggered.current) {
150 setInView(true);
151 if (once) {
152 triggered.current = true;
153 observer.disconnect();
154 }
155 }
156 },
157 { threshold: 0.1 },
158 );
159 observer.observe(el);
160 return () => observer.disconnect();
161 }, [ref, once]);
162
163 return inView;
164}
165
166type TokenType =
167 | "command"
168 | "flag"
169 | "string"
170 | "number"
171 | "operator"
172 | "path"
173 | "variable"
174 | "comment"
175 | "default";
176
177interface Token {
178 type: TokenType;
179 value: string;
180}
181
182function tokenizeBash(text: string): Token[] {
183 const tokens: Token[] = [];
184 const words = text.split(/(\s+)/);
185
186 let isFirstWord = true;
187
188 for (const word of words) {
189 if (/^\s+$/.test(word)) {
190 tokens.push({ type: "default", value: word });
191 continue;
192 }
193
194 if (word.startsWith("#")) {
195 tokens.push({ type: "comment", value: word });
196 continue;
197 }
198
199 if (word.startsWith("$")) {
200 tokens.push({ type: "variable", value: word });
201 isFirstWord = false;
202 continue;
203 }
204
205 if (word.startsWith("--") || word.startsWith("-")) {
206 tokens.push({ type: "flag", value: word });
207 isFirstWord = false;
208 continue;
209 }
210
211 if (/^["'].*["']$/.test(word)) {
212 tokens.push({ type: "string", value: word });
213 isFirstWord = false;
214 continue;
215 }
216
217 if (/^\d+$/.test(word)) {
218 tokens.push({ type: "number", value: word });
219 isFirstWord = false;
220 continue;
221 }
222
223 if (/^[|>&<]+$/.test(word)) {
224 tokens.push({ type: "operator", value: word });
225 isFirstWord = true;
226 continue;
227 }
228
229 if (word.includes("/") || word.startsWith(".") || word.startsWith("~")) {
230 tokens.push({ type: "path", value: word });
231 isFirstWord = false;
232 continue;
233 }
234
235 if (isFirstWord) {
236 tokens.push({ type: "command", value: word });
237 isFirstWord = false;
238 continue;
239 }
240
241 tokens.push({ type: "default", value: word });
242 }
243
244 return tokens;
245}
246
247const tokenColors: Record<TokenType, string> = {
248 command: "text-emerald-400",
249 flag: "text-sky-400",
250 string: "text-amber-300",
251 number: "text-purple-400",
252 operator: "text-red-400",
253 path: "text-cyan-300",
254 variable: "text-pink-400",
255 comment: "text-neutral-500",
256 default: "text-neutral-300",
257};
258
259function SyntaxHighlightedText({ text }: { text: string }) {
260 const tokens = tokenizeBash(text);
261
262 return (
263 <>
264 {tokens.map((token, i) => (
265 <span key={i} className={tokenColors[token.type]}>
266 {token.value}
267 </span>
268 ))}
269 </>
270 );
271}
272
273interface TerminalLine {
274 type: "command" | "output";
275 content: string;
276}
277
278export interface TerminalProps {
279 commands: string[];
280 outputs?: Record<number, string[]>;
281 username?: string;
282 className?: string;
283 typingSpeed?: number;
284 delayBetweenCommands?: number;
285 initialDelay?: number;
286 enableSound?: boolean;
287}
288
289export function Terminal({
290 commands = ["npx shadcn@latest init"],
291 outputs = {},
292 username = "Manus-Macbook",
293 className,
294 typingSpeed = 50,
295 delayBetweenCommands = 800,
296 initialDelay = 500,
297 enableSound = true,
298}: TerminalProps) {
299 const containerRef = useRef<HTMLDivElement>(null);
300 const contentRef = useRef<HTMLDivElement>(null);
301 const inView = useInView(containerRef);
302 const { down, up } = useAudio(enableSound);
303
304 const [lines, setLines] = useState<TerminalLine[]>([]);
305 const [currentText, setCurrentText] = useState("");
306 const [commandIdx, setCommandIdx] = useState(0);
307 const [charIdx, setCharIdx] = useState(0);
308 const [outputIdx, setOutputIdx] = useState(-1);
309 const [phase, setPhase] = useState<
310 "idle" | "typing" | "executing" | "outputting" | "pausing" | "done"
311 >("idle");
312 const [cursorVisible, setCursorVisible] = useState(true);
313
314 const currentCommand = commands[commandIdx] || "";
315 const currentOutputs = useMemo(
316 () => outputs[commandIdx] || [],
317 [outputs, commandIdx],
318 );
319 const isLastCommand = commandIdx === commands.length - 1;
320
321 useEffect(() => {
322 if (!inView || phase !== "idle") return;
323 const t = setTimeout(() => setPhase("typing"), initialDelay);
324 return () => clearTimeout(t);
325 }, [inView, phase, initialDelay]);
326
327 useEffect(() => {
328 if (phase !== "typing") return;
329
330 if (charIdx < currentCommand.length) {
331 const char = currentCommand[charIdx];
332 down(char);
333 const t = setTimeout(
334 () => {
335 up(char);
336 setCurrentText(currentCommand.slice(0, charIdx + 1));
337 setCharIdx((c) => c + 1);
338 },
339 typingSpeed + Math.random() * 30,
340 );
341 return () => clearTimeout(t);
342 } else {
343 down("Enter");
344 const t = setTimeout(() => {
345 up("Enter");
346 setPhase("executing");
347 }, 80);
348 return () => clearTimeout(t);
349 }
350 }, [phase, charIdx, currentCommand, typingSpeed, down, up]);
351
352 useEffect(() => {
353 if (phase !== "executing") return;
354
355 setLines((prev) => [...prev, { type: "command", content: currentCommand }]);
356 setCurrentText("");
357
358 if (currentOutputs.length > 0) {
359 setOutputIdx(0);
360 setPhase("outputting");
361 } else if (isLastCommand) {
362 setPhase("done");
363 } else {
364 setPhase("pausing");
365 }
366 }, [phase, currentCommand, currentOutputs.length, isLastCommand]);
367
368 useEffect(() => {
369 if (phase !== "outputting") return;
370
371 if (outputIdx >= 0 && outputIdx < currentOutputs.length) {
372 const t = setTimeout(() => {
373 setLines((prev) => [
374 ...prev,
375 { type: "output", content: currentOutputs[outputIdx] },
376 ]);
377 setOutputIdx((i) => i + 1);
378 }, 150);
379 return () => clearTimeout(t);
380 } else if (outputIdx >= currentOutputs.length) {
381 const t = setTimeout(() => {
382 if (isLastCommand) {
383 setPhase("done");
384 } else {
385 setPhase("pausing");
386 }
387 }, 300);
388 return () => clearTimeout(t);
389 }
390 }, [phase, outputIdx, currentOutputs, isLastCommand]);
391
392 useEffect(() => {
393 if (phase !== "pausing") return;
394 const t = setTimeout(() => {
395 setCharIdx(0);
396 setOutputIdx(-1);
397 setCommandIdx((c) => c + 1);
398 setPhase("typing");
399 }, delayBetweenCommands);
400 return () => clearTimeout(t);
401 }, [phase, delayBetweenCommands]);
402
403 useEffect(() => {
404 const interval = setInterval(() => setCursorVisible((v) => !v), 530);
405 return () => clearInterval(interval);
406 }, []);
407
408 useEffect(() => {
409 if (contentRef.current) {
410 contentRef.current.scrollTop = contentRef.current.scrollHeight;
411 }
412 }, [lines, phase]);
413
414 const prompt = (
415 <span className="text-neutral-500">
416 <span className="text-sky-500">{username}</span>
417 <span className="text-emerald-600">:</span>
418 <span className="text-sky-400">~</span>
419 <span className="text-neutral-500">$</span>{" "}
420 </span>
421 );
422
423 return (
424 <div
425 ref={containerRef}
426 className={cn(
427 "mx-auto w-full max-w-xl px-4 font-mono text-xs",
428 className,
429 )}
430 >
431 <div className="overflow-hidden rounded-lg border border-neutral-800 bg-neutral-900 shadow-2xl">
432 {/* Title Bar */}
433 <div className="flex items-center gap-2 bg-neutral-800 px-4 py-3">
434 <div className="flex items-center gap-1.5">
435 <div className="h-3 w-3 rounded-full bg-red-500 transition-colors hover:bg-red-600" />
436 <div className="h-3 w-3 rounded-full bg-yellow-500 transition-colors hover:bg-yellow-600" />
437 <div className="h-3 w-3 rounded-full bg-green-500 transition-colors hover:bg-green-600" />
438 </div>
439 <div className="flex-1 text-center">
440 <span className="truncate text-xs text-neutral-400">
441 {username} — bash
442 </span>
443 </div>
444 <div className="w-[52px]" />
445 </div>
446
447 {/* Terminal Content */}
448 <div
449 ref={contentRef}
450 className="no-visible-scrollbar h-80 overflow-y-auto p-4 font-mono"
451 >
452 {lines.map((line, i) => (
453 <div key={i} className="leading-relaxed whitespace-pre-wrap">
454 {line.type === "command" ? (
455 <span>
456 {prompt}
457 <SyntaxHighlightedText text={line.content} />
458 </span>
459 ) : (
460 <span className="text-neutral-400">{line.content}</span>
461 )}
462 </div>
463 ))}
464
465 {phase === "typing" && (
466 <div className="leading-relaxed whitespace-pre-wrap">
467 {prompt}
468 <SyntaxHighlightedText text={currentText} />
469 <span className="ml-0.5 inline-block h-4 w-2 bg-neutral-300 align-middle" />
470 </div>
471 )}
472
473 {(phase === "done" ||
474 phase === "pausing" ||
475 phase === "outputting") && (
476 <div className="leading-relaxed whitespace-pre-wrap">
477 {prompt}
478 <span
479 className={cn(
480 "inline-block h-4 w-2 bg-neutral-300 align-middle transition-opacity duration-100",
481 !cursorVisible && "opacity-0",
482 )}
483 />
484 </div>
485 )}
486 </div>
487 </div>
488 </div>
489 );
490}
491