快拍播放器
全屏回顾快拍播放器,带分段进度条、点击翻页、长按暂停,最后两张会出现收尾操作栏;另附四张现成的 9:16 年度回顾幻灯片(最活跃月份、年度关键词、连续发帖、百分位排名),暗色杂志风,只用一个琥珀强调色。
适合使用的场景
- 年度或月度回顾快拍(Wrapped 风格)
- 简短的全屏新手引导或精彩集锦
注意事项
- 最后两张刻意停留 5 倍时间,请把总结内容放在那里
- 两侧箭头位于卡片外,且只在 md 以上显示
交给你的 agent 安装
一次复制就包含安装命令、使用时机、props 与设计规则。粘贴到 Claude Code、Cursor 或 Codex 即可。
用 CLI 安装
使用 shadcn CLI。源码会复制到你的项目中,每一行都由你掌控。
$ npx shadcn@latest add https://sunui.synvize.com/r/story-player.json或手动安装
- 1. 安装依赖。
$ npm install clsx tailwind-merge framer-motion - 2. 如果还没有,在
lib/utils.ts添加cn辅助函数。没有用 shadcn/ui?再加上 sunui-theme.css 提供颜色变量(做法)。然后复制组件代码。story-player.tsx"use client"; import { AnimatePresence, motion, useReducedMotion } from "framer-motion"; import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode, } from "react"; import { cn } from "@/lib/utils"; type Direction = "left" | "right"; export interface StoryAction { key: string; /** The button's title and aria-label */ label: string; icon: ReactNode; onClick: () => void; /** In progress: shows a spinner and disables the whole row of buttons (originally the downloading state) */ loading?: boolean; loadingLabel?: string; /** Shown only on the last slide (originally "View all pets") */ lastOnly?: boolean; } export interface StoryPlayerProps { /** Content of each card; the card itself is a #0f0f0f rounded dark surface */ slides: ReactNode[]; /** Milliseconds each slide stays; the last two are automatically multiplied by 5 */ duration?: number; autoPlay?: boolean; /** Current index in controlled mode */ index?: number; defaultIndex?: number; onIndexChange?: (index: number) => void; onPause?: () => void; onResume?: () => void; /** Bottom dynamic-island buttons shown on the last two slides */ actions?: StoryAction[]; /** Card width (px), originally 480 */ cardWidth?: number; /** When true, fills the whole viewport (originally the fullscreen mode) */ fixed?: boolean; /** UI language: en, zh-TW, zh-CN, ja. Tags such as zh-Hant-HK or ja-JP are also accepted */ locale?: string; /** Override built-in strings; takes precedence over locale */ labels?: Partial<StoryPlayerLabels>; className?: string; } export interface StoryPlayerLabels { region: string; paused: string; prev: string; next: string; slideOf: (n: number, total: number) => string; } export type SunLocale = "en" | "zh-TW" | "zh-CN" | "ja"; /** Map any language tag to one of the four built-in languages; everything else falls back to English (recap-slides.tsx shares this too) */ export 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, StoryPlayerLabels> = { en: { region: "Story", paused: "Paused", prev: "Previous story", next: "Next story", slideOf: (n, total) => `Story ${n} of ${total}`, }, "zh-TW": { region: "限時動態", paused: "已暫停", prev: "上一則", next: "下一則", slideOf: (n, total) => `第 ${n} 則,共 ${total} 則`, }, "zh-CN": { region: "快拍", paused: "已暂停", prev: "上一条", next: "下一条", slideOf: (n, total) => `第 ${n} 条,共 ${total} 条`, }, ja: { region: "ストーリー", paused: "一時停止中", prev: "前のストーリー", next: "次のストーリー", slideOf: (n, total) => `ストーリー ${n}/${total}`, }, }; /** Icon originally used by the dynamic island (heroicons outline) */ export const storyIcons = { download: <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />, share: ( <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" /> ), replay: ( <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /> ), heart: ( <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" /> ), }; export function StoryIcon({ children, className }: { children: ReactNode; className?: string }) { return ( <svg className={cn("h-4 w-4 md:h-[18px] md:w-[18px]", className)} fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"> {children} </svg> ); } const LONG_PRESS_MS = 300; export function StoryPlayer({ slides, duration = 5000, autoPlay = true, index: controlledIndex, defaultIndex = 0, onIndexChange, onPause, onResume, actions = [], cardWidth = 480, fixed = false, locale = "en", labels, className, }: StoryPlayerProps) { const t = { ...MESSAGES[resolveLocale(locale)], ...labels }; const reduce = useReducedMotion() ?? false; const total = slides.length; const [innerIndex, setInnerIndex] = useState(defaultIndex); const currentIndex = controlledIndex ?? innerIndex; const [isPaused, setIsPaused] = useState(false); const [isLongPressing, setIsLongPressing] = useState(false); const [progress, setProgress] = useState(0); const directionRef = useRef<Direction>("left"); const pendingDirectionRef = useRef<Direction | null>(null); const prevIndexRef = useRef(currentIndex); const longPressTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null); const suppressClickRef = useRef(false); const elapsedRef = useRef(0); const setIndex = useCallback( (next: number) => { if (controlledIndex === undefined) setInnerIndex(next); onIndexChange?.(next); }, [controlledIndex, onIndexChange], ); const goNext = useCallback(() => { if (currentIndex >= total - 1) return; pendingDirectionRef.current = "left"; directionRef.current = "left"; setIndex(currentIndex + 1); }, [currentIndex, total, setIndex]); const goPrev = useCallback(() => { if (currentIndex <= 0) return; pendingDirectionRef.current = "right"; directionRef.current = "right"; setIndex(currentIndex - 1); }, [currentIndex, setIndex]); // When the index changes, decide the slide direction and reset progress synchronously (before paint, to avoid flicker) useLayoutEffect(() => { if (prevIndexRef.current === currentIndex) return; directionRef.current = pendingDirectionRef.current ?? (currentIndex > prevIndexRef.current ? "left" : "right"); pendingDirectionRef.current = null; prevIndexRef.current = currentIndex; elapsedRef.current = 0; setProgress(0); }, [currentIndex]); // The last two slides are five times slower const actualDuration = currentIndex >= total - 2 ? duration * 5 : duration; // The progress bar and auto-advance share one rAF loop const goNextRef = useRef(goNext); goNextRef.current = goNext; useEffect(() => { if (isPaused) return; let start = Date.now() - elapsedRef.current; let raf = 0; const animate = () => { const elapsed = Date.now() - start; elapsedRef.current = elapsed; const p = Math.min((elapsed / actualDuration) * 100, 100); setProgress(p); if (p < 100) { raf = requestAnimationFrame(animate); } else if (autoPlay && currentIndex < total - 1) { start = Date.now(); goNextRef.current(); } }; raf = requestAnimationFrame(animate); return () => cancelAnimationFrame(raf); }, [currentIndex, isPaused, actualDuration, autoPlay, total]); // Long press for 300ms pauses, release resumes const handleLongPressStart = useCallback(() => { suppressClickRef.current = false; longPressTimerRef.current = setTimeout(() => { suppressClickRef.current = true; setIsLongPressing(true); setIsPaused(true); onPause?.(); }, LONG_PRESS_MS); }, [onPause]); const handleLongPressEnd = useCallback(() => { if (longPressTimerRef.current) { clearTimeout(longPressTimerRef.current); longPressTimerRef.current = null; } if (isLongPressing) { setIsLongPressing(false); setIsPaused(false); onResume?.(); } }, [isLongPressing, onResume]); useEffect( () => () => { if (longPressTimerRef.current) clearTimeout(longPressTimerRef.current); }, [], ); // The tap area changes page on the next frame, so the direction is updated first const tap = (dir: Direction) => () => { if (suppressClickRef.current) { suppressClickRef.current = false; return; } requestAnimationFrame(() => (dir === "left" ? goNextRef.current() : goPrevRef.current())); }; const goPrevRef = useRef(goPrev); goPrevRef.current = goPrev; function onKeyDown(e: KeyboardEvent<HTMLDivElement>) { if (e.key === "ArrowRight") goNext(); else if (e.key === "ArrowLeft") goPrev(); else if (e.key === " " && e.target === e.currentTarget) { setIsPaused((p) => { if (p) onResume?.(); else onPause?.(); return !p; }); } else return; e.preventDefault(); } const isEnd = currentIndex >= total - 2; const busy = actions.some((a) => a.loading); const visibleActions = actions.filter((a) => !a.lastOnly || currentIndex === total - 1); const dir = directionRef.current; const cardStyle: CSSProperties = fixed ? { width: "100%", height: "calc(100vh - 120px)", maxHeight: 800 } : { width: "100%", aspectRatio: "3 / 5", maxHeight: 800 }; const pulse = reduce ? { duration: 0 } : ({ delay: 0.5, duration: 0.24 } as const); return ( <div role="region" aria-roledescription="story" aria-label={t.region} tabIndex={0} onKeyDown={onKeyDown} className={cn( "overflow-hidden bg-black text-white outline-none select-none focus-visible:ring-2 focus-visible:ring-white/60", fixed ? "fixed inset-0 h-screen w-screen" : "relative w-full", className, )} style={{ touchAction: "pan-x pan-y" }} > <div className="relative flex h-full w-full items-center justify-center p-4 md:p-8"> <div className="relative flex w-full flex-col items-center"> {/* Progress bar, above the card */} <div className="z-50 mb-2 px-3 md:mb-3" style={{ width: `min(${cardWidth}px, 100%)` }} aria-hidden="true"> <div className="pointer-events-none relative flex w-full gap-[2px]"> {slides.map((_, i) => { const p = i < currentIndex ? 100 : i === currentIndex ? progress : 0; return ( <div key={i} className="relative h-[3px] min-w-0 flex-1 overflow-hidden rounded-[1.5px] bg-white/40"> <div className="absolute top-0 left-0 h-full w-full origin-left rounded-[1.5px] bg-white will-change-transform" style={{ transform: `scaleX(${p / 100})`, transition: "transform 0.05s linear" }} /> </div> ); })} </div> </div> {/* Card with left and right hint arrows */} <div className="relative" style={{ width: fixed ? `min(${cardWidth}px, calc(100vw - 32px))` : `min(${cardWidth}px, 100%)` }}> <AnimatePresence mode="wait" initial={false} custom={dir}> <motion.div key={currentIndex} custom={dir} variants={{ enter: (d: Direction) => ({ opacity: 0, scale: reduce ? 1 : 0.95, x: reduce ? 0 : d === "left" ? 100 : -100 }), center: { opacity: 1, scale: 1, x: 0 }, exit: (d: Direction) => ({ opacity: 0, scale: reduce ? 1 : 0.95, x: reduce ? 0 : d === "left" ? -100 : 100 }), }} initial="enter" animate="center" exit="exit" transition={{ duration: reduce ? 0 : 0.3, ease: "easeInOut" }} className="relative z-10 shrink-0 overflow-hidden rounded-xl border border-white/[0.08] bg-[#0f0f0f] shadow-[0_8px_24px_rgba(0,0,0,0.5)]" style={{ ...cardStyle, touchAction: "pan-y" }} onPointerDown={handleLongPressStart} onPointerUp={handleLongPressEnd} onPointerCancel={handleLongPressEnd} onContextMenu={(e) => e.preventDefault()} > {/* Left third: previous slide */} {currentIndex > 0 && <div aria-hidden="true" className="absolute top-0 bottom-0 left-0 z-40 w-1/3 cursor-pointer" onClick={tap("right")} />} {/* Right third: next slide */} {currentIndex < total - 1 && ( <div aria-hidden="true" className="absolute top-0 right-0 bottom-0 z-40 w-1/3 cursor-pointer" onClick={tap("left")} /> )} {slides[currentIndex]} </motion.div> </AnimatePresence> {/* Right hint arrow (falls outside the screen on narrow screens, so shown only from md up) */} {currentIndex < total - 1 && ( <motion.button type="button" aria-label={t.next} className="absolute top-1/2 left-full z-20 hidden -translate-y-1/2 cursor-pointer md:block" initial={{ opacity: 0, x: reduce ? 0 : -5 }} animate={{ opacity: 1, x: 0 }} transition={pulse} onClick={(e) => { e.stopPropagation(); requestAnimationFrame(() => goNextRef.current()); }} > <ArrowBubble d="M9 5l7 7-7 7" /> </motion.button> )} {currentIndex > 0 && ( <motion.button type="button" aria-label={t.prev} className="absolute top-1/2 right-full z-20 hidden -translate-y-1/2 cursor-pointer md:block" initial={{ opacity: 0, x: reduce ? 0 : 5 }} animate={{ opacity: 1, x: 0 }} transition={pulse} onClick={(e) => { e.stopPropagation(); requestAnimationFrame(() => goPrevRef.current()); }} > <ArrowBubble d="M15 19l-7-7 7-7" /> </motion.button> )} </div> </div> </div> {isPaused && ( <div className="pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-black/20"> <div className="flex items-center gap-2 text-lg text-white"> <svg viewBox="0 0 24 24" className="h-5 w-5" fill="currentColor" aria-hidden="true"> <path d="M7 5h3v14H7zM14 5h3v14h-3z" /> </svg> {t.paused} </div> </div> )} {/* Bottom dynamic island: appears on the last two slides */} {isEnd && visibleActions.length > 0 && ( <div className={cn("pointer-events-auto bottom-1 left-0 right-0 z-[100] flex justify-center", fixed ? "fixed" : "absolute")}> <motion.div initial={reduce ? { opacity: 0 } : { opacity: 0, y: 20, scale: 0.9 }} animate={{ opacity: 1, y: 0, scale: 1 }} transition={{ delay: reduce ? 0 : 0.7, duration: reduce ? 0 : 0.4 }} > <div className="rounded-full border border-white/10 bg-[#161616]/95 px-3 py-2 shadow-sm md:px-4 md:py-2.5"> <div className="flex flex-row items-center justify-center gap-2 md:gap-2.5"> {visibleActions.map((a, i) => { const label = a.loading ? (a.loadingLabel ?? a.label) : a.label; return ( <motion.button key={a.key} type="button" initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 }} animate={{ opacity: 1, scale: 1 }} transition={{ delay: reduce ? 0 : 0.85 + i * 0.05, duration: reduce ? 0 : 0.3 }} onClick={a.onClick} disabled={busy} title={label} aria-label={label} aria-busy={a.loading || undefined} className={cn( "flex h-9 w-9 items-center justify-center rounded-full transition-all outline-none focus-visible:ring-2 focus-visible:ring-white/70 md:h-10 md:w-10", a.loading ? "cursor-not-allowed bg-white/20 text-white/50" : "bg-white/10 text-white hover:bg-white/20 active:scale-90 disabled:cursor-not-allowed disabled:opacity-50", )} > {a.loading ? ( <span className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white motion-reduce:animate-none" /> ) : ( <StoryIcon>{a.icon}</StoryIcon> )} </motion.button> ); })} </div> </div> </motion.div> </div> )} <span className="sr-only" aria-live="polite"> {t.slideOf(currentIndex + 1, total)} </span> </div> ); } function ArrowBubble({ d }: { d: string }) { return ( <span className="flex h-10 w-10 items-center justify-center rounded-full border border-white/15 bg-white/[0.06] transition-colors hover:bg-white/15 md:h-12 md:w-12"> <svg className="h-5 w-5 text-white md:h-6 md:w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={d} /> </svg> </span> ); }recap-slides.tsx"use client"; import { motion, useReducedMotion, type Transition } from "framer-motion"; import { useMemo, type CSSProperties, type ReactNode } from "react"; import { cn } from "@/lib/utils"; import { resolveLocale, type SunLocale } from "./story-player"; /* ------------------------------------------------------------------ */ /* Shared: dark editorial palette, easing and frame */ /* ------------------------------------------------------------------ */ /** Dark palette for the year-in-review slides (showcase series). accent is only a default; every component can override it with the accent prop. */ export const recapPalette = { base: "#0a0a0a", surface: "#141414", line: "rgb(255 255 255 / 0.08)", text: "#f5f5f5", soft: "#d4d4d4", muted: "#a3a3a3", accent: "#7aa2ff", } as const; const EASE = [0.23, 1, 0.32, 1] as const; /** In reduced motion, make all transitions 0 seconds */ function useRecapTransition() { const reduce = useReducedMotion() ?? false; return (t: Transition): Transition => (reduce ? { duration: 0 } : t); } export interface RecapFrameProps { /** Small heading at the top, with a thin line below it */ title: ReactNode; /** One line at the bottom, with a thin line above it */ footer?: ReactNode; /** The single accent colour, written into the --recap-accent variable */ accent?: string; className?: string; style?: CSSProperties; /** Middle content; add flex-1 yourself so it fills the space */ children: ReactNode; } /** * Shared frame of the four recap slides: #0a0a0a background, a small heading on top, one line below, and a single fade-in overall. * Use it directly when building your own cover or closing slide, so the layout matches the others. */ export function RecapFrame({ title, footer, accent = recapPalette.accent, className, style, children }: RecapFrameProps) { const tr = useRecapTransition(); return ( <div className={cn("@container relative flex h-full w-full flex-col overflow-hidden p-6 @md:p-8", className)} style={{ backgroundColor: recapPalette.base, color: recapPalette.text, ["--recap-accent" as string]: accent, ...style }} > <motion.div className="flex h-full min-h-0 flex-col" initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} transition={tr({ duration: 0.5, ease: EASE })} > <h2 className="border-b pb-3 text-[11px] font-medium uppercase tracking-[0.16em]" style={{ borderColor: recapPalette.line, color: recapPalette.muted }} > {title} </h2> {children} {footer != null && ( <div className="border-t pt-4" style={{ borderColor: recapPalette.line }}> {footer} </div> )} </motion.div> </div> ); } function FooterLine({ children, tone = recapPalette.soft }: { children: ReactNode; tone?: string }) { return ( <p className="text-[15px] leading-relaxed @md:text-base" style={{ color: tone }}> {children} </p> ); } /** Shared props: accent colour, language, class */ interface RecapBaseProps { /** The single accent colour, default the SunUI cobalt (dark) #7aa2ff */ accent?: string; /** UI language: en, zh-TW, zh-CN, ja. Tags such as zh-Hant-HK or ja-JP are also accepted */ locale?: string; className?: string; } /* ------------------------------------------------------------------ */ /* Most active month */ /* ------------------------------------------------------------------ */ export interface RecapMonthData { /** 0 to 11 */ monthIndex: number; /** Post count for that month */ count: number; /** Fallback name when monthNames has no match */ month?: string; } export interface RecapMonthLabels { title: string; posts: string; comments: { low: string; medium: string; high: string }; } const zhMonths = ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]; const MONTH_MESSAGES: Record<SunLocale, RecapMonthLabels & { months: string[] }> = { en: { title: "Most Active Month", posts: "posts", comments: { low: "You were quieter this month", medium: "You were very active this month", high: "You were super active this month!", }, months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], }, "zh-TW": { title: "最活躍的月份", posts: "則貼文", comments: { low: "這個月你比較安靜", medium: "這個月你非常活躍", high: "這個月你超級活躍!" }, months: zhMonths, }, "zh-CN": { title: "最活跃的月份", posts: "条动态", comments: { low: "这个月你比较安静", medium: "这个月你非常活跃", high: "这个月你超级活跃!" }, months: zhMonths, }, ja: { title: "いちばん活発だった月", posts: "件の投稿", comments: { low: "今月はちょっと静かでした", medium: "今月はとても活発でした", high: "今月は大活躍でした!" }, months: Array.from({ length: 12 }, (_, i) => `${i + 1}月`), }, }; /** English month names (exported for backward compatibility) */ export const recapMonthNames = MONTH_MESSAGES.en.months; /** English default strings (exported for backward compatibility) */ export const recapMonthLabels: RecapMonthLabels = { title: MONTH_MESSAGES.en.title, posts: MONTH_MESSAGES.en.posts, comments: MONTH_MESSAGES.en.comments, }; export interface RecapActiveMonthProps extends RecapBaseProps { data: RecapMonthData; /** 12 month names, by locale by default */ monthNames?: string[]; /** Override built-in strings; takes precedence over locale */ labels?: Partial<Omit<RecapMonthLabels, "comments">> & { comments?: Partial<RecapMonthLabels["comments"]> }; } const allMonths = Array.from({ length: 12 }, (_, i) => i); /** * "Most active month": the month name and post count in a large serif face, with a 12-cell month bar below marking which month in the accent colour. */ export function RecapActiveMonth({ data, monthNames: monthNamesProp, accent = recapPalette.accent, locale = "en", labels, className }: RecapActiveMonthProps) { const base = MONTH_MESSAGES[resolveLocale(locale)]; const l = { ...base, ...labels, comments: { ...base.comments, ...labels?.comments } }; const monthNames = monthNamesProp ?? base.months; const monthData = data ?? { month: "", monthIndex: 0, count: 0 }; const monthName = monthNames[monthData.monthIndex] || monthData.month || monthNames[0] || base.months[0]; // Pick the comment based on the post count const comment = monthData.count < 5 ? l.comments.low : monthData.count < 15 ? l.comments.medium : l.comments.high; return ( <RecapFrame title={l.title} accent={accent} className={className} footer={<FooterLine>{comment}</FooterLine>}> <div className="flex flex-1 flex-col justify-center"> <div className="font-serif text-5xl leading-[1.02] tracking-[-0.02em] break-words @md:text-6xl">{monthName}</div> <div className="mt-5 flex items-baseline gap-2.5"> <span className="font-serif text-6xl leading-none tabular-nums lining-nums @md:text-7xl">{monthData.count}</span> <span className="text-base @md:text-lg" style={{ color: recapPalette.muted }}> {l.posts} </span> </div> <div className="mt-3 h-px w-12" style={{ background: accent }} /> {/* 12-cell month bar: the current month in the accent colour */} <div aria-hidden className="mt-10 grid grid-cols-12 gap-1"> {allMonths.map((i) => ( <div key={i} className="h-6 rounded-[2px]" style={{ background: i === monthData.monthIndex ? accent : recapPalette.line }} /> ))} </div> </div> </RecapFrame> ); } /* ------------------------------------------------------------------ */ /* Yearly keywords */ /* ------------------------------------------------------------------ */ export interface RecapKeyword { word: string; count: number; } export interface RecapKeywordCloudLabels { title: string; } const KEYWORD_MESSAGES: Record<SunLocale, RecapKeywordCloudLabels> = { en: { title: "Top Keywords" }, "zh-TW": { title: "年度關鍵字" }, "zh-CN": { title: "年度关键词" }, ja: { title: "よく使ったキーワード" }, }; /** English default strings, keeping the old export name */ export const recapKeywordLabels: RecapKeywordCloudLabels = KEYWORD_MESSAGES.en; export interface RecapKeywordCloudProps extends RecapBaseProps { /** Keywords and occurrence counts, ideally sorted from most to least frequent */ keywords: RecapKeyword[]; /** Override built-in strings; takes precedence over locale */ labels?: Partial<RecapKeywordCloudLabels>; } // Compute font size from frequency (@md is a container width breakpoint) function keywordSize(ratio: number) { if (ratio > 0.8) return "text-5xl @md:text-6xl"; if (ratio > 0.6) return "text-4xl @md:text-5xl"; if (ratio > 0.4) return "text-3xl @md:text-4xl"; if (ratio > 0.2) return "text-2xl @md:text-3xl"; return "text-xl @md:text-2xl"; } // The fewer the occurrences, the lighter the word: only shades of one warm grey, and only the most frequent words use the accent colour function keywordTone(ratio: number) { if (ratio > 0.6) return recapPalette.text; if (ratio > 0.3) return recapPalette.soft; return recapPalette.muted; } /** * "Yearly keywords": serif words sized by occurrence run together as a paragraph, like a magazine pull quote; an accent underline appears when the mouse is over a word. */ export function RecapKeywordCloud({ keywords, accent = recapPalette.accent, locale = "en", labels, className }: RecapKeywordCloudProps) { const l = { ...KEYWORD_MESSAGES[resolveLocale(locale)], ...labels }; const maxCount = Math.max(1, ...keywords.map((k) => k.count)); return ( <RecapFrame title={l.title} accent={accent} className={className}> <ul className="m-0 flex flex-1 flex-wrap content-center items-baseline gap-x-4 gap-y-2 p-0 @md:gap-x-5"> {keywords.map((keyword) => { const ratio = keyword.count / maxCount; return ( <li key={keyword.word} className={cn( "cursor-default list-none font-serif leading-[1.1] tracking-[-0.01em] underline-offset-[6px] decoration-1 transition-[text-decoration-color] duration-200 hover:underline hover:decoration-[var(--recap-accent)]", keywordSize(ratio), )} style={{ color: keyword.count === maxCount ? accent : keywordTone(ratio) }} > {keyword.word} <sup className="ml-1 align-super font-sans text-[11px] font-medium tabular-nums @md:text-xs" style={{ color: recapPalette.muted }}> {keyword.count} </sup> </li> ); })} </ul> </RecapFrame> ); } /* ------------------------------------------------------------------ */ /* Percentile rank */ /* ------------------------------------------------------------------ */ export type RecapRankLevel = "top01" | "top1" | "top5" | "top10" | "top25" | "top50" | "unknown"; export interface RecapPercentileLabels { title: string; subtitle: string; noData: string; /** What the large text shows when there is no rank data */ notAvailable: string; levels: Record<RecapRankLevel, string>; } const PERCENTILE_MESSAGES: Record<SunLocale, RecapPercentileLabels> = { en: { title: "Percentile Rank", subtitle: "Top", noData: "Ranking data requires comparison with other users to calculate", notAvailable: "N/A", levels: { top01: "Top 0.1% Creator", top1: "Top 1% Creator", top5: "Top 5% Creator", top10: "Top 10% Creator", top25: "Top 25% Creator", top50: "Top 50% Creator", unknown: "Calculating Rank", }, }, "zh-TW": { title: "百分位排名", subtitle: "頂尖", noData: "排名需要與其他使用者比較後才能計算", notAvailable: "無", levels: { top01: "前 0.1% 創作者", top1: "前 1% 創作者", top5: "前 5% 創作者", top10: "前 10% 創作者", top25: "前 25% 創作者", top50: "前 50% 創作者", unknown: "排名計算中", }, }, "zh-CN": { title: "百分位排名", subtitle: "顶尖", noData: "排名需要与其他用户比较后才能计算", notAvailable: "无", levels: { top01: "前 0.1% 创作者", top1: "前 1% 创作者", top5: "前 5% 创作者", top10: "前 10% 创作者", top25: "前 25% 创作者", top50: "前 50% 创作者", unknown: "排名计算中", }, }, ja: { title: "パーセンタイル順位", subtitle: "上位", noData: "ランキングの算出には、ほかのユーザーとの比較データが必要です", notAvailable: "なし", levels: { top01: "上位 0.1% のクリエイター", top1: "上位 1% のクリエイター", top5: "上位 5% のクリエイター", top10: "上位 10% のクリエイター", top25: "上位 25% のクリエイター", top50: "上位 50% のクリエイター", unknown: "順位を計算中", }, }, }; /** English default strings, keeping the old export name */ export const recapPercentileLabels = PERCENTILE_MESSAGES.en; export interface RecapPercentileRingProps extends RecapBaseProps { /** Rank percentage (lower is better); null means no comparable data */ percentileRank: number | null; /** Override built-in strings; takes precedence over locale */ labels?: Partial<Omit<RecapPercentileLabels, "levels">> & { levels?: Partial<Record<RecapRankLevel, string>> }; } /** Format the rank percentage for display */ export function formatPercentile(rank: number | null): string { if (rank === null || rank === undefined) return "N/A"; if (rank < 0.01) return "0.01"; // Minimum displayed is 0.01% if (rank < 1) return rank.toFixed(2); // Below 1%: two decimals if (rank < 10) return rank.toFixed(1); // 1 to 10%: one decimal return Math.round(rank).toString(); // Above 10%: whole number } /** * Get the tier from the rank percentage. * color and glow are fields kept for the old API; the component no longer uses them and always returns neutral values. */ export function getRankLevel(rank: number | null): { level: RecapRankLevel; color: string; glow: string } { const neutral = { color: "from-neutral-400 to-neutral-300", glow: "transparent" }; if (rank === null || rank === undefined) return { level: "unknown", ...neutral }; if (rank <= 0.1) return { level: "top01", ...neutral }; if (rank <= 1) return { level: "top1", ...neutral }; if (rank <= 5) return { level: "top5", ...neutral }; if (rank <= 10) return { level: "top10", ...neutral }; if (rank <= 25) return { level: "top25", ...neutral }; return { level: "top50", ...neutral }; } /** * "Percentile rank": 100 tick dots in a ring, filled with 100 minus the rank; a large serif number sits in the centre. */ export function RecapPercentileRing({ percentileRank, accent = recapPalette.accent, locale = "en", labels, className }: RecapPercentileRingProps) { const base = PERCENTILE_MESSAGES[resolveLocale(locale)]; const l = { ...base, ...labels, levels: { ...base.levels, ...labels?.levels } }; const rank = percentileRank ?? null; const displayValue = formatPercentile(rank); const rankLevel = getRankLevel(rank); // Generate the circular tick dots (a lower rank percentage is better, so use 100 - rank) const progressDots = useMemo(() => { const totalDots = 100; const activeDots = rank !== null ? Math.round(100 - rank) : 0; return Array.from({ length: totalDots }, (_, i) => ({ id: i, angle: (i / totalDots) * 360, isActive: i < activeDots })); }, [rank]); const footer = rank !== null ? ( <p className="flex items-center gap-2 text-[15px] font-medium @md:text-base" style={{ color: recapPalette.text }}> <span aria-hidden className="size-1.5 shrink-0 rounded-full" style={{ background: accent }} /> {l.levels[rankLevel.level]} </p> ) : ( <FooterLine tone={recapPalette.muted}>{l.noData}</FooterLine> ); return ( <RecapFrame title={l.title} accent={accent} className={className} footer={footer}> <div className="relative flex flex-1 items-center justify-center"> {/* Tick ring */} <svg aria-hidden className="absolute aspect-square w-full max-w-[22rem]" viewBox="0 0 200 200" style={{ transform: "rotate(-90deg)" }}> {progressDots.map((dot) => { const radian = (dot.angle * Math.PI) / 180; return ( <circle key={dot.id} cx={100 + Math.cos(radian) * 88} cy={100 + Math.sin(radian) * 88} r={dot.isActive ? 1.6 : 1} fill={dot.isActive ? accent : "rgb(255 255 255 / 0.16)"} /> ); })} </svg> <div className="relative text-center"> {rank !== null && ( <div className="mb-1 text-sm font-medium uppercase tracking-[0.14em]" style={{ color: recapPalette.muted }}> {l.subtitle} </div> )} <div className="font-serif text-7xl leading-none tracking-[-0.03em] tabular-nums lining-nums @md:text-8xl"> {rank !== null ? ( <> {displayValue} <span className="ml-0.5 align-top text-[0.45em]" style={{ color: recapPalette.muted }}> % </span> </> ) : ( l.notAvailable )} </div> </div> </div> </RecapFrame> ); } /* ------------------------------------------------------------------ */ /* Consecutive posting */ /* ------------------------------------------------------------------ */ export interface RecapStreakLabels { title: string; subtitle: string; /** Day unit; pass a function to handle singular and plural by day count */ days: string | ((n: number) => string); comments: { low: string; medium: string; high: string; veryHigh: string }; } const STREAK_MESSAGES: Record<SunLocale, RecapStreakLabels> = { en: { title: "Posting Streak", subtitle: "Your longest streak was", days: (n) => (n === 1 ? "day" : "days"), comments: { low: "You like to post casually", medium: "You have a habit of posting regularly", high: "You are a persistent creator!", veryHigh: "You are a super persistent creator!", }, }, "zh-TW": { title: "連續發文", subtitle: "你最長的連續紀錄是", days: "天", comments: { low: "你喜歡隨興發文", medium: "你有固定發文的習慣", high: "你是一位堅持不懈的創作者!", veryHigh: "你是超級堅持的創作者!" }, }, "zh-CN": { title: "连续发帖", subtitle: "你最长的连续纪录是", days: "天", comments: { low: "你喜欢随性发帖", medium: "你有定期发帖的习惯", high: "你是一位坚持不懈的创作者!", veryHigh: "你是超级坚持的创作者!" }, }, ja: { title: "連続投稿", subtitle: "最長の連続記録は", days: "日", comments: { low: "気ままに投稿するタイプです", medium: "定期的に投稿する習慣があります", high: "粘り強いクリエイターです!", veryHigh: "超粘り強いクリエイターです!", }, }, }; /** English default strings (kept under the old export name) */ export const recapStreakLabels = STREAK_MESSAGES.en; export interface RecapStreakFlameProps extends RecapBaseProps { /** Longest streak of consecutive posting days */ streak: number; /** Override built-in strings; takes precedence over locale */ labels?: Partial<Omit<RecapStreakLabels, "comments">> & { comments?: Partial<RecapStreakLabels["comments"]> }; } /** Day cells: 28 cells over four weeks; if exceeded, all are filled */ const GRID_DAYS = 28; /** * "Consecutive posting": a large serif number plus a four-week day grid, with consecutive days filled in the accent colour; the number fades in as a replacement when the days change. */ export function RecapStreakFlame({ streak: streakProp, accent = recapPalette.accent, locale = "en", labels, className }: RecapStreakFlameProps) { const tr = useRecapTransition(); const base = STREAK_MESSAGES[resolveLocale(locale)]; const l = { ...base, ...labels, comments: { ...base.comments, ...labels?.comments } }; const streak = streakProp ?? 0; const days = typeof l.days === "function" ? l.days(streak) : l.days; // Pick the comment based on the streak length const comment = streak < 3 ? l.comments.low : streak < 7 ? l.comments.medium : streak < 14 ? l.comments.high : l.comments.veryHigh; return ( <RecapFrame title={l.title} accent={accent} className={className} footer={<FooterLine>{comment}</FooterLine>}> <div className="flex flex-1 flex-col justify-center"> <p className="text-[15px] @md:text-base" style={{ color: recapPalette.muted }}> {l.subtitle} </p> <div className="mt-2 flex items-baseline gap-3"> <motion.span key={streak} initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={tr({ duration: 0.3, ease: EASE })} className="font-serif text-8xl leading-none tracking-[-0.03em] tabular-nums lining-nums @md:text-9xl" > {streak} </motion.span> <span className="text-xl @md:text-2xl" style={{ color: recapPalette.soft }}> {days} </span> </div> {/* Four-week day grid: consecutive days fill in order */} <div aria-hidden className="mt-8 grid grid-cols-7 gap-1.5"> {Array.from({ length: GRID_DAYS }, (_, i) => ( <div key={i} className="aspect-square rounded-[3px]" style={{ background: i < streak ? accent : recapPalette.line }} /> ))} </div> </div> </RecapFrame> ); }





