RendyUI English

组件 / Testimonial wall

Testimonial wall

营销 · React / TypeScript Free

录制演示

Testimonial wall 实现预览

源码

testimonial-wall.tsx
/**
 * Testimonial wall - original UI Stacks free component, MIT licensed.
 * Source: public page https://uistacks.dev/components/testimonial-wall (code block reproduced verbatim, unmodified).
 * Upstream project: https://github.com/nazmijavier/uistacks
 */
"use client";

import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
import { useReducedMotion } from "motion/react";
import { Pause, Play } from "lucide-react";

export interface WallQuote {
  /** The words only; the card adds the curly quotes. Keep it to two or three lines. */
  quote: string;
  name: string;
  /** Job title, e.g. "Design lead". */
  role?: string;
  /** Company name as plain text. */
  company?: string;
}

export interface TestimonialWallProps {
  quotes: WallQuote[];
  /** Columns; by default 3 on wide containers, 2 from 440 px, 1 below. */
  columns?: number;
  /** Visible height of the wall in px. Default 520. Give each column enough quotes to fill it. */
  height?: number;
  /** Drift speed in px per second. Default 18. Columns run a little faster or slower and alternate direction. */
  speed?: number;
  /** Holds the wall still (also under reduced motion). */
  paused?: boolean;
  /** The small pause and play button in the corner. Default true. */
  showControl?: boolean;
  /** An accessible name for the wall. Default "What customers say". */
  "aria-label"?: string;
  className?: string;
}

const noSubscribe = () => () => {};
const GAP = 16;
// Each column drifts at its own pace and alternates direction, so the wall never moves as one sheet.
const PACE = [1, 0.8, 1.15, 0.9];
const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-[var(--select)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface)]";

function Card({ q }: { q: WallQuote }) {
  const meta = [q.role, q.company].filter(Boolean).join(", ");
  return (
    <figure className="flex flex-col gap-4 rounded-[20px] bg-surface p-5 shadow-[var(--shadow-card)]">
      <blockquote className="text-pretty text-[14px] leading-[22px] tracking-[-0.006em] text-fg">
        {/* The opening quote hangs into the padding so every line starts on the same edge. */}
        <p className="-indent-[0.435em]">“{q.quote}”</p>
      </blockquote>
      <figcaption className="flex items-center gap-3">
        <span aria-hidden className="grid size-9 shrink-0 place-items-center rounded-full bg-muted text-[14px] font-medium text-fg-muted">
          {q.name.trim().charAt(0).toUpperCase()}
        </span>
        <span className="flex min-w-0 flex-col">
          <span className="truncate text-[13px] font-medium leading-5 text-fg">{q.name}</span>
          {meta && <span className="text-pretty text-[12px] leading-4 text-fg-muted">{meta}</span>}
        </span>
      </figcaption>
    </figure>
  );
}

/**
 * A masonry wall of short customer quotes in columns that drift slowly, each at its own pace and in alternating
 * directions, looping without a seam. Pointing at the wall or focusing inside it eases the drift to a stop, and the
 * corner button pauses it for good. Reduced motion shows a still wall.
 */
