BizzPocket

Announcement bar with rotating messages

A dismissible bar above the header that rotates a few short messages, each with an optional link, in the seller's colours, without moving the page.

On this page

Goal: a thin bar at the top of every page that cycles through a few messages ("Free shipping over ₹599", "New: winter collection"), in colours the seller picks, with an optional link per message and a close button, and that never pushes the page around while it rotates.


The island

The bar is one island: it renders on the server (so the first message is in the HTML), then rotates and handles the close button in the browser.

blocks/announcement-bar/announcement-view.tsx
'use client';
import { useEffect, useState } from 'react';

export type Message = { text: string; link: string | null };

/** A short, stable key for a set of messages: a new set shows again after a dismissal. */
function keyOf(messages: Message[]): string {
  let h = 0;
  for (const ch of messages.map((m) => m.text).join('|')) h = (h * 31 + ch.charCodeAt(0)) | 0;
  return `bp-announcement:${(h >>> 0).toString(36)}`;
}

function readDismissed(key: string): boolean {
  try {
    return window.localStorage.getItem(key) === '1';
  } catch {
    return false; // storage blocked (private mode, settings)
  }
}

export function AnnouncementView({
  messages,
  seconds,
  dismissible,
  remember,
  background,
  color,
}: {
  messages: Message[];
  seconds: number;
  dismissible: boolean;
  remember: boolean;
  background: string;
  color: string;
}) {
  const [active, setActive] = useState(0);
  const [paused, setPaused] = useState(false);
  const [closed, setClosed] = useState(false);
  const key = keyOf(messages);

  // A remembered dismissal (opt-in, see "Layout shift" below).
  useEffect(() => {
    if (remember && readDismissed(key)) setClosed(true);
  }, [remember, key]);

  // Rotate, unless there is one message, the shopper is hovering or focused in the bar, or asked for less motion.
  useEffect(() => {
    if (messages.length < 2 || paused || closed) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const t = window.setInterval(() => setActive((i) => (i + 1) % messages.length), Math.max(3, seconds) * 1000);
    return () => window.clearInterval(t);
  }, [messages.length, paused, closed, seconds]);

  if (closed) return null;

  const close = () => {
    setClosed(true);
    if (remember) {
      try {
        window.localStorage.setItem(key, '1');
      } catch {
        // not remembered; it closes for this page anyway
      }
    }
  };

  return (
    <div
      className="ab"
      role="region"
      aria-label="Announcements"
      style={{ '--ab-bg': background, '--ab-fg': color } as Record<string, string>}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
      onFocus={() => setPaused(true)}
      onBlur={() => setPaused(false)}
    >
      {/* Every message sits in the same grid cell: the bar is as tall as the tallest one, always. */}
      <div className="ab__stack" aria-live="off">
        {messages.map((m, i) => (
          <p key={i} className="ab__msg" data-active={i === active ? '' : undefined} aria-hidden={i === active ? undefined : true}>
            {m.link ? (
              <a href={m.link} tabIndex={i === active ? undefined : -1}>
                {m.text}
              </a>
            ) : (
              m.text
            )}
          </p>
        ))}
      </div>
      {dismissible ? (
        <button type="button" className="ab__close" aria-label="Close announcements" onClick={close}>
          ×
        </button>
      ) : null}
    </div>
  );
}

The block

blocks/announcement-bar/announcement-bar.tsx
import { block, f } from '@bizzpocket/theme';
import { AnnouncementView } from './announcement-view';
import './announcement-bar.css';

export default block({
  name: 'Announcement bar',
  category: 'header',
  description: 'A thin bar of short messages above the header, one at a time.',
  // Above the fold on every page: rotate and close from the start.
  hydrate: 'load',
  aboveFold: true,
  fields: {
    messages: f.list(
      {
        text: f.text({ default: 'Free shipping on orders over ₹599', label: 'Message' }),
        link: f.link({ label: 'Link (optional)' }),
      },
      { max: 5, label: 'Messages' },
    ),
    seconds: f.number({ default: 5, min: 3, max: 15, step: 1, label: 'Seconds per message' }),
    background: f.color({ default: '#111111', label: 'Background colour' }),
    color: f.color({ default: '#ffffff', label: 'Text colour' }),
    dismissible: f.boolean({ default: true, label: 'Shoppers can close it' }),
    remember: f.boolean({
      default: false,
      label: 'Keep it closed on later visits',
      help: 'The bar then disappears just after the page loads for shoppers who closed it, which moves the page a little.',
    }),
  },
  render: ({ messages, seconds, background, color, dismissible, remember }) => {
    const list = messages.filter((m) => m.text.trim() !== '').map((m) => ({ text: m.text, link: m.link ?? null }));
    if (list.length === 0) return null;
    return (
      <AnnouncementView
        messages={list}
        seconds={seconds}
        dismissible={dismissible}
        remember={remember}
        background={background}
        color={color}
      />
    );
  },
});
blocks/announcement-bar/announcement-bar.css
[data-theme] .ab {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: var(--ab-bg, #111);
  color: var(--ab-fg, #fff);
  font-size: 0.875rem;
  line-height: 1.4;
}
/* One cell, every message in it: rotating never changes the height. */
[data-theme] .ab__stack {
  flex: 1 1 auto;
  display: grid;
  min-width: 0;
}
[data-theme] .ab__msg {
  grid-area: 1 / 1;
  margin: 0;
  text-align: center;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.4s ease, visibility 0.4s;
}
[data-theme] .ab__msg[data-active] {
  opacity: 1;
  visibility: visible;
}
[data-theme] .ab__msg a {
  color: inherit;
  text-decoration: underline;
  text-underline-offset: 2px;
}
[data-theme] .ab__close {
  flex: 0 0 auto;
  width: 2rem;
  height: 2rem;
  border: 0;
  background: transparent;
  color: inherit;
  font-size: 1.25rem;
  line-height: 1;
  cursor: pointer;
}
@media (prefers-reduced-motion: reduce) {
  [data-theme] .ab__msg {
    transition: none;
  }
}

It belongs on every page, so put it in the announcement region of layouts/global.json (edit the file by hand; add-to-layout does not write global.json). Both storefronts render that region above the header:

json
"regions": {
  "announcement": [
    { "id": "5e7a1c2d-3b4f-4a5e-9c6d-7e8f90a1b2c3", "type": "announcement-bar", "props": {} }
  ],
  "header": [
    { "id": "...", "type": "header", "props": {} }
  ],
  "footer": [ ... ]
}

How it works

  • Rotation. The island moves data-active from one message to the next every seconds (3 at the least). It stops while the pointer is over the bar or focus is inside it, and does not rotate at all for shoppers who ask for reduced motion: they see the first message. A single message never rotates.
  • No layout shift while it rotates. All messages are in the HTML, stacked in one grid cell, so the bar's height is the tallest message's from the first paint, and switching changes only opacity and visibility. Hidden messages are aria-hidden and their links leave the tab order.
  • Colours and links. f.color() and f.link() values are cleaned before render sees them, so the colour goes straight into two CSS variables and the link straight into href. A message without a link is plain text.
  • Closing. The close button removes the bar. That shift follows the shopper's click, which layout shift scores do not count.
  • Layout shift on later visits. The page HTML is cached and the same for every shopper, and a theme cannot run a script of its own before the first paint (an inline <script> in a block is blocked: the runtime's content security policy allows only the scripts it adds itself, by nonce). So the server cannot leave the bar out for a shopper who closed it before. With remember on, the island reads localStorage when it wakes and removes the bar, which moves the page up a little just after load. That is why remember is off by default: by default a closed bar comes back on the next page.
  • The seller's own announcements. The store's settings also have announcements: store().announcements (with title, message, link, linkText and backgroundColor). Use them instead of the messages field if the seller should edit them in one place for every theme.

JS cost

One island, about 0.8 KB gzip in the client gz column (React is shared with every other island). hydrate: 'load' wakes it with the page's scripts; before that, the first message shows and the close button does nothing yet. CSS is about 0.4 KB gzip.

See also