RendyUI 中文

Components / Sticky signup

Sticky signup

Marketing · React / TypeScript Free

Recorded demo

Sticky signup preview

Source

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

import { useEffect, useId, useRef, useState, type FormEvent, type RefObject } from "react";
import { AnimatePresence, motion, useAnimationControls, useReducedMotion } from "motion/react";
import { Check, Loader2, X } from "lucide-react";

export interface StickySignupProps {
  /** Bold line on the left (hidden when the pill is narrow). */
  title?: string;
  /** Line under the title. */
  description?: string;
  placeholder?: string;
  buttonLabel?: string;
  /** The joined state's heading and line. */
  joinedTitle?: string;
  joinedDescription?: string;
  /** Called with the address once it passes the format check. A promise keeps the button busy until it settles; a
   *  rejection shows its message. Without it the pill waits a moment and succeeds (handy for previews). */
  onJoin?: (email: string) => Promise<unknown> | void;
  /** The pill slides up once this element (your hero form) has scrolled out above the top. Without it the pill
   *  shows from the start. */
  showAfter?: RefObject<Element | null>;
  /** The pill tucks away while this element (a final sign-up section, the footer) is on screen. */
  hideNear?: RefObject<Element | null>;
  /** The scroll container to watch. Default the window. */
  root?: RefObject<Element | null>;
  /** "fixed" to the viewport (default) or "absolute" to the bottom of a positioned parent (previews, app panes). */
  position?: "fixed" | "absolute";
  /** Controlled visibility; overrides the scroll logic. */
  open?: boolean;
  /** How long the joined state stays before the pill tucks away for good, in ms. Default 4000. */
  joinedFor?: number;
  className?: string;
}

type Status = "idle" | "sending" | "joined" | "dismissed";

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
// A little overshoot on the way up, then it settles (the owner's "bouncy" feel).
const slide = { type: "spring", stiffness: 380, damping: 24, mass: 0.9 } as const;
const swap = { type: "spring", stiffness: 520, damping: 34 } as const;
const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-[var(--select)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--surface)]";
const btn =
  "relative isolate inline-flex h-11 shrink-0 items-center justify-center gap-1.5 whitespace-nowrap rounded-full px-5 text-[15px] font-medium leading-5 transition-transform active:scale-[0.97] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-full before:opacity-0 before:transition-opacity";
const primary = `${btn} bg-[image:var(--grad-primary)] text-[var(--inverse-fg)] shadow-[var(--shadow-btn-primary)] before:bg-[var(--inverse-fg)] hover:before:opacity-[0.08] active:before:opacity-[0.14] disabled:cursor-default ${focusRing}`;

/**
 * A floating email pill pinned to the bottom of the page. It slides up on a spring once the hero form has scrolled
 * away, tucks back down near the final sign-up section or footer, and never moves while someone is typing in it.
 * Join checks the address, shows a busy state, then a joined state that tucks the pill away for good.
 */
