Components

Collapsible

A part that opens in place and pushes what follows: a quiet DM Sans Medium trigger with a muted chevron that turns, and content that grows to its height and settles in.

Install

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

npx spyglass-ds add collapsible
<script type="module" src="/spyglass-ds/elements/collapsible.js"></script>
More filters
The rest of a list

Acme hooks that work

  • Acme skincare
  • Acme summer UGC
  • Acme founder stories

Usage

More filters under a search, the rest of a list, details a person asks for. Several questions in a stack are an accordion.

Never

  • Hiding what most people need
  • A chevron that moves on hover
  • Animating it when it is toggled from the keyboard

Adds with it: packages lucide-react

Props

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

<Collapsible>

PropTypeDefault
triggerClassstring

Classes for the trigger button, in place of the quiet row.

triggerReactNode | ((open: boolean) => ReactNode)

The trigger's content, or a function of whether it is open.

openboolean
defaultOpenbooleanfalse
onOpenChange(open: boolean) => void
childrenReactNode

Examples

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

react/examples/collapsible/Filters.tsx
import { Checkbox } from '@/react/components/ui/Checkbox'
import { Collapsible } from '@/react/components/ui/Collapsible'
// More filters, tucked under the search until a person asks for them.

export default function Filters() {
  return (
    <div className="w-100 max-w-full rounded-container bg-surface-raised px-4 py-2">
      <Collapsible trigger="More filters">
        <div className="flex flex-col pb-2">
          <Checkbox label="Still running" defaultChecked />
          <Checkbox label="Has a voiceover" />
          <Checkbox label="Under 30 seconds" />
        </div>
      </Collapsible>
    </div>
  )
}
elements/examples/collapsible/Filters.html
<!-- More filters, tucked under the search until a person asks for them. -->
<div class="w-100 max-w-full rounded-container bg-surface-raised px-4 py-2">
  <spyglass-collapsible>
    <span slot="trigger" class="contents">More filters</span>
    <div class="flex flex-col pb-2">
      <spyglass-checkbox label="Still running" checked></spyglass-checkbox>
      <spyglass-checkbox label="Has a voiceover"></spyglass-checkbox>
      <spyglass-checkbox label="Under 30 seconds"></spyglass-checkbox>
    </div>
  </spyglass-collapsible>
</div>
react/examples/collapsible/Boards.tsx
'use client'
import { Collapsible } from '@/react/components/ui/Collapsible'
// A list that shows its first boards and opens to the rest, open with the page.
const boards = ['Acme skincare', 'Acme summer UGC', 'Acme founder stories']

export default function Boards() {
  return (
    <div className="w-100 max-w-full">
      <p className="py-2 type-ui text-fg">Acme hooks that work</p>
      <Collapsible defaultOpen trigger={(open) => <span className="text-fg-muted">{open ? 'Show fewer boards' : 'Show 3 more boards'}</span>}>
        <ul className="flex flex-col">
          {boards.map((b) => <li key={b} className="py-2 type-ui text-fg">{b}</li>)}
        </ul>
      </Collapsible>
    </div>
  )
}
elements/examples/collapsible/Boards.html
<!-- A list that shows its first boards and opens to the rest, open with the page. -->
<div class="w-100 max-w-full">
  <p class="py-2 type-ui text-fg">Acme hooks that work</p>
  <spyglass-collapsible id="boards-more" open>
    <span slot="trigger" class="contents"><span class="text-fg-muted" data-label>Show fewer boards</span></span>
    <ul class="flex flex-col">
      <li class="py-2 type-ui text-fg">Acme skincare</li>
      <li class="py-2 type-ui text-fg">Acme summer UGC</li>
      <li class="py-2 type-ui text-fg">Acme founder stories</li>
    </ul>
  </spyglass-collapsible>
</div>
<script type="module">
  const more = document.getElementById('boards-more')
  more.addEventListener('open-change', (e) => {
    more.querySelector('[data-label]').textContent = e.detail.value ? 'Show fewer boards' : 'Show 3 more boards'
  })
</script>

Source

react/components/ui/Collapsible.tsx
'use client'
import { useId, useState, type MouseEvent, type ReactNode } from 'react'
import { ChevronDown } from 'lucide-react'
import { useControllable } from '@/react/hooks/useControllable'

