Skip to Content
Cristal

Forms

Quantity

Quantity picker, a number between a − button and a + button.

<cr-quantity>CrQuantity

Example

The number sits between two round buttons, in a pill. Each click adds or removes one step; the number can also be typed, and is committed with Enter or when leaving the field. onCrInput gives every new value in event.detail, onCrChange every committed value (a step, or committed typing).

animation picks the effect of a step, played on click and on keyboard alike, in the direction of the change.

Orbit Mug

$28

'use client';

import { useState } from 'react';
import { CrBox, CrQuantity, CrSegmented } from '@cristal-ui/react';

const animations = [
  ['press', 'Press'],
  ['slide', 'Slide'],
  ['ripple', 'Ripple'],
  ['stretch', 'Stretch'],
  ['spin', 'Spin'],
  ['halo', 'Halo'],
] as const;

const PRICE = 14;

export default function QuantityProduct() {
  const [animation, setAnimation] = useState(0);
  const [quantity, setQuantity] = useState<number | undefined>(2);

  return (
    <CrBox display="flex" direction="column" gap="xl" align="center">
      <CrSegmented label="Animation" fit value={String(animation)} onCrChange={(event) => setAnimation(Number(event.detail))}>
        {animations.map(([value, label], index) => (
          <option key={value} value={index}>
            {label}
          </option>
        ))}
      </CrSegmented>
      <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 24, padding: 24, borderRadius: 'var(--cr-radius-l)', background: 'var(--cr-color-surface)', boxShadow: 'var(--cr-shadow-m)' }}>
        <div aria-hidden="true" style={{ width: 64, height: 64, borderRadius: 'var(--cr-radius-l)', background: 'radial-gradient(circle at 35% 30%, var(--cr-color-primary-subtle), var(--cr-color-primary))' }} />
        <div style={{ minWidth: 120 }}>
          <h3 style={{ margin: 0 }}>Orbit Mug</h3>
          <p style={{ margin: '4px 0 0', color: 'var(--cr-color-text-muted)' }}>${(PRICE * (quantity ?? 0)).toLocaleString('en-US')}</p>
        </div>
        <CrQuantity label="Quantity" max={9} value={quantity} animation={animations[animation][0]} onCrInput={(event) => setQuantity(event.detail)} />
      </div>
    </CrBox>
  );
}
animationEffect
pressthe button squishes softly, the new number pops up from small (default)
slidethe pill nudges toward the button, the new number slides in from that side and pushes the old one out
ripplea ripple spreads from the button across the pill and reveals the new number as it passes
stretchthe pill stretches toward the button and springs back; the number wobbles
spinthe − or + glyph spins half a turn, the number flips over edge-on
haloa glow ring bursts from the button, the new number zooms down from a larger size

When the user asks for less motion (prefers-reduced-motion), nothing moves: the number changes instantly.

Bounds and step

min (0 by default), max (none by default) and step (1 by default) bound the value. Without value, the picker starts at 0, brought between min and max. Steps start from min: with min={5} and step={5}, the allowed values are 5, 10, 15… The decimals of step set those of the number, shown in the page language format (2.5 in English).

At a bound, the matching button becomes inactive but keeps the focus: one more click does nothing. A typed number outside the bounds is brought back inside when committed.

Forms and validation

The picker sends its value under its name and goes back to its initial value with the form reset button. Errors show up by themselves, in English on an English page:

CaseMessage
required and emptiedThis field is required.
Out of bounds (value set by code)Choose a value between 5 and 50.
Off step (7 with a step of 5)Choose 5 or 10 (steps of 5).

error-animation animates the error when it appears and on every rejected submit: see Animated error. Type 7 then click Order.

OrderCancel

'use client';

import { useState } from 'react';
import { CrBox, CrButton, CrQuantity } from '@cristal-ui/react';

