Skip to content
Shaken UI
Sign in

Banner

Save

A dismissible announcement bar for the top of a page or a section, in info, success, warning and critical tones, with an optional action, countdown or date and a remembered dismissal.

Category
Feedback
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Banner preview

Information: Scheduled maintenance. Agent runs pause on Sunday from 02:00 to 02:20 UTC.

Runs

1,284 runs this week across 12 agents. 31 need review.

Triage new support ticketsSucceeded, 2m ago
Draft the weekly changelogWaiting for approval, 9m ago
Reconcile Stripe payoutsSucceeded, 14m ago

Installation

npx @shakenui/cli add banner

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add banner --dry-run

Usage

banner-example.tsx
import { Banner } from "@/components/shaken/ui/banner";

export default function BannerExample() {
  return (
    <div className="grid w-full max-w-2xl gap-3">
      <Banner
        layout="inline"
        variant="info"
        title="Scheduled maintenance."
        countdownTo="2026-11-22T02:00:00Z"
        action={{ label: "View status", href: "#status" }}
        storageKey="maintenance-2026-11-22"
      >
        Agent runs pause on Sunday from 02:00 to 02:20 UTC.
      </Banner>
    </div>
  );
}

States

Every state, rendered from local fixture data.

Banner states

Information: Claude Sonnet 5.5 is now the default model. Existing workspaces switch on December 1.

Success: Your usage export is ready. It covers 48,210 runs from October.

Warning: 92% of this month's tokens are used. New runs will queue once the limit is reached.

Critical: Tool calls to GitHub are failing. We are investigating elevated 502 errors.

API

PropTypeDefaultDescription
variant"info" | "success" | "warning" | "critical""info"Tone and glyph.
title / childrenReactNode—The lead in medium weight, then the message.
action{ label, href?, onClick? }—A link (with href) or button at the end of the bar.
countdownToDate | string | number—Counts down to this moment, such as "Starts in 2d 4h". Seconds show in the last hour.
countdownLabelstring"Starts in"Words before the countdown.
onCountdownEnd() => void—Called once when the countdown reaches zero.
date / dateFormat / localeDate | string | number / Intl.DateTimeFormatOptions / string—A fixed moment to show instead of a countdown.
dismissiblebooleantrueShows the close button.
storageKeystring—Remembers the dismissal in local storage under this key. Storage errors are ignored.
onDismiss() => void—Called when the banner is dismissed.
layout"page" | "inline""page"A full-width bar with a bottom hairline, or a rounded box for a section.
appearbooleantrueOpens with the entrance. Off (and without storageKey), it renders open at once.

Accessibility

  • The banner is a region named by its tone (Information, Success, Warning, Critical), and the message starts with that word for screen readers, so tone does not rely on color.
  • The close button is labeled "Dismiss". When it had focus, focus moves to the next focusable element after the banner instead of falling to the page.
  • While collapsed (before opening and while closing) the banner is inert, so its link and button cannot take focus.
  • The countdown is a time element with a machine-readable dateTime; it is not a live region, so it never interrupts.
  • With reduced motion the banner opens and closes without the height, fade, blur or glyph transitions.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/banner.tsxbanner
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/banner/0.1.0.json.

ui/banner.tsxShow
ui/banner.tsx
"use client";

import { useEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

export type BannerVariant = "info" | "success" | "warning" | "critical";

const variants: Record<BannerVariant, { name: string; glyph: string; surface: string }> = {
  info: { name: "Information", glyph: "text-sky-600 dark:text-sky-400", surface: "border-sky-500/35 bg-sky-500/[0.08]" },
  success: { name: "Success", glyph: "text-emerald-600 dark:text-emerald-400", surface: "border-emerald-500/30 bg-emerald-500/[0.08]" },
  warning: { name: "Warning", glyph: "text-amber-600 dark:text-amber-400", surface: "border-amber-500/35 bg-amber-500/[0.08]" },
  critical: { name: "Critical", glyph: "text-red-600 dark:text-red-400", surface: "border-red-500/35 bg-red-500/[0.08]" },
};

export interface BannerAction {
  label: ReactNode;
  /** Renders a link. Leave it out and pass `onClick` for a button. */
  href?: string;
  onClick?: () => void;
}

export interface BannerProps extends Omit<ComponentProps<"section">, "title"> {
  /** Tone and glyph. Defaults to `info`. */
  variant?: BannerVariant;
  /** The lead, in medium weight. */
  title?: ReactNode;
  /** The message after the title. */
  children?: ReactNode;
  /** A link or button at the end of the bar, such as "Read the notes". */
  action?: BannerAction;
  /** Counts down to this moment ("Starts in 2d 4h"); shows "Now" once it passes. */
  countdownTo?: Date | string | number;
  /** Words before the countdown. Defaults to "Starts in". */
  countdownLabel?: string;
  /** Called once when the countdown reaches zero. */
  onCountdownEnd?: () => void;
  /** A fixed moment to show instead of a countdown, formatted with `dateFormat`. */
  date?: Date | string | number;
  dateFormat?: Intl.DateTimeFormatOptions;
  locale?: string;
  /** Shows the close button. Defaults to true. */
  dismissible?: boolean;
  /** Remembers the dismissal under this key in local storage, so the banner stays closed on later visits. */
  storageKey?: string;
  /** Called when the person dismisses the banner. */
  onDismiss?: () => void;
  /** `page` is a full-width bar for the top of a page; `inline` is a rounded box for a section. */
  layout?: "page" | "inline";
  /** Opens with the entrance (height grows, content settles in). Off, it renders open at once. */
  appear?: boolean;
}

type Phase = "pending" | "open" | "closing" | "closed";

const focusable = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';

function readDismissed(key: string) {
  try {
    return window.localStorage.getItem(key) != null;
  } catch {
    return false;
  }
}

function writeDismissed(key: string) {
  try {
    window.localStorage.setItem(key, new Date().toISOString());
  } catch {
    // Storage can be full or blocked (private mode, sandboxed frames); the dismissal still holds for this view.
  }
}

/**
 * A dismissible announcement bar for the top of a page or a section, in four tones, with an
 * optional action, countdown or date. It opens by growing to its height while the content settles
 * in, and closes by fading the content and collapsing the height, so the page below rises instead
 * of jumping. With `storageKey` a dismissal is remembered.
 */
export function Banner({
  variant = "info",
  title,
  children,
  action,
  countdownTo,
  countdownLabel = "Starts in",
  onCountdownEnd,
  date,
  dateFormat,
  locale,
  dismissible = true,
  storageKey,
  onDismiss,
  layout = "page",
  appear = true,
  className,
  ...props
}: BannerProps) {
  const tone = variants[variant];
  // A remembered dismissal can only be read in the browser, so a banner with a storage key (or an
  // entrance) renders collapsed first and opens after mount; nothing flashes and then disappears.
  const [phase, setPhase] = useState<Phase>(appear || storageKey ? "pending" : "open");
  const [mounted, setMounted] = useState(false);
  const root = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setMounted(true);
    if (storageKey && readDismissed(storageKey)) {
      setPhase("closed");
      return;
    }
    // Two frames so the collapsed state is painted before the transition starts.
    let second = 0;
    const first = requestAnimationFrame(() => {
      second = requestAnimationFrame(() => setPhase((p) => (p === "pending" ? "open" : p)));
    });
    return () => {
      cancelAnimationFrame(first);
      cancelAnimationFrame(second);
    };
  }, [storageKey]);

  function dismiss() {
    if (storageKey) writeDismissed(storageKey);
    // Focus would fall to the page when the bar closes, so hand it to whatever comes next.
    const here = root.current;
    if (here?.contains(document.activeElement)) {
      const next = Array.from(document.querySelectorAll<HTMLElement>(focusable)).find(
        (el) => !here.contains(el) && here.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING && el.offsetParent !== null,
      );
      next?.focus({ preventScroll: true });
    }
    // Reduced motion has no transition to wait for, so the banner goes at once.
    setPhase(window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "closed" : "closing");
    onDismiss?.();
  }

  if (phase === "closed") return null;
  const open = phase === "open";

  return (
    <div
      ref={root}
      data-state={phase}
      inert={!open || undefined}
      onTransitionEnd={(event) => {
        if (phase === "closing" && event.target === event.currentTarget && event.propertyName === "grid-template-rows") setPhase("closed");
      }}
      className={cx(
        "grid motion-reduce:transition-none",
        open
          ? "grid-rows-[1fr] transition-[grid-template-rows] duration-300 ease-[cubic-bezier(0.23,1,0.32,1)]"
          : "grid-rows-[0fr] transition-[grid-template-rows] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]",
      )}
    >
      <div className="min-h-0 overflow-hidden">
        <section
          aria-label={tone.name}
          className={cx(
            "border text-sm text-zinc-950 dark:text-white",
            tone.surface,
            layout === "page" ? "border-x-0 border-t-0" : "rounded-xl",
            className,
          )}
          {...props}
        >
          <div
            className={cx(
              "flex items-start gap-3",
              layout === "page" ? "mx-auto max-w-6xl py-2.5 pr-2.5 pl-4 sm:pl-6" : "py-2.5 pr-2.5 pl-4",
              "motion-reduce:transition-none",
              open
                ? "translate-y-0 opacity-100 blur-none transition-[opacity,translate,filter] delay-75 duration-300 ease-[cubic-bezier(0.23,1,0.32,1)]"
                : "-translate-y-1.5 opacity-0 blur-[2px] transition-[opacity,translate,filter] duration-150 ease-out",
            )}
          >
            <BannerGlyph
              variant={variant}
              className={cx(
                "mt-0.5 size-4 shrink-0 motion-reduce:transition-none",
                tone.glyph,
                open ? "scale-100 transition-[scale] delay-150 duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]" : "scale-90",
              )}
            />
            <div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-4 gap-y-1">
              <p className="min-w-[min(100%,16rem)] flex-1 leading-5">
                <span className="sr-only">{tone.name}: </span>
                {title != null ? <span className="font-medium">{title}</span> : null}
                {title != null && children != null ? " " : null}
                {children != null ? <span className="text-zinc-700 dark:text-zinc-300">{children}</span> : null}
              </p>
              {countdownTo != null || date != null || action ? (
                <div className="flex min-h-5 flex-wrap items-center gap-x-4 gap-y-1">
                  {countdownTo != null ? (
                    <Countdown to={countdownTo} label={countdownLabel} onEnd={onCountdownEnd} mounted={mounted} />
                  ) : date != null ? (
                    <FormattedDate value={date} format={dateFormat} locale={locale} mounted={mounted} />
                  ) : null}
                  {action ? <BannerActionLink action={action} /> : null}
                </div>
              ) : null}
            </div>
            {dismissible ? (
              <button
                type="button"
                onClick={dismiss}
                aria-label="Dismiss"
                className={cx(
                  "-my-1 inline-flex size-7 shrink-0 items-center justify-center rounded-md text-zinc-500",
                  "transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.97] motion-reduce:transition-none",
                  "hover:bg-zinc-950/[0.06] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.08] dark:hover:text-white",
                  "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
                )}
              >
                <svg aria-hidden="true" viewBox="0 0 16 16" className="size-4">
                  <path d="m4.5 4.5 7 7m0-7-7 7" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
                </svg>
              </button>
            ) : null}
          </div>
        </section>
      </div>
    </div>
  );
}

