Components

Toggle Group

Buttons that stay pressed, side by side on one track with the brand corner. Each pressed one is a White block with Black text. On a narrow screen the track scrolls with fading edges.

Install

React apps get the React files; every other stack gets the web component.

npx spyglass-ds add toggle-group
<script type="module" src="/spyglass-ds/elements/toggle-group.js"></script>
Several or one

Formats

Grid

Usage

Options that are on or off together in a filter row: which formats to show, a grid size. multiple for several at once.

Never

  • Views of one thing: use Tabs
  • Actions: use Button
  • A spectrum color or a glow on the pressed block

Props

The web component takes the same as attributes or properties (<spyglass-toggle-group>); title is heading there.

<ToggleGroup>

PropTypeDefault
optionsreadonly ToggleGroupOption<T>[]

The buttons: a label that is its own value, or { value, label, disabled }.

labelstring

The group's name for assistive tech.

multipleboolean

Several can stay on (the value is an array).

sizeToggleGroupSize

sm (32px) or md (40px) in all.

'md'
valueT | T[] | null
defaultValueT | T[] | nullnull
onValueChange(value: T | T[] | null) => void
classNamestring

Examples

The same example in React and as web components; both render identically.

react/examples/toggle-group/Formats.tsx
import { ToggleGroup } from '@/react/components/ui/ToggleGroup'
// Which formats to show: several can stay on. And a size for the grid: one at most.

export default function Formats() {
  return (
    <div className="flex flex-col items-start gap-6">
      <div className="flex flex-col items-start gap-2">
        <p className="type-label text-fg-soft">Formats</p>
        <ToggleGroup label="Formats" multiple defaultValue={['Video', 'Image']} options={['Video', 'Image', 'Carousel', { value: 'Story', label: 'Story', disabled: true }]} />
      </div>
      <div className="flex flex-col items-start gap-2">
        <p className="type-label text-fg-soft">Grid</p>
        <ToggleGroup label="Grid" size="sm" defaultValue="Medium" options={['Small', 'Medium', 'Large']} />
      </div>
    </div>
  )
}
elements/examples/toggle-group/Formats.html
<!-- Which formats to show: several can stay on. And a size for the grid: one at most. -->
<div class="flex flex-col items-start gap-6">
  <div class="flex flex-col items-start gap-2">
    <p class="type-label text-fg-soft">Formats</p>
    <spyglass-toggle-group label="Formats" multiple value='["Video","Image"]' options='["Video","Image","Carousel",{"value":"Story","label":"Story","disabled":true}]'></spyglass-toggle-group>
  </div>
  <div class="flex flex-col items-start gap-2">
    <p class="type-label text-fg-soft">Grid</p>
    <spyglass-toggle-group label="Grid" size="sm" value="Medium" options='["Small","Medium","Large"]'></spyglass-toggle-group>
  </div>
</div>

Source

react/components/ui/ToggleGroup.tsx
'use client'
import { cn } from '@/react/lib/cn'
import { useControllable } from '@/react/hooks/useControllable'

// Buttons that stay pressed, side by side on one track, as the site's segmented control (controls.css --seg-*): a
// #1A1A1A tray in a #262626 ring with the 8px corner, 4px in, each pressed one a #363636 segment with White text (the
// small corner, nested inside the tray's), the rest soft gray that turns White under a hovering pointer. 32px (sm) or 40px (md) tall in all. `multiple` lets several stay on (the
// value is an array); otherwise one at most, and pressing it again lets it go. Colors change over 160ms; like the site's
// controls, nothing scales on press. For views of one thing use Tabs; this is for options that are on or
// off. `value` with `onValueChange` controls it (or `defaultValue` alone).
export type ToggleGroupOption<T extends string> = T | { value: T, label: string, disabled?: boolean }
export type ToggleGroupSize = 'sm' | 'md'

const ITEM: Record<ToggleGroupSize, string> = { sm: 'h-5.5 px-2', md: 'h-7.5 px-3' }

export interface ToggleGroupProps<T extends string> {
  /** The buttons: a label that is its own value, or { value, label, disabled }. */
  options: readonly ToggleGroupOption<T>[]
  /** The group's name for assistive tech. */
  label: string
  /** Several can stay on (the value is an array). */
  multiple?: boolean
  /** sm (32px) or md (40px) in all. */
  size?: ToggleGroupSize
  value?: T | T[] | null
  defaultValue?: T | T[] | null
  onValueChange?: (value: T | T[] | null) => void
  className?: string
}

const norm = <T extends string>(o: ToggleGroupOption<T>) => (typeof o === 'string' ? { value: o, label: o, disabled: false } : { disabled: false, ...o })

export function ToggleGroup<T extends string>({ options, label, multiple, size = 'md', value, defaultValue = null, onValueChange, className }: ToggleGroupProps<T>) {
  const [model, setModel] = useControllable<T | T[] | null>(value, defaultValue, onValueChange)
  const on = (v: T) => (Array.isArray(model) ? model.includes(v) : model === v)
  function press(v: T) {
    if (multiple) {
      const list = Array.isArray(model) ? model : []
      setModel(list.includes(v) ? list.filter(x => x !== v) : [...list, v])
    }
    else setModel(model === v ? null : v)
  }
  return (
    <div data-ds="toggle-group" role="group" aria-label={label} className={cn('inline-flex max-w-full rounded-control bg-surface-subtle shadow-[inset_0_0_0_var(--ds-border-hairline)_var(--ds-color-neutral-4)]', className)}>
      <div className="flex min-w-0 items-center gap-1 overflow-x-auto p-1 fade-x">
        {options.map(norm).map(o => (
          <button
            key={o.value}
            type="button"
            aria-pressed={on(o.value)}
            disabled={o.disabled}
            onClick={() => press(o.value)}
            className={cn('inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-ds-sm whitespace-nowrap type-ui-strong text-fg-soft select-none transition-[background-color,color] duration-160 ease-out not-aria-pressed:hover:not-disabled:text-fg aria-pressed:bg-surface-inset aria-pressed:text-fg disabled:cursor-not-allowed disabled:text-action-disabled-fg', ITEM[size])}
          >
            {o.label}
          </button>
        ))}
      </div>
    </div>
  )
}

