|
| 1 | +import React, { useState, useEffect } from 'react'; |
| 2 | +import styles from './styles.module.scss'; |
| 3 | +import clsx from 'clsx'; |
| 4 | +import Icon from '@site/src/components/Icon'; |
| 5 | + |
| 6 | +const NewsTicker = ({ newsItems, interval = 5000 }) => { |
| 7 | + const [currentIndex, setCurrentIndex] = useState(0); |
| 8 | + const [isFading, setIsFading] = useState(false); |
| 9 | + const [isPaused, setIsPaused] = useState(false); |
| 10 | + |
| 11 | + const handleNavigation = (newIndex) => { |
| 12 | + const isWrapping = |
| 13 | + (currentIndex === newsItems.length - 1 && newIndex === 0) || |
| 14 | + (currentIndex === 0 && newIndex === newsItems.length - 1); |
| 15 | + |
| 16 | + if (isWrapping) { |
| 17 | + setIsFading(true); |
| 18 | + setTimeout(() => { |
| 19 | + setCurrentIndex(newIndex); |
| 20 | + setIsFading(false); |
| 21 | + }, 250); // Half of the fade animation duration |
| 22 | + } else { |
| 23 | + setCurrentIndex(newIndex); |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + // Auto-rotation effect |
| 28 | + useEffect(() => { |
| 29 | + if (isPaused || newsItems.length <= 1) { |
| 30 | + return; // Do nothing if paused or not enough items |
| 31 | + } |
| 32 | + |
| 33 | + const timer = setInterval(() => { |
| 34 | + handleNavigation((currentIndex + 1) % newsItems.length); |
| 35 | + }, interval); |
| 36 | + |
| 37 | + return () => clearInterval(timer); |
| 38 | + }, [isPaused, currentIndex, newsItems, interval]); |
| 39 | + |
| 40 | + if (!newsItems || newsItems.length === 0) { |
| 41 | + return null; |
| 42 | + } |
| 43 | + |
| 44 | + return ( |
| 45 | + <div |
| 46 | + className={clsx(styles.newsTicker, 'news-ticker-container', isFading && styles.isFading)} |
| 47 | + onMouseEnter={() => setIsPaused(true)} |
| 48 | + onMouseLeave={() => setIsPaused(false)} |
| 49 | + > |
| 50 | + <div className={styles.contentViewport}> |
| 51 | + <div className={styles.filmStrip} style={{ transform: `translateX(-${currentIndex * 100}%)` }}> |
| 52 | + {newsItems.map((item, index) => ( |
| 53 | + <div key={index} className={styles.newsItem}> |
| 54 | + <a href={item.link} target="_blank" rel="noopener noreferrer"> |
| 55 | + {item.icon && <Icon name={item.icon} classes="ph-fill" />} |
| 56 | + <span>{item.text}</span> |
| 57 | + </a> |
| 58 | + </div> |
| 59 | + ))} |
| 60 | + </div> |
| 61 | + </div> |
| 62 | + |
| 63 | + {newsItems.length > 1 && ( |
| 64 | + <div className={styles.dotsContainer}> |
| 65 | + {newsItems.map((_, index) => ( |
| 66 | + <button |
| 67 | + key={index} |
| 68 | + className={clsx(styles.dot, { [styles.active]: currentIndex === index })} |
| 69 | + onClick={() => handleNavigation(index)} |
| 70 | + aria-label={`Go to news item ${index + 1}`} |
| 71 | + /> |
| 72 | + ))} |
| 73 | + </div> |
| 74 | + )} |
| 75 | + </div> |
| 76 | + ); |
| 77 | +}; |
| 78 | + |
| 79 | +export default NewsTicker; |
0 commit comments