Skip to content

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

feat: update the scroll based velocity component api (#741)

Arghya Das32e35b9190c9
diff --git a/__registry__/index.tsx b/__registry__/index.tsx
index 7a596cf2..e937c16e 100644
--- a/__registry__/index.tsx
+++ b/__registry__/index.tsx
@@ -3444,6 +3444,32 @@ export const Index: Record<string, any> = {
}),
meta: undefined,
},
+ "scroll-based-velocity-images-demo": {
+ name: "scroll-based-velocity-images-demo",
+ description:
+ "Example showing Unsplash images scrolling with speed reacting to scroll velocity.",
+ type: "registry:example",
+ registryDependencies: ["https://magicui.design/r/scroll-based-velocity"],
+ files: [
+ {
+ path: "registry/example/scroll-based-velocity-images-demo.tsx",
+ type: "registry:example",
+ target: "components/scroll-based-velocity-images-demo.tsx",
+ },
+ ],
+ component: React.lazy(async () => {
+ const mod = await import(
+ "@/registry/example/scroll-based-velocity-images-demo.tsx"
+ );
+ const exportName =
+ Object.keys(mod).find(
+ (key) =>
+ typeof mod[key] === "function" || typeof mod[key] === "object",
+ ) || item.name;
+ return { default: mod.default || mod[exportName] };
+ }),
+ meta: undefined,
+ },
"scratch-to-reveal-demo": {
name: "scratch-to-reveal-demo",
description: "Example showing an interactive scratch-off reveal effect.",
diff --git a/content/docs/components/scroll-based-velocity.mdx b/content/docs/components/scroll-based-velocity.mdx
index 8e56710b..177bedab 100644
--- a/content/docs/components/scroll-based-velocity.mdx
+++ b/content/docs/components/scroll-based-velocity.mdx
@@ -8,6 +8,8 @@ published: true
<ComponentPreview name="scroll-based-velocity-demo" />
+<ComponentPreview name="scroll-based-velocity-images-demo" />
+
## Installation
<Tabs defaultValue="cli">
@@ -49,18 +51,42 @@ npm install motion
## Usage
```tsx
-import { VelocityScroll } from "@/components/magicui/scroll-based-velocity";
+import {
+ ScrollVelocityContainer,
+ ScrollVelocityRow,
+} from "@/components/magicui/scroll-based-velocity";
```
```tsx
-<VelocityScroll>Scroll Based Velocity</VelocityScroll>
+<ScrollVelocityContainer className="text-4xl md:text-7xl font-bold">
+ <ScrollVelocityRow baseVelocity={20} direction={1}>
+ Velocity Scroll
+ </ScrollVelocityRow>
+ <ScrollVelocityRow baseVelocity={20} direction={-1}>
+ Velocity Scroll
+ </ScrollVelocityRow>
+</ScrollVelocityContainer>
```
## Props
-| Prop | Type | Default | Description |
-| ----------------- | ----------- | ------- | --------------------------------------------- |
-| `className` | `string` | `-` | The class name to be applied to the component |
-| `children` | `ReactNode` | `-` | Content to be animated |
-| `defaultVelocity` | `number` | `5` | Base scroll velocity of text |
-| `numRows` | `number` | `2` | Number of rows to be animated |
+### ScrollVelocityContainer
+
+| Prop | Type | Default | Description |
+| ----------- | ----------- | ------- | --------------------------------------------- |
+| `className` | `string` | `-` | The class name to be applied to the component |
+| `children` | `ReactNode` | `-` | Content to be animated |
+
+### ScrollVelocityRow
+
+| Prop | Type | Default | Description |
+| -------------- | ----------- | ------- | -------------------------------------------------- |
+| `className` | `string` | `-` | The class name to be applied to the row container |
+| `children` | `ReactNode` | `-` | Content to be duplicated and scrolled |
+| `baseVelocity` | `number` | `5` | Base scroll velocity percentage of content width |
+| `direction` | `1 \| -1` | `1` | Scroll direction (1 = left-to-right, -1 = reverse) |
+
+## Performance
+
+- Pauses updates when offscreen and when the tab is hidden.
+- Respects user preference for reduced motion.
diff --git a/public/r/scroll-based-velocity-demo.json b/public/r/scroll-based-velocity-demo.json
index 0ec1f3d5..10a4fd11 100644
--- a/public/r/scroll-based-velocity-demo.json
+++ b/public/r/scroll-based-velocity-demo.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/example/scroll-based-velocity-demo.tsx",
- "content": "import { VelocityScroll } from \"@/registry/magicui/scroll-based-velocity\";\n\nexport default function ScrollBasedVelocityDemo() {\n return (\n <div className=\"relative flex w-full flex-col items-center justify-center overflow-hidden\">\n <VelocityScroll>Velocity Scroll</VelocityScroll>\n <div className=\"pointer-events-none absolute inset-y-0 left-0 w-1/4 bg-gradient-to-r from-background\"></div>\n <div className=\"pointer-events-none absolute inset-y-0 right-0 w-1/4 bg-gradient-to-l from-background\"></div>\n </div>\n );\n}\n",
+ "content": "import {\n ScrollVelocityContainer,\n ScrollVelocityRow,\n} from \"@/registry/magicui/scroll-based-velocity\";\n\nexport default function ScrollBasedVelocityDemo() {\n return (\n <div className=\"relative flex w-full flex-col items-center justify-center overflow-hidden\">\n <ScrollVelocityContainer className=\"text-4xl md:text-7xl md:leading-[5rem] font-bold tracking-[-0.02em]\">\n <ScrollVelocityRow baseVelocity={20} direction={1}>\n Velocity Scroll\n </ScrollVelocityRow>\n <ScrollVelocityRow baseVelocity={20} direction={-1}>\n Velocity Scroll\n </ScrollVelocityRow>\n </ScrollVelocityContainer>\n <div className=\"pointer-events-none absolute inset-y-0 left-0 w-1/4 bg-gradient-to-r from-background\"></div>\n <div className=\"pointer-events-none absolute inset-y-0 right-0 w-1/4 bg-gradient-to-l from-background\"></div>\n </div>\n );\n}\n",
"type": "registry:example",
"target": "components/scroll-based-velocity-demo.tsx"
}
diff --git a/public/r/scroll-based-velocity-images-demo.json b/public/r/scroll-based-velocity-images-demo.json
new file mode 100644
index 00000000..c4eeb5f7
--- /dev/null
+++ b/public/r/scroll-based-velocity-images-demo.json
@@ -0,0 +1,18 @@
+{
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
+ "name": "scroll-based-velocity-images-demo",
+ "type": "registry:example",
+ "title": "Scroll Based Velocity Images",
+ "description": "Example showing Unsplash images scrolling with speed reacting to scroll velocity.",
+ "registryDependencies": [
+ "https://magicui.design/r/scroll-based-velocity"
+ ],
+ "files": [
+ {
+ "path": "registry/example/scroll-based-velocity-images-demo.tsx",
+ "content": "import {\n ScrollVelocityContainer,\n ScrollVelocityRow,\n} from \"@/registry/magicui/scroll-based-velocity\";\n\nconst IMAGES_ROW_A = [\n \"https://images.unsplash.com/photo-1749738456487-2af715ab65ea?q=80&w=2340&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D\",\n \"https://plus.unsplash.com/premium_photo-1720139288219-e20aa9c8895b?q=80&w=1810&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D\",\n];\n\nconst IMAGES_ROW_B = [\n \"https://images.unsplash.com/photo-1749738456487-2af715ab65ea?q=80&w=2340&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D\",\n \"https://plus.unsplash.com/premium_photo-1720139288219-e20aa9c8895b?q=80&w=1810&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D\",\n];\n\nexport default function ScrollBasedVelocityImagesDemo() {\n return (\n <div className=\"relative flex w-full flex-col items-center justify-center overflow-hidden py-8\">\n <ScrollVelocityContainer className=\"w-full\">\n <ScrollVelocityRow baseVelocity={6} direction={1} className=\"py-4\">\n {IMAGES_ROW_A.map((src, idx) => (\n <img\n key={idx}\n src={`${src}&ixlib=rb-4.0.3`}\n alt=\"Unsplash sample\"\n width={240}\n height={160}\n loading=\"lazy\"\n decoding=\"async\"\n className=\"mx-4 inline-block h-40 w-60 rounded-lg object-cover shadow-sm\"\n />\n ))}\n </ScrollVelocityRow>\n <ScrollVelocityRow baseVelocity={6} direction={-1} className=\"py-4\">\n {IMAGES_ROW_B.map((src, idx) => (\n <img\n key={idx}\n src={`${src}&ixlib=rb-4.0.3`}\n alt=\"Unsplash sample\"\n width={240}\n height={160}\n loading=\"lazy\"\n decoding=\"async\"\n className=\"mx-4 inline-block h-40 w-60 rounded-lg object-cover shadow-sm\"\n />\n ))}\n </ScrollVelocityRow>\n </ScrollVelocityContainer>\n\n <div className=\"pointer-events-none absolute inset-y-0 left-0 w-1/4 bg-gradient-to-r from-background\"></div>\n <div className=\"pointer-events-none absolute inset-y-0 right-0 w-1/4 bg-gradient-to-l from-background\"></div>\n </div>\n );\n}\n",
+ "type": "registry:example",
+ "target": "components/scroll-based-velocity-images-demo.tsx"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/public/r/scroll-based-velocity.json b/public/r/scroll-based-velocity.json
index a41ec6ff..6351b59a 100644
--- a/public/r/scroll-based-velocity.json
+++ b/public/r/scroll-based-velocity.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/magicui/scroll-based-velocity.tsx",
- "content": "\"use client\";\n\nimport {\n motion,\n useAnimationFrame,\n useMotionValue,\n useScroll,\n useSpring,\n useTransform,\n useVelocity,\n} from \"motion/react\";\nimport React, { useEffect, useRef, useState } from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface VelocityScrollProps extends React.HTMLAttributes<HTMLDivElement> {\n defaultVelocity?: number;\n className?: string;\n numRows?: number;\n}\n\ninterface ParallaxProps extends React.HTMLAttributes<HTMLDivElement> {\n children: React.ReactNode;\n baseVelocity: number;\n}\n\nexport const wrap = (min: number, max: number, v: number) => {\n const rangeSize = max - min;\n return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;\n};\n\nfunction ParallaxText({\n children,\n baseVelocity = 100,\n ...props\n}: ParallaxProps) {\n const baseX = useMotionValue(0);\n const { scrollY } = useScroll();\n const scrollVelocity = useVelocity(scrollY);\n const smoothVelocity = useSpring(scrollVelocity, {\n damping: 50,\n stiffness: 400,\n });\n\n const velocityFactor = useTransform(smoothVelocity, [0, 1000], [0, 5], {\n clamp: false,\n });\n\n const [repetitions, setRepetitions] = useState(1);\n const containerRef = useRef<HTMLDivElement>(null);\n const textRef = useRef<HTMLSpanElement>(null);\n\n useEffect(() => {\n const calculateRepetitions = () => {\n if (containerRef.current && textRef.current) {\n const containerWidth = containerRef.current.offsetWidth;\n const textWidth = textRef.current.offsetWidth;\n const newRepetitions = Math.ceil(containerWidth / textWidth) + 2;\n setRepetitions(newRepetitions);\n }\n };\n\n calculateRepetitions();\n\n window.addEventListener(\"resize\", calculateRepetitions);\n return () => window.removeEventListener(\"resize\", calculateRepetitions);\n }, [children]);\n\n const x = useTransform(baseX, (v) => `${wrap(-100 / repetitions, 0, v)}%`);\n\n const directionFactor = React.useRef<number>(1);\n useAnimationFrame((t, delta) => {\n let moveBy = directionFactor.current * baseVelocity * (delta / 1000);\n\n if (velocityFactor.get() < 0) {\n directionFactor.current = -1;\n } else if (velocityFactor.get() > 0) {\n directionFactor.current = 1;\n }\n\n moveBy += directionFactor.current * moveBy * velocityFactor.get();\n\n baseX.set(baseX.get() + moveBy);\n });\n\n return (\n <div\n ref={containerRef}\n className=\"w-full overflow-hidden whitespace-nowrap\"\n {...props}\n >\n <motion.div className=\"inline-block\" style={{ x }}>\n {Array.from({ length: repetitions }).map((_, i) => (\n <span key={i} ref={i === 0 ? textRef : null}>\n {children}{\" \"}\n </span>\n ))}\n </motion.div>\n </div>\n );\n}\n\nexport function VelocityScroll({\n defaultVelocity = 5,\n numRows = 2,\n children,\n className,\n ...props\n}: VelocityScrollProps) {\n return (\n <div\n className={cn(\n \"relative w-full text-4xl font-bold tracking-[-0.02em] md:text-7xl md:leading-[5rem]\",\n className,\n )}\n {...props}\n >\n {Array.from({ length: numRows }).map((_, i) => (\n <ParallaxText\n key={i}\n baseVelocity={defaultVelocity * (i % 2 === 0 ? 1 : -1)}\n >\n {children}\n </ParallaxText>\n ))}\n </div>\n );\n}\n",
+ "content": "\"use client\";\n\nimport {\n motion,\n useAnimationFrame,\n useMotionValue,\n useScroll,\n useSpring,\n useTransform,\n useVelocity,\n} from \"motion/react\";\nimport React, { useContext, useEffect, useRef, useState } from \"react\";\nimport type { MotionValue } from \"motion/react\";\n\nimport { cn } from \"@/lib/utils\";\n\ninterface ScrollVelocityRowProps extends React.HTMLAttributes<HTMLDivElement> {\n children: React.ReactNode;\n baseVelocity?: number;\n direction?: 1 | -1;\n}\n\nexport const wrap = (min: number, max: number, v: number) => {\n const rangeSize = max - min;\n return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;\n};\n\nconst ScrollVelocityContext = React.createContext<MotionValue<number> | null>(\n null,\n);\n\nexport function ScrollVelocityContainer({\n children,\n className,\n ...props\n}: React.HTMLAttributes<HTMLDivElement>) {\n const { scrollY } = useScroll();\n const scrollVelocity = useVelocity(scrollY);\n const smoothVelocity = useSpring(scrollVelocity, {\n damping: 50,\n stiffness: 400,\n });\n const velocityFactor = useTransform(smoothVelocity, (v) => {\n const sign = v < 0 ? -1 : 1;\n const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5);\n return sign * magnitude;\n });\n\n return (\n <ScrollVelocityContext.Provider value={velocityFactor}>\n <div className={cn(\"relative w-full\", className)} {...props}>\n {children}\n </div>\n </ScrollVelocityContext.Provider>\n );\n}\n\nexport function ScrollVelocityRow(props: ScrollVelocityRowProps) {\n const sharedVelocityFactor = useContext(ScrollVelocityContext);\n if (sharedVelocityFactor) {\n return (\n <ScrollVelocityRowImpl {...props} velocityFactor={sharedVelocityFactor} />\n );\n }\n return <ScrollVelocityRowLocal {...props} />;\n}\n\ninterface ScrollVelocityRowImplProps extends ScrollVelocityRowProps {\n velocityFactor: MotionValue<number>;\n}\n\nfunction ScrollVelocityRowImpl({\n children,\n baseVelocity = 5,\n direction = 1,\n className,\n velocityFactor,\n ...props\n}: ScrollVelocityRowImplProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const blockRef = useRef<HTMLDivElement>(null);\n const [numCopies, setNumCopies] = useState(1);\n\n const baseX = useMotionValue(0);\n const baseDirectionRef = useRef<number>(direction >= 0 ? 1 : -1);\n const currentDirectionRef = useRef<number>(direction >= 0 ? 1 : -1);\n const unitWidth = useMotionValue(0);\n\n const isInViewRef = useRef(true);\n const isPageVisibleRef = useRef(true);\n const prefersReducedMotionRef = useRef(false);\n\n useEffect(() => {\n const container = containerRef.current;\n const block = blockRef.current;\n if (!container || !block) return;\n\n const updateSizes = () => {\n const cw = container.offsetWidth || 0;\n const bw = block.scrollWidth || 0;\n unitWidth.set(bw);\n const nextCopies = bw > 0 ? Math.max(3, Math.ceil(cw / bw) + 2) : 1;\n setNumCopies((prev) => (prev === nextCopies ? prev : nextCopies));\n };\n\n updateSizes();\n\n const ro = new ResizeObserver(updateSizes);\n ro.observe(container);\n ro.observe(block);\n\n const io = new IntersectionObserver(([entry]) => {\n isInViewRef.current = entry.isIntersecting;\n });\n io.observe(container);\n\n const handleVisibility = () => {\n isPageVisibleRef.current = document.visibilityState === \"visible\";\n };\n document.addEventListener(\"visibilitychange\", handleVisibility, {\n passive: true,\n });\n handleVisibility();\n\n const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n const handlePRM = () => {\n prefersReducedMotionRef.current = mq.matches;\n };\n mq.addEventListener(\"change\", handlePRM);\n handlePRM();\n\n return () => {\n ro.disconnect();\n io.disconnect();\n document.removeEventListener(\"visibilitychange\", handleVisibility);\n mq.removeEventListener(\"change\", handlePRM);\n };\n }, [children, unitWidth]);\n\n const x = useTransform([baseX, unitWidth], ([v, bw]) => {\n const width = Number(bw) || 1;\n const offset = Number(v) || 0;\n return `${-wrap(0, width, offset)}px`;\n });\n\n useAnimationFrame((_, delta) => {\n if (!isInViewRef.current || !isPageVisibleRef.current) return;\n const dt = delta / 1000;\n const vf = velocityFactor.get();\n const absVf = Math.min(5, Math.abs(vf));\n const speedMultiplier = prefersReducedMotionRef.current ? 1 : 1 + absVf;\n\n if (absVf > 0.1) {\n const scrollDirection = vf >= 0 ? 1 : -1;\n currentDirectionRef.current = baseDirectionRef.current * scrollDirection;\n }\n\n const bw = unitWidth.get() || 0;\n if (bw <= 0) return;\n const pixelsPerSecond = (bw * baseVelocity) / 100;\n const moveBy =\n currentDirectionRef.current * pixelsPerSecond * speedMultiplier * dt;\n baseX.set(baseX.get() + moveBy);\n });\n\n return (\n <div\n ref={containerRef}\n className={cn(\"w-full overflow-hidden whitespace-nowrap\", className)}\n {...props}\n >\n <motion.div\n className=\"inline-flex items-center will-change-transform transform-gpu select-none\"\n style={{ x }}\n >\n {Array.from({ length: numCopies }).map((_, i) => (\n <div\n key={i}\n ref={i === 0 ? blockRef : null}\n aria-hidden={i !== 0}\n className=\"inline-flex shrink-0 items-center\"\n >\n {children}\n </div>\n ))}\n </motion.div>\n </div>\n );\n}\n\nfunction ScrollVelocityRowLocal(props: ScrollVelocityRowProps) {\n const { scrollY } = useScroll();\n const localVelocity = useVelocity(scrollY);\n const localSmoothVelocity = useSpring(localVelocity, {\n damping: 50,\n stiffness: 400,\n });\n const localVelocityFactor = useTransform(localSmoothVelocity, (v) => {\n const sign = v < 0 ? -1 : 1;\n const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5);\n return sign * magnitude;\n });\n return (\n <ScrollVelocityRowImpl {...props} velocityFactor={localVelocityFactor} />\n );\n}\n",
"type": "registry:ui",
"target": "components/magicui/scroll-based-velocity.tsx"
}
diff --git a/public/r/terminal.json b/public/r/terminal.json
index 9ae9c185..f31a3614 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, 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};",
+ "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 ? hasStarted : startOnView ? isInView : 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 }, [\n delay,\n startOnView,\n isInView,\n started,\n sequence?.activeIndex,\n sequence?.sequenceStarted,\n itemIndex,\n ]);\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) =>\n index === current ? current + 1 : current,\n );\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}>\n {content}\n </SequenceContext.Provider>\n );\n};\n",
"type": "registry:ui",
"target": "components/magicui/terminal.tsx"
}
diff --git a/public/registry.json b/public/registry.json
index a43d5f49..7ae619d3 100644
--- a/public/registry.json
+++ b/public/registry.json
@@ -2562,6 +2562,22 @@
}
]
},
+ {
+ "name": "scroll-based-velocity-images-demo",
+ "type": "registry:example",
+ "title": "Scroll Based Velocity Images",
+ "description": "Example showing Unsplash images scrolling with speed reacting to scroll velocity.",
+ "registryDependencies": [
+ "https://magicui.design/r/scroll-based-velocity"
+ ],
+ "files": [
+ {
+ "path": "registry/example/scroll-based-velocity-images-demo.tsx",
+ "type": "registry:example",
+ "target": "components/scroll-based-velocity-images-demo.tsx"
+ }
+ ]
+ },
{
"name": "scratch-to-reveal-demo",
"type": "registry:example",
diff --git a/registry.json b/registry.json
index a43d5f49..7ae619d3 100644
--- a/registry.json
+++ b/registry.json
@@ -2562,6 +2562,22 @@
}
]
},
+ {
+ "name": "scroll-based-velocity-images-demo",
+ "type": "registry:example",
+ "title": "Scroll Based Velocity Images",
+ "description": "Example showing Unsplash images scrolling with speed reacting to scroll velocity.",
+ "registryDependencies": [
+ "https://magicui.design/r/scroll-based-velocity"
+ ],
+ "files": [
+ {
+ "path": "registry/example/scroll-based-velocity-images-demo.tsx",
+ "type": "registry:example",
+ "target": "components/scroll-based-velocity-images-demo.tsx"
+ }
+ ]
+ },
{
"name": "scratch-to-reveal-demo",
"type": "registry:example",
diff --git a/registry/example/scroll-based-velocity-demo.tsx b/registry/example/scroll-based-velocity-demo.tsx
index b1bf2897..bdf9d6e3 100644
--- a/registry/example/scroll-based-velocity-demo.tsx
+++ b/registry/example/scroll-based-velocity-demo.tsx
@@ -1,9 +1,19 @@
-import { VelocityScroll } from "@/registry/magicui/scroll-based-velocity";
+import {
+ ScrollVelocityContainer,
+ ScrollVelocityRow,
+} from "@/registry/magicui/scroll-based-velocity";
export default function ScrollBasedVelocityDemo() {
return (
<div className="relative flex w-full flex-col items-center justify-center overflow-hidden">
- <VelocityScroll>Velocity Scroll</VelocityScroll>
+ <ScrollVelocityContainer className="text-4xl md:text-7xl md:leading-[5rem] font-bold tracking-[-0.02em]">
+ <ScrollVelocityRow baseVelocity={20} direction={1}>
+ Velocity Scroll
+ </ScrollVelocityRow>
+ <ScrollVelocityRow baseVelocity={20} direction={-1}>
+ Velocity Scroll
+ </ScrollVelocityRow>
+ </ScrollVelocityContainer>
<div className="pointer-events-none absolute inset-y-0 left-0 w-1/4 bg-gradient-to-r from-background"></div>
<div className="pointer-events-none absolute inset-y-0 right-0 w-1/4 bg-gradient-to-l from-background"></div>
</div>
diff --git a/registry/example/scroll-based-velocity-images-demo.tsx b/registry/example/scroll-based-velocity-images-demo.tsx
new file mode 100644
index 00000000..8f820b17
--- /dev/null
+++ b/registry/example/scroll-based-velocity-images-demo.tsx
@@ -0,0 +1,54 @@
+import {
+ ScrollVelocityContainer,
+ ScrollVelocityRow,
+} from "@/registry/magicui/scroll-based-velocity";
+
+const IMAGES_ROW_A = [
+ "https://images.unsplash.com/photo-1749738456487-2af715ab65ea?q=80&w=2340&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
+ "https://plus.unsplash.com/premium_photo-1720139288219-e20aa9c8895b?q=80&w=1810&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
+];
+
+const IMAGES_ROW_B = [
+ "https://images.unsplash.com/photo-1749738456487-2af715ab65ea?q=80&w=2340&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
+ "https://plus.unsplash.com/premium_photo-1720139288219-e20aa9c8895b?q=80&w=1810&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
+];
+
+export default function ScrollBasedVelocityImagesDemo() {
+ return (
+ <div className="relative flex w-full flex-col items-center justify-center overflow-hidden py-8">
+ <ScrollVelocityContainer className="w-full">
+ <ScrollVelocityRow baseVelocity={6} direction={1} className="py-4">
+ {IMAGES_ROW_A.map((src, idx) => (
+ <img
+ key={idx}
+ src={`${src}&ixlib=rb-4.0.3`}
+ alt="Unsplash sample"
+ width={240}
+ height={160}
+ loading="lazy"
+ decoding="async"
+ className="mx-4 inline-block h-40 w-60 rounded-lg object-cover shadow-sm"
+ />
+ ))}
+ </ScrollVelocityRow>
+ <ScrollVelocityRow baseVelocity={6} direction={-1} className="py-4">
+ {IMAGES_ROW_B.map((src, idx) => (
+ <img
+ key={idx}
+ src={`${src}&ixlib=rb-4.0.3`}
+ alt="Unsplash sample"
+ width={240}
+ height={160}
+ loading="lazy"
+ decoding="async"
+ className="mx-4 inline-block h-40 w-60 rounded-lg object-cover shadow-sm"
+ />
+ ))}
+ </ScrollVelocityRow>
+ </ScrollVelocityContainer>
+
+ <div className="pointer-events-none absolute inset-y-0 left-0 w-1/4 bg-gradient-to-r from-background"></div>
+ <div className="pointer-events-none absolute inset-y-0 right-0 w-1/4 bg-gradient-to-l from-background"></div>
+ </div>
+ );
+}
diff --git a/registry/magicui/scroll-based-velocity.tsx b/registry/magicui/scroll-based-velocity.tsx
index f77db99c..6ca8c10a 100644
--- a/registry/magicui/scroll-based-velocity.tsx
+++ b/registry/magicui/scroll-based-velocity.tsx
@@ -9,19 +9,15 @@ import {
useTransform,
useVelocity,
} from "motion/react";
-import React, { useEffect, useRef, useState } from "react";
+import React, { useContext, useEffect, useRef, useState } from "react";
+import type { MotionValue } from "motion/react";
import { cn } from "@/lib/utils";
-interface VelocityScrollProps extends React.HTMLAttributes<HTMLDivElement> {
- defaultVelocity?: number;
- className?: string;
- numRows?: number;
-}
-
-interface ParallaxProps extends React.HTMLAttributes<HTMLDivElement> {
+interface ScrollVelocityRowProps extends React.HTMLAttributes<HTMLDivElement> {
children: React.ReactNode;
- baseVelocity: number;
+ baseVelocity?: number;
+ direction?: 1 | -1;
}
export const wrap = (min: number, max: number, v: number) => {
@@ -29,100 +25,182 @@ export const wrap = (min: number, max: number, v: number) => {
return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;
};
-function ParallaxText({
+const ScrollVelocityContext = React.createContext<MotionValue<number> | null>(
+ null,
+);
+
+export function ScrollVelocityContainer({
children,
- baseVelocity = 100,
+ className,
...props
-}: ParallaxProps) {
- const baseX = useMotionValue(0);
+}: React.HTMLAttributes<HTMLDivElement>) {
const { scrollY } = useScroll();
const scrollVelocity = useVelocity(scrollY);
const smoothVelocity = useSpring(scrollVelocity, {
damping: 50,
stiffness: 400,
});
-
- const velocityFactor = useTransform(smoothVelocity, [0, 1000], [0, 5], {
- clamp: false,
+ const velocityFactor = useTransform(smoothVelocity, (v) => {
+ const sign = v < 0 ? -1 : 1;
+ const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5);
+ return sign * magnitude;
});
- const [repetitions, setRepetitions] = useState(1);
+ return (
+ <ScrollVelocityContext.Provider value={velocityFactor}>
+ <div className={cn("relative w-full", className)} {...props}>
+ {children}
+ </div>
+ </ScrollVelocityContext.Provider>
+ );
+}
+
+export function ScrollVelocityRow(props: ScrollVelocityRowProps) {
+ const sharedVelocityFactor = useContext(ScrollVelocityContext);
+ if (sharedVelocityFactor) {
+ return (
+ <ScrollVelocityRowImpl {...props} velocityFactor={sharedVelocityFactor} />
+ );
+ }
+ return <ScrollVelocityRowLocal {...props} />;
+}
+
+interface ScrollVelocityRowImplProps extends ScrollVelocityRowProps {
+ velocityFactor: MotionValue<number>;
+}
+
+function ScrollVelocityRowImpl({
+ children,
+ baseVelocity = 5,
+ direction = 1,
+ className,
+ velocityFactor,
+ ...props
+}: ScrollVelocityRowImplProps) {
const containerRef = useRef<HTMLDivElement>(null);
- const textRef = useRef<HTMLSpanElement>(null);
+ const blockRef = useRef<HTMLDivElement>(null);
+ const [numCopies, setNumCopies] = useState(1);
+
+ const baseX = useMotionValue(0);
+ const baseDirectionRef = useRef<number>(direction >= 0 ? 1 : -1);
+ const currentDirectionRef = useRef<number>(direction >= 0 ? 1 : -1);
+ const unitWidth = useMotionValue(0);
+
+ const isInViewRef = useRef(true);
+ const isPageVisibleRef = useRef(true);
+ const prefersReducedMotionRef = useRef(false);
useEffect(() => {
- const calculateRepetitions = () => {
- if (containerRef.current && textRef.current) {
- const containerWidth = containerRef.current.offsetWidth;
- const textWidth = textRef.current.offsetWidth;
- const newRepetitions = Math.ceil(containerWidth / textWidth) + 2;
- setRepetitions(newRepetitions);
- }
+ const container = containerRef.current;
+ const block = blockRef.current;
+ if (!container || !block) return;
+
+ const updateSizes = () => {
+ const cw = container.offsetWidth || 0;
+ const bw = block.scrollWidth || 0;
+ unitWidth.set(bw);
+ const nextCopies = bw > 0 ? Math.max(3, Math.ceil(cw / bw) + 2) : 1;
+ setNumCopies((prev) => (prev === nextCopies ? prev : nextCopies));
};
- calculateRepetitions();
+ updateSizes();
- window.addEventListener("resize", calculateRepetitions);
- return () => window.removeEventListener("resize", calculateRepetitions);
- }, [children]);
+ const ro = new ResizeObserver(updateSizes);
+ ro.observe(container);
+ ro.observe(block);
- const x = useTransform(baseX, (v) => `${wrap(-100 / repetitions, 0, v)}%`);
+ const io = new IntersectionObserver(([entry]) => {
+ isInViewRef.current = entry.isIntersecting;
+ });
+ io.observe(container);
- const directionFactor = React.useRef<number>(1);
- useAnimationFrame((t, delta) => {
- let moveBy = directionFactor.current * baseVelocity * (delta / 1000);
+ const handleVisibility = () => {
+ isPageVisibleRef.current = document.visibilityState === "visible";
+ };
+ document.addEventListener("visibilitychange", handleVisibility, {
+ passive: true,
+ });
+ handleVisibility();
+
+ const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
+ const handlePRM = () => {
+ prefersReducedMotionRef.current = mq.matches;
+ };
+ mq.addEventListener("change", handlePRM);
+ handlePRM();
+
+ return () => {
+ ro.disconnect();
+ io.disconnect();
+ document.removeEventListener("visibilitychange", handleVisibility);
+ mq.removeEventListener("change", handlePRM);
+ };
+ }, [children, unitWidth]);
- if (velocityFactor.get() < 0) {
- directionFactor.current = -1;
- } else if (velocityFactor.get() > 0) {
- directionFactor.current = 1;
- }
+ const x = useTransform([baseX, unitWidth], ([v, bw]) => {
+ const width = Number(bw) || 1;
+ const offset = Number(v) || 0;
+ return `${-wrap(0, width, offset)}px`;
+ });
- moveBy += directionFactor.current * moveBy * velocityFactor.get();
+ useAnimationFrame((_, delta) => {
+ if (!isInViewRef.current || !isPageVisibleRef.current) return;
+ const dt = delta / 1000;
+ const vf = velocityFactor.get();
+ const absVf = Math.min(5, Math.abs(vf));
+ const speedMultiplier = prefersReducedMotionRef.current ? 1 : 1 + absVf;
+ if (absVf > 0.1) {
+ const scrollDirection = vf >= 0 ? 1 : -1;
+ currentDirectionRef.current = baseDirectionRef.current * scrollDirection;
+ }
+
+ const bw = unitWidth.get() || 0;
+ if (bw <= 0) return;
+ const pixelsPerSecond = (bw * baseVelocity) / 100;
+ const moveBy =
+ currentDirectionRef.current * pixelsPerSecond * speedMultiplier * dt;
baseX.set(baseX.get() + moveBy);
});
return (
<div
ref={containerRef}
- className="w-full overflow-hidden whitespace-nowrap"
+ className={cn("w-full overflow-hidden whitespace-nowrap", className)}
{...props}
>
- <motion.div className="inline-block" style={{ x }}>
- {Array.from({ length: repetitions }).map((_, i) => (
- <span key={i} ref={i === 0 ? textRef : null}>
- {children}{" "}
- </span>
+ <motion.div
+ className="inline-flex items-center will-change-transform transform-gpu select-none"
+ style={{ x }}
+ >
+ {Array.from({ length: numCopies }).map((_, i) => (
+ <div
+ key={i}
+ ref={i === 0 ? blockRef : null}
+ aria-hidden={i !== 0}
+ className="inline-flex shrink-0 items-center"
+ >
+ {children}
+ </div>
))}
</motion.div>
</div>
);
}
-export function VelocityScroll({
- defaultVelocity = 5,
- numRows = 2,
- children,
- className,
- ...props
-}: VelocityScrollProps) {
+function ScrollVelocityRowLocal(props: ScrollVelocityRowProps) {
+ const { scrollY } = useScroll();
+ const localVelocity = useVelocity(scrollY);
+ const localSmoothVelocity = useSpring(localVelocity, {
+ damping: 50,
+ stiffness: 400,
+ });
+ const localVelocityFactor = useTransform(localSmoothVelocity, (v) => {
+ const sign = v < 0 ? -1 : 1;
+ const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5);
+ return sign * magnitude;
+ });
return (
- <div
- className={cn(
- "relative w-full text-4xl font-bold tracking-[-0.02em] md:text-7xl md:leading-[5rem]",
- className,
- )}
- {...props}
- >
- {Array.from({ length: numRows }).map((_, i) => (
- <ParallaxText
- key={i}
- baseVelocity={defaultVelocity * (i % 2 === 0 ? 1 : -1)}
- >
- {children}
- </ParallaxText>
- ))}
- </div>
+ <ScrollVelocityRowImpl {...props} velocityFactor={localVelocityFactor} />
);
}
diff --git a/registry/registry-examples.ts b/registry/registry-examples.ts
index a257dff6..d6e7178a 100644
--- a/registry/registry-examples.ts
+++ b/registry/registry-examples.ts
@@ -1046,6 +1046,21 @@ export const examples: Registry["items"] = [
},
],
},
+ {
+ name: "scroll-based-velocity-images-demo",
+ type: "registry:example",
+ title: "Scroll Based Velocity Images",
+ description:
+ "Example showing Unsplash images scrolling with speed reacting to scroll velocity.",
+ registryDependencies: ["https://magicui.design/r/scroll-based-velocity"],
+ files: [
+ {
+ path: "registry/example/scroll-based-velocity-images-demo.tsx",
+ type: "registry:example",
+ target: "components/scroll-based-velocity-images-demo.tsx",
+ },
+ ],
+ },
{
name: "scratch-to-reveal-demo",
type: "registry:example",