Components

Toggle

A button that stays pressed: no fill or a hairline at rest, the primary White with Black text while it is on. Sizes match the button's.

Install

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

npx spyglass-ds add toggle
<script type="module" src="/spyglass-ds/elements/toggle.js"></script>
Filters
Sizes

Usage

One option that is on or off in a row of filters or tools: video only, saved only, show captions.

Never

  • A setting saved at once: use Switch
  • A pick of one from several: use Toggle Group or Tabs
  • A spectrum color for the pressed state

Props

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

<Toggle>

PropTypeDefault
variantToggleVariant

default (no fill at rest) or outline (a hairline).

'default'
sizeToggleSize

sm (32px), md (40px) or lg (48px).

'md'
iconboolean

A square icon toggle: put its name in aria-label.

pressedboolean
defaultPressedbooleanfalse
onPressedChange(pressed: boolean) => void
childrenReactNode

Examples

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

react/examples/toggle/Toolbar.tsx
import { Bookmark, Grid2x2, Play } from 'lucide-react'
import { Toggle } from '@/react/components/ui/Toggle'
// Filters over a grid of creatives: each stays on until pressed again.

export default function Toolbar() {
  return (
    <div className="flex flex-wrap items-center gap-2">
      <Toggle defaultPressed><Play size={16} strokeWidth={1.5} aria-hidden="true" />Video</Toggle>
      <Toggle><Grid2x2 size={16} strokeWidth={1.5} aria-hidden="true" />Carousel</Toggle>
      <Toggle variant="outline" icon aria-label="Saved only"><Bookmark size={16} strokeWidth={1.5} aria-hidden="true" /></Toggle>
      <Toggle variant="outline" disabled>UGC</Toggle>
    </div>
  )
}
elements/examples/toggle/Toolbar.html
<!-- Filters over a grid of creatives: each stays on until pressed again. -->
<div class="flex flex-wrap items-center gap-2">
  <spyglass-toggle pressed><i data-lucide="play" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Video</spyglass-toggle>
  <spyglass-toggle><i data-lucide="grid-2x2" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Carousel</spyglass-toggle>
  <spyglass-toggle variant="outline" icon aria-label="Saved only"><i data-lucide="bookmark" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i></spyglass-toggle>
  <spyglass-toggle variant="outline" disabled>UGC</spyglass-toggle>
</div>
react/examples/toggle/Sizes.tsx
import { Toggle } from '@/react/components/ui/Toggle'
// The three sizes, pressed, beside the button's.

export default function Sizes() {
  return (
    <div className="flex flex-wrap items-center gap-2">
      <Toggle size="sm" variant="outline" defaultPressed>Small</Toggle>
      <Toggle size="md" variant="outline" defaultPressed>Medium</Toggle>
      <Toggle size="lg" variant="outline" defaultPressed>Large</Toggle>
    </div>
  )
}
elements/examples/toggle/Sizes.html
<!-- The three sizes, pressed, beside the button's. -->
<div class="flex flex-wrap items-center gap-2">
  <spyglass-toggle size="sm" variant="outline" pressed>Small</spyglass-toggle>
  <spyglass-toggle size="md" variant="outline" pressed>Medium</spyglass-toggle>
  <spyglass-toggle size="lg" variant="outline" pressed>Large</spyglass-toggle>
</div>

Source

react/components/ui/Toggle.tsx
'use client'
import type { ButtonHTMLAttributes, ReactNode } from 'react'
import { cn } from '@/react/lib/cn'
import { useControllable } from '@/react/hooks/useControllable'

// A button that stays pressed: no fill at rest (soft gray text, the ghost fill under a hovering pointer) or, as
// `outline`, a #666666 hairline; pressed it takes the primary White with Black text, the brand's one White state. Sizes
// follow the button's: sm 32px, md 40px, lg 56px; `icon` makes it square (put its name in aria-label). Nothing scales on press
// (the site's controls do not); colors change over 160ms. Icons never move. `pressed`
// with `onPressedChange` controls it (or `defaultPressed` alone). Every other prop lands on the <button>.
export type ToggleVariant = 'default' | 'outline'
export type ToggleSize = 'sm' | 'md' | 'lg'

const VARIANTS: Record<ToggleVariant, string> = {
  default: 'bg-transparent',
  outline: 'border border-edge-strong bg-surface aria-pressed:border-action-primary not-aria-pressed:hover:not-disabled:border-action-secondary-edge-hover',
}
const SIZES: Record<ToggleSize, string> = { sm: 'h-control-sm gap-1.5 type-ui-strong', md: 'h-control-md gap-2 type-ui-strong', lg: 'h-control-lg gap-2 type-body font-medium' }
// One padding class per toggle, so a square toggle's 0 never competes with a label's padding.
const PADDING: Record<ToggleSize, string> = { sm: 'px-2.5', md: 'px-3', lg: 'px-4' }
const SQUARE: Record<ToggleSize, string> = { sm: 'w-control-sm px-0', md: 'w-control-md px-0', lg: 'w-control-lg px-0' }

