Skip to content

Rating

A star-based rating input that lets users select a score. Supports hover preview, keyboard navigation, readonly and disabled modes, and HTML form integration.

Features

  • ⌨️ Keyboard Navigation/ arrows adjust value; Home/End jump to extremes
  • Configurable Stars — any number of stars via max (default 5)
  • 🌈 6 Semantic Colors — primary, secondary, info, success, warning, error
  • 📏 3 Sizes — sm, md, lg
  • 🔒 Readonly & Disabled — readonly shows a non-interactive score; disabled removes from tab order
  • 🔗 Form-Associatedname attribute & native form reset support
  • 🖱️ Hover Preview — stars fill on hover before selection is committed

Source Code

View Source Code
ts
import { computed, defineComponent, typed, defineField, html, inject, signal } from '@vielzeug/craftit';

import type { DisablableProps, SizableProps, ThemableProps } from '../../types';

import { coarsePointerMixin, colorThemeMixin, reducedMotionMixin, sizeVariantMixin } from '../../styles';
import { mountFormContextSync } from '../shared/dom-sync';
import { FORM_CTX } from '../shared/form-context';
import { createFieldValidation } from '../shared/validation';
import styles from './rating.css?inline';

const FULL_STAR_PATH = 'M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z';

export type BitRatingEvents = {
  change: { originalEvent?: Event; value: number };
};

/** Rating props */
export type BitRatingProps = ThemableProps &
  SizableProps &
  DisablableProps & {
    /** Accessible group label */
    label?: string;
    /** Maximum rating (number of stars) */
    max?: number;
    /** Form field name */
    name?: string;
    /** Make rating read-only */
    readonly?: boolean;
    /** Current rating value */
    value?: number;
  };

/**
 * A star rating input.
 *
 * @element bit-rating
 *
 * @attr {number} value - Current rating value (default: 0)
 * @attr {number} max - Maximum number of stars (default: 5)
 * @attr {boolean} readonly - Read-only display mode
 * @attr {boolean} disabled - Disabled state
 * @attr {string} label - aria-label for the group (default: 'Rating')
 * @attr {string} color - Theme color for filled stars
 * @attr {string} size - 'sm' | 'md' | 'lg'
 * @attr {string} name - Form field name
 *
 * @fires change - Emitted when value changes. detail: { value: number, originalEvent?: Event }
 *
 * @cssprop --rating-star-size - Star diameter
 * @cssprop --rating-color-empty - Empty star color
 * @cssprop --rating-color-filled - Filled star color
 * @cssprop --rating-gap - Gap between stars
 *
 * @example
 * ```html
 * <bit-rating value="3" max="5" color="warning"></bit-rating>
 * ```
 */