// shadcn's collapsible in the brand: a part that opens in place and pushes what follows. The part grows to its
// content's height over 320ms on the strong ease-out and closes in 160ms; the content fades and settles 4px down; the
// muted chevron turns half a circle. Toggled from the keyboard it opens at once. The trigger's content is `trigger` (a
// node, or a function of `open`), drawn as a quiet DM Sans Medium row unless `triggerClass` says otherwise; it is a
// real button with aria-expanded and aria-controls. `open` with `onOpenChange` (or `defaultOpen` alone).
export interface CollapsibleProps {
  /** Classes for the trigger button, in place of the quiet row. */
  triggerClass?: string
  /** The trigger's content, or a function of whether it is open. */
  trigger?: ReactNode | ((open: boolean) => ReactNode)
  open?: boolean
  defaultOpen?: boolean
  onOpenChange?: (open: boolean) => void
  children?: ReactNode
}

export function Collapsible({ triggerClass, trigger, open: openProp, defaultOpen = false, onOpenChange, children }: CollapsibleProps) {
  const [open, setOpen] = useControllable(openProp, defaultOpen, onOpenChange)
  const [instant, setInstant] = useState(false)
  const id = `collapse-${useId()}`
  function toggle(event: MouseEvent) {
    setInstant(event.detail === 0)
    setOpen(!open)
  }
  return (
    <>
      <style href="ds-collapsible" precedence="ds">{css}</style>
      <div data-ds="collapsible" className="ds-collapsible" data-open={open || undefined} data-instant={instant || undefined}>
        <button
          type="button"
          className={triggerClass ?? 'flex w-full cursor-pointer items-center gap-2 rounded-control py-2 text-left type-ui-strong text-fg max-md:min-h-control-touch'}
          aria-expanded={open}
          aria-controls={id}
          onClick={toggle}
        >
          {typeof trigger === 'function' ? trigger(open) : trigger}
          <ChevronDown size={16} strokeWidth={1.5} className="ds-collapsible-chev ml-auto shrink-0 text-fg-muted" aria-hidden="true" />
        </button>
        <div id={id} className="ds-collapsible-region" inert={!open || undefined}>
          <div><div className="ds-collapsible-content">{children}</div></div>
        </div>
      </div>
    </>
  )
}

export default Collapsible

const css = `
/* The part opens to its content's height (0fr to 1fr) over 320ms and closes in 160ms, on the strong ease-out; the
   content fades and settles 4px down. The chevron turns half a circle (320ms, ease-in-out). Toggled from the keyboard
   it opens at once. Reduced motion: no height, move or turn, opacity only. */
.ds-collapsible-region { display: grid; grid-template-rows: 0fr; transition: grid-template-rows var(--ds-duration-exit) var(--ds-easing-out); }
.ds-collapsible[data-open] > .ds-collapsible-region { grid-template-rows: 1fr; transition-duration: var(--ds-duration-glide); }
.ds-collapsible-region > div { min-height: 0; overflow: hidden; }
.ds-collapsible-content { opacity: 0; transform: translateY(-4px); transition: opacity var(--ds-duration-exit) var(--ds-easing-standard), transform var(--ds-duration-exit) var(--ds-easing-out); }
.ds-collapsible[data-open] > .ds-collapsible-region .ds-collapsible-content { opacity: 1; transform: none; transition-duration: var(--ds-duration-glide); }
.ds-collapsible-chev { transition: rotate var(--ds-duration-glide) var(--ds-easing-in-out); }
.ds-collapsible[data-open] > button .ds-collapsible-chev { rotate: 180deg; }
.ds-collapsible[data-instant] :is(.ds-collapsible-region, .ds-collapsible-content, .ds-collapsible-chev) { transition: none; }
@media (prefers-reduced-motion: reduce) {
  .ds-collapsible-region, .ds-collapsible-chev { transition: none; }
  .ds-collapsible-content, .ds-collapsible[data-open] > .ds-collapsible-region .ds-collapsible-content { transform: none; }
}
`
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/collapsible.ts
import { html, type PropertyValues } from 'lit'
import { ChevronDown } from 'lucide'
import { DsElement, define, uid } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import styles from 'virtual:tw'

// Collapsible.tsx as <spyglass-collapsible>: a part that opens in place and pushes what follows. The part grows to its
// content's height over 320ms on the strong ease-out and closes in 160ms; the content fades and settles 4px down; the
// muted chevron turns half a circle. Toggled from the keyboard it opens at once. The trigger: content in the `trigger`
// slot, drawn as a quiet DM Sans Medium row with the chevron, or a <button slot="trigger"> you style yourself (React's
// triggerClass; draw your own chevron in it). `open` (the attribute) with `open-change`.

