Skip to content

Marketing components ​

Components of the Marketing group of frame_demo_umami. Four are React islands; the sign-up form is Twig with a small script. None has a slot, so all of them run in the editor as on the page.

How a React component of the examples is built ​

pricing-table/
  pricing-table.component.yml   # props, libraryOverrides: assets/pricing-table.{js,css} + frame/react
  pricing-table.twig            # the content as HTML, and the props as one JSON attribute
  index.jsx                     # Drupal behavior: once(), executeWhenVisible(), createRoot()
  PricingTable.jsx              # the component
  pricing-table.scss            # @use 'frame/tokens' as frame;
  __tests__/pricing-table.test.js
twig
{% set data = { heading: heading, currency: currency, plans: plans } %}
<section {{ attributes.addClass('pricing-table').setAttribute('data-props', data|json_encode) }}>
  …the plans as HTML…
</section>
jsx
Drupal.behaviors.frameDemoPricingTable = {
  attach(context) {
    once('react', '.pricing-table', context)
      .forEach((element) => executeWhenVisible(element, mount, 'pricing-table'));
  },
  detach(context, settings, trigger) {
    if (trigger !== 'unload') return;
    once.remove('react', '.pricing-table', context).forEach((element) => roots.get(element)?.unmount());
  },
};
  • The Twig template prints the content, so the page reads without JavaScript and before React has loaded. React replaces what is inside the root element; the root element, with the attributes of Frame's features, stays.
  • All props travel in data-props, a list as a list. Rich text props would arrive as markup objects, which do not encode to JSON: the React components take plain text (x-builder-widget: textarea) for their texts.
  • Texts are Drupal.t('literal') and Drupal.formatPlural() with literal strings, so Drupal finds them in the built file (Translations).
  • See React + Drupal behaviors for once() and executeWhenVisible().

Pricing table ​

components/pricing-table, React. Plans side by side with a switch between paying monthly and yearly.

Prop
heading, introabove the plans
currencyan ISO code (EUR, USD) for the price format of the page's language, or a sign to put before the number
start_yearlyshow yearly prices first
yearly_notea label on the yearly switch: "2 months free"
plansup to 4: name, description, monthly, yearly (both per month), features (a list of lines), button, url, highlight, badge

The switch is a pair of radio buttons in a fieldset, so it works with the keyboard and screen readers as a choice of two; a polite live region says which prices are shown. The yearly total is worked out ("€288 billed yearly"). Prices are formatted with Intl.NumberFormat in the language of the page: €24 in English, 24 € in German. Leave the yearly price empty on every plan for a table without a switch.

Uses numbers, a list of strings inside a list of objects, a checkbox and a badge per item, tokens in SCSS (frame.space(l), @include frame.breakpoint(tablet)).

yaml
$schema: https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json
name: 'Pricing table'
status: experimental
description: 'Plans side by side with their price, what they include and a button, and a switch between paying monthly and yearly. One plan can be highlighted. React.'
group: Marketing
help: |
  Each plan has a price per month when paid monthly and a price per month when paid yearly. With both, visitors get a switch; the yearly total is worked out for them.

  Leave the yearly price empty on every plan for a table without the switch. Prices are shown in the number format of the page's language.
props:
  type: object
  properties:
    heading:
      type: string
      title: Heading
      examples: ['Choose your membership']
    intro:
      type: string
      title: Introduction
      x-builder-widget: textarea
      examples: ['Cook as often as you like. Change or cancel at any time.']
    currency:
      type: string
      title: Currency
      description: 'An ISO code (EUR, USD, GBP) for a price in the format of the language, or any sign to put before the number.'
      examples: [EUR]
    start_yearly:
      type: boolean
      title: 'Show yearly prices first'
      examples: [false]
    yearly_note:
      type: string
      title: 'Note on the yearly switch'
      description: 'For example "2 months free".'
      examples: ['Save 20%']
    plans:
      type: array
      title: Plans
      x-builder-summary: name
      minItems: 1
      maxItems: 4
      items:
        type: object
        properties:
          name:
            type: string
            title: Name
            examples: ['Plan']
          description:
            type: string
            title: 'Short description'
          monthly:
            type: number
            title: 'Price per month, paid monthly'
            minimum: 0
            examples: [10]
          yearly:
            type: number
            title: 'Price per month, paid yearly'
            minimum: 0
          features:
            type: array
            title: 'What it includes'
            items:
              type: string
              title: Line
          button:
            type: string
            title: 'Button text'
          url:
            type: string
            title: 'Button link'
            format: uri-reference
          highlight:
            type: boolean
            title: Highlight
            description: 'Shown larger, in the accent colour.'
          badge:
            type: string
            title: Badge
            description: 'A word over the highlighted plan: "Popular".'
        required: [name, monthly]
      examples:
        - - { name: Taster, description: 'Try a class a month.', monthly: 29, yearly: 24, features: ['1 class a month', 'Recipes by e-mail', 'Members'' newsletter'], button: 'Start tasting', url: '/contact' }
          - { name: Cook, description: 'For the regulars.', monthly: 79, yearly: 63, features: ['4 classes a month', 'Bring a friend once a month', 'Recipes and videos', '10% off in the shop'], button: 'Become a cook', url: '/contact', highlight: true, badge: Popular }
          - { name: Chef, description: 'Cook whenever you like.', monthly: 149, yearly: 119, features: ['Unlimited classes', 'Chef''s table once a quarter', 'Private lesson every year', '20% off in the shop'], button: 'Go chef', url: '/contact' }
  required: [plans]
thirdPartySettings:
  frame_editor:
    icon: 'bi bi-tags'
    example: { type: 'frame_demo_umami:pricing-table', props: { heading: 'Membership', currency: EUR, yearly_note: '2 months free', plans: [ { name: Basic, monthly: 9, yearly: 7.5, features: ['50 recipes'], button: Join, url: '/join' }, { name: Pro, monthly: 19, yearly: 15.8, features: ['All recipes', 'Live classes'], button: 'Go pro', url: '/join', highlight: true, badge: Popular } ] } }