export const RATING_TAG = defineComponent<BitRatingProps, BitRatingEvents>({
  formAssociated: true,
  props: {
    color: typed<BitRatingProps['color']>(undefined),
    disabled: typed<boolean>(false),
    label: typed<string>('Rating'),
    max: typed<number>(5),
    name: typed<string | undefined>(undefined),
    readonly: typed<boolean>(false),
    size: typed<BitRatingProps['size']>(undefined),
    value: typed<number>(0),
  },
  setup({ emit, host, props }) {
    const formCtx = inject(FORM_CTX, undefined);

    mountFormContextSync(host, formCtx, props);

    const normalizedValue = computed(() => {
      const max = Math.max(1, Number(props.max.value) || 5);
      const raw = Number(props.value.value);
      const safe = Number.isFinite(raw) ? raw : 0;

      return Math.min(max, Math.max(0, safe));
    });

    const fd = defineField(
      {
        disabled: computed(() => Boolean(props.disabled.value)),
        value: computed(() => String(normalizedValue.value || 0)),
      },
      {
        onReset: () => {
          host.removeAttribute('value');
        },
      },
    );

    const { triggerValidation } = createFieldValidation(formCtx, fd);

    const hovered = signal<number | null>(null);
    const displayValue = computed(() => hovered.value ?? normalizedValue.value);

    function spawnSparkles(star: number) {
      const layer = host.shadowRoot?.querySelector<HTMLElement>('.sparkle-layer');
      const btn = host.shadowRoot?.querySelector<HTMLElement>(`[data-star="${star}"]`);

      if (!layer || !btn) return;

      const cx = btn.offsetLeft + btn.offsetWidth / 2;
      const cy = btn.offsetTop + btn.offsetHeight / 2;
      const count = 10;

      for (let i = 0; i < count; i++) {
        const p = document.createElement('span');
        const angle = (360 / count) * i + (Math.random() * 30 - 15);
        const dist = 18 + Math.random() * 20;
        const size = 3 + Math.random() * 4;
        const dur = 380 + Math.random() * 220;

        p.className = 'sparkle';
        p.style.cssText = [
          `left:${cx}px`,
          `top:${cy}px`,
          `--_angle:${angle}deg`,
          `--_dist:${dist}px`,
          `width:${size}px`,
          `height:${size}px`,
          `--_dur:${dur}ms`,
          `animation-delay:${Math.random() * 60}ms`,
        ].join(';');
        layer.appendChild(p);
        p.addEventListener('animationend', () => p.remove(), { once: true });
      }
    }
    function select(star: number, originalEvent?: Event) {
      if (props.readonly.value || props.disabled.value) return;

      const max = Math.max(1, Number(props.max.value) || 5);
      const nextValue = Math.min(max, Math.max(0, star));

      if (nextValue === normalizedValue.value) return;

      // Write through the reactive prop signal; craftit handles host reflection.
      props.value.value = nextValue;
      emit('change', { originalEvent, value: nextValue });
      triggerValidation('change');
      spawnSparkles(nextValue);
    }
    function handleKeydown(e: KeyboardEvent, star: number) {
      const max = Number(props.max.value) || 5;

      if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
        e.preventDefault();
        select(Math.min(max, star + 1), e);

        const nextBtn = host.shadowRoot?.querySelector<HTMLButtonElement>(`[data-star="${Math.min(max, star + 1)}"]`);

        nextBtn?.focus();
      } else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
        e.preventDefault();
        select(Math.max(1, star - 1), e);

        const prevBtn = host.shadowRoot?.querySelector<HTMLButtonElement>(`[data-star="${Math.max(1, star - 1)}"]`);

        prevBtn?.focus();
      }
    }

    const stars = computed(() => {
      const max = Number(props.max.value) || 5;

      return Array.from({ length: max }, (_, i) => i + 1);
    });

    return html`
      <div
        class="stars"
        part="stars"
        role="radiogroup"
        :aria-label="${() => props.label.value}"
        :aria-required="${() => null}">
        ${() =>
          stars.value.map(
            (star) =>
              html`<button
                class="star-btn"
                part="star"
                type="button"
                role="radio"
                :aria-label="${() => `${star} ${star === 1 ? 'star' : 'stars'}`}"
                :aria-checked="${() => String(star === normalizedValue.value)}"
                :data-star="${star}"
                ?data-filled="${() => star <= displayValue.value}"
                :disabled="${() => props.disabled.value || props.readonly.value || null}"
                @click="${(e: Event) => select(star, e)}"
                @pointerenter="${() => {
                  if (!props.readonly.value && !props.disabled.value) hovered.value = star;
                }}"
                @pointerleave="${() => {
                  hovered.value = null;
                }}"
                @keydown="${(e: KeyboardEvent) => handleKeydown(e, star)}">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  aria-hidden="true"
                  fill="${() => (star <= displayValue.value ? 'currentColor' : 'none')}"
                  stroke="currentColor"
                  stroke-width="${() => (star <= displayValue.value ? 0 : 1.5)}"
                  stroke-linecap="round"
                  stroke-linejoin="round">
                  <path d="${FULL_STAR_PATH}" />
                </svg>
              </button>`,
          )}
        <div class="sparkle-layer"></div>
      </div>
    `;
  },
  styles: [colorThemeMixin, sizeVariantMixin({}), coarsePointerMixin, reducedMotionMixin, styles],
  tag: 'bit-rating',
});

Basic Usage

html
<bit-rating label="Product rating" value="3"></bit-rating>

<script type="module">
  import '@vielzeug/buildit';
</script>

Listen for changes:

html
<bit-rating id="rating" label="Rate this article" color="warning"></bit-rating>

<script type="module">
  import '@vielzeug/buildit';

  document.getElementById('rating').addEventListener('change', (e) => {
    console.log('Rating:', e.detail.value);
  });
</script>

Colors

PreviewCode
RTL

Sizes

PreviewCode
RTL

Custom Max

PreviewCode
RTL

Readonly

Use readonly to display a rating without allowing user interaction — useful for showing review scores.

PreviewCode
RTL

Disabled

PreviewCode
RTL

API Reference

Attributes

AttributeTypeDefaultDescription
valuenumber0Current selected rating
maxnumber5Total number of stars
readonlybooleanfalsePrevents user interaction; shows value only
disabledbooleanfalseDisables the rating input
labelstringAccessible label for the rating group
namestringForm field name
color'primary' | 'secondary' | 'info' | 'success' | 'warning' | 'error'Star highlight color
size'sm' | 'md' | 'lg''md'Star size

Events

EventDetailDescription
change{ value: number }Fired when the user selects a rating

CSS Custom Properties

PropertyDescription
--rating-star-sizeSize of each star icon
--rating-color-emptyColor of unselected stars
--rating-color-filledColor of selected / hovered stars
--rating-gapGap between stars

Accessibility

The rating component follows WCAG 2.1 Level AA standards.

bit-rating

Keyboard Navigation

  • / arrow keys move and commit the selection.
  • Home / End jump to 1 / max; Tab moves focus in and out.

Screen Readers

  • The group uses role="radiogroup"; each star uses role="radio" with aria-checked reflecting the current selection.
  • aria-labelledby links the group label.
  • aria-disabled reflects the disabled state; aria-readonly reflects the readonly state.
  • Hover previews stars visually without committing the value.

Best Practices

Do:

  • Always provide a label attribute so screen readers announce the context (e.g. "Product rating").
  • Use readonly rather than disabled when showing an existing score that the user cannot change — readonly keeps the element accessible in the reading order.
  • Use colour together with label text to reinforce meaning (e.g. color="warning" for a gold star aesthetic).

Don't:

  • Use rating for non-numeric preference input — a bit-select or bit-radio-group conveys options more clearly.
  • Omit the label attribute — an unlabelled rating group is inaccessible.
  • Slider — drag-based numeric value picker