Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
jsx 384 lines 9.63 KB
Raw
1 "use client";
2
3 import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
4 import "./logo-loop.css";
5
6 const ANIMATION_CONFIG = { SMOOTH_TAU: 0.25, MIN_COPIES: 2, COPY_HEADROOM: 2 };
7
8 const toCssLength = (value) =>
9 typeof value === "number" ? `${value}px` : (value ?? undefined);
10
11 const useResizeObserver = (callback, elements, dependencies) => {
12 useEffect(() => {
13 if (!window.ResizeObserver) {
14 const handleResize = () => callback();
15 window.addEventListener("resize", handleResize);
16 callback();
17 return () => window.removeEventListener("resize", handleResize);
18 }
19 const observers = elements.map((ref) => {
20 if (!ref.current) return null;
21 const observer = new ResizeObserver(callback);
22 observer.observe(ref.current);
23 return observer;
24 });
25 callback();
26 return () => {
27 observers.forEach((observer) => observer?.disconnect());
28 };
29 }, [callback, elements, dependencies]);
30 };
31
32 const useImageLoader = (seqRef, onLoad, dependencies) => {
33 useEffect(() => {
34 const images = seqRef.current?.querySelectorAll("img") ?? [];
35 if (images.length === 0) {
36 onLoad();
37 return;
38 }
39 let remainingImages = images.length;
40 const handleImageLoad = () => {
41 remainingImages -= 1;
42 if (remainingImages === 0) onLoad();
43 };
44 images.forEach((img) => {
45 const htmlImg = img;
46 if (htmlImg.complete) {
47 handleImageLoad();
48 } else {
49 htmlImg.addEventListener("load", handleImageLoad, { once: true });
50 htmlImg.addEventListener("error", handleImageLoad, { once: true });
51 }
52 });
53 return () => {
54 images.forEach((img) => {
55 img.removeEventListener("load", handleImageLoad);
56 img.removeEventListener("error", handleImageLoad);
57 });
58 };
59 }, [onLoad, seqRef, dependencies]);
60 };
61
62 const useAnimationLoop = (
63 trackRef,
64 targetVelocity,
65 seqWidth,
66 seqHeight,
67 isHovered,
68 hoverSpeed,
69 isVertical,
70 ) => {
71 const rafRef = useRef(null);
72 const lastTimestampRef = useRef(null);
73 const offsetRef = useRef(0);
74 const velocityRef = useRef(0);
75
76 useEffect(() => {
77 const track = trackRef.current;
78 if (!track) return;
79
80 const seqSize = isVertical ? seqHeight : seqWidth;
81
82 if (seqSize > 0) {
83 offsetRef.current = ((offsetRef.current % seqSize) + seqSize) % seqSize;
84 const transformValue = isVertical
85 ? `translate3d(0, ${-offsetRef.current}px, 0)`
86 : `translate3d(${-offsetRef.current}px, 0, 0)`;
87 track.style.transform = transformValue;
88 }
89
90 const animate = (timestamp) => {
91 if (lastTimestampRef.current === null) {
92 lastTimestampRef.current = timestamp;
93 }
94
95 const deltaTime =
96 Math.max(0, timestamp - lastTimestampRef.current) / 1000;
97 lastTimestampRef.current = timestamp;
98
99 const target =
100 isHovered && hoverSpeed !== undefined ? hoverSpeed : targetVelocity;
101
102 const easingFactor =
103 1 - Math.exp(-deltaTime / ANIMATION_CONFIG.SMOOTH_TAU);
104 velocityRef.current += (target - velocityRef.current) * easingFactor;
105
106 if (seqSize > 0) {
107 let nextOffset = offsetRef.current + velocityRef.current * deltaTime;
108 nextOffset = ((nextOffset % seqSize) + seqSize) % seqSize;
109 offsetRef.current = nextOffset;
110
111 const transformValue = isVertical
112 ? `translate3d(0, ${-offsetRef.current}px, 0)`
113 : `translate3d(${-offsetRef.current}px, 0, 0)`;
114 track.style.transform = transformValue;
115 }
116
117 rafRef.current = requestAnimationFrame(animate);
118 };
119
120 rafRef.current = requestAnimationFrame(animate);
121
122 return () => {
123 if (rafRef.current !== null) {
124 cancelAnimationFrame(rafRef.current);
125 rafRef.current = null;
126 }
127 lastTimestampRef.current = null;
128 };
129 }, [
130 targetVelocity,
131 seqWidth,
132 seqHeight,
133 isHovered,
134 hoverSpeed,
135 isVertical,
136 trackRef,
137 ]);
138 };
139
140 export const LogoLoop = memo(
141 ({
142 logos,
143 speed = 120,
144 direction = "left",
145 width = "100%",
146 logoHeight = 28,
147 gap = 32,
148 pauseOnHover,
149 hoverSpeed,
150 fadeOut = false,
151 fadeOutColor,
152 scaleOnHover = false,
153 renderItem,
154 ariaLabel = "Partner logos",
155 className,
156 style,
157 }) => {
158 const containerRef = useRef(null);
159 const trackRef = useRef(null);
160 const seqRef = useRef(null);
161
162 const [seqWidth, setSeqWidth] = useState(0);
163 const [seqHeight, setSeqHeight] = useState(0);
164 const [copyCount, setCopyCount] = useState(ANIMATION_CONFIG.MIN_COPIES);
165 const [isHovered, setIsHovered] = useState(false);
166
167 const effectiveHoverSpeed = useMemo(() => {
168 if (hoverSpeed !== undefined) return hoverSpeed;
169 if (pauseOnHover === true) return 0;
170 if (pauseOnHover === false) return undefined;
171 return 0;
172 }, [hoverSpeed, pauseOnHover]);
173
174 const isVertical = direction === "up" || direction === "down";
175
176 const targetVelocity = useMemo(() => {
177 const magnitude = Math.abs(speed);
178 let directionMultiplier;
179 if (isVertical) {
180 directionMultiplier = direction === "up" ? 1 : -1;
181 } else {
182 directionMultiplier = direction === "left" ? 1 : -1;
183 }
184 const speedMultiplier = speed < 0 ? -1 : 1;
185 return magnitude * directionMultiplier * speedMultiplier;
186 }, [speed, direction, isVertical]);
187
188 const updateDimensions = useCallback(() => {
189 const containerWidth = containerRef.current?.clientWidth ?? 0;
190 const sequenceRect = seqRef.current?.getBoundingClientRect?.();
191 const sequenceWidth = sequenceRect?.width ?? 0;
192 const sequenceHeight = sequenceRect?.height ?? 0;
193 if (isVertical) {
194 const parentHeight =
195 containerRef.current?.parentElement?.clientHeight ?? 0;
196 if (containerRef.current && parentHeight > 0) {
197 const targetHeight = Math.ceil(parentHeight);
198 if (containerRef.current.style.height !== `${targetHeight}px`)
199 containerRef.current.style.height = `${targetHeight}px`;
200 }
201 if (sequenceHeight > 0) {
202 setSeqHeight(Math.ceil(sequenceHeight));
203 const viewport =
204 containerRef.current?.clientHeight ??
205 parentHeight ??
206 sequenceHeight;
207 const copiesNeeded =
208 Math.ceil(viewport / sequenceHeight) +
209 ANIMATION_CONFIG.COPY_HEADROOM;
210 setCopyCount(Math.max(ANIMATION_CONFIG.MIN_COPIES, copiesNeeded));
211 }
212 } else if (sequenceWidth > 0) {
213 setSeqWidth(Math.ceil(sequenceWidth));
214 const copiesNeeded =
215 Math.ceil(containerWidth / sequenceWidth) +
216 ANIMATION_CONFIG.COPY_HEADROOM;
217 setCopyCount(Math.max(ANIMATION_CONFIG.MIN_COPIES, copiesNeeded));
218 }
219 }, [isVertical]);
220
221 useResizeObserver(
222 updateDimensions,
223 [containerRef, seqRef],
224 [logos, gap, logoHeight, isVertical],
225 );
226
227 useImageLoader(seqRef, updateDimensions, [
228 logos,
229 gap,
230 logoHeight,
231 isVertical,
232 ]);
233
234 useAnimationLoop(
235 trackRef,
236 targetVelocity,
237 seqWidth,
238 seqHeight,
239 isHovered,
240 effectiveHoverSpeed,
241 isVertical,
242 );
243
244 const cssVariables = useMemo(
245 () => ({
246 "--logoloop-gap": `${gap}px`,
247 "--logoloop-logoHeight": `${logoHeight}px`,
248 ...(fadeOutColor && { "--logoloop-fadeColor": fadeOutColor }),
249 }),
250 [gap, logoHeight, fadeOutColor],
251 );
252
253 const rootClassName = useMemo(
254 () =>
255 [
256 "logoloop",
257 isVertical ? "logoloop--vertical" : "logoloop--horizontal",
258 fadeOut && "logoloop--fade",
259 scaleOnHover && "logoloop--scale-hover",
260 className,
261 ]
262 .filter(Boolean)
263 .join(" "),
264 [isVertical, fadeOut, scaleOnHover, className],
265 );
266
267 const handleMouseEnter = useCallback(() => {
268 if (effectiveHoverSpeed !== undefined) setIsHovered(true);
269 }, [effectiveHoverSpeed]);
270 const handleMouseLeave = useCallback(() => {
271 if (effectiveHoverSpeed !== undefined) setIsHovered(false);
272 }, [effectiveHoverSpeed]);
273
274 const renderLogoItem = useCallback(
275 (item, key) => {
276 if (renderItem) {
277 return (
278 <li className="logoloop__item" key={key} role="listitem">
279 {renderItem(item, key)}
280 </li>
281 );
282 }
283 const isNodeItem = "node" in item;
284 const content = isNodeItem ? (
285 <span
286 aria-hidden={!!item.href && !item.ariaLabel}
287 className="logoloop__node"
288 >
289 {item.node}
290 </span>
291 ) : (
292 <img
293 alt={item.alt ?? ""}
294 decoding="async"
295 draggable={false}
296 height={item.height}
297 loading="lazy"
298 sizes={item.sizes}
299 src={item.src}
300 srcSet={item.srcSet}
301 title={item.title}
302 width={item.width}
303 />
304 );
305 const itemAriaLabel = isNodeItem
306 ? (item.ariaLabel ?? item.title)
307 : (item.alt ?? item.title);
308 const itemContent = item.href ? (
309 <a
310 aria-label={itemAriaLabel || "logo link"}
311 className="logoloop__link"
312 href={item.href}
313 rel="noreferrer noopener"
314 target="_blank"
315 >
316 {content}
317 </a>
318 ) : (
319 content
320 );
321 return (
322 <li className="logoloop__item" key={key} role="listitem">
323 {itemContent}
324 </li>
325 );
326 },
327 [renderItem],
328 );
329
330 const logoLists = useMemo(
331 () =>
332 Array.from({ length: copyCount }, (_, copyIndex) => (
333 <ul
334 aria-hidden={copyIndex > 0}
335 className="logoloop__list"
336 key={`copy-${copyIndex}`}
337 ref={copyIndex === 0 ? seqRef : undefined}
338 role="list"
339 >
340 {logos.map((item, itemIndex) =>
341 renderLogoItem(item, `${copyIndex}-${itemIndex}`),
342 )}
343 </ul>
344 )),
345 [copyCount, logos, renderLogoItem],
346 );
347
348 const containerStyle = useMemo(
349 () => ({
350 width: isVertical
351 ? toCssLength(width) === "100%"
352 ? undefined
353 : toCssLength(width)
354 : (toCssLength(width) ?? "100%"),
355 ...cssVariables,
356 ...style,
357 }),
358 [width, cssVariables, style, isVertical],
359 );
360
361 return (
362 <div
363 aria-label={ariaLabel}
364 className={rootClassName}
365 ref={containerRef}
366 role="region"
367 style={containerStyle}
368 >
369 <div
370 className="logoloop__track"
371 onMouseEnter={handleMouseEnter}
372 onMouseLeave={handleMouseLeave}
373 ref={trackRef}
374 >
375 {logoLists}
376 </div>
377 </div>
378 );
379 },
380 );
381
382 LogoLoop.displayName = "LogoLoop";
383
384 export default LogoLoop;