function BannerActionLink({ action }: { action: BannerAction }) {
  const className = cx(
    "group/action inline-flex items-center gap-1 rounded-sm font-medium whitespace-nowrap text-zinc-950 dark:text-white",
    "underline decoration-zinc-950/25 underline-offset-4 transition-[text-decoration-color] duration-150 ease-out hover:decoration-current motion-reduce:transition-none",
    "dark:decoration-white/30",
    "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
  );
  const content = (
    <>
      {action.label}
      <svg
        aria-hidden="true"
        viewBox="0 0 16 16"
        className="size-3.5 transition-transform duration-150 ease-out group-hover/action:translate-x-0.5 motion-reduce:transition-none"
      >
        <path d="M3.5 8h9m-3.5-3.5L12.5 8 9 11.5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    </>
  );
  return action.href ? (
    <a href={action.href} onClick={action.onClick} className={className}>
      {content}
    </a>
  ) : (
    <button type="button" onClick={action.onClick} className={cx(className, "cursor-pointer")}>
      {content}
    </button>
  );
}

function toDate(value: Date | string | number) {
  return value instanceof Date ? value : new Date(value);
}

function Countdown({ to, label, onEnd, mounted }: { to: Date | string | number; label: string; onEnd?: () => void; mounted: boolean }) {
  const target = toDate(to).getTime();
  const [now, setNow] = useState<number | null>(null);
  const ended = useRef(false);
  const endRef = useRef(onEnd);
  endRef.current = onEnd;

  useEffect(() => {
    if (!mounted) return;
    let timer: ReturnType<typeof setTimeout>;
    const tick = () => {
      const t = Date.now();
      setNow(t);
      const left = target - t;
      if (left <= 0) {
        if (!ended.current) {
          ended.current = true;
          endRef.current?.();
        }
        return;
      }
      // Seconds only matter in the last hour; before that the minute is enough.
      const step = left < 3_600_000 ? 1000 - (t % 1000) : 60_000 - (t % 60_000);
      timer = setTimeout(tick, step + 5);
    };
    tick();
    return () => clearTimeout(timer);
  }, [target, mounted]);

  const iso = Number.isFinite(target) ? new Date(target).toISOString() : undefined;
  const text = now == null ? "" : formatLeft(target - now);
  return (
    // Written after mount: a target computed from the clock differs between server and browser.
    <time dateTime={mounted ? iso : undefined} className="min-w-[9ch] font-mono text-xs whitespace-nowrap text-zinc-600 tabular-nums dark:text-zinc-400">
      {now == null ? " " : target - now <= 0 ? "Now" : `${label} ${text}`}
    </time>
  );
}

