Try 'magnetic button'
View code

Specification

Catalogue
No. 100 of 110
Interaction
Feedback
Element
Overlay, Form, Toggle
Preview
Live component
Imports
react 19.3.1, framer-motion 12.40.0
Added

Notes

A consent bar that grows into a preferences panel, then folds into a small button once a choice is saved. The visitor can reopen it from that button and change their mind.

One surface changes shape the whole way, so nothing pops in from somewhere else. Reject all sits beside Accept all at the same weight, and the optional categories start off, so refusing is as easy as agreeing.

The surface springs its position, width, height and corner radius together: 0.3s with no bounce when it grows, 0.2s when it shrinks, written as stiffness and damping so a change of mind mid-move keeps its speed. Each face enters from 10px below and a 4px blur over 200ms cubic-bezier(.16, 1, .3, 1) and leaves in 100ms. Opening the panel moves focus to its heading; Escape or the close button shuts it without saving and returns focus to the bar or the button. Every control is at least 44px tall. Faces crossfade without movement under reduced motion.

The category wording is a generic set (strictly necessary, preferences, analytics, marketing); a client's site names its own cookies and links its policy. Nothing is stored in the preview.

Code

React and plain CSS
"use client";

import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { AnimatePresence, animate, motion, useIsPresent, useMotionValue, type Variants } from "framer-motion";
import type { LivePreviewProps } from "@/components/live/types";
import { EASE_ENTER, physicalSpring } from "@/components/pieces/kit/physical-spring";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { useStageMode } from "@/components/pieces/stage/mode";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./cookie-consent.css";

type Mode = "bar" | "panel" | "chip";
type Optional = "preferences" | "analytics" | "marketing";
type Choice = Record<Optional, boolean>;

const OPTIONAL: { id: Optional; label: string; note: string }[] = [
  { id: "preferences", label: "Preferences", note: "Remembers language and text size" },
  { id: "analytics", label: "Analytics", note: "Anonymous visit counts" },
  { id: "marketing", label: "Marketing", note: "Ads and campaign measurement" },
];
const NONE: Choice = { preferences: false, analytics: false, marketing: false };
const ALL: Choice = { preferences: true, analytics: true, marketing: true };

const PANEL_MAX = 380;
const CHIP = 44;
const GROW = physicalSpring(0.3);
const SHRINK = physicalSpring(0.2);

const faces: Variants = {
  hidden: { opacity: 0, y: 10, filter: "blur(4px)" },
  shown: { opacity: 1, y: 0, filter: "blur(0px)", transition: { duration: 0.2, ease: EASE_ENTER, delay: 0.04 } },
  gone: { opacity: 0, y: 4, filter: "blur(4px)", transition: { duration: 0.1 } },
};
const still: Variants = { hidden: { opacity: 0 }, shown: { opacity: 1, transition: { duration: 0 } }, gone: { opacity: 0, transition: { duration: 0 } } };

function summary(choice: Choice | null): string {
  if (!choice) return "No choice made yet";
  const on = OPTIONAL.filter((c) => choice[c.id]).map((c) => c.label);
  if (on.length === 0) return "Saved: optional cookies off";
  if (on.length === OPTIONAL.length) return "Saved: all cookies allowed";
  return `Saved: ${on.join(" and ")} on, the rest off`;
}

/** One face of the surface. It reports its natural height so the surface can spring to it. */
function Face({ mode, width, reduce, onSize, children, ...rest }: { mode: Mode; width: number; reduce: boolean; onSize: (m: Mode, h: number) => void; children: ReactNode; role?: string; "aria-labelledby"?: string; onKeyDown?: (e: KeyboardEvent<HTMLDivElement>) => void }) {
  const ref = useRef<HTMLDivElement>(null);
  // Only the current face reports its height and takes input; a leaving face is inert while it fades.
  const present = useIsPresent();
  useLayoutEffect(() => {
    const el = ref.current;
    if (!el || !present) return;
    const report = () => onSize(mode, el.offsetHeight);
    report();
    const ro = new ResizeObserver(report);
    ro.observe(el);
    return () => ro.disconnect();
  }, [mode, onSize, present]);
  return (
    <motion.div {...rest} ref={ref} className="cc-face" data-face={mode} inert={!present || undefined} style={{ width }} variants={reduce ? still : faces} initial="hidden" animate="shown" exit="gone">
      {children}
    </motion.div>
  );
}