export interface ToggleProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'type' | 'onClick'> {
  /** default (no fill at rest) or outline (a hairline). */
  variant?: ToggleVariant
  /** sm (32px), md (40px) or lg (48px). */
  size?: ToggleSize
  /** A square icon toggle: put its name in aria-label. */
  icon?: boolean
  pressed?: boolean
  defaultPressed?: boolean
  onPressedChange?: (pressed: boolean) => void
  children?: ReactNode
}

export function toggleClasses({ variant = 'default', size = 'md', icon }: Pick<ToggleProps, 'variant' | 'size' | 'icon'> = {}) {
  return cn(
    'inline-flex shrink-0 cursor-pointer items-center justify-center rounded-control whitespace-nowrap select-none text-fg-soft',
    'transition-[background-color,color,border-color] duration-160 ease-out',
    'not-aria-pressed:hover:not-disabled:bg-action-ghost-hover not-aria-pressed:hover:not-disabled:text-fg aria-pressed:bg-action-primary aria-pressed:text-action-primary-fg aria-pressed:hover:not-disabled:bg-action-primary-hover',
    'disabled:cursor-not-allowed disabled:text-action-disabled-fg disabled:aria-pressed:bg-action-disabled',
    SIZES[size],
    icon ? SQUARE[size] : PADDING[size],
    VARIANTS[variant],
  )
}

export function Toggle({ variant = 'default', size = 'md', icon, pressed, defaultPressed = false, onPressedChange, className, children, ...rest }: ToggleProps) {
  const [on, setOn] = useControllable(pressed, defaultPressed, onPressedChange)
  return <button data-ds="toggle" type="button" {...rest} className={cn(toggleClasses({ variant, size, icon }), className)} aria-pressed={on} onClick={() => setOn(!on)}>{children}</button>
}

export default Toggle
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.ts
import { html } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { DsElement, define, HostLayoutController } from '@/elements/lib/element'
import styles from 'virtual:tw'

// Toggle.tsx as <spyglass-toggle>: a button that stays pressed: no fill at rest (or, as `outline`, a #363636
// hairline); pressed it takes the primary White with Black text. Sizes sm (32px), md (40px), lg (48px); `icon` makes it
// square (put its name in aria-label). colors change over 160ms. `pressed` (an
// attribute) with `pressed-change`.

const VARIANTS = {
	default: 'bg-transparent',
	outline: 'border border-edge-strong bg-surface aria-pressed:border-action-primary not-aria-pressed:hover:not-disabled:border-action-secondary-edge-hover',
} as const
const SIZES = { sm: 'h-control-sm gap-1.5 type-ui-strong', md: 'h-control-md gap-2 type-ui-strong', lg: 'h-control-lg gap-2 type-body font-medium' } as const
const PADDING = { sm: 'px-2.5', md: 'px-3', lg: 'px-4' } as const
const SQUARE = { sm: 'w-control-sm px-0', md: 'w-control-md px-0', lg: 'w-control-lg px-0' } as const
export type ToggleVariant = keyof typeof VARIANTS
export type ToggleSize = keyof typeof SIZES

/**
 * @summary A button that stays pressed.
 * @slot - The label, with a Lucide icon before it if any.
 * @fires pressed-change - It was pressed; detail.value is the new state.
 */
export class Toggle extends DsElement {
	static styles = [DsElement.styles, styles]
	protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('button'))
	static properties = {
		pressed: { type: Boolean, reflect: true },
		disabled: { type: Boolean, reflect: true },
		variant: { reflect: true },
		size: { reflect: true },
		icon: { type: Boolean },
		label: { attribute: 'aria-label' },
	}

	pressed = false
	disabled = false
	/** default (no fill at rest) or outline (a hairline). */
	variant: ToggleVariant = 'default'
	/** sm (32px), md (40px) or lg (48px). */
	size: ToggleSize = 'md'
	/** A square icon toggle (put its name in aria-label). */
	icon = false
	/** The name for assistive tech, passed to the inner button. */
	label?: string

	render() {
		const size = SIZES[this.size] ? this.size : 'md'
		const classes = [
			'inline-flex shrink-0 cursor-pointer items-center justify-center rounded-control whitespace-nowrap select-none text-fg-soft',
			'transition-[background-color,color,border-color] duration-160 ease-out',
			'not-aria-pressed:hover:not-disabled:bg-action-ghost-hover not-aria-pressed:hover:not-disabled:text-fg aria-pressed:bg-action-primary aria-pressed:text-action-primary-fg aria-pressed:hover:not-disabled:bg-action-primary-hover',
			'disabled:cursor-not-allowed disabled:text-action-disabled-fg disabled:aria-pressed:bg-action-disabled',
			SIZES[size],
			this.icon ? SQUARE[size] : PADDING[size],
			VARIANTS[this.variant] ?? VARIANTS.default,
		].join(' ')
		return html`<button data-ds="toggle" type="button" class=${classes} aria-pressed=${String(this.pressed)} aria-label=${ifDefined(this.label)} ?disabled=${this.disabled} @click=${() => this.commit(!this.pressed, 'pressed')}><slot></slot></button>`
	}
}

define('toggle', Toggle)

Reference: Derived from the brand guidelines (no toggle in the brand assets): the button's sizes, corner and press, White as the one pressed state.