export default function QuantityForm() {
  const [sent, setSent] = useState('');

  return (
    <form
      style={{ display: 'grid', gap: 24, justifyItems: 'start' }}
      onSubmit={(event) => {
        event.preventDefault();
        setSent(`${new FormData(event.currentTarget).get('boxes')} boxes ordered.`);
      }}
    >
      <CrQuantity label="Boxes" name="boxes" hint="In packs of 5, from 5 to 50." min={5} max={50} step={5} required errorAnimation="zigzag" onCrInput={() => setSent('')} />
      <CrBox display="flex" gap="sm">
        <CrButton type="submit">Order</CrButton>
        <CrButton type="reset" variant="secondary">
          Cancel
        </CrButton>
      </CrBox>
      <p role="status" style={{ margin: 0 }}>
        {sent}
      </p>
    </form>
  );
}

Keyboard

KeyEffect
Up / Down Arrowone step more / less
Page Up / Page Downten steps more / less
Homethe minimum value
Endthe maximum value (when max is set)
Digits, then Entertypes a number and commits it; a second Enter submits the form
Tabmoves from − to the number, then to +

Accessibility

  • The number is a role="spinbutton" field (APG Spinbutton pattern), named by the label, with aria-valuenow, aria-valuemin and aria-valuemax; the numeric keyboard opens on mobile.
  • − and + are real buttons, named "Decrease" and "Increase" followed by the label ("Increase Quantity"): two pickers on the same page have distinct buttons. They point to the number with aria-controls.
  • At a bound, the button gets aria-disabled="true", not disabled: the focus stays on it, and the screen reader announces it as unavailable.
  • After a click on − or +, the new value is read by an invisible role="status" region; with the arrows in the field the screen reader already reads the value, so nothing is repeated.
  • 40 px buttons, 2 px visible focus, contrasted glyph and number in light and dark themes (the buttons lighten on a dark background). The new number never fades in from transparent: it grows, slides, flips or is revealed. In forced colours, the pill, buttons and focus take the system colours.

API

Properties

PropertyTypeDefaultDescription
animation"halo" | "press" | "ripple" | "slide" | "spin" | "stretch"'press'Animation d'un pas (bouton ou flèches) : press (le bouton s'écrase, le nombre surgit en grandissant, par défaut), slide (le nombre arrive du côté du bouton), ripple (une onde part du bouton et dévoile le nombre), stretch (la pastille s'étire, le nombre tangue), spin (le signe tourne, le nombre bascule) ou halo (un anneau jaillit, le nombre descend).
disabledbooleanfalseDésactive le sélecteur.
errorstring—Message d'erreur ; remplace le message automatique de validation.
errorAnimation"drop" | "echo" | "jitter" | "none" | "pop" | "wobble" | "zigzag"'none'Animation de l'erreur quand elle apparaît et à chaque envoi refusé : none (par défaut), zigzag, pop, drop, echo, jitter ou wobble.
hintstring—Texte d'aide, lu par les lecteurs d'écran.
label (obligatoire)string—Libellé affiché au-dessus du sélecteur ; il nomme aussi les boutons (« Augmenter Quantité »).
maxnumber—Valeur maximale ; aucune par défaut.
minnumber0Valeur minimale ; les pas partent d'elle.
namestring—Nom envoyé avec le formulaire.
requiredbooleanfalseRend la saisie obligatoire (le champ ne peut pas rester vide).
stepnumber1Écart entre deux valeurs permises ; ses décimales donnent celles du nombre affiché.
valuenumber—Quantité choisie ; undefined quand l'utilisateur a vidé le champ. Par défaut : 0 ramené entre min et max.

Events

Reactevent.detailDescription
onCrChangenumberÉmis quand une valeur est validée : chaque pas, ou la frappe validée par Entrée ou en quittant le champ ; detail : la quantité.
onCrInputnumberÉmis à chaque nouvelle valeur : chaque pas, et pendant la frappe ; detail : la quantité (undefined si le champ est vide).

CSS parts

To style it from outside: cr-quantity::part(name) { … }

PartDescription
buttonLes boutons − et +.
controlLe nombre (champ role="spinbutton").
labelLe libellé.

On this page