function CookieConsentDemo() {
  const reduce = useSafeReducedMotion();
  const { context } = useStageMode();
  const uid = useId();
  const layer = useRef<HTMLDivElement>(null);
  const [layerW, setLayerW] = useState(0);
  const [heights, setHeights] = useState<Partial<Record<Mode, number>>>({});
  const [saved, setSaved] = useState<Choice | null>(null);
  const [panel, setPanel] = useState(false);
  const [draft, setDraft] = useState<Choice>(NONE);
  // Where focus goes once the next face exists.
  const focusTo = useRef<Mode | null>(null);
  const mode: Mode = panel ? "panel" : saved ? "chip" : "bar";

  const x = useMotionValue(0);
  const w = useMotionValue(0);
  const h = useMotionValue(0);
  const r = useMotionValue(16);

  useLayoutEffect(() => {
    const el = layer.current;
    if (!el) return;
    const read = () => setLayerW(el.clientWidth);
    read();
    const ro = new ResizeObserver(read);
    ro.observe(el);
    return () => ro.disconnect();
  }, []);

  const onSize = useCallback((m: Mode, height: number) => setHeights((prev) => (prev[m] === height ? prev : { ...prev, [m]: height })), []);

  const widths: Record<Mode, number> = { bar: layerW, panel: Math.min(layerW, PANEL_MAX), chip: CHIP };
  // Preferences reopened from the corner button grow out of that corner; the first time they open centred over the bar.
  const panelX = saved ? 0 : (layerW - widths.panel) / 2;
  const target = { x: mode === "panel" ? panelX : 0, w: widths[mode], h: heights[mode] ?? 0, r: mode === "chip" ? CHIP / 2 : 16 };
  const placed = useRef(false);

  useLayoutEffect(() => {
    if (!layerW || !target.h) return;
    if (!placed.current || reduce) {
      placed.current = true;
      x.jump(target.x);
      w.jump(target.w);
      h.jump(target.h);
      r.jump(target.r);
      return;
    }
    const growing = target.w * target.h > w.get() * h.get();
    const t = growing ? GROW : SHRINK;
    const runs = [animate(x, target.x, t), animate(w, target.w, t), animate(h, target.h, t), animate(r, target.r, t)];
    return () => runs.forEach((a) => a.stop());
  }, [layerW, target.x, target.w, target.h, target.r, reduce, x, w, h, r]);

  // Move focus to what the visitor will use next, once that face exists.
  useEffect(() => {
    if (focusTo.current !== mode) return;
    focusTo.current = null;
    const sel = mode === "panel" ? ".cc-title" : mode === "chip" ? ".cc-chip" : ".cc-customize";
    layer.current?.querySelector<HTMLElement>(sel)?.focus({ preventScroll: true });
  }, [mode]);

  const openPanel = () => {
    setDraft(saved ?? NONE);
    focusTo.current = "panel";
    setPanel(true);
  };
  const closePanel = () => {
    focusTo.current = saved ? "chip" : "bar";
    setPanel(false);
  };
  const choose = (next: Choice) => {
    setSaved(next);
    focusTo.current = "chip";
    setPanel(false);
  };
  const onPanelKey = (e: KeyboardEvent<HTMLDivElement>) => {
    if (e.key !== "Escape") return;
    e.stopPropagation();
    closePanel();
  };

  const arrive = context === "detail" && !reduce;

  return (
    <div className="cc">
      <div className="cc-page">
        <p className="cc-status" role="status">
          {summary(saved)}
        </p>
        <p className="cc-note">Nothing is stored in this preview.</p>
        <div ref={layer} className="cc-layer">
          <motion.div
            className="cc-surface"
            data-mode={mode}
            style={{ x, width: w, height: h, borderRadius: r }}
            initial={arrive ? { y: 24, scale: 0.98, opacity: 0 } : false}
            animate={{ y: 0, scale: 1, opacity: 1 }}
            transition={GROW}
          >
            <AnimatePresence initial={false}>
              {mode === "bar" && layerW > 0 && (
                <Face key="bar" mode="bar" width={widths.bar} reduce={reduce} onSize={onSize} role="region" aria-labelledby={`${uid}-msg`}>
                  <p id={`${uid}-msg`} className="cc-msg">
                    This site uses the cookies it needs to work. Optional ones stay off unless you allow them.
                  </p>
                  <div className="cc-actions">
                    <button type="button" className="cc-btn cc-customize" data-variant="ghost" onClick={openPanel}>
                      Customize
                    </button>
                    <span className="cc-gap" />
                    <button type="button" className="cc-btn" onClick={() => choose(NONE)}>
                      Reject all
                    </button>
                    <button type="button" className="cc-btn" onClick={() => choose(ALL)}>
                      Accept all
                    </button>
                  </div>
                </Face>
              )}
              {mode === "panel" && (
                <Face key="panel" mode="panel" width={widths.panel} reduce={reduce} onSize={onSize} role="dialog" aria-labelledby={`${uid}-title`} onKeyDown={onPanelKey}>
                  <div className="cc-head">
                    <h3 id={`${uid}-title`} className="cc-title" tabIndex={-1}>
                      Cookie preferences
                    </h3>
                    <button type="button" className="cc-x" aria-label="Close without saving" onClick={closePanel}>
                      <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
                        <path d="M6 6l12 12M18 6 6 18" />
                      </svg>
                    </button>
                  </div>
                  <ul className="cc-rows">
                    <li className="cc-row" data-fixed>
                      <span className="cc-label">
                        <strong>Strictly necessary</strong>
                        <span>Keeps you signed in and the site secure</span>
                      </span>
                      <span className="cc-always">Always on</span>
                    </li>
                    {OPTIONAL.map((c) => (
                      <li key={c.id}>
                        <button type="button" role="switch" aria-checked={draft[c.id]} className="cc-row cc-switch" onClick={() => setDraft((d) => ({ ...d, [c.id]: !d[c.id] }))}>
                          <span className="cc-label">
                            <strong>{c.label}</strong>
                            <span>{c.note}</span>
                          </span>
                          <span className="cc-track" aria-hidden="true">
                            <span className="cc-thumb" />
                          </span>
                        </button>
                      </li>
                    ))}
                  </ul>
                  <div className="cc-actions" data-panel>
                    <button type="button" className="cc-btn" onClick={() => choose(NONE)}>
                      Reject all
                    </button>
                    <button type="button" className="cc-btn" onClick={() => choose(ALL)}>
                      Accept all
                    </button>
                    <button type="button" className="cc-btn cc-save" data-variant="solid" onClick={() => choose(draft)}>
                      Save choices
                    </button>
                  </div>
                </Face>
              )}
              {mode === "chip" && (
                <Face key="chip" mode="chip" width={CHIP} reduce={reduce} onSize={onSize}>
                  <button type="button" className="cc-chip" aria-label="Cookie preferences" onClick={openPanel}>
                    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" aria-hidden="true">
                      <path d="M4 7h10M18 7h2M4 17h4M12 17h8" />
                      <circle cx="16" cy="7" r="2" />
                      <circle cx="10" cy="17" r="2" />
                    </svg>
                  </button>
                </Face>
              )}
            </AnimatePresence>
          </motion.div>
        </div>
      </div>
    </div>
  );
}

// What a hovered card shows: open the preferences, allow analytics, save, and the panel folds into its button.
const TOUR: Tour = [
  // The bar measures the stage on its first frame; give it that frame before the first click.
  { wait: 300 },
  { click: ".cc-customize", wait: 1200 },
  { click: ".cc-switch", nth: 1, wait: 700 },
  { click: ".cc-save", wait: 1400 },
];

export default function CookieConsentEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Cookie choice that folds away" tour={TOUR} replay>
      <CookieConsentDemo />
    </PieceStage>
  );
}

More like this

Form in named steps

Type, FeedbackForms and inputs

File upload with progress per file

Loading, FeedbackForms and inputs

Header that steps aside

ScrollNavigation

One question at a time

Layout AnimationForms and inputs

Button that shows its own progress

Press, LoadingButtons and toggles

Button that grows into its form

Press, TypeButtons and toggles