| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- import { ChevronLeft, ChevronRight } from 'lucide-react';
- import { useEffect, useState } from 'react';
- import { useStorefront } from '../context';
- import { storefrontText } from '../text';
-
- /** How long each message stays, in milliseconds. */
- const ROTATE_EVERY = 4500;
-
- /**
- * The slim bar above the header: free shipping, running automatic discounts and the merchant's own lines.
- * Several messages take turns. They stop moving while the shopper points at the bar or uses the arrows,
- * and never move for shoppers whose device asks for less motion.
- */
- export function AnnouncementBar() {
- const { shop, language } = useStorefront();
- const t = storefrontText(language);
- const messages = shop.announcements;
- const [index, setIndex] = useState(0);
- const [paused, setPaused] = useState(false);
-
- useEffect(() => {
- const calm = window.matchMedia(
- '(prefers-reduced-motion: reduce)',
- ).matches;
-
- if (messages.length < 2 || paused || calm) {
- return;
- }
-
- const timer = setInterval(
- () => setIndex((current) => (current + 1) % messages.length),
- ROTATE_EVERY,
- );
-
- return () => clearInterval(timer);
- }, [messages.length, paused]);
-
- if (messages.length === 0) {
- return null;
- }
-
- const current = messages[index % messages.length];
- const step = (by: number) => {
- setPaused(true);
- setIndex((value) => (value + by + messages.length) % messages.length);
- };
-
- return (
- <div
- className="bg-(--sf-primary) text-(--sf-primary-fg)"
- data-test="announcement-bar"
- onMouseEnter={() => setPaused(true)}
- onMouseLeave={() => setPaused(false)}
- >
- <div className="mx-auto flex max-w-6xl items-center justify-between gap-2 px-3 py-2 text-center text-xs font-medium sm:text-sm">
- {messages.length > 1 ? (
- <button
- type="button"
- onClick={() => step(-1)}
- aria-label={t.previousMessage}
- className="rounded p-1 opacity-80 hover:opacity-100 focus-visible:outline-2 focus-visible:outline-current"
- >
- <ChevronLeft className="size-4" aria-hidden="true" />
- </button>
- ) : (
- <span className="w-6" aria-hidden="true" />
- )}
- <p key={index} className="sf-fade-in min-w-0 flex-1 truncate">
- {current}
- </p>
- {messages.length > 1 ? (
- <button
- type="button"
- onClick={() => step(1)}
- aria-label={t.nextMessage}
- className="rounded p-1 opacity-80 hover:opacity-100 focus-visible:outline-2 focus-visible:outline-current"
- >
- <ChevronRight className="size-4" aria-hidden="true" />
- </button>
- ) : (
- <span className="w-6" aria-hidden="true" />
- )}
- </div>
- </div>
- );
- }
|