/**
 * @summary A part that opens in place and pushes what follows.
 * @slot - What opens.
 * @slot trigger - The trigger's content, or a <button> to use as the trigger.
 * @fires open-change - It opened or closed (detail.value).
 */
export class Collapsible extends DsElement {
	static styles = [DsElement.styles, styles]
	static properties = { open: { type: Boolean, reflect: true }, instant: { state: true } }

	open = false
	private instant = false
	private regionId = uid('collapse')

	private toggle = (event: MouseEvent) => {
		this.instant = event.detail === 0
		this.commit(!this.open, 'open')
	}

	// The page's own trigger button gets the button's attributes and the press.
	private wired: HTMLElement | null = null
	protected updated(changed: PropertyValues<this>) {
		super.updated(changed)
		const own = this.querySelector<HTMLElement>(':scope > button[slot="trigger"]')
		if (own !== this.wired) {
			this.wired?.removeEventListener('click', this.toggle)
			own?.addEventListener('click', this.toggle)
			this.wired = own
		}
		own?.setAttribute('aria-expanded', String(this.open))
	}
	disconnectedCallback() {
		super.disconnectedCallback()
		this.wired?.removeEventListener('click', this.toggle)
		this.wired = null
	}

	render() {
		const own = !!this.querySelector(':scope > button[slot="trigger"]')
		const trigger = own
			? html`<slot name="trigger"></slot>`
			: html`<button type="button" class="flex w-full cursor-pointer items-center gap-2 rounded-control py-2 text-left type-ui-strong text-fg max-md:min-h-control-touch" aria-expanded=${String(this.open)} aria-controls=${this.regionId} @click=${this.toggle}><slot name="trigger"></slot>${icon(ChevronDown, 'chevron-down', { size: 16, strokeWidth: 1.5, class: 'ds-collapsible-chev ml-auto shrink-0 text-fg-muted', attrs: { 'aria-hidden': 'true' } })}</button>`
		return html`<div data-ds="collapsible" class="ds-collapsible" ?data-open=${this.open} ?data-instant=${this.instant}>
			${trigger}
			<div id=${this.regionId} class="ds-collapsible-region" ?inert=${!this.open}>
				<div><div class="ds-collapsible-content"><slot></slot></div></div>
			</div>
		</div>`
	}
}

define('collapsible', Collapsible)
elements/components/ui/collapsible.css
/* Collapsible.tsx's styles, as they are. */
/* The part opens to its content's height (0fr to 1fr) over 320ms and closes in 160ms, on the strong ease-out; the
   content fades and settles 4px down. The chevron turns half a circle (320ms, ease-in-out). Toggled from the keyboard
   it opens at once. Reduced motion: no height, move or turn, opacity only. */
.ds-collapsible-region { display: grid; grid-template-rows: 0fr; transition: grid-template-rows var(--ds-duration-exit) var(--ds-easing-out); }
.ds-collapsible[data-open] > .ds-collapsible-region { grid-template-rows: 1fr; transition-duration: var(--ds-duration-glide); }
.ds-collapsible-region > div { min-height: 0; overflow: hidden; }
.ds-collapsible-content { opacity: 0; transform: translateY(-4px); transition: opacity var(--ds-duration-exit) var(--ds-easing-standard), transform var(--ds-duration-exit) var(--ds-easing-out); }
.ds-collapsible[data-open] > .ds-collapsible-region .ds-collapsible-content { opacity: 1; transform: none; transition-duration: var(--ds-duration-glide); }
.ds-collapsible-chev { transition: rotate var(--ds-duration-glide) var(--ds-easing-in-out); }
.ds-collapsible[data-open] > button .ds-collapsible-chev { rotate: 180deg; }
.ds-collapsible[data-instant] :is(.ds-collapsible-region, .ds-collapsible-content, .ds-collapsible-chev) { transition: none; }
@media (prefers-reduced-motion: reduce) {
  .ds-collapsible-region, .ds-collapsible-chev { transition: none; }
  .ds-collapsible-content, .ds-collapsible[data-open] > .ds-collapsible-region .ds-collapsible-content { transform: none; }
}

Reference: Derived from the guidelines: DM Sans Medium labels, muted neutrals for secondary text, the #262626 card fill. shadcn's collapsible for anatomy and ARIA..