function formatLeft(ms: number) {
  const total = Math.max(0, Math.floor(ms / 1000));
  const d = Math.floor(total / 86_400);
  const h = Math.floor((total % 86_400) / 3600);
  const m = Math.floor((total % 3600) / 60);
  const s = total % 60;
  const pad = (n: number) => String(n).padStart(2, "0");
  if (d > 0) return `${d}d ${h}h`;
  if (h > 0) return `${h}h ${pad(m)}m`;
  return `${m}m ${pad(s)}s`;
}

function FormattedDate({
  value,
  format,
  locale,
  mounted,
}: {
  value: Date | string | number;
  format?: Intl.DateTimeFormatOptions;
  locale?: string;
  mounted: boolean;
}) {
  const date = toDate(value);
  // Time zones differ between server and browser, so the text is written after mount.
  const text = useMemo(
    () =>
      mounted && !Number.isNaN(date.getTime())
        ? new Intl.DateTimeFormat(locale, format ?? { month: "short", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" }).format(date)
        : " ",
    [mounted, date.getTime(), locale, format], // eslint-disable-line react-hooks/exhaustive-deps
  );
  return (
    <time dateTime={Number.isNaN(date.getTime()) ? undefined : date.toISOString()} className="font-mono text-xs whitespace-nowrap text-zinc-600 tabular-nums dark:text-zinc-400">
      {text}
    </time>
  );
}

function BannerGlyph({ variant, className }: { variant: BannerVariant; className?: string }) {
  const stroke = { fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" } as const;
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" className={className}>
      {variant === "info" ? (
        <>
          <circle cx="8" cy="8" r="6.25" {...stroke} />
          <path d="M8 7.25V11" {...stroke} />
          <circle cx="8" cy="5" r="0.85" fill="currentColor" />
        </>
      ) : variant === "success" ? (
        <>
          <circle cx="8" cy="8" r="6.25" {...stroke} />
          <path d="m5.5 8.25 1.75 1.75 3.25-3.75" {...stroke} />
        </>
      ) : variant === "warning" ? (
        <>
          <path d="M7.13 2.5a1 1 0 0 1 1.74 0l5.25 9.5a1 1 0 0 1-.87 1.5H2.75a1 1 0 0 1-.87-1.5Z" {...stroke} />
          <path d="M8 6.25V9" {...stroke} />
          <circle cx="8" cy="11.1" r="0.85" fill="currentColor" />
        </>
      ) : (
        <>
          <path d="M5.4 1.75h5.2l3.65 3.65v5.2l-3.65 3.65H5.4L1.75 10.6V5.4Z" {...stroke} />
          <path d="M8 4.75v3.75" {...stroke} />
          <circle cx="8" cy="10.9" r="0.85" fill="currentColor" />
        </>
      )}
    </svg>
  );
}