export function TestimonialWall({
  quotes,
  columns,
  height = 520,
  speed = 18,
  paused = false,
  showControl = true,
  "aria-label": label = "What customers say",
  className = "",
}: TestimonialWallProps) {
  const prefers = useReducedMotion();
  const mounted = useSyncExternalStore(noSubscribe, () => true, () => false);
  const reduce = mounted && Boolean(prefers);
  const root = useRef<HTMLDivElement>(null);
  const [auto, setAuto] = useState(3);
  const [stopped, setStopped] = useState(false);
  const hold = useRef(false);
  const stop = useRef(false);
  const off = useRef<number[]>([]);
  const tracks = useRef<(HTMLDivElement | null)[]>([]);
  const copies = useRef<(HTMLDivElement | null)[]>([]);

  const count = Math.max(1, columns ?? auto);
  const still = paused || reduce;
  const cols = Array.from({ length: count }, (_, c) => quotes.filter((_, i) => i % count === c));

  useEffect(() => {
    stop.current = stopped;
  }, [stopped]);

  // Columns follow the wall's own width, not the window.
  useLayoutEffect(() => {
    const el = root.current;
    if (!el || columns) return;
    const ro = new ResizeObserver(([e]) => {
      const w = e.contentRect.width;
      setAuto(w < 440 ? 1 : w < 760 ? 2 : 3);
    });
    ro.observe(el);
    return () => ro.disconnect();
  }, [columns]);

  // One rAF loop for every column, started in the effect and cancelled in cleanup, so a Strict Mode remount never
  // leaves a second loop running. Offsets live in a ref; the drift eases to a stop while held or paused by the button.
  useEffect(() => {
    const els = tracks.current.slice(0, count);
    if (still) {
      els.forEach((t) => t && (t.style.transform = ""));
      return;
    }
    const o = off.current;
    let factor = stop.current ? 0 : 1;
    let last = performance.now();
    let raf = 0;
    const tick = (now: number) => {
      const dt = Math.min(0.05, (now - last) / 1000);
      last = now;
      factor += ((hold.current || stop.current ? 0 : 1) - factor) * Math.min(1, dt * 5);
      els.forEach((t, i) => {
        const copy = copies.current[i];
        if (!t || !copy) return;
        const period = copy.offsetHeight + GAP;
        o[i] = ((o[i] ?? 0) + speed * PACE[i % PACE.length] * factor * dt) % period;
        const y = i % 2 === 0 ? -o[i] : o[i] - period;
        t.style.transform = `translate3d(0, ${y.toFixed(2)}px, 0)`;
      });
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [still, count, speed]);

  return (
    <section
      ref={root}
      aria-label={label}
      onPointerEnter={() => (hold.current = true)}
      onPointerLeave={() => (hold.current = false)}
      onFocus={() => (hold.current = true)}
      onBlur={(e) => {
        if (!e.currentTarget.contains(e.relatedTarget as Node | null)) hold.current = false;
      }}
      className={`relative w-full ${className}`}
    >
      <div
        className="flex gap-4 overflow-hidden px-3 [mask-image:linear-gradient(to_bottom,transparent,#000_56px,#000_calc(100%-56px),transparent)]"
        style={{ height }}
      >
        {cols.map((list, c) => (
          <div key={c} className="min-w-0 flex-1">
            <div
              ref={(el) => {
                tracks.current[c] = el;
              }}
              className="flex flex-col gap-4 py-4 will-change-transform"
            >
              <div
                ref={(el) => {
                  copies.current[c] = el;
                }}
                className="flex flex-col gap-4"
              >
                {list.map((q, i) => (
                  <Card key={i} q={q} />
                ))}
              </div>
              {/* The second copy closes the loop; screen readers and Tab skip it. */}
              <div aria-hidden inert className="flex flex-col gap-4">
                {list.map((q, i) => (
                  <Card key={i} q={q} />
                ))}
              </div>
            </div>
          </div>
        ))}
      </div>
      {showControl && !paused && !reduce && (
        <button
          type="button"
          aria-pressed={stopped}
          aria-label={stopped ? "Play the wall" : "Pause the wall"}
          onClick={() => setStopped((s) => !s)}
          className={`absolute bottom-3 right-4 isolate grid size-9 place-items-center rounded-full bg-surface text-fg shadow-[var(--shadow-btn-secondary)] transition-transform active:scale-[0.92] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-full before:bg-fg before:opacity-0 before:transition-opacity hover:before:opacity-[0.04] active:before:opacity-[0.08] dark:bg-raised ${focusRing}`}
        >
          {stopped ? <Play size={16} strokeWidth={1.5} aria-hidden /> : <Pause size={16} strokeWidth={1.5} aria-hidden />}
        </button>
      )}
    </section>
  );
}

使用说明

把 TSX 加入 React 项目,并安装组件引用的依赖。页面样式依赖 Tailwind CSS 与 主题变量。

包依赖 · lucide-react、motion、react

参数

名称类型说明
`quotes``{ quote; name; role?; company? }[]`Dealt into the columns in order. Each card shows a one-letter avatar.
`columns``number`Fixed column count. By default 3, 2 from 440 px and 1 below, from the wall's own width.
`height``number`Visible height in px. Default 520.
`speed``number`Drift in px per second. Default 18; each column runs a little faster or slower.
`paused``boolean`Holds the wall still (also under reduced motion).
`showControl``boolean`The pause and play button in the corner. Default true.