export function StickySignup({
  title = "Get early access",
  description = "One email when your invite is ready.",
  placeholder = "you@company.com",
  buttonLabel = "Join",
  joinedTitle = "You're on the list",
  joinedDescription = "We'll email you when your invite is ready.",
  onJoin,
  showAfter,
  hideNear,
  root,
  position = "fixed",
  open,
  joinedFor = 4000,
  className = "",
}: StickySignupProps) {
  const reduce = useReducedMotion();
  const id = useId();
  const box = useRef<HTMLDivElement>(null);
  const input = useRef<HTMLInputElement>(null);
  const shake = useAnimationControls();
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");
  const [status, setStatus] = useState<Status>("idle");
  const [inView, setInView] = useState(!showAfter);
  const [hasFocus, setHasFocus] = useState(false);

  // Scroll logic: past the hero form and not yet near the end.
  useEffect(() => {
    if (open !== undefined) return;
    const scroller: Element | Window = root?.current ?? window;
    const measure = () => {
      const r = root?.current?.getBoundingClientRect() ?? { top: 0, bottom: window.innerHeight };
      const start = showAfter?.current?.getBoundingClientRect();
      const end = hideNear?.current?.getBoundingClientRect();
      const past = start ? start.bottom < r.top : true;
      const near = end ? end.top < r.bottom : false;
      setInView(past && !near);
    };
    measure();
    scroller.addEventListener("scroll", measure, { passive: true });
    window.addEventListener("resize", measure);
    return () => {
      scroller.removeEventListener("scroll", measure);
      window.removeEventListener("resize", measure);
    };
  }, [open, root, showAfter, hideNear]);

  // The joined state stays a moment, then the pill tucks away for good.
  useEffect(() => {
    if (status !== "joined") return;
    const t = window.setTimeout(() => setStatus("dismissed"), joinedFor);
    return () => window.clearTimeout(t);
  }, [status, joinedFor]);

  const wanted = status === "dismissed" ? false : status === "joined" ? true : (open ?? inView);
  // Never pull the field away from someone typing in it.
  const shown = wanted || (hasFocus && status !== "dismissed");

  const fail = (text: string) => {
    setError(text);
    input.current?.focus();
    if (!reduce) shake.start({ x: [0, -7, 6, -4, 2, 0], transition: { duration: 0.38, ease: "easeOut" } });
  };

  const submit = async (e: FormEvent) => {
    e.preventDefault();
    if (status === "sending") return;
    const value = email.trim();
    if (!value) return fail("Enter your email address.");
    if (!EMAIL.test(value)) return fail("That address looks incomplete.");
    setError("");
    setStatus("sending");
    try {
      await (onJoin ? onJoin(value) : new Promise((r) => setTimeout(r, 1000)));
      setStatus("joined");
      requestAnimationFrame(() => box.current?.querySelector<HTMLElement>("[data-joined]")?.focus({ preventScroll: true }));
    } catch (err) {
      setStatus("idle");
      fail(err instanceof Error && err.message ? err.message : "We couldn't add you. Try again in a moment.");
    }
  };

  return (
    <motion.div
      ref={box}
      initial={false}
      animate={reduce ? { opacity: shown ? 1 : 0 } : { y: shown ? 0 : "calc(100% + 32px)", opacity: shown ? 1 : 0 }}
      transition={reduce ? { duration: 0.2 } : { y: slide, opacity: { duration: 0.25 } }}
      aria-hidden={!shown}
      inert={!shown}
      onFocus={() => setHasFocus(true)}
      onBlur={(e) => {
        if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setHasFocus(false);
      }}
      className={`${position === "fixed" ? "fixed" : "absolute"} inset-x-0 bottom-4 z-40 flex justify-center px-3 @container sm:bottom-6 ${shown ? "" : "pointer-events-none"} ${className}`}
    >
      <div className="pointer-events-auto relative w-full max-w-[720px]">
        <AnimatePresence>
          {error && status === "idle" && (
            <motion.p
              id={`${id}-error`}
              role="alert"
              initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6, scale: 0.96 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={reduce ? { opacity: 0 } : { opacity: 0, y: 4, scale: 0.98 }}
              transition={swap}
              className="absolute bottom-full right-4 mb-2 rounded-full bg-surface px-3 py-1.5 text-[13px] leading-[18px] text-danger shadow-[var(--shadow-card)]"
            >
              {error}
            </motion.p>
          )}
        </AnimatePresence>
        <div className="rounded-full bg-[color-mix(in_srgb,var(--raised)_88%,transparent)] p-2 shadow-[var(--shadow-card),0_12px_32px_-12px_rgb(0_0_0/0.16),0_32px_64px_-24px_rgb(0_0_0/0.14)] backdrop-blur-xl">
          <AnimatePresence mode="popLayout" initial={false}>
            {status === "joined" || status === "dismissed" ? (
              <motion.div
                key="joined"
                initial={reduce ? { opacity: 0 } : { opacity: 0, y: 12, filter: "blur(4px)" }}
                animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
                exit={{ opacity: 0 }}
                transition={swap}
                className="flex min-h-11 items-center gap-3 pl-2"
              >
                <motion.span
                  aria-hidden
                  initial={reduce ? false : { scale: 0.4 }}
                  animate={{ scale: 1 }}
                  transition={{ type: "spring", stiffness: 600, damping: 18, delay: 0.05 }}
                  className="grid size-8 shrink-0 place-items-center rounded-full bg-[image:var(--grad-primary)] text-[var(--inverse-fg)] shadow-[var(--shadow-btn-primary)]"
                >
                  <Check size={16} strokeWidth={2} />
                </motion.span>
                <div data-joined tabIndex={-1} className="min-w-0 flex-1 outline-none">
                  <p className="truncate text-[15px] font-medium leading-5 text-fg">{joinedTitle}</p>
                  <p className="truncate text-[13px] leading-[18px] text-fg-muted">{joinedDescription}</p>
                </div>
                <motion.button
                  type="button"
                  aria-label="Close"
                  onClick={() => setStatus("dismissed")}
                  whileTap={reduce ? undefined : { scale: 0.9 }}
                  className={`relative isolate grid size-11 shrink-0 place-items-center rounded-full bg-surface text-fg shadow-[var(--shadow-btn-secondary)] 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] ${focusRing}`}
                >
                  <X size={20} strokeWidth={1.5} />
                </motion.button>
              </motion.div>
            ) : (
              <motion.form
                key="join"
                noValidate
                onSubmit={submit}
                exit={reduce ? { opacity: 0 } : { opacity: 0, y: -10, filter: "blur(4px)" }}
                transition={swap}
                className="flex items-center gap-3 @[560px]:pl-3"
              >
                <div className="hidden min-w-0 flex-1 @[560px]:block">
                  <p className="truncate text-[15px] font-medium leading-5 text-fg">{title}</p>
                  <p className="truncate text-[13px] leading-[18px] text-fg-muted">{description}</p>
                </div>
                <motion.div animate={shake} className="flex min-w-0 flex-1 items-center gap-2 @[560px]:max-w-[380px]">
                  <label htmlFor={`${id}-email`} className="sr-only">
                    Email address
                  </label>
                  <input
                    ref={input}
                    id={`${id}-email`}
                    type="email"
                    autoComplete="email"
                    inputMode="email"
                    placeholder={placeholder}
                    value={email}
                    disabled={status === "sending"}
                    aria-invalid={error ? true : undefined}
                    aria-describedby={error ? `${id}-error` : undefined}
                    onChange={(e) => {
                      setEmail(e.target.value);
                      if (error) setError("");
                    }}
                    className={`h-11 min-w-0 flex-1 rounded-full bg-subtle px-4 text-[15px] leading-5 text-fg placeholder:text-fg-subtle disabled:opacity-60 ${
                      error ? "shadow-[inset_0_0_0_1px_var(--danger)]" : "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--fg)_8%,transparent)]"
                    } ${focusRing}`}
                  />
                  <motion.button type="submit" disabled={status === "sending"} aria-busy={status === "sending"} whileTap={reduce ? undefined : { scale: 0.94 }} transition={{ type: "spring", stiffness: 600, damping: 26 }} className={primary}>
                    {status === "sending" ? <Loader2 aria-hidden size={16} strokeWidth={2} className="animate-spin" /> : null}
                    {status === "sending" ? "Joining" : buttonLabel}
                  </motion.button>
                </motion.div>
              </motion.form>
            )}
          </AnimatePresence>
        </div>
      </div>
      <p aria-live="polite" className="sr-only">
        {status === "joined" ? `${joinedTitle}. ${joinedDescription}` : ""}
      </p>
    </motion.div>
  );
}

Usage

Add the TSX to your React project and install the required dependencies. Styles use Tailwind CSS and theme tokens。

Package dependencies · lucide-react、motion、react

Props

NameTypeDescription
`showAfter / hideNear``RefObject<Element>`Show once this element (your hero form) is above the top; hide while this one (final section, footer) is on screen.
`root``RefObject<Element>`The scroll container to watch. The window by default.
`position``"fixed" \| "absolute"`Fixed to the viewport (default) or absolute inside a positioned parent.
`open``boolean`Controlled visibility, overrides the scroll logic.
`onJoin``(email) => Promise \| void`A promise keeps Join busy; a rejection shows its message above the pill.
`title / description``string`The text on the left, shown when the pill is at least 560 px wide.
`placeholder / buttonLabel``string`Default you@company.com and Join.
`joinedTitle / joinedDescription / joinedFor``string / string / number`The joined state and how long it stays (4000 ms) before the pill tucks away.