Skip to content

Cookie consent

A banner where Reject looks the same as Accept, and settings to change the answer later.

203 lines · React · Tailwind 4

Install

$ bunx shadcn@latest add @blocco/cookie-consent

Code

blocks/free/cookie-consent.tsx203 lines
import { useEffect, useState } from "react";
import { Button } from "@/registry/blocco/ui/button";
import { Dialog } from "@/registry/blocco/ui/dialog";
import { Switch } from "@/registry/blocco/ui/switch";
import { cn } from "@/registry/blocco/ui/cn";

type Answer = "accepted" | "rejected" | null;

/** A consent switch row: what it is for, and the switch. */
function Choice({
  id,
  title,
  hint,
  checked,
  onChange,
  locked,
}: {
  id: string;
  title: string;
  hint: string;
  checked: boolean;
  onChange?: (on: boolean) => void;
  locked?: boolean;
}) {
  return (
    <div className="flex items-start justify-between gap-4 py-3">
      <div className="min-w-0">
        <p className="text-sm font-medium">{title}</p>
        <p id={id} className="mt-0.5 text-xs text-pretty text-muted">
          {hint}
        </p>
      </div>
      <Switch
        label={title}
        describedBy={id}
        checked={checked}
        disabled={locked}
        onCheckedChange={(on) => onChange?.(on)}
        className="mt-0.5"
      />
    </div>
  );
}

/** The settings behind "Cookie settings": the one cookie that needs no
 * consent, shown on and fixed, and one switch for each that does. */
function CookieSettings({
  open,
  onOpenChange,
  analytics,
  onSave,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  analytics: boolean;
  onSave: (analytics: boolean) => void;
}) {
  const [draft, setDraft] = useState(analytics);
  // Each open starts from the saved answer, not from a draft left behind.
  useEffect(() => {
    if (open) setDraft(analytics);
  }, [open, analytics]);
  return (
    <Dialog open={open} onOpenChange={onOpenChange} title="Cookie settings">
      <div className="flex flex-col gap-4">
        <div className="divide-y divide-border/60">
          <Choice
            id="ck-necessary"
            title="Strictly necessary"
            hint="Keeps you signed in. Needs no consent, so it stays on."
            checked
            locked
          />
          <Choice
            id="ck-analytics"
            title="Analytics"
            hint="Shows us how the product is used, including this visit. Off until you say yes."
            checked={draft}
            onChange={setDraft}
          />
        </div>
        <div className="flex justify-end gap-2">
          <Button variant="ghost" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={() => {
              onSave(draft);
              onOpenChange(false);
            }}
          >
            Save choices
          </Button>
        </div>
      </div>
    </Dialog>
  );
}

/**
 * Analytics stays off (nothing loads, nothing is sent) until the visitor
 * picks Accept. Reject is as easy as Accept and looks the same: a bright
 * Accept beside a muted Reject steers the answer, which regulators treat as
 * invalid consent. "Cookie settings" brings the banner back, so either answer
 * can change later.
 */
export function ConsentBanner({
  onAnswer,
  onSettings,
}: {
  onAnswer: (answer: Exclude<Answer, null>) => void;
  onSettings: () => void;
}) {
  return (
    <div
      role="region"
      aria-label="Cookie consent"
      className="fixed right-4 bottom-4 z-30 max-w-xs rounded-xl bg-surface/95 p-4 text-xs text-muted smooth-shadow-ring-xl backdrop-blur max-sm:left-4 max-sm:max-w-none"
    >
      <p className="leading-relaxed">
        A cookie keeps you signed in. With your consent we also count visits to see how Acme is
        used. No advertising.{" "}
        <a
          href="#privacy"
          className="text-accent underline decoration-accent/40 underline-offset-2 [@media(hover:hover)]:hover:decoration-accent"
        >
          Privacy policy
        </a>
      </p>
      <div className="mt-3 flex gap-2">
        <Button size="sm" variant="outline" className="flex-1" onClick={() => onAnswer("rejected")}>
          Reject
        </Button>
        <Button size="sm" variant="outline" className="flex-1" onClick={() => onAnswer("accepted")}>
          Accept
        </Button>
      </div>
      <button
        type="button"
        onClick={onSettings}
        className="mt-3 cursor-pointer text-xs underline decoration-border underline-offset-2 transition-colors [@media(hover:hover)]:hover:text-text"
      >
        Settings
      </button>
    </div>
  );
}

/** The banner on a page, with its settings. Answering hides it; the link
 * below the page text brings it back. */
export default function CookieConsent() {
  const [answer, setAnswer] = useState<Answer>(null);
  const [settings, setSettings] = useState(false);
  const [bannerOpen, setBannerOpen] = useState(true);

  return (
    <section className="mx-auto flex min-h-[28rem] max-w-3xl flex-col justify-center gap-3 px-6 py-16 text-center">
      <h1 className="text-2xl font-semibold tracking-tight text-balance">
        A page with a consent banner
      </h1>
      <p
        className={cn(
          "text-sm text-muted transition-colors",
          answer === "accepted" && "text-accent",
        )}
        aria-live="polite"
      >
        {answer === null && "No answer yet. Analytics is off."}
        {answer === "accepted" && "Analytics is on."}
        {answer === "rejected" && "Analytics is off. You said no."}
      </p>
      <div>
        <button
          type="button"
          onClick={() => setBannerOpen(true)}
          className="cursor-pointer text-sm text-muted underline decoration-border underline-offset-2 [@media(hover:hover)]:hover:text-text"
        >
          Cookie settings
        </button>
      </div>
      {bannerOpen && (
        <ConsentBanner
          onAnswer={(a) => {
            setAnswer(a);
            setBannerOpen(false);
          }}
          onSettings={() => setSettings(true)}
        />
      )}
      <CookieSettings
        open={settings}
        onOpenChange={setSettings}
        analytics={answer === "accepted"}
        onSave={(on) => {
          setAnswer(on ? "accepted" : "rejected");
          setBannerOpen(false);
        }}
      />
    </section>
  );
}