export default ToggleGroup
react/lib/cn.ts
// Joins class names, skipping falsy ones: cn('a', on && 'b', ['c', undefined]). It does not merge conflicting
// utilities (no tailwind-merge), as Vue's class binding does not: the library's classes are written not to compete,
// and a className from the caller is appended after them, as Vue appends a fallthrough class.
export type ClassValue = string | false | null | undefined | 0 | ClassValue[]

export function cn(...values: ClassValue[]): string {
	const out: string[] = []
	for (const v of values) {
		if (!v) continue
		if (Array.isArray(v)) {
			const s = cn(...v)
			if (s) out.push(s)
		}
		else out.push(v)
	}
	return out.join(' ')
}
react/hooks/useControllable.ts
'use client'
import { useCallback, useRef, useState } from 'react'

// Vue's defineModel in React: a value that is controlled when the caller passes it (value + onValueChange, as Radix
// does) and kept inside otherwise (defaultValue). setValue calls onChange either way.
export function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
	const [inner, setInner] = useState<T>(defaultValue)
	const controlled = value !== undefined
	const current = controlled ? value : inner
	const ref = useRef(onChange)
	ref.current = onChange
	const set = useCallback((next: T) => {
		if (!controlled) setInner(next)
		ref.current?.(next)
	}, [controlled])
	return [current, set] as const
}
elements/components/ui/toggle-group.ts
import { html } from 'lit'
import { DsElement, define, HostLayoutController } from '@/elements/lib/element'
import styles from 'virtual:tw'

// ToggleGroup.tsx as <spyglass-toggle-group>: buttons that stay pressed, side by side on one track: the site's
// segmented control, a #1A1A1A tray in a #262626 ring, each pressed one a #363636 segment with White text, the rest soft
// gray. sm (32px) or md
// (40px) tall in all. `multiple` lets several stay on (the value is an array); otherwise one at most, and pressing it
// again lets it go. `options` is a JSON attribute or a property; the value is `value` (a string, a JSON array with
// `multiple`, or null) with `input` and `change`.

export type ToggleGroupOption = string | { value: string, label: string, disabled?: boolean }
export type ToggleGroupValue = string | string[] | null
const ITEM = { sm: 'h-5.5 px-2', md: 'h-7.5 px-3' } as const
export type ToggleGroupSize = keyof typeof ITEM

const norm = (o: ToggleGroupOption) => (typeof o === 'string' ? { value: o, label: o, disabled: false } : { disabled: false, ...o })
// value="Video" or value='["Video","Image"]'.
const fromAttribute = (v: string | null): ToggleGroupValue => (v === null ? null : v.trim().startsWith('[') ? JSON.parse(v) as string[] : v)

/**
 * @summary Buttons that stay pressed, on one track.
 * @fires input - A button was pressed (read `value`).
 * @fires change - A button was pressed (read `value`).
 */
export class ToggleGroup extends DsElement {
	static styles = [DsElement.styles, styles]
	protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('[data-ds="toggle-group"]'))
	static properties = { options: { type: Array }, label: {}, multiple: { type: Boolean }, size: { reflect: true }, value: { converter: { fromAttribute } } }

	/** The buttons: a label that is its own value, or { value, label, disabled }. */
	options: ToggleGroupOption[] = []
	/** The group's name for assistive tech. */
	label = ''
	/** Several can stay on (the value is an array). */
	multiple = false
	/** sm (32px) or md (40px) in all. */
	size: ToggleGroupSize = 'md'
	value: ToggleGroupValue = null

	private on(v: string) {
		return Array.isArray(this.value) ? this.value.includes(v) : this.value === v
	}
	private press(v: string) {
		if (this.multiple) {
			const list = Array.isArray(this.value) ? this.value : []
			this.commit(list.includes(v) ? list.filter((x) => x !== v) : [...list, v])
		} else this.commit(this.value === v ? null : v)
	}

	render() {
		const item = ITEM[this.size] ?? ITEM.md
		const classes = `inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-ds-sm whitespace-nowrap type-ui-strong text-fg-soft select-none transition-[background-color,color] duration-160 ease-out not-aria-pressed:hover:not-disabled:text-fg aria-pressed:bg-surface-inset aria-pressed:text-fg disabled:cursor-not-allowed disabled:text-action-disabled-fg ${item}`
		return html`<div data-ds="toggle-group" role="group" aria-label=${this.label} class="inline-flex max-w-full rounded-control bg-surface-subtle shadow-[inset_0_0_0_var(--ds-border-hairline)_var(--ds-color-neutral-4)]"><div class="flex min-w-0 items-center gap-1 overflow-x-auto p-1 fade-x">${this.options.map(norm).map((o) => html`<button type="button" aria-pressed=${String(this.on(o.value))} ?disabled=${o.disabled} class=${classes} @click=${() => this.press(o.value)}>${o.label}</button>`)}</div></div>`
	}
}

define('toggle-group', ToggleGroup)

Reference: Derived from the brand guidelines (no segmented control in the brand assets): the input's hairline and corner, White as the one pressed state.