Skip to content

UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.

feat: added auto sequence and useInView in terminal (#740)

Arghya Das7f936c9ed8c1
diff --git a/content/docs/components/terminal.mdx b/content/docs/components/terminal.mdx
index e51642b6..ee16ba3e 100644
--- a/content/docs/components/terminal.mdx
+++ b/content/docs/components/terminal.mdx
@@ -50,36 +50,62 @@ import {
```tsx
<Terminal>
- <TypingAnimation>
- <AnimatedSpan>Hello, world!</AnimatedSpan>
- <TypingAnimation>MagicUI is awesome!</TypingAnimation>
+ <TypingAnimation>&gt; pnpm dlx shadcn@latest init</TypingAnimation>
+
+ <AnimatedSpan className="text-green-500">✔ Preflight checks.</AnimatedSpan>
+
+ <AnimatedSpan className="text-green-500">
+ ✔ Validating Tailwind CSS.
+ </AnimatedSpan>
+
+ <TypingAnimation className="text-muted-foreground">
+ Success! Project initialization completed.
</TypingAnimation>
</Terminal>
```
+The terminal sequences its children automatically. Each `TypingAnimation` or `AnimatedSpan` starts when the previous finishes. Manual `delay` props are optional and typically unnecessary.
+
## Props
### Terminal
-| Prop | Type | Default | Description |
-| ----------- | ----------- | ------- | ---------------------------------------- |
-| `children` | `ReactNode` | `-` | Content to be typed out in the terminal. |
-| `className` | `string` | `-` | Custom CSS class for styling. |
+| Prop | Type | Default | Description |
+| ------------- | ----------- | ------- | -------------------------------------------------------------- |
+| `children` | `ReactNode` | `-` | Terminal content: a list of `TypingAnimation`/`AnimatedSpan`. |
+| `className` | `string` | `-` | Custom CSS class for styling. |
+| `sequence` | `boolean` | `true` | Enable auto sequencing so each line starts after the previous. |
+| `startOnView` | `boolean` | `true` | Start sequencing when the terminal enters the viewport. |
### AnimatedSpan
-| Prop | Type | Default | Description |
-| ----------- | ----------- | ------- | -------------------------------------------------- |
-| `children` | `ReactNode` | `-` | Content to be animated. |
-| `delay` | `number` | `0` | Delay in milliseconds before the animation starts. |
-| `className` | `string` | `-` | Custom CSS class for styling. |
+| Prop | Type | Default | Description |
+| ------------- | ----------- | ------- | --------------------------------------------------------------------------- |
+| `children` | `ReactNode` | `-` | Content to be faded in. |
+| `className` | `string` | `-` | Custom CSS class for styling. |
+| `delay` | `number` | `0` | Delay in ms before animation starts (used when `sequence` is `false`). |
+| `startOnView` | `boolean` | `false` | If `true`, waits for viewport visibility before animating when unsequenced. |
### TypingAnimation
-| Prop | Type | Default | Description |
-| ----------- | ------------------- | -------- | -------------------------------------------------- |
-| `children` | `ReactNode` | `-` | Content to be animated. |
-| `delay` | `number` | `0` | Delay in milliseconds before the animation starts. |
-| `className` | `string` | `-` | Custom CSS class for styling. |
-| `duration` | `number` | `100` | Duration in milliseconds for each character typed. |
-| `as` | `React.ElementType` | `"span"` | The component type to render. |
+| Prop | Type | Default | Description |
+| ------------- | ------------------- | -------- | ------------------------------------------------------------------------ |
+| `children` | `string` | `-` | Text to be typed. |
+| `className` | `string` | `-` | Custom CSS class for styling. |
+| `duration` | `number` | `60` | Milliseconds per character. |
+| `delay` | `number` | `0` | Delay in ms before typing starts (used when `sequence` is `false`). |
+| `as` | `React.ElementType` | `"span"` | The component type to render. |
+| `startOnView` | `boolean` | `true` | If `true`, waits for viewport visibility before typing when unsequenced. |
+
+```tsx
+// Start immediately (ignore viewport)
+<Terminal startOnView={false}>
+ <TypingAnimation>Immediate start</TypingAnimation>
+</Terminal>
+
+// Opt out of sequencing and use manual delays
+<Terminal sequence={false}>
+ <TypingAnimation delay={500}>First</TypingAnimation>
+ <AnimatedSpan delay={1500}>Second</AnimatedSpan>
+</Terminal>
+```
diff --git a/public/r/terminal-demo.json b/public/r/terminal-demo.json
index dc5b1fd7..6f033a5b 100644
--- a/public/r/terminal-demo.json
+++ b/public/r/terminal-demo.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/example/terminal-demo.tsx",
- "content": "import {\n AnimatedSpan,\n Terminal,\n TypingAnimation,\n} from \"@/registry/magicui/terminal\";\n\nexport default function TerminalDemo() {\n return (\n <Terminal>\n <TypingAnimation>&gt; pnpm dlx shadcn@latest init</TypingAnimation>\n\n <AnimatedSpan delay={1500} className=\"text-green-500\">\n <span>✔ Preflight checks.</span>\n </AnimatedSpan>\n\n <AnimatedSpan delay={2000} className=\"text-green-500\">\n <span>✔ Verifying framework. Found Next.js.</span>\n </AnimatedSpan>\n\n <AnimatedSpan delay={2500} className=\"text-green-500\">\n <span>✔ Validating Tailwind CSS.</span>\n </AnimatedSpan>\n\n <AnimatedSpan delay={3000} className=\"text-green-500\">\n <span>✔ Validating import alias.</span>\n </AnimatedSpan>\n\n <AnimatedSpan delay={3500} className=\"text-green-500\">\n <span>✔ Writing components.json.</span>\n </AnimatedSpan>\n\n <AnimatedSpan delay={4000} className=\"text-green-500\">\n <span>✔ Checking registry.</span>\n </AnimatedSpan>\n\n <AnimatedSpan delay={4500} className=\"text-green-500\">\n <span>✔ Updating tailwind.config.ts</span>\n </AnimatedSpan>\n\n <AnimatedSpan delay={5000} className=\"text-green-500\">\n <span>✔ Updating app/globals.css</span>\n </AnimatedSpan>\n\n <AnimatedSpan delay={5500} className=\"text-green-500\">\n <span>✔ Installing dependencies.</span>\n </AnimatedSpan>\n\n <AnimatedSpan delay={6000} className=\"text-blue-500\">\n <span>ℹ Updated 1 file:</span>\n <span className=\"pl-2\">- lib/utils.ts</span>\n </AnimatedSpan>\n\n <TypingAnimation delay={6500} className=\"text-muted-foreground\">\n Success! Project initialization completed.\n </TypingAnimation>\n\n <TypingAnimation delay={7000} className=\"text-muted-foreground\">\n You may now add components.\n </TypingAnimation>\n </Terminal>\n );\n}\n",
+ "content": "import {\n AnimatedSpan,\n Terminal,\n TypingAnimation,\n} from \"@/registry/magicui/terminal\";\n\nexport default function TerminalDemo() {\n return (\n <div className=\"w-full h-[200vh] overflow-auto flex items-center justify-center\">\n <Terminal>\n <TypingAnimation>&gt; pnpm dlx shadcn@latest init</TypingAnimation>\n\n <AnimatedSpan className=\"text-green-500\">\n <span>✔ Preflight checks.</span>\n </AnimatedSpan>\n\n <AnimatedSpan className=\"text-green-500\">\n <span>✔ Verifying framework. Found Next.js.</span>\n </AnimatedSpan>\n\n <AnimatedSpan className=\"text-green-500\">\n <span>✔ Validating Tailwind CSS.</span>\n </AnimatedSpan>\n\n <AnimatedSpan className=\"text-green-500\">\n <span>✔ Validating import alias.</span>\n </AnimatedSpan>\n\n <AnimatedSpan className=\"text-green-500\">\n <span>✔ Writing components.json.</span>\n </AnimatedSpan>\n\n <AnimatedSpan className=\"text-green-500\">\n <span>✔ Checking registry.</span>\n </AnimatedSpan>\n\n <AnimatedSpan className=\"text-green-500\">\n <span>✔ Updating tailwind.config.ts</span>\n </AnimatedSpan>\n\n <AnimatedSpan className=\"text-green-500\">\n <span>✔ Updating app/globals.css</span>\n </AnimatedSpan>\n\n <AnimatedSpan className=\"text-green-500\">\n <span>✔ Installing dependencies.</span>\n </AnimatedSpan>\n\n <AnimatedSpan className=\"text-blue-500\">\n <span>ℹ Updated 1 file:</span>\n <span className=\"pl-2\">- lib/utils.ts</span>\n </AnimatedSpan>\n\n <TypingAnimation className=\"text-muted-foreground\">\n Success! Project initialization completed.\n </TypingAnimation>\n\n <TypingAnimation className=\"text-muted-foreground\">\n You may now add components.\n </TypingAnimation>\n </Terminal>\n </div>\n );\n}\n",
"type": "registry:example",
"target": "components/terminal-demo.tsx"
}
diff --git a/public/r/terminal.json b/public/r/terminal.json
index 9ceccc96..9ae9c185 100644
--- a/public/r/terminal.json
+++ b/public/r/terminal.json
@@ -7,7 +7,7 @@
"files": [
{
"path": "registry/magicui/terminal.tsx",
- "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport { motion, MotionProps } from \"motion/react\";\nimport { useEffect, useRef, useState } from \"react\";\n\ninterface AnimatedSpanProps extends MotionProps {\n children: React.ReactNode;\n delay?: number;\n className?: string;\n}\n\nexport const AnimatedSpan = ({\n children,\n delay = 0,\n className,\n ...props\n}: AnimatedSpanProps) => (\n <motion.div\n initial={{ opacity: 0, y: -5 }}\n animate={{ opacity: 1, y: 0 }}\n transition={{ duration: 0.3, delay: delay / 1000 }}\n className={cn(\"grid text-sm font-normal tracking-tight\", className)}\n {...props}\n >\n {children}\n </motion.div>\n);\n\ninterface TypingAnimationProps extends MotionProps {\n children: string;\n className?: string;\n duration?: number;\n delay?: number;\n as?: React.ElementType;\n}\n\nexport const TypingAnimation = ({\n children,\n className,\n duration = 60,\n delay = 0,\n as: Component = \"span\",\n ...props\n}: TypingAnimationProps) => {\n if (typeof children !== \"string\") {\n throw new Error(\"TypingAnimation: children must be a string. Received:\");\n }\n\n const MotionComponent = motion.create(Component, {\n forwardMotionProps: true,\n });\n\n const [displayedText, setDisplayedText] = useState<string>(\"\");\n const [started, setStarted] = useState(false);\n const elementRef = useRef<HTMLElement | null>(null);\n\n useEffect(() => {\n const startTimeout = setTimeout(() => {\n setStarted(true);\n }, delay);\n return () => clearTimeout(startTimeout);\n }, [delay]);\n\n useEffect(() => {\n if (!started) return;\n\n let i = 0;\n const typingEffect = setInterval(() => {\n if (i < children.length) {\n setDisplayedText(children.substring(0, i + 1));\n i++;\n } else {\n clearInterval(typingEffect);\n }\n }, duration);\n\n return () => {\n clearInterval(typingEffect);\n };\n }, [children, duration, started]);\n\n return (\n <MotionComponent\n ref={elementRef}\n className={cn(\"text-sm font-normal tracking-tight\", className)}\n {...props}\n >\n {displayedText}\n </MotionComponent>\n );\n};\n\ninterface TerminalProps {\n children: React.ReactNode;\n className?: string;\n}\n\nexport const Terminal = ({ children, className }: TerminalProps) => {\n return (\n <div\n className={cn(\n \"z-0 h-full max-h-[400px] w-full max-w-lg rounded-xl border border-border bg-background\",\n className,\n )}\n >\n <div className=\"flex flex-col gap-y-2 border-b border-border p-4\">\n <div className=\"flex flex-row gap-x-2\">\n <div className=\"h-2 w-2 rounded-full bg-red-500\"></div>\n <div className=\"h-2 w-2 rounded-full bg-yellow-500\"></div>\n <div className=\"h-2 w-2 rounded-full bg-green-500\"></div>\n </div>\n </div>\n <pre className=\"p-4\">\n <code className=\"grid gap-y-1 overflow-auto\">{children}</code>\n </pre>\n </div>\n );\n};\n",
+ "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport { motion, MotionProps, useInView } from \"motion/react\";\nimport {\n Children,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\n\ninterface SequenceContextValue {\n completeItem: (index: number) => void;\n activeIndex: number;\n sequenceStarted: boolean;\n}\n\nconst SequenceContext = createContext<SequenceContextValue | null>(null);\n\nconst useSequence = () => useContext(SequenceContext);\n\nconst ItemIndexContext = createContext<number | null>(null);\nconst useItemIndex = () => useContext(ItemIndexContext);\n\ninterface AnimatedSpanProps extends MotionProps {\n children: React.ReactNode;\n delay?: number;\n className?: string;\n startOnView?: boolean;\n}\n\nexport const AnimatedSpan = ({\n children,\n delay = 0,\n className,\n startOnView = false,\n ...props\n}: AnimatedSpanProps) => {\n const elementRef = useRef<HTMLDivElement | null>(null);\n const isInView = useInView(elementRef as React.RefObject<Element>, {\n amount: 0.3,\n once: true,\n });\n\n const sequence = useSequence();\n const itemIndex = useItemIndex();\n const [hasStarted, setHasStarted] = useState(false);\n useEffect(() => {\n if (!sequence || itemIndex === null) return;\n if (!sequence.sequenceStarted) return;\n if (hasStarted) return;\n if (sequence.activeIndex === itemIndex) {\n setHasStarted(true);\n }\n }, [sequence?.activeIndex, sequence?.sequenceStarted, hasStarted, itemIndex]);\n\n const shouldAnimate = sequence\n ? hasStarted\n : startOnView\n ? isInView\n : true;\n\n return (\n <motion.div\n ref={elementRef}\n initial={{ opacity: 0, y: -5 }}\n animate={shouldAnimate ? { opacity: 1, y: 0 } : { opacity: 0, y: -5 }}\n transition={{ duration: 0.3, delay: sequence ? 0 : delay / 1000 }}\n className={cn(\"grid text-sm font-normal tracking-tight\", className)}\n onAnimationComplete={() => {\n if (!sequence) return;\n if (itemIndex === null) return;\n sequence.completeItem(itemIndex);\n }}\n {...props}\n >\n {children}\n </motion.div>\n );\n};\n\ninterface TypingAnimationProps extends MotionProps {\n children: string;\n className?: string;\n duration?: number;\n delay?: number;\n as?: React.ElementType;\n startOnView?: boolean;\n}\n\nexport const TypingAnimation = ({\n children,\n className,\n duration = 60,\n delay = 0,\n as: Component = \"span\",\n startOnView = true,\n ...props\n}: TypingAnimationProps) => {\n if (typeof children !== \"string\") {\n throw new Error(\"TypingAnimation: children must be a string. Received:\");\n }\n\n const MotionComponent = useMemo(\n () =>\n motion.create(Component, {\n forwardMotionProps: true,\n }),\n [Component],\n );\n\n const [displayedText, setDisplayedText] = useState<string>(\"\");\n const [started, setStarted] = useState(false);\n const elementRef = useRef<HTMLElement | null>(null);\n const isInView = useInView(elementRef as React.RefObject<Element>, {\n amount: 0.3,\n once: true,\n });\n\n const sequence = useSequence();\n const itemIndex = useItemIndex();\n\n useEffect(() => {\n if (sequence && itemIndex !== null) {\n if (!sequence.sequenceStarted) return;\n if (started) return;\n if (sequence.activeIndex === itemIndex) {\n setStarted(true);\n }\n return;\n }\n\n if (!startOnView) {\n const startTimeout = setTimeout(() => setStarted(true), delay);\n return () => clearTimeout(startTimeout);\n }\n\n if (!isInView) return;\n\n const startTimeout = setTimeout(() => setStarted(true), delay);\n return () => clearTimeout(startTimeout);\n }, [delay, startOnView, isInView, started, sequence?.activeIndex, sequence?.sequenceStarted, itemIndex]);\n\n useEffect(() => {\n if (!started) return;\n\n let i = 0;\n const typingEffect = setInterval(() => {\n if (i < children.length) {\n setDisplayedText(children.substring(0, i + 1));\n i++;\n } else {\n clearInterval(typingEffect);\n if (sequence && itemIndex !== null) {\n sequence.completeItem(itemIndex);\n }\n }\n }, duration);\n\n return () => {\n clearInterval(typingEffect);\n };\n }, [children, duration, started]);\n\n return (\n <MotionComponent\n ref={elementRef}\n className={cn(\"text-sm font-normal tracking-tight\", className)}\n {...props}\n >\n {displayedText}\n </MotionComponent>\n );\n};\n\ninterface TerminalProps {\n children: React.ReactNode;\n className?: string;\n sequence?: boolean;\n startOnView?: boolean;\n}\n\nexport const Terminal = ({\n children,\n className,\n sequence = true,\n startOnView = true,\n}: TerminalProps) => {\n const containerRef = useRef<HTMLDivElement | null>(null);\n const isInView = useInView(containerRef as React.RefObject<Element>, {\n amount: 0.3,\n once: true,\n });\n\n const [activeIndex, setActiveIndex] = useState(0);\n const sequenceHasStarted = sequence ? (!startOnView || isInView) : false;\n\n const contextValue = useMemo<SequenceContextValue | null>(() => {\n if (!sequence) return null;\n return {\n completeItem: (index: number) => {\n setActiveIndex((current) => (index === current ? current + 1 : current));\n },\n activeIndex,\n sequenceStarted: sequenceHasStarted,\n };\n }, [sequence, activeIndex, sequenceHasStarted]);\n\n const wrappedChildren = useMemo(() => {\n if (!sequence) return children;\n const array = Children.toArray(children);\n return array.map((child, index) => (\n <ItemIndexContext.Provider key={index} value={index}>\n {child as React.ReactNode}\n </ItemIndexContext.Provider>\n ));\n }, [children, sequence]);\n\n const content = (\n <div\n ref={containerRef}\n className={cn(\n \"z-0 h-full max-h-[400px] w-full max-w-lg rounded-xl border border-border bg-background\",\n className,\n )}\n >\n <div className=\"flex flex-col gap-y-2 border-b border-border p-4\">\n <div className=\"flex flex-row gap-x-2\">\n <div className=\"h-2 w-2 rounded-full bg-red-500\"></div>\n <div className=\"h-2 w-2 rounded-full bg-yellow-500\"></div>\n <div className=\"h-2 w-2 rounded-full bg-green-500\"></div>\n </div>\n </div>\n <pre className=\"p-4\">\n <code className=\"grid gap-y-1 overflow-auto\">{wrappedChildren}</code>\n </pre>\n </div>\n );\n\n if (!sequence) return content;\n\n return (\n <SequenceContext.Provider value={contextValue}>{content}</SequenceContext.Provider>\n );\n};",
"type": "registry:ui",
"target": "components/magicui/terminal.tsx"
}
diff --git a/registry/example/terminal-demo.tsx b/registry/example/terminal-demo.tsx
index d36aa6f5..4ab9a7b5 100644
--- a/registry/example/terminal-demo.tsx
+++ b/registry/example/terminal-demo.tsx
@@ -6,57 +6,59 @@ import {
export default function TerminalDemo() {
return (
- <Terminal>
- <TypingAnimation>&gt; pnpm dlx shadcn@latest init</TypingAnimation>
-
- <AnimatedSpan delay={1500} className="text-green-500">
- <span>✔ Preflight checks.</span>
- </AnimatedSpan>
-
- <AnimatedSpan delay={2000} className="text-green-500">
- <span>✔ Verifying framework. Found Next.js.</span>
- </AnimatedSpan>
-
- <AnimatedSpan delay={2500} className="text-green-500">
- <span>✔ Validating Tailwind CSS.</span>
- </AnimatedSpan>
-
- <AnimatedSpan delay={3000} className="text-green-500">
- <span>✔ Validating import alias.</span>
- </AnimatedSpan>
-
- <AnimatedSpan delay={3500} className="text-green-500">
- <span>✔ Writing components.json.</span>
- </AnimatedSpan>
-
- <AnimatedSpan delay={4000} className="text-green-500">
- <span>✔ Checking registry.</span>
- </AnimatedSpan>
-
- <AnimatedSpan delay={4500} className="text-green-500">
- <span>✔ Updating tailwind.config.ts</span>
- </AnimatedSpan>
-
- <AnimatedSpan delay={5000} className="text-green-500">
- <span>✔ Updating app/globals.css</span>
- </AnimatedSpan>
-
- <AnimatedSpan delay={5500} className="text-green-500">
- <span>✔ Installing dependencies.</span>
- </AnimatedSpan>
-
- <AnimatedSpan delay={6000} className="text-blue-500">
- <span>ℹ Updated 1 file:</span>
- <span className="pl-2">- lib/utils.ts</span>
- </AnimatedSpan>
-
- <TypingAnimation delay={6500} className="text-muted-foreground">
- Success! Project initialization completed.
- </TypingAnimation>
-
- <TypingAnimation delay={7000} className="text-muted-foreground">
- You may now add components.
- </TypingAnimation>
- </Terminal>
+ <div className="w-full h-[200vh] overflow-auto flex items-center justify-center">
+ <Terminal>
+ <TypingAnimation>&gt; pnpm dlx shadcn@latest init</TypingAnimation>
+
+ <AnimatedSpan className="text-green-500">
+ <span>✔ Preflight checks.</span>
+ </AnimatedSpan>
+
+ <AnimatedSpan className="text-green-500">
+ <span>✔ Verifying framework. Found Next.js.</span>
+ </AnimatedSpan>
+
+ <AnimatedSpan className="text-green-500">
+ <span>✔ Validating Tailwind CSS.</span>
+ </AnimatedSpan>
+
+ <AnimatedSpan className="text-green-500">
+ <span>✔ Validating import alias.</span>
+ </AnimatedSpan>
+
+ <AnimatedSpan className="text-green-500">
+ <span>✔ Writing components.json.</span>
+ </AnimatedSpan>
+
+ <AnimatedSpan className="text-green-500">
+ <span>✔ Checking registry.</span>
+ </AnimatedSpan>
+
+ <AnimatedSpan className="text-green-500">
+ <span>✔ Updating tailwind.config.ts</span>
+ </AnimatedSpan>
+
+ <AnimatedSpan className="text-green-500">
+ <span>✔ Updating app/globals.css</span>
+ </AnimatedSpan>
+
+ <AnimatedSpan className="text-green-500">
+ <span>✔ Installing dependencies.</span>
+ </AnimatedSpan>
+
+ <AnimatedSpan className="text-blue-500">
+ <span>ℹ Updated 1 file:</span>
+ <span className="pl-2">- lib/utils.ts</span>
+ </AnimatedSpan>
+
+ <TypingAnimation className="text-muted-foreground">
+ Success! Project initialization completed.
+ </TypingAnimation>
+
+ <TypingAnimation className="text-muted-foreground">
+ You may now add components.
+ </TypingAnimation>
+ </Terminal>
+ </div>
);
}
diff --git a/registry/magicui/terminal.tsx b/registry/magicui/terminal.tsx
index dd8b2c64..5f5373ca 100644
--- a/registry/magicui/terminal.tsx
+++ b/registry/magicui/terminal.tsx
@@ -1,56 +1,76 @@
"use client";
import { cn } from "@/lib/utils";
-import { motion, MotionProps } from "motion/react";
-import { useEffect, useRef, useState } from "react";
+import { motion, MotionProps, useInView } from "motion/react";
+import {
+ Children,
+ createContext,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+
+interface SequenceContextValue {
+ completeItem: (index: number) => void;
+ activeIndex: number;
+ sequenceStarted: boolean;
+}
+
+const SequenceContext = createContext<SequenceContextValue | null>(null);
+
+const useSequence = () => useContext(SequenceContext);
+
+const ItemIndexContext = createContext<number | null>(null);
+const useItemIndex = () => useContext(ItemIndexContext);
interface AnimatedSpanProps extends MotionProps {
children: React.ReactNode;
delay?: number;
className?: string;
- isView?: boolean; // Prop to control animation trigger on visibility
+ startOnView?: boolean;
}
export const AnimatedSpan = ({
children,
delay = 0,
className,
- isView = false, // Default: animation waits for visibility
+ startOnView = false,
...props
}: AnimatedSpanProps) => {
- const [isVisible, setIsVisible] = useState(!isView); // Start with false if isView=false
const elementRef = useRef<HTMLDivElement | null>(null);
+ const isInView = useInView(elementRef as React.RefObject<Element>, {
+ amount: 0.3,
+ once: true,
+ });
+ const sequence = useSequence();
+ const itemIndex = useItemIndex();
+ const [hasStarted, setHasStarted] = useState(false);
useEffect(() => {
- if (!isView) {
- // Use IntersectionObserver to trigger animation when component is visible
- const observer = new IntersectionObserver(
- ([entry]) => {
- if (entry.isIntersecting) {
- setIsVisible(true);
- observer.disconnect(); // Disconnect observer after triggering
- }
- },
- { threshold: 0.1 } // Trigger when 10% of the component is visible
- );
-
- if (elementRef.current) {
- observer.observe(elementRef.current);
- }
-
- return () => {
- observer.disconnect();
- };
+ if (!sequence || itemIndex === null) return;
+ if (!sequence.sequenceStarted) return;
+ if (hasStarted) return;
+ if (sequence.activeIndex === itemIndex) {
+ setHasStarted(true);
}
- }, [isView]);
+ }, [sequence?.activeIndex, sequence?.sequenceStarted, hasStarted, itemIndex]);
+
+ const shouldAnimate = sequence ? hasStarted : startOnView ? isInView : true;
return (
<motion.div
ref={elementRef}
initial={{ opacity: 0, y: -5 }}
- animate={isVisible ? { opacity: 1, y: 0 } : { opacity: 0, y: -5 }}
- transition={{ duration: 0.3, delay: delay / 1000 }}
+ animate={shouldAnimate ? { opacity: 1, y: 0 } : { opacity: 0, y: -5 }}
+ transition={{ duration: 0.3, delay: sequence ? 0 : delay / 1000 }}
className={cn("grid text-sm font-normal tracking-tight", className)}
+ onAnimationComplete={() => {
+ if (!sequence) return;
+ if (itemIndex === null) return;
+ sequence.completeItem(itemIndex);
+ }}
{...props}
>
{children}
@@ -64,7 +84,7 @@ interface TypingAnimationProps extends MotionProps {
duration?: number;
delay?: number;
as?: React.ElementType;
- isView?: boolean; // Prop to control animation trigger on visibility
+ startOnView?: boolean;
}
export const TypingAnimation = ({
@@ -73,58 +93,64 @@ export const TypingAnimation = ({
duration = 60,
delay = 0,
as: Component = "span",
- isView = false, // Default: animation waits for visibility
+ startOnView = true,
...props
}: TypingAnimationProps) => {
if (typeof children !== "string") {
throw new Error("TypingAnimation: children must be a string. Received:");
}
- const MotionComponent = motion.create(Component, {
- forwardMotionProps: true,
- });
+ const MotionComponent = useMemo(
+ () =>
+ motion.create(Component, {
+ forwardMotionProps: true,
+ }),
+ [Component],
+ );
const [displayedText, setDisplayedText] = useState<string>("");
const [started, setStarted] = useState(false);
const elementRef = useRef<HTMLElement | null>(null);
+ const isInView = useInView(elementRef as React.RefObject<Element>, {
+ amount: 0.3,
+ once: true,
+ });
+
+ const sequence = useSequence();
+ const itemIndex = useItemIndex();
useEffect(() => {
- if (!isView) {
- // Use IntersectionObserver to start typing animation when component is visible
- const observer = new IntersectionObserver(
- ([entry]) => {
- if (entry.isIntersecting) {
- // Start animation with specified delay after visibility
- const startTimeout = setTimeout(() => {
- setStarted(true);
- }, delay);
- observer.disconnect(); // Disconnect observer after triggering
- return () => clearTimeout(startTimeout);
- }
- },
- { threshold: 0.1 } // Trigger when 10% of the component is visible
- );
-
- if (elementRef.current) {
- observer.observe(elementRef.current);
+ if (sequence && itemIndex !== null) {
+ if (!sequence.sequenceStarted) return;
+ if (started) return;
+ if (sequence.activeIndex === itemIndex) {
+ setStarted(true);
}
+ return;
+ }
- return () => {
- observer.disconnect();
- };
- } else {
- // Start animation with delay if isView=true
- const startTimeout = setTimeout(() => {
- setStarted(true);
- }, delay);
+ if (!startOnView) {
+ const startTimeout = setTimeout(() => setStarted(true), delay);
return () => clearTimeout(startTimeout);
}
- }, [delay, isView]);
+
+ if (!isInView) return;
+
+ const startTimeout = setTimeout(() => setStarted(true), delay);
+ return () => clearTimeout(startTimeout);
+ }, [
+ delay,
+ startOnView,
+ isInView,
+ started,
+ sequence?.activeIndex,
+ sequence?.sequenceStarted,
+ itemIndex,
+ ]);
useEffect(() => {
if (!started) return;
- // Handle typing animation
let i = 0;
const typingEffect = setInterval(() => {
if (i < children.length) {
@@ -132,6 +158,9 @@ export const TypingAnimation = ({
i++;
} else {
clearInterval(typingEffect);
+ if (sequence && itemIndex !== null) {
+ sequence.completeItem(itemIndex);
+ }
}
}, duration);
@@ -154,11 +183,51 @@ export const TypingAnimation = ({
interface TerminalProps {
children: React.ReactNode;
className?: string;
+ sequence?: boolean;
+ startOnView?: boolean;
}
-export const Terminal = ({ children, className }: TerminalProps) => {
- return (
+export const Terminal = ({
+ children,
+ className,
+ sequence = true,
+ startOnView = true,
+}: TerminalProps) => {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const isInView = useInView(containerRef as React.RefObject<Element>, {
+ amount: 0.3,
+ once: true,
+ });
+
+ const [activeIndex, setActiveIndex] = useState(0);
+ const sequenceHasStarted = sequence ? !startOnView || isInView : false;
+
+ const contextValue = useMemo<SequenceContextValue | null>(() => {
+ if (!sequence) return null;
+ return {
+ completeItem: (index: number) => {
+ setActiveIndex((current) =>
+ index === current ? current + 1 : current,
+ );
+ },
+ activeIndex,
+ sequenceStarted: sequenceHasStarted,
+ };
+ }, [sequence, activeIndex, sequenceHasStarted]);
+
+ const wrappedChildren = useMemo(() => {
+ if (!sequence) return children;
+ const array = Children.toArray(children);
+ return array.map((child, index) => (
+ <ItemIndexContext.Provider key={index} value={index}>
+ {child as React.ReactNode}
+ </ItemIndexContext.Provider>
+ ));
+ }, [children, sequence]);
+
+ const content = (
<div
+ ref={containerRef}
className={cn(
"z-0 h-full max-h-[400px] w-full max-w-lg rounded-xl border border-border bg-background",
className,
@@ -172,8 +241,16 @@ export const Terminal = ({ children, className }: TerminalProps) => {
</div>
</div>
<pre className="p-4">
- <code className="grid gap-y-1 overflow-auto">{children}</code>
+ <code className="grid gap-y-1 overflow-auto">{wrappedChildren}</code>
</pre>
</div>
);
-};
\ No newline at end of file
+
+ if (!sequence) return content;
+
+ return (
+ <SequenceContext.Provider value={contextValue}>
+ {content}
+ </SequenceContext.Provider>
+ );
+};