SunUI
創始會員NT$2,490 終身更新,1月11日截止取得席位
免費點按

公告列

放在商店頂端的公告列,主題表面上下各一條細線,多則訊息可手動切換上一則與下一則;關閉時高度收起,並可用 storageKey 記住。

適合使用的時機

  • 免運門檻、節慶退貨或營業時間這類全站公告
  • 在一條公告列裡輪替兩三則短訊息,且不自動播放

注意事項

  • 設定 storageKey 時公告列在掛載後才渲染,所以不要預留空間,或接受些微位移;訊息更換時記得改 key
  • 手機上每則訊息盡量控制在一行,文字太長會換行讓公告列變高

交給你的 agent 安裝

一次複製就包含安裝指令、使用時機、props 與設計規則。貼進 Claude Code、Cursor 或 Codex 即可。

用 CLI 安裝

使用 shadcn CLI。原始碼會複製到你的專案裡,每一行都由你掌握。

$ npx shadcn@latest add https://sunui.synvize.com/r/announcement-strip.json

或手動安裝

  1. 1. 安裝相依套件。
    $ npm install clsx tailwind-merge framer-motion
  2. 2. 如果還沒有,在 lib/utils.ts 加上 cn 輔助函式。沒有用 shadcn/ui?再加上 sunui-theme.css 提供顏色變數(做法)。然後複製元件程式碼。
    announcement-strip.tsx
    "use client";
    
    import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
    import { useEffect, useState, type ReactNode } from "react";
    
    import { cn } from "@/lib/utils";
    
    export interface Announcement {
      id: string;
      content: ReactNode;
      /** Optional link, for example a campaign page */
      href?: string;
      linkLabel?: ReactNode;
    }
    
    export interface AnnouncementStripLabels {
      region?: string;
      eyebrow?: ReactNode;
      previous?: string;
      next?: string;
      dismiss?: string;
      more?: ReactNode;
      position?: (current: number, total: number) => string;
    }
    
    export interface AnnouncementStripProps {
      messages: Announcement[];
      /** When set, remembers "dismissed" in localStorage. Change the key (for example append -v2) to show the strip again with new content */
      storageKey?: string;
      dismissible?: boolean;
      onDismiss?: () => void;
      /** UI language: en, zh-TW, zh-CN, ja. Tags like ja-JP are also accepted */
      locale?: string;
      /** Overrides built-in strings, takes precedence over locale */
      labels?: AnnouncementStripLabels;
      className?: string;
    }
    
    type SunLocale = "en" | "zh-TW" | "zh-CN" | "ja";
    
    /** Maps any language tag to one of the four built-in languages, falling back to English */
    function resolveLocale(tag?: string): SunLocale {
      const t = (tag ?? "en").toLowerCase();
      if (t.startsWith("zh")) return /hant|tw|hk|mo/.test(t) ? "zh-TW" : "zh-CN";
      if (t.startsWith("ja")) return "ja";
      return "en";
    }
    
    const MESSAGES: Record<SunLocale, Required<AnnouncementStripLabels>> = {
      en: {
        region: "Store announcements",
        eyebrow: "Notice",
        previous: "Previous announcement",
        next: "Next announcement",
        dismiss: "Dismiss announcements",
        more: "Learn more",
        position: (current, total) => `${current} of ${total}`,
      },
      "zh-TW": {
        region: "商店公告",
        eyebrow: "公告",
        previous: "上一則公告",
        next: "下一則公告",
        dismiss: "關閉公告",
        more: "了解更多",
        position: (current, total) => `第 ${current} 則,共 ${total} 則`,
      },
      "zh-CN": {
        region: "商店公告",
        eyebrow: "公告",
        previous: "上一条公告",
        next: "下一条公告",
        dismiss: "关闭公告",
        more: "了解更多",
        position: (current, total) => `第 ${current} 条,共 ${total} 条`,
      },
      ja: {
        region: "ストアからのお知らせ",
        eyebrow: "お知らせ",
        previous: "前のお知らせ",
        next: "次のお知らせ",
        dismiss: "お知らせを閉じる",
        more: "詳しく見る",
        position: (current, total) => `${total}件中${current}件目`,
      },
    };
    
    // Design language (DESIGN.md, craft quality): surface, hairline, text colors, brand accent
    const surface = "bg-card shadow-[0_1px_2px_rgb(0_0_0/0.05),0_4px_12px_-6px_rgb(0_0_0/0.06)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]";
    const edge = "border-foreground/10";
    const ink = "text-foreground";
    const inkMuted = "text-muted-foreground";
    const vermilion = "text-foreground";
    
    const springs = {
      snappy: { type: "spring", stiffness: 520, damping: 34 },
      gentle: { type: "spring", stiffness: 240, damping: 30 },
    } as const;
    
    
    function readDismissed(key: string) {
      try {
        return window.localStorage.getItem(key) === "dismissed";
      } catch {
        return false;
      }
    }
    
    export function AnnouncementStrip({ messages, storageKey, dismissible = true, onDismiss, locale = "en", labels, className }: AnnouncementStripProps) {
      const t = { ...MESSAGES[resolveLocale(locale)], ...labels };
      const reduce = useReducedMotion() ?? false;
      // With a storageKey, whether it was dismissed is only known after mount. Render nothing until then so dismissed visitors do not see a flash
      const [visible, setVisible] = useState(!storageKey);
      const [index, setIndex] = useState(0);
      const [dir, setDir] = useState(1);
    
      useEffect(() => {
        if (storageKey) setVisible(!readDismissed(storageKey));
      }, [storageKey]);
    
      const total = messages.length;
      const current = messages[Math.min(index, total - 1)];
    
      function go(step: number) {
        setDir(step);
        setIndex((i) => (i + step + total) % total);
      }
    
      function dismiss() {
        setVisible(false);
        if (storageKey) {
          try {
            window.localStorage.setItem(storageKey, "dismissed");
          } catch {
            // In private mode or with storage disabled, dismiss for this visit only
          }
        }
        onDismiss?.();
      }
    
      const iconButton =
        "grid size-8 shrink-0 place-items-center rounded-md hover:bg-current/5 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none";
    
      return (
        <AnimatePresence initial={false}>
          {visible && current && (
            <motion.section
              key="strip"
              aria-label={t.region}
              initial={false}
              animate={{ height: "auto" }}
              exit={reduce ? { height: 0, transition: { duration: 0 } } : { height: 0 }}
              transition={springs.gentle}
              className={cn("w-full overflow-hidden font-sans", ink, className)}
            >
              <div className={cn("flex min-h-11 items-center gap-2 border-y px-3 py-1.5 text-sm sm:px-5", surface, edge)}>
                <span className={cn("hidden shrink-0 text-[11px] font-semibold tracking-[0.14em] uppercase sm:inline", vermilion)}>{t.eyebrow}</span>
                <span aria-hidden="true" className={cn("hidden h-4 shrink-0 border-l sm:block", edge)} />
    
                {total > 1 && (
                  <motion.button type="button" aria-label={t.previous} onClick={() => go(-1)} whileTap={reduce ? undefined : { x: -2 }} transition={springs.snappy} className={iconButton}>
                    <Chevron dir="left" />
                  </motion.button>
                )}
    
                <div className="relative min-w-0 flex-1 overflow-hidden" aria-live="polite" aria-atomic="true">
                  <AnimatePresence mode="popLayout" initial={false}>
                    <motion.p
                      key={current.id}
                      initial={reduce ? false : { x: dir * 16, opacity: 0 }}
                      animate={{ x: 0, opacity: 1 }}
                      exit={reduce ? { opacity: 0, transition: { duration: 0 } } : { x: dir * -16, opacity: 0, transition: { duration: 0.12 } }}
                      transition={springs.snappy}
                      className="text-center leading-5 text-pretty"
                    >
                      <span className="sr-only">{total > 1 ? `${t.position(index + 1, total)}: ` : ""}</span>
                      {current.content}
                      {current.href && (
                        <a href={current.href} className="ml-2 font-medium whitespace-nowrap underline decoration-1 underline-offset-4 hover:decoration-2 focus-visible:rounded-sm focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
                          {current.linkLabel ?? t.more}
                        </a>
                      )}
                    </motion.p>
                  </AnimatePresence>
                </div>
    
                {total > 1 && (
                  <>
                    <span aria-hidden="true" className={cn("hidden shrink-0 font-mono text-[11px] tracking-[0.12em] tabular-nums sm:inline", inkMuted)}>
                      {index + 1}/{total}
                    </span>
                    <motion.button type="button" aria-label={t.next} onClick={() => go(1)} whileTap={reduce ? undefined : { x: 2 }} transition={springs.snappy} className={iconButton}>
                      <Chevron dir="right" />
                    </motion.button>
                  </>
                )}
    
                {dismissible && (
                  <button type="button" aria-label={t.dismiss} onClick={dismiss} className={cn(iconButton, "-mr-1 motion-safe:active:scale-[0.97] transition-[color,background-color,border-color,opacity,scale]")}>
                    <CloseIcon />
                  </button>
                )}
              </div>
            </motion.section>
          )}
        </AnimatePresence>
      );
    }
    
    function Chevron({ dir }: { dir: "left" | "right" }) {
      return (
        <svg aria-hidden="true" viewBox="0 0 24 24" className="size-4" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
          <path d={dir === "left" ? "M14.5 6l-6 6 6 6" : "M9.5 6l6 6-6 6"} />
        </svg>
      );
    }
    
    function CloseIcon() {
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" className="size-4">
          <path d="M6.5 6.5l11 11M17.5 6.5l-11 11" />
        </svg>
      );
    }