Skip to content

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

feat: scroll based velocity text (#37)

Rudy3b3604447a94
diff --git a/config/docs.ts b/config/docs.ts
index 95d7e006..bbeb670e 100644
--- a/config/docs.ts
+++ b/config/docs.ts
@@ -175,6 +175,12 @@ export const docsConfig: DocsConfig = {
items: [],
label: "New",
},
+ {
+ title: "Scroll Based Velocity",
+ href: `/docs/components/scroll-based-velocity`,
+ items: [],
+ label: "New",
+ },
],
},
{
diff --git a/content/docs/components/scroll-based-velocity.mdx b/content/docs/components/scroll-based-velocity.mdx
new file mode 100644
index 00000000..97e59f8c
--- /dev/null
+++ b/content/docs/components/scroll-based-velocity.mdx
@@ -0,0 +1,31 @@
+---
+title: Scroll Based Velocity
+date: 2024-05-22
+description: Scrolling text whose speed changes based on scroll speed
+author: whyismynamerudy
+published: true
+---
+
+<ComponentPreview name="scroll-based-velocity-demo" />
+
+<Steps>
+
+### Installation
+
+Copy and paste the following code into your project.
+
+```text
+components/magicui/scroll-based-velocity.tsx
+```
+
+<ComponentSource name="scroll-based-velocity-demo" />
+
+</Steps>
+
+## Props
+
+| Prop | Type | Description | Default |
+| ---------------- | --------------- | -------------------------------------------------- | ------- |
+| className | string | The class name to be applied to the component | |
+| text | string | Text to be animated | "" |
+| default_velocity | number | Base scroll velocity of text | 5 |
diff --git a/package.json b/package.json
index a2d1b13a..20aeb221 100644
--- a/package.json
+++ b/package.json
@@ -27,6 +27,7 @@
"@headlessui/react": "^1.7.17",
"@heroicons/react": "^2.1.3",
"@hookform/resolvers": "^3.1.1",
+ "@motionone/utils": "^10.17.0",
"@next-auth/prisma-adapter": "^1.0.7",
"@prisma/client": "^5.11.0",
"@radix-ui/react-accordion": "^1.1.2",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a4f18dae..e6c416e3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -23,6 +23,9 @@ importers:
'@hookform/resolvers':
specifier: ^3.1.1
+ '@motionone/utils':
+ specifier: ^10.17.0
+ version: 10.17.0
'@next-auth/prisma-adapter':
specifier: ^1.0.7
@@ -1562,6 +1565,12 @@ packages:
'@mdx-js/[email protected]':
resolution: {integrity: sha512-jLuwRlz8DQfQNiUCJR50Y09CGPq3fLtmtUQfVrj79E0JWu3dvsVcxVIcfhR5h0iXu+/z++zDrYeiJqifRynJkA==}
+ '@motionone/[email protected]':
+ resolution: {integrity: sha512-EgeeqOZVdRUTEHq95Z3t8Rsirc7chN5xFAPMYFobx8TPubkEfRSm5xihmMUkbaR2ErKJTUw3347QDPTHIW12IA==}
+
+ '@motionone/[email protected]':
+ resolution: {integrity: sha512-bGwrki4896apMWIj9yp5rAS2m0xyhxblg6gTB/leWDPt+pb410W8lYWsxyurX+DH+gO1zsQsfx2su/c1/LtTpg==}
+
'@next-auth/[email protected]':
resolution: {integrity: sha512-Cdko4KfcmKjsyHFrWwZ//lfLUbcLqlyFqjd/nYE2m3aZ7tjMNUjpks47iw7NTCnXf+5UWz5Ypyt1dSs1EP5QJw==}
peerDependencies:
@@ -4374,6 +4383,9 @@ packages:
resolution: {integrity: sha512-Ox1pJVrDCyGHMG9CFg1tmrRUMRPRsAWYc/PinY0XzJU4K7y7vjNoLKIQ7BR5UJMCxNN8EM1MNDmHWA/B3aZUuw==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-COpmrF2NOg4TBWUJ5UVyaCU2A88wEMkUPK4hNqyCkqHbxT92BbvfjoSozkAIIm6XhicGlJHhFdullInrdhwU8Q==}
+
resolution: {integrity: sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==}
@@ -8623,6 +8635,14 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@motionone/[email protected]': {}
+
+ '@motionone/[email protected]':
+ dependencies:
+ '@motionone/types': 10.17.0
+ hey-listen: 1.0.8
+ tslib: 2.6.2
+
dependencies:
'@prisma/client': 5.11.0([email protected])
@@ -12067,6 +12087,8 @@ snapshots:
+
diff --git a/registry/components/example/scroll-based-velocity-demo.tsx b/registry/components/example/scroll-based-velocity-demo.tsx
new file mode 100644
index 00000000..73e0cf48
--- /dev/null
+++ b/registry/components/example/scroll-based-velocity-demo.tsx
@@ -0,0 +1,11 @@
+import { VelocityScroll } from "@/registry/components/magicui/scroll-based-velocity";
+
+export default function ScrollBasedVelocityDemo() {
+ return (
+ <VelocityScroll
+ text="Velocity Scroll"
+ default_velocity={5}
+ className="font-display text-center text-4xl font-bold tracking-[-0.02em] text-black drop-shadow-sm dark:text-white md:text-7xl md:leading-[5rem]"
+ />
+ );
+}
diff --git a/registry/components/magicui/scroll-based-velocity.tsx b/registry/components/magicui/scroll-based-velocity.tsx
new file mode 100644
index 00000000..8064837b
--- /dev/null
+++ b/registry/components/magicui/scroll-based-velocity.tsx
@@ -0,0 +1,113 @@
+"use client";
+
+import { cn } from "@/lib/utils";
+import { wrap } from "@motionone/utils";
+import {
+ motion,
+ useAnimationFrame,
+ useMotionValue,
+ useScroll,
+ useSpring,
+ useTransform,
+ useVelocity,
+} from "framer-motion";
+import React, { useEffect, useRef, useState } from "react";
+
+interface VelocityScrollProps {
+ text: string;
+ default_velocity?: number;
+ className?: string;
+}
+
+interface ParallaxProps {
+ children: string;
+ baseVelocity: number;
+ className?: string;
+}
+
+export function VelocityScroll({
+ text,
+ default_velocity = 5,
+ className,
+}: VelocityScrollProps) {
+ function ParallaxText({
+ children,
+ baseVelocity = 100,
+ className,
+ }: ParallaxProps) {
+ const baseX = useMotionValue(0);
+ 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 [repetitions, setRepetitions] = useState(1);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const textRef = useRef<HTMLSpanElement>(null);
+
+ 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);
+ }
+ };
+
+ calculateRepetitions();
+
+ window.addEventListener("resize", calculateRepetitions);
+ return () => window.removeEventListener("resize", calculateRepetitions);
+ }, [children]);
+
+ const x = useTransform(baseX, (v) => `${wrap(-100 / repetitions, 0, v)}%`);
+
+ const directionFactor = React.useRef<number>(1);
+ useAnimationFrame((t, delta) => {
+ let moveBy = directionFactor.current * baseVelocity * (delta / 1000);
+
+ if (velocityFactor.get() < 0) {
+ directionFactor.current = -1;
+ } else if (velocityFactor.get() > 0) {
+ directionFactor.current = 1;
+ }
+
+ moveBy += directionFactor.current * moveBy * velocityFactor.get();
+
+ baseX.set(baseX.get() + moveBy);
+ });
+
+ return (
+ <div
+ className="w-full overflow-hidden whitespace-nowrap"
+ ref={containerRef}
+ >
+ <motion.div className={cn("inline-block", className)} style={{ x }}>
+ {Array.from({ length: repetitions }).map((_, i) => (
+ <span key={i} ref={i === 0 ? textRef : null}>
+ {children}{" "}
+ </span>
+ ))}
+ </motion.div>
+ </div>
+ );
+ }
+
+ return (
+ <section className="relative w-full">
+ <ParallaxText baseVelocity={default_velocity} className={className}>
+ {text}
+ </ParallaxText>
+ <ParallaxText baseVelocity={-default_velocity} className={className}>
+ {text}
+ </ParallaxText>
+ </section>
+ );
+}
diff --git a/registry/index.tsx b/registry/index.tsx
index 8cd8d108..0b090de2 100644
--- a/registry/index.tsx
+++ b/registry/index.tsx
@@ -617,6 +617,14 @@ const example: Registry = {
() => import("@/registry/components/example/separate-away-demo"),
),
},
+ "scroll-based-velocity-demo": {
+ name: "scroll-based-velocity-demo",
+ type: "components:example",
+ files: ["registry/components/example/scroll-based-velocity-demo.tsx"],
+ component: React.lazy(
+ () => import("@/registry/components/example/scroll-based-velocity-demo"),
+ ),
+ },
};
export const registry: Registry = {