libraryOverrides:
  js:
    ../../assets/pricing-table.js: { attributes: { type: module } }
  css:
    theme:
      ../../assets/pricing-table.css: { }
  dependencies:
    - frame/react
twig
{#
/**
 * @file
 * Pricing table. The server prints the plans with one price, so they read without JavaScript; React (index.jsx)
 * adds the switch between monthly and yearly.
 */
#}
{% set yearly_first = start_yearly and plans|filter(plan => plan.yearly is not null)|length > 0 %}
{% set data = { heading: heading, intro: intro, currency: currency|default(''), startYearly: start_yearly ? true : false, yearlyNote: yearly_note, plans: plans } %}
<section {{ attributes.addClass('pricing-table').setAttribute('data-props', data|json_encode) }}>
  <div class="pricing-table__header">
    {% if heading %}<h2 class="pricing-table__heading">{{ heading }}</h2>{% endif %}
    {% if intro %}<p class="pricing-table__intro">{{ intro }}</p>{% endif %}
  </div>
  <ul class="pricing-table__plans">
    {% for plan in plans %}
      {% set price = yearly_first and plan.yearly is not null ? plan.yearly : plan.monthly %}
      <li class="pricing-table__plan{{ plan.highlight ? ' pricing-table__plan--highlight' }}">
        {% if plan.highlight and plan.badge %}<p class="pricing-table__badge">{{ plan.badge }}</p>{% endif %}
        <h3 class="pricing-table__name">{{ plan.name }}</h3>
        {% if plan.description %}<p class="pricing-table__description">{{ plan.description }}</p>{% endif %}
        <p class="pricing-table__price"><span class="pricing-table__amount">{{ currency|length == 3 ? '' : currency }}{{ price }}{{ currency|length == 3 ? ' ' ~ currency }}</span> <span class="pricing-table__per">{{ '/ month'|t }}</span></p>
        {% if plan.features %}
          <ul class="pricing-table__features">
            {% for line in plan.features %}<li>{{ line }}</li>{% endfor %}
          </ul>
        {% endif %}
        {% if plan.button and plan.url %}<a class="pricing-table__button" href="{{ plan.url }}">{{ plan.button }}</a>{% endif %}
      </li>
    {% endfor %}
  </ul>
</section>
jsx
import { createRoot } from 'react-dom/client';
import { PricingTable } from './PricingTable';
import './pricing-table.scss';

// The props of the SDC arrive as one JSON attribute (data-props) printed by the Twig template.
(function (Drupal, once) {
  const roots = new WeakMap();
  const mount = (element) => {
    const root = createRoot(element);
    roots.set(element, root);
    root.render(<PricingTable {...JSON.parse(element.dataset.props || '{}')} />);
  };

  Drupal.behaviors.frameDemoPricingTable = {
    attach(context) {
      once('react', '.pricing-table', context).forEach((element) => executeWhenVisible(element, mount, 'pricing-table'));
    },
    detach(context, settings, trigger) {
      if (trigger !== 'unload') return;
      once.remove('react', '.pricing-table', context).forEach((element) => roots.get(element)?.unmount());
    },
  };
})(Drupal, once);
jsx
import { useId, useMemo, useState } from 'react';

/** A price in the format of the page's language: "€24", "24 €", "$24.50"; a sign that is no ISO code goes first. */
export function formatPrice(amount, currency, lang = document.documentElement.lang || 'en') {
  const digits = Number.isInteger(amount) ? 0 : 2;
  if (/^[A-Z]{3}$/.test(currency || '')) {
    try {
      return new Intl.NumberFormat(lang, { style: 'currency', currency, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(amount);
    }
    catch {
      // An unknown code: the number and the code.
    }
  }
  const number = new Intl.NumberFormat(lang, { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(amount);
  return /^[A-Z]{3}$/.test(currency || '') ? `${number} ${currency}` : `${currency || ''}${number}`;
}

export function PricingTable({ heading, intro, currency = '', startYearly = false, yearlyNote, plans = [] }) {
  const canSwitch = plans.some((plan) => typeof plan.yearly === 'number');
  const [yearly, setYearly] = useState(canSwitch && startYearly);
  const name = useId();
  const status = useMemo(
    () => (yearly ? Drupal.t('Prices per month, paid yearly.') : Drupal.t('Prices per month, paid monthly.')),
    [yearly],
  );

  return (
    <>
      <div className="pricing-table__header">
        {heading && <h2 className="pricing-table__heading">{heading}</h2>}
        {intro && <p className="pricing-table__intro">{intro}</p>}
        {canSwitch && (
          <fieldset className="pricing-table__switch">
            <legend className="visually-hidden">{Drupal.t('Billing')}</legend>
            <label className={!yearly ? 'is-active' : undefined}>
              <input type="radio" name={name} checked={!yearly} onChange={() => setYearly(false)} />
              {Drupal.t('Monthly')}
            </label>
            <label className={yearly ? 'is-active' : undefined}>
              <input type="radio" name={name} checked={yearly} onChange={() => setYearly(true)} />
              {Drupal.t('Yearly')}
              {yearlyNote && <span className="pricing-table__save">{yearlyNote}</span>}
            </label>
          </fieldset>
        )}
        <p className="visually-hidden" aria-live="polite">{canSwitch ? status : ''}</p>
      </div>
      <ul className="pricing-table__plans">
        {plans.map((plan, index) => {
          const hasYearly = typeof plan.yearly === 'number';
          const price = yearly && hasYearly ? plan.yearly : plan.monthly;
          return (
            <li key={index} className={`pricing-table__plan${plan.highlight ? ' pricing-table__plan--highlight' : ''}`}>
              {plan.highlight && plan.badge && <p className="pricing-table__badge">{plan.badge}</p>}
              <h3 className="pricing-table__name">{plan.name}</h3>
              {plan.description && <p className="pricing-table__description">{plan.description}</p>}
              <p className="pricing-table__price">
                <span className="pricing-table__amount" key={`${yearly}`}>{formatPrice(price, currency)}</span>{' '}
                <span className="pricing-table__per">{Drupal.t('/ month')}</span>
              </p>
              <p className="pricing-table__billed">
                {yearly && hasYearly
                  ? Drupal.t('@total billed yearly', { '@total': formatPrice(Math.round(plan.yearly * 12 * 100) / 100, currency) })
                  : Drupal.t('Billed monthly')}
              </p>
              {plan.features?.length > 0 && (
                <ul className="pricing-table__features">
                  {plan.features.map((line, n) => <li key={n}>{line}</li>)}
                </ul>
              )}
              {plan.button && plan.url && <a className="pricing-table__button" href={plan.url}>{plan.button}</a>}
            </li>
          );
        })}
      </ul>
    </>
  );
}
scss
@use 'frame/tokens' as frame;

.pricing-table {
  --pricing-accent: var(--frame-accent, #{frame.color(green)});
  margin-block: 0 frame.space(l);
}

.pricing-table__header {
  max-width: 44rem;
  margin: 0 auto frame.space(l);
  text-align: center;
}

.pricing-table__heading { margin: 0 0 0.35em; font-size: clamp(1.75rem, 1.3rem + 1.6vw, 2.6rem); }
.pricing-table__intro { margin: 0; font-size: 1.1rem; opacity: 0.85; }

.pricing-table__switch {
  display: inline-flex;
  gap: 0.25rem;
  margin: frame.space(m) 0 0;
  padding: 0.3rem;
  border: 0;
  border-radius: 999px;
  background: color-mix(in srgb, var(--pricing-accent) 10%, #fff);

  label {
    position: relative;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.55rem 1.2rem;
    border-radius: 999px;
    font-weight: 600;
    cursor: pointer;
    transition: background-color 0.2s, color 0.2s;
  }

  label.is-active { background: var(--pricing-accent); color: #fff; }

  input { position: absolute; opacity: 0; pointer-events: none; }

  label:has(input:focus-visible) { outline: 3px solid color-mix(in srgb, var(--pricing-accent) 45%, transparent); outline-offset: 2px; }
}

.pricing-table__save {
  padding: 0.1rem 0.5rem;
  border-radius: 999px;
  background: #ffe9a8;
  color: #5c4500;
  font-size: 0.75rem;
  font-weight: 700;
}

.pricing-table__plans {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
  gap: frame.space(m);
  align-items: stretch;
  margin: 0;
  padding: 0;
  list-style: none;

  @include frame.breakpoint(desktop) {
    gap: frame.space(l);
  }
}

.pricing-table__plan {
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 2rem 1.75rem;
  border: 1px solid rgb(0 0 0 / 10%);
  border-radius: 1rem;
  background: #fff;
}

.pricing-table__plan--highlight {
  border: 2px solid var(--pricing-accent);
  box-shadow: 0 18px 40px color-mix(in srgb, var(--pricing-accent) 22%, transparent);

  @include frame.breakpoint(tablet) {
    transform: scale(1.03);
  }
}

.pricing-table__badge {
  position: absolute;
  inset-block-start: 0;
  inset-inline-start: 50%;
  margin: 0;
  padding: 0.25rem 0.85rem;
  border-radius: 999px;
  background: var(--pricing-accent);
  color: #fff;
  font-size: 0.75rem;
  font-weight: 700;
  letter-spacing: 0.06em;
  text-transform: uppercase;
  transform: translate(-50%, -50%);

  [dir='rtl'] & { transform: translate(50%, -50%); }
}

.pricing-table__name { margin: 0; font-size: 1.4rem; }
.pricing-table__description { margin: 0.35rem 0 0; opacity: 0.75; }

.pricing-table__price { margin: 1.25rem 0 0; }

.pricing-table__amount {
  display: inline-block;
  font-size: 2.75rem;
  font-weight: 700;
  line-height: 1;
  letter-spacing: -0.02em;
  animation: pricing-in 0.35s ease;
}

.pricing-table__per { opacity: 0.7; }
.pricing-table__billed { min-height: 1.4em; margin: 0.35rem 0 0; font-size: 0.875rem; opacity: 0.7; }

.pricing-table__features {
  flex: 1;
  margin: 1.25rem 0 1.5rem;
  padding: 1.25rem 0 0;
  border-top: 1px solid rgb(0 0 0 / 8%);
  list-style: none;

  li {
    position: relative;
    padding-inline-start: 1.75rem;

    & + li { margin-top: 0.55rem; }

    &::before {
      content: '';
      position: absolute;
      inset-inline-start: 0.2rem;
      top: 0.3em;
      width: 0.45rem;
      height: 0.8rem;
      border-right: 2px solid var(--pricing-accent);
      border-bottom: 2px solid var(--pricing-accent);
      transform: rotate(45deg);
    }
  }
}

.pricing-table__button {
  display: block;
  margin-top: auto;
  padding: 0.8rem 1rem;
  border: 2px solid var(--pricing-accent);
  border-radius: 0.6rem;
  color: var(--pricing-accent);
  font-weight: 700;
  text-align: center;
  text-decoration: none;
  transition: background-color 0.15s, color 0.15s;

  &:hover, &:focus-visible { background: var(--pricing-accent); color: #fff; }
  &:focus-visible { outline: 3px solid color-mix(in srgb, var(--pricing-accent) 45%, transparent); outline-offset: 2px; }

  .pricing-table__plan--highlight & { background: var(--pricing-accent); color: #fff; }
  .pricing-table__plan--highlight &:hover { filter: brightness(0.92); }
}

@keyframes pricing-in {
  from { opacity: 0; transform: translateY(-0.35rem); }
}

@media (prefers-reduced-motion: reduce) {
  .pricing-table__amount { animation: none; }
  .pricing-table__plan--highlight { transform: none; }
}

Numbers that count up ​

components/stats-counter, React. Key figures that count up from zero when they scroll into view.

Prop
headingabove the figures
statsup to 8: value, decimals, prefix, suffix, label, icon
duration1, 2 or 3.5 seconds
lookPlain, Cards or Accent band

Counting starts when half of the figures are in view (IntersectionObserver), eases out, and uses requestAnimationFrame. Screen readers get the final number as text; the number that counts is hidden from them. Visitors who prefer less motion see the final numbers at once, and so does a browser without IntersectionObserver. Digits have a fixed width (tabular-nums), so the line does not jump while it counts.

yaml
$schema: https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json
name: 'Numbers that count up'
status: experimental
description: 'Key figures that count up from zero when they scroll into view: "12,000 cooks", "4.9 / 5". Each with an icon and a label. React.'
group: Marketing
help: |
  Each figure is a number, with text before and after it ("€", "+", "%", "k") and a label.

  The page has the final numbers, for search engines and screen readers; counting up is only the look. Visitors who prefer less motion see the final numbers at once.
props:
  type: object
  properties:
    heading:
      type: string
      title: Heading
      examples: ['The school in numbers']
    stats:
      type: array
      title: Figures
      x-builder-summary: label
      minItems: 1
      maxItems: 8
      items:
        type: object
        properties:
          value:
            type: number
            title: Number
            examples: [100]
          decimals:
            type: integer
            title: Decimals
            minimum: 0
            maximum: 3
          prefix:
            type: string
            title: 'Before the number'
          suffix:
            type: string
            title: 'After the number'
          label:
            type: string
            title: Label
            examples: ['What it counts']
          icon:
            type: string
            title: Icon
            x-builder-widget: icon
            x-builder-icon-class: 'bi bi-{name}'
            enum: [star, heart, check-circle, lightning, trophy, rocket, shield-check, clock, calendar-event, geo-alt, people, person, chat-dots, envelope, telephone, globe, cart, bag, gift, tag, truck, basket, cup-hot, egg-fried, fire, leaf, flower1, sun, moon, snow, droplet, award, bookmark, camera, music-note, play-circle, graph-up, gear, lock, info-circle]
        required: [value, label]
      examples:
        - - { value: 12500, suffix: '+', label: 'cooks taught', icon: people }
          - { value: 4.9, decimals: 1, suffix: ' / 5', label: 'average rating', icon: star }
          - { value: 340, label: 'recipes in the book', icon: egg-fried }
          - { value: 98, suffix: '%', label: 'would come again', icon: heart }
    duration:
      type: string
      title: 'Counting time'
      enum: [short, normal, long]
      meta:enum: { short: 'Short (1 s)', normal: 'Normal (2 s)', long: 'Long (3.5 s)' }
      examples: [normal]
    look:
      type: string
      title: Look
      enum: [plain, cards, band]
      meta:enum: { plain: Plain, cards: Cards, band: 'Accent band' }
      examples: [cards]
  required: [stats]
thirdPartySettings:
  frame_editor:
    icon: 'bi bi-graph-up-arrow'
    example: { type: 'frame_demo_umami:stats-counter', props: { heading: 'In numbers', look: band, stats: [ { value: 12500, suffix: '+', label: 'cooks taught', icon: people }, { value: 4.9, decimals: 1, suffix: ' / 5', label: 'average rating', icon: star } ] } }
libraryOverrides:
  js:
    ../../assets/stats-counter.js: { attributes: { type: module } }
  css:
    theme:
      ../../assets/stats-counter.css: { }
  dependencies:
    - frame/react
jsx
import { useEffect, useRef, useState } from 'react';

const DURATIONS = { short: 1000, normal: 2000, long: 3500 };
const easeOut = (x) => 1 - (1 - x) ** 3;

export const formatNumber = (value, decimals = 0, lang = document.documentElement.lang || 'en') =>
  new Intl.NumberFormat(lang, { minimumFractionDigits: decimals, maximumFractionDigits: decimals }).format(value);

const reducedMotion = () => window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;

/**
 * 0 to 1 over `duration` ms, from the moment the element is half in view. 1 at once without IntersectionObserver
 * or for visitors who prefer less motion.
 */
export function useProgress(ref, duration) {
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    if (reducedMotion() || typeof IntersectionObserver === 'undefined') {
      setProgress(1);
      return undefined;
    }
    let frame;
    const observer = new IntersectionObserver(([entry]) => {
      if (!entry.isIntersecting) return;
      observer.disconnect();
      const start = performance.now();
      const step = (now) => {
        const x = Math.min(1, (now - start) / duration);
        setProgress(easeOut(x));
        if (x < 1 && ref.current?.isConnected) frame = requestAnimationFrame(step);
      };
      frame = requestAnimationFrame(step);
    }, { threshold: 0.5 });
    observer.observe(ref.current);
    return () => { observer.disconnect(); cancelAnimationFrame(frame); };
  }, [duration]);
  return progress;
}

export function StatsCounter({ heading, stats = [], duration = 'normal' }) {
  const list = useRef(null);
  const progress = useProgress(list, DURATIONS[duration] || DURATIONS.normal);

  return (
    <>
      {heading && <h2 className="stats-counter__heading">{heading}</h2>}
      <ul className="stats-counter__items" ref={list}>
        {stats.map((stat, index) => {
          const decimals = stat.decimals || 0;
          const final = `${stat.prefix || ''}${formatNumber(stat.value, decimals)}${stat.suffix || ''}`;
          return (
            <li className="stats-counter__item" key={index}>
              {stat.icon && <span className="stats-counter__icon" aria-hidden="true"><i className={`bi bi-${stat.icon}`} /></span>}
              {/* The final number for screen readers; the number that counts is only drawn. */}
              <span className="stats-counter__value">
                <span className="visually-hidden">{final}</span>
                <span aria-hidden="true">
                  {stat.prefix}
                  <span className="stats-counter__digits">{formatNumber(stat.value * progress, decimals)}</span>
                  {stat.suffix}
                </span>
              </span>
              <span className="stats-counter__label">{stat.label}</span>
            </li>
          );
        })}
      </ul>
    </>
  );
}

Testimonials ​

components/testimonials, React. Quotes with a name, a role, a photo and stars.

Prop
headingabove the quotes
itemsquote, name, role, photo (an image object), rating (1–5)
layoutWall of cards (columns of cards of their own height) or One at a time (a slider)
autoplay, intervalthe slider plays by itself

A person without a photo gets a badge with their initials. The stars are one image for screen readers ("Rated 4 out of 5"). The slider is a region with aria-roledescription="carousel"; the slides that are not shown are inert, so their content cannot be reached with the keyboard. It moves with its arrows, its dots, a swipe and the arrow keys, and has a pause button when it plays by itself. Playing stops while the pointer or the focus is on it and never starts for visitors who prefer less motion.

yaml
$schema: https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json
name: Testimonials
status: experimental
description: 'What people say: quotes with a name, a role, a photo and stars, as a wall of cards or one at a time in a slider that can play by itself. React.'
group: Marketing
help: |
  A person without a photo gets a round badge with their initials.

  The slider moves with its arrows, its dots, a swipe and the arrow keys. Playing by itself stops while the pointer or the keyboard is on it, and never starts for visitors who prefer less motion.
props:
  type: object
  properties:
    heading:
      type: string
      title: Heading
      examples: ['What our cooks say']
    items:
      type: array
      title: Quotes
      x-builder-summary: name
      minItems: 1
      items:
        type: object
        properties:
          quote:
            type: string
            title: Quote
            x-builder-widget: textarea
            examples: ['A quote.']
          name:
            type: string
            title: Name
            examples: ['A name']
          role:
            type: string
            title: 'Role or place'
          photo:
            type: object
            title: Photo
            x-builder-widget: image
            properties: { url: { type: string }, alt: { type: string }, width: { type: integer }, height: { type: integer } }
          rating:
            type: integer
            title: Stars
            enum: [1, 2, 3, 4, 5]
        required: [quote, name]
      examples:
        - - { quote: 'I came for the pasta and stayed for the people. Three months later I still make tagliatelle every Sunday.', name: 'Giulia Ferri', role: 'Cook member since 2023', rating: 5 }
          - { quote: 'The chef made a nervous beginner feel at home. The tiramisu alone was worth it.', name: 'Marco Bianchi', role: 'Taster class', rating: 5 }
          - { quote: 'A perfect gift for my parents. They talk about their evening in Milan to everyone.', name: 'Sophie Laurent', role: 'Gift voucher', rating: 4 }
          - { quote: 'Small group, real ingredients, and dinner at a long table. Exactly what I hoped for.', name: 'Daniel Okafor', role: 'Chef member', rating: 5 }
    layout:
      type: string
      title: Arrangement
      enum: [grid, slider]
      meta:enum: { grid: 'Wall of cards', slider: 'One at a time' }
      examples: [slider]
    autoplay:
      type: boolean
      title: 'Play by itself'
      description: 'Only for the slider. With a pause button.'
      examples: [true]
    interval:
      type: integer
      title: 'Seconds per quote'
      minimum: 3
      maximum: 20
      examples: [7]
  required: [items]
thirdPartySettings:
  frame_editor:
    icon: quote
    example: { type: 'frame_demo_umami:testimonials', props: { heading: 'What our cooks say', layout: grid, items: [ { quote: 'I still make tagliatelle every Sunday.', name: 'Giulia Ferri', role: 'Member', rating: 5 }, { quote: 'The tiramisu alone was worth it.', name: 'Marco Bianchi', rating: 4 } ] } }
libraryOverrides:
  js:
    ../../assets/testimonials.js: { attributes: { type: module } }
  css:
    theme:
      ../../assets/testimonials.css: { }
  dependencies:
    - frame/react
jsx
import { useEffect, useRef, useState } from 'react';

const reducedMotion = () => Boolean(window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches);

export const initials = (name = '') => name.split(/\s+/).filter(Boolean).slice(0, 2).map((part) => part[0].toUpperCase()).join('');

function Stars({ rating }) {
  if (!rating) return null;
  return (
    <p className="testimonials__stars" role="img" aria-label={Drupal.t('Rated @n out of 5', { '@n': rating })}>
      {Array.from({ length: 5 }, (_, i) => <span key={i} className={i < rating ? 'is-on' : undefined} aria-hidden="true">★</span>)}
    </p>
  );
}

export function Card({ item }) {
  return (
    <figure>
      <Stars rating={item.rating} />
      <blockquote className="testimonials__quote"><p>{item.quote}</p></blockquote>
      <figcaption className="testimonials__person">
        {item.photo?.url
          ? <img className="testimonials__photo" src={item.photo.url} alt="" loading="lazy" />
          : <span className="testimonials__photo testimonials__photo--initials" aria-hidden="true">{initials(item.name)}</span>}
        <span>
          <strong className="testimonials__name">{item.name}</strong>
          {item.role && <span className="testimonials__role">{item.role}</span>}
        </span>
      </figcaption>
    </figure>
  );
}

/** Calls `next` every `seconds` while `running`. */
function useInterval(next, seconds, running) {
  const saved = useRef(next);
  saved.current = next;
  useEffect(() => {
    if (!running) return undefined;
    const timer = setInterval(() => { if (!document.hidden) saved.current(); }, seconds * 1000);
    return () => clearInterval(timer);
  }, [running, seconds]);
}

export function Slider({ items, autoplay, interval }) {
  const [index, setIndex] = useState(0);
  const [paused, setPaused] = useState(false);
  const [hovered, setHovered] = useState(false);
  const canPlay = autoplay && !reducedMotion() && items.length > 1;
  const playing = canPlay && !paused && !hovered;
  const touch = useRef(null);
  const count = items.length;
  const go = (to) => setIndex((to + count) % count);
  useInterval(() => go(index + 1), Math.min(Math.max(interval || 7, 3), 20), playing);

  const onKeyDown = (event) => {
    const step = { ArrowLeft: -1, ArrowRight: 1 }[event.key];
    if (!step) return;
    event.preventDefault();
    go(index + (document.dir === 'rtl' ? -step : step));
  };

  return (
    <div
      className="testimonials__slider"
      role="region"
      aria-roledescription={Drupal.t('carousel')}
      aria-label={Drupal.t('Testimonials')}
      onKeyDown={onKeyDown}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      onFocus={() => setHovered(true)}
      onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) setHovered(false); }}
    >
      <div
        className="testimonials__viewport"
        aria-live={playing ? 'off' : 'polite'}
        onTouchStart={(event) => { touch.current = event.touches[0].clientX; }}
        onTouchEnd={(event) => {
          const delta = event.changedTouches[0].clientX - (touch.current ?? event.changedTouches[0].clientX);
          if (Math.abs(delta) > 40) go(index + ((delta < 0) !== (document.dir === 'rtl') ? 1 : -1));
          touch.current = null;
        }}
      >
        <ul className="testimonials__track" style={{ '--testimonials-index': index }}>
          {items.map((item, i) => (
            <li
              key={i}
              className="testimonials__slide"
              role="group"
              aria-roledescription={Drupal.t('slide')}
              aria-label={Drupal.t('@index of @count', { '@index': i + 1, '@count': count })}
              aria-hidden={i !== index}
              inert={i !== index ? '' : undefined}
            >
              <Card item={item} />
            </li>
          ))}
        </ul>
      </div>
      {count > 1 && (
        <div className="testimonials__controls">
          {canPlay && (
            <button type="button" className="testimonials__button" onClick={() => setPaused(!paused)} aria-label={paused ? Drupal.t('Play the quotes') : Drupal.t('Pause the quotes')}>
              <i className={`bi bi-${paused ? 'play-fill' : 'pause-fill'}`} aria-hidden="true" />
            </button>
          )}
          <button type="button" className="testimonials__button" onClick={() => go(index - 1)} aria-label={Drupal.t('Previous quote')}>
            <i className="bi bi-chevron-left" aria-hidden="true" />
          </button>
          <div className="testimonials__dots">
            {items.map((item, i) => (
              <button key={i} type="button" className="testimonials__dot" aria-current={i === index} aria-label={Drupal.t('Quote by @name', { '@name': item.name })} onClick={() => go(i)} />
            ))}
          </div>
          <button type="button" className="testimonials__button" onClick={() => go(index + 1)} aria-label={Drupal.t('Next quote')}>
            <i className="bi bi-chevron-right" aria-hidden="true" />
          </button>
        </div>
      )}
    </div>
  );
}

export function Testimonials({ heading, items = [], layout = 'slider', autoplay = true, interval = 7 }) {
  return (
    <>
      {heading && <h2 className="testimonials__heading">{heading}</h2>}
      {layout === 'slider'
        ? <Slider items={items} autoplay={autoplay} interval={interval} />
        : (
          <ul className="testimonials__grid">
            {items.map((item, i) => <li key={i} className="testimonials__card"><Card item={item} /></li>)}
          </ul>
        )}
    </>
  );
}

Countdown ​

components/countdown, React. Days, hours, minutes and seconds to a date.

Prop
heading, textaround the counter
targetthe date and time, in the time zone of the site
show_seconds
finishedthe message once the time has come
button, urla button under the counter
lookNumber cards, Plain or Accent band

The template turns the date into an ISO date with the offset of the site's time zone (target|date('c')), so every visitor counts down to the same moment. The server prints only the date, never the time left: a cached page would show a wrong one. The counter is hidden from screen readers; they get the time left in words ("12 days, 3 hours and 4 minutes") when they reach it, not every second.

Uses the date and time field of the editor. The prop names the widget (x-builder-widget: datetime) and checks the value with a pattern, instead of format: date-time: the field gives 2027-06-01T09:00, without seconds and offset, which core's validation of format: date-time rejects when assertions are on.

yaml
$schema: https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json
name: Countdown
status: experimental
description: 'Days, hours, minutes and seconds to a date: an opening, a sale, the next class. When the time comes it shows a message of its own. React.'
group: Marketing
help: |
  The date and time are in the time zone of the site, so every visitor counts down to the same moment.

  The page itself has the date in words; the counting runs in the browser. Screen readers hear the time left when they reach it, not every second.
props:
  type: object
  properties:
    heading:
      type: string
      title: Heading
      examples: ['The summer school opens in']
    target:
      type: string
      title: 'Date and time'
      description: 'In the time zone of the site: 2027-06-01T09:00.'
      # The editor's date and time field gives YYYY-MM-DDThh:mm, which core's "format: date-time" (RFC 3339, with
      # seconds and an offset) rejects. So the widget is named and the pattern checks the value.
      x-builder-widget: datetime
      pattern: '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}'
      examples: ['2027-06-01T09:00']
    text:
      type: string
      title: Text
      x-builder-widget: textarea
    show_seconds:
      type: boolean
      title: 'Show seconds'
      examples: [true]
    finished:
      type: string
      title: 'Message when the time has come'
      examples: ['We are open! Come and cook with us.']
    button:
      type: string
      title: 'Button text'
    url:
      type: string
      title: 'Button link'
      format: uri-reference
    look:
      type: string
      title: Look
      enum: [cards, plain, accent]
      meta:enum: { cards: 'Number cards', plain: Plain, accent: 'Accent band' }
      examples: [cards]
  required: [target]
thirdPartySettings:
  frame_editor:
    icon: 'bi bi-hourglass-split'
    example: { type: 'frame_demo_umami:countdown', props: { heading: 'Summer school opens in', target: '2027-06-01T09:00', show_seconds: true, finished: 'We are open!', button: 'Book now', url: '/classes', look: accent } }
libraryOverrides:
  js:
    ../../assets/countdown.js: { attributes: { type: module } }
  css:
    theme:
      ../../assets/countdown.css: { }
  dependencies:
    - frame/react
twig
{#
/**
 * @file
 * Countdown. The server prints the date (in the time zone of the site, with its offset for the browser); React
 * (index.jsx) counts down to it. No time left is printed by the server: the page may be cached.
 */
#}
{% set iso = target|date('c') %}
{% set data = { heading: heading, text: text, target: iso, showSeconds: show_seconds is same as(false) ? false : true, finished: finished, button: button, url: url } %}
<section {{ attributes.addClass('countdown', 'countdown--' ~ look|default('cards')).setAttribute('data-props', data|json_encode) }}>
  {% if heading %}<h2 class="countdown__heading">{{ heading }}</h2>{% endif %}
  <p class="countdown__date"><time datetime="{{ iso }}">{{ target|date('U')|format_date('long') }}</time></p>
  {% if text %}<p class="countdown__text">{{ text }}</p>{% endif %}
  {% if button and url %}<p class="countdown__action"><a class="countdown__button" href="{{ url }}">{{ button }}</a></p>{% endif %}
</section>
jsx
import { useEffect, useRef, useState } from 'react';

/** Days, hours, minutes and seconds from `now` to `target` (ms); all 0 once it has passed. */
export function remaining(target, now = Date.now()) {
  const left = Math.max(0, Math.floor((target - now) / 1000));
  return {
    done: left === 0,
    days: Math.floor(left / 86400),
    hours: Math.floor(left / 3600) % 24,
    minutes: Math.floor(left / 60) % 60,
    seconds: left % 60,
  };
}

/** The time left in words, for screen readers: "12 days, 3 hours and 4 minutes". */
export function inWords({ days, hours, minutes }) {
  const parts = [
    days && Drupal.formatPlural(days, '1 day', '@count days'),
    hours && Drupal.formatPlural(hours, '1 hour', '@count hours'),
    Drupal.formatPlural(minutes, '1 minute', '@count minutes'),
  ].filter(Boolean);
  return parts.length > 1 ? Drupal.t('@list and @last', { '@list': parts.slice(0, -1).join(', '), '@last': parts.at(-1) }) : parts[0];
}

export function Countdown({ heading, text, target, showSeconds = true, finished, button, url }) {
  const end = Date.parse(target);
  const [now, setNow] = useState(() => Date.now());
  const self = useRef(null);
  const left = remaining(end, now);

  useEffect(() => {
    if (left.done) return undefined;
    // On the second, so that all units change together.
    const timer = setInterval(() => (self.current?.isConnected === false ? clearInterval(timer) : setNow(Date.now())), 1000);
    return () => clearInterval(timer);
  }, [left.done]);

  if (Number.isNaN(end)) return null;
  const units = [
    ['days', left.days, Drupal.formatPlural(left.days, 'day', 'days')],
    ['hours', left.hours, Drupal.formatPlural(left.hours, 'hour', 'hours')],
    ['minutes', left.minutes, Drupal.formatPlural(left.minutes, 'minute', 'minutes')],
    ...(showSeconds ? [['seconds', left.seconds, Drupal.formatPlural(left.seconds, 'second', 'seconds')]] : []),
  ];
  const date = new Intl.DateTimeFormat(document.documentElement.lang || undefined, { dateStyle: 'long', timeStyle: 'short' }).format(end);

  return (
    <div ref={self}>
      {heading && <h2 className="countdown__heading">{heading}</h2>}
      {left.done
        ? <p className="countdown__finished" role="status">{finished || Drupal.t('The time has come.')}</p>
        : (
          <>
            <p className="visually-hidden">{Drupal.t('Time left: @time.', { '@time': inWords(left) })}</p>
            <ol className="countdown__units" role="timer" aria-hidden="true">
              {units.map(([key, value, label]) => (
                <li key={key} className={`countdown__unit countdown__unit--${key}`}>
                  <span className="countdown__number" key={value}>{String(value).padStart(2, '0')}</span>
                  <span className="countdown__label">{label}</span>
                </li>
              ))}
            </ol>
          </>
        )}
      <p className="countdown__date"><time dateTime={target}>{date}</time></p>
      {text && <p className="countdown__text">{text}</p>}
      {button && url && <p className="countdown__action"><a className="countdown__button" href={url}>{button}</a></p>}
    </div>
  );
}

Sign-up form ​

components/newsletter. A newsletter or waiting list sign-up.

Prop
heading, textbeside or above the form
action, field_namethe address the form is sent to, and the name of its e-mail field, as your mailing service gives them
ask_namea first name field
buttonthe text of the button
consentwith a text, a box to tick before sending
privacy_urla link under the form
thanksthe message after sending
layoutIn one line, One under the other, Text beside the form
lookAccent, Soft, Plain

Every field has a label and autocomplete. newsletter.js checks the fields with the browser's own validity, shows a message under the field (aria-invalid, aria-describedby) once it was left, and puts the focus on the first wrong field. Without an action the form sends nothing and shows the thank-you message, which is what a demo needs.

Limitations. The form posts to the mailing service as a normal form: the visitor leaves the page. There is no spam protection; a Drupal form (Webform, Contact) is the choice for data that should stay on the site.

yaml
$schema: https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json
name: 'Sign-up form'
status: experimental
description: 'A newsletter or waiting list sign-up: e-mail, an optional name and consent box, checked in the browser with readable messages. Sends to the address of your mailing service.'
group: Marketing
help: |
  "Send to" is the address the form is sent to: the form action your mailing service (Mailchimp, Brevo, Buttondown…) gives you, with "Field name" as it expects the e-mail.

  Without an address the form only checks what was typed and shows the thank-you message: good for a demo, it sends nothing.
props:
  type: object
  properties:
    heading:
      type: string
      title: Heading
      examples: ['Recipes in your inbox']
    text:
      type: string
      title: Text
      x-builder-widget: textarea
      examples: ['One seasonal recipe and the new classes, once a month. No spam, ever.']
    action:
      type: string
      title: 'Send to'
      description: 'The form action of your mailing service. Leave empty for a form that sends nothing.'
      format: uri
    field_name:
      type: string
      title: 'Field name of the e-mail'
      examples: ['email']
    ask_name:
      type: boolean
      title: 'Ask for the first name'
      examples: [false]
    button:
      type: string
      title: 'Button text'
      examples: ['Sign up']
    consent:
      type: string
      title: 'Consent text'
      description: 'With a text, a box to tick before sending: "I agree to receive the newsletter."'
      x-builder-widget: textarea
    privacy_url:
      type: string
      title: 'Privacy page'
      description: 'Linked under the form.'
      format: uri-reference
    thanks:
      type: string
      title: 'Thank-you message'
      x-builder-widget: textarea
      examples: ['Thank you! Check your inbox to confirm.']
    layout:
      type: string
      title: Arrangement
      enum: [inline, stacked, split]
      meta:enum: { inline: 'Field and button in one line', stacked: 'One under the other', split: 'Text beside the form' }
      examples: [split]
    look:
      type: string
      title: Look
      enum: [accent, soft, plain]
      meta:enum: { accent: Accent, soft: Soft, plain: Plain }
      examples: [soft]
  required: [heading]
thirdPartySettings:
  frame_editor:
    icon: form
    example: { type: 'frame_demo_umami:newsletter', props: { heading: 'Recipes in your inbox', text: 'One seasonal recipe a month.', button: 'Sign up', consent: 'I agree to receive the newsletter.', layout: split, look: accent } }
libraryOverrides:
  dependencies:
    - core/drupal
    - core/once
twig
{#
/**
 * @file
 * Sign-up form. newsletter.js checks the fields; without an action it shows the thank-you message and sends nothing.
 */
#}
{% set id = 'signup-' ~ random() %}
<section {{ attributes.addClass('signup', 'signup--' ~ layout|default('split'), 'signup--' ~ look|default('soft')).setAttribute('data-signup', '') }}>
  <div class="signup__intro">
    <h2 class="signup__heading" id="{{ id }}-heading">{{ heading }}</h2>
    {% if text %}<p class="signup__text">{{ text }}</p>{% endif %}
  </div>
  <form class="signup__form" aria-labelledby="{{ id }}-heading" novalidate{% if action %} action="{{ action }}" method="post"{% endif %} data-thanks="{{ thanks|default('Thank you!'|t) }}">
    <div class="signup__fields">
      {% if ask_name %}
        <div class="signup__field">
          <label for="{{ id }}-name">{{ 'First name'|t }}</label>
          <input id="{{ id }}-name" name="name" type="text" autocomplete="given-name">
        </div>
      {% endif %}
      <div class="signup__field signup__field--email">
        <label for="{{ id }}-email">{{ 'E-mail address'|t }}</label>
        <input id="{{ id }}-email" name="{{ field_name|default('email') }}" type="email" autocomplete="email" required aria-describedby="{{ id }}-email-error" placeholder="{{ 'you@example.com'|t }}">
        <p class="signup__error" id="{{ id }}-email-error" hidden></p>
      </div>
      <button class="signup__button" type="submit">{{ button|default('Sign up'|t) }}</button>
    </div>
    {% if consent %}
      <div class="signup__consent">
        <input id="{{ id }}-consent" name="consent" type="checkbox" value="1" required aria-describedby="{{ id }}-consent-error">
        <label for="{{ id }}-consent">{{ consent }}</label>
        <p class="signup__error" id="{{ id }}-consent-error" hidden></p>
      </div>
    {% endif %}
    {% if privacy_url %}<p class="signup__privacy"><a href="{{ privacy_url }}">{{ 'How we use your data'|t }}</a></p>{% endif %}
    <p class="signup__status" role="status" aria-live="polite"></p>
  </form>
</section>
js
/**
 * @file
 * Sign-up form: messages for the fields, and the thank-you message when the form has no action.
 */
((Drupal, once) => {
  const message = (input) => {
    if (input.validity.valueMissing) {
      return input.type === 'checkbox' ? Drupal.t('Please tick the box to sign up.') : Drupal.t('Please enter your e-mail address.');
    }
    if (input.validity.typeMismatch) return Drupal.t('This does not look like an e-mail address: name@example.com.');
    return '';
  };

  function check(input) {
    const error = document.getElementById(input.getAttribute('aria-describedby'));
    const text = message(input);
    input.setAttribute('aria-invalid', String(Boolean(text)));
    if (error) {
      error.textContent = text;
      error.hidden = !text;
    }
    return !text;
  }

  function init(root) {
    const form = root.querySelector('form');
    const status = form.querySelector('.signup__status');
    const inputs = [...form.querySelectorAll('input[required]')];
    inputs.forEach((input) => {
      // Messages show once the field was left, then follow what is typed.
      input.addEventListener('blur', () => check(input));
      input.addEventListener('input', () => input.getAttribute('aria-invalid') === 'true' && check(input));
      input.addEventListener('change', () => input.type === 'checkbox' && check(input));
    });
    form.addEventListener('submit', (event) => {
      const invalid = inputs.filter((input) => !check(input));
      if (invalid.length) {
        event.preventDefault();
        invalid[0].focus();
        return;
      }
      if (!form.getAttribute('action')) {
        event.preventDefault();
        form.classList.add('signup__form--done');
        status.textContent = form.dataset.thanks;
        form.reset();
      }
    });
  }

  Drupal.behaviors.frameDemoSignup = {
    attach(context) {
      once('frame-demo-signup', '[data-signup]', context).forEach(init);
    },
  };
})(Drupal, once);