Components
Accordion
A stack of disclosures on Black: neutral hairlines between the rows, a DM Sans question, a muted answer that opens in place and a chevron that turns. One open at a time, or several.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add accordion<script type="module" src="/spyglass-ds/elements/accordion.js"></script>Usage
Questions on a pricing or help page, filters a person opens one by one, settings that would crowd a view.
Never
- Hiding the one thing a person came for: put it on the page
- A #262626 card per row: rows are hairlines on Black
- A chevron that moves on hover
Adds with it: packages lucide-react
Props
The web component takes the same as attributes or properties (<spyglass-accordion>); title is heading there.
<Accordion>
| Prop | Type | Default |
|---|---|---|
multiple | boolean Several rows stay open. | |
value | AccordionValue The open row's value, or the list of them with `multiple`. | |
defaultValue | AccordionValue | null |
onValueChange | (value: AccordionValue) => void | |
className | string | |
children | ReactNode |
<AccordionItem>
| Prop | Type | Default |
|---|---|---|
value | string The value the accordion opens it by. | |
title | ReactNode The question. | |
disabled | boolean | |
children | ReactNode |
Examples
The same example in React and as web components; both render identically.
import { Accordion } from '@/react/components/ui/Accordion'
import { AccordionItem } from '@/react/components/ui/AccordionItem'
// Questions on a pricing page, one open at a time; the first opens with the page.
export default function Faq() {
return (
<Accordion defaultValue="what" className="w-160 max-w-full">
<AccordionItem value="what" title="What is Spyglass?">The only creative search engine. Ask in words for ads, product shots and UGC, and see what is running.</AccordionItem>
<AccordionItem value="price" title="How much does it cost?">$10 for your first month, then $20/month.</AccordionItem>
<AccordionItem value="boards" title="Can I share a board with my team?">Yes. Save creatives to a board and send the link to Acme's whole team.</AccordionItem>
</Accordion>
)
}<!-- Questions on a pricing page, one open at a time; the first opens with the page. -->
<spyglass-accordion value="what" class="w-160 max-w-full">
<spyglass-accordion-item value="what" heading="What is Spyglass?">The only creative search engine. Ask in words for ads, product shots and UGC, and see what is running.</spyglass-accordion-item>
<spyglass-accordion-item value="price" heading="How much does it cost?">$10 for your first month, then $20/month.</spyglass-accordion-item>
<spyglass-accordion-item value="boards" heading="Can I share a board with my team?">Yes. Save creatives to a board and send the link to Acme's whole team.</spyglass-accordion-item>
</spyglass-accordion>import { Accordion } from '@/react/components/ui/Accordion'
import { AccordionItem } from '@/react/components/ui/AccordionItem'
// Several rows open at once, for filters a person compares side by side; the last is not available yet.
export default function Multiple() {
return (
<Accordion multiple defaultValue={['format', 'platform']} className="w-120 max-w-full">
<AccordionItem value="format" title="Format">Video, carousel, static image.</AccordionItem>
<AccordionItem value="platform" title="Platform">Meta, TikTok, YouTube.</AccordionItem>
<AccordionItem value="spend" title="Estimated spend" disabled>Coming soon.</AccordionItem>
</Accordion>
)
}<!-- Several rows open at once, for filters a person compares side by side; the last is not available yet. -->
<spyglass-accordion multiple value='["format","platform"]' class="w-120 max-w-full">
<spyglass-accordion-item value="format" heading="Format">Video, carousel, static image.</spyglass-accordion-item>
<spyglass-accordion-item value="platform" heading="Platform">Meta, TikTok, YouTube.</spyglass-accordion-item>
<spyglass-accordion-item value="spend" heading="Estimated spend" disabled>Coming soon.</spyglass-accordion-item>
</spyglass-accordion>Source
'use client'
import type { ReactNode } from 'react'
import { AccordionContext } from '@/react/hooks/useAccordion'
import { useControllable } from '@/react/hooks/useControllable'
import { cn } from '@/react/lib/cn'
// shadcn's accordion in the brand: a stack of disclosures on Black with neutral hairlines between the rows, a muted
// chevron that turns as a row opens, the row opening to its content's height over 320ms on the strong ease-out and
// closing in 160ms. One open at a time by default (a second press closes it); `multiple` lets several stay open.
// `value` with `onValueChange` (or `defaultValue` alone) is the open row's value, or the list of them with `multiple`.
// Compose with AccordionItem.
export type AccordionValue = string | string[] | null
export interface AccordionProps {
/** Several rows stay open. */
multiple?: boolean
/** The open row's value, or the list of them with `multiple`. */
value?: AccordionValue
defaultValue?: AccordionValue
onValueChange?: (value: AccordionValue) => void
className?: string
children?: ReactNode
}
export function Accordion({ multiple, value, defaultValue = null, onValueChange, className, children }: AccordionProps) {
const [model, setModel] = useControllable<AccordionValue>(value, defaultValue, onValueChange)
const list = Array.isArray(model) ? model : model ? [model] : []
const ctx = {
isOpen: (v: string) => list.includes(v),
toggle: (v: string) => {
if (multiple) setModel(list.includes(v) ? list.filter(x => x !== v) : [...list, v])
else setModel(list.includes(v) ? null : v)
},
}
return (
<AccordionContext.Provider value={ctx}>
<div data-ds="accordion" className={cn('border-t border-edge', className)}>{children}</div>
</AccordionContext.Provider>
)
}
export default Accordion'use client'
import { useId, type ReactNode } from 'react'
import { ChevronDown } from 'lucide-react'
import { useAccordion } from '@/react/hooks/useAccordion'
// One row of an Accordion: the question as a full-width button (DM Sans 16px, soft White that turns full White under
// the pointer and while open) over a neutral hairline, and the answer under it in #D4D4D4 DM Sans 16/24, no wider than 640px (the site's FAQ: rows 56px tall, 20px in). The chevron turns
// half a circle as the row opens (320ms, ease-in-out); it never moves on hover. The closed answer is inert, so its
// links leave the tab order. `title` names the row; children are the answer.
export interface AccordionItemProps {
/** The value the accordion opens it by. */
value: string
/** The question. */
title?: ReactNode
disabled?: boolean
children?: ReactNode
}
export function AccordionItem({ value, title, disabled, children }: AccordionItemProps) {
const ctx = useAccordion()
const open = ctx?.isOpen(value) ?? false
const id = useId()
return (
<>
<style href="ds-accordion-item" precedence="ds">{css}</style>
<div data-ds="accordion-item" className="border-b border-edge" data-open={open}>
<h3>
<button
id={`${id}-head`}
type="button"
aria-expanded={open}
aria-controls={`${id}-body`}
disabled={disabled}
className="flex min-h-control-lg w-full cursor-pointer items-center justify-between gap-6 py-5 text-left type-body text-fg-soft transition-[color] duration-160 ease-standard hover:text-fg aria-expanded:text-fg disabled:cursor-not-allowed disabled:text-fg-faint"
onClick={() => ctx?.toggle(value)}
>
{title}
<ChevronDown size={16} strokeWidth={1.5} aria-hidden="true" className="ds-accordion-chev shrink-0 text-fg-muted" />
</button>
</h3>
<div id={`${id}-body`} role="region" aria-labelledby={`${id}-head`} inert={!open} className="ds-collapse" data-open={open}>
<div><div className="ds-collapse-body max-w-measure pb-6 type-body text-fg-soft">{children}</div></div>
</div>
</div>
</>
)
}
export default AccordionItem
const css = `
/* The row opens to its content's height (0fr to 1fr) over 320ms and closes in 160ms, on the strong ease-out; the words
fade and settle 4px down, so they never pop. Reduced motion: no height or move, opacity only. */
.ds-collapse { display: grid; grid-template-rows: 0fr; transition: grid-template-rows var(--ds-duration-exit) var(--ds-easing-out); }
.ds-collapse[data-open="true"] { grid-template-rows: 1fr; transition-duration: var(--ds-duration-glide); }
.ds-collapse > div { min-height: 0; overflow: hidden; }
.ds-collapse-body { 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-collapse[data-open="true"] .ds-collapse-body { opacity: 1; transform: none; transition-duration: var(--ds-duration-glide); }
.ds-accordion-chev { transition: rotate var(--ds-duration-glide) var(--ds-easing-in-out); }
[aria-expanded="true"] > .ds-accordion-chev { rotate: 180deg; }
@media (prefers-reduced-motion: reduce) {
.ds-collapse, .ds-collapse[data-open="true"], .ds-accordion-chev { transition: none; }
.ds-collapse-body, .ds-collapse[data-open="true"] .ds-collapse-body { transform: none; transition: opacity var(--ds-duration-micro) var(--ds-easing-standard); }
}
`'use client'
import { createContext, useContext } from 'react'
// What an Accordion gives its items: whether a value is open, and the press that opens or closes it.
export type AccordionContextValue = { isOpen: (v: string) => boolean, toggle: (v: string) => void }
export const AccordionContext = createContext<AccordionContextValue | null>(null)
/** The Accordion around an item, or null outside one. */
export function useAccordion() {
return useContext(AccordionContext)
}'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
}// 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(' ')
}import { html, type PropertyValues } from 'lit'
import { DsElement, define, HostLayoutController, tagName } from '@/elements/lib/element'
import styles from 'virtual:tw'
// Accordion.tsx as <spyglass-accordion>: a stack of disclosures on Black with neutral hairlines between the rows, a
// muted chevron that turns as a row opens, the row opening to its content's height over 320ms on the strong ease-out
// and closing in 160ms. One open at a time by default (a second press closes it); `multiple` lets several stay open.
// `value` is the open row's value (or a JSON list of them with `multiple`), with `input` and `change` events. Compose
// with <spyglass-accordion-item>.
export type AccordionValue = string | string[] | null
/**
* @summary A stack of disclosures, one open at a time or several.
* @slot - The rows: <spyglass-accordion-item>.
* @fires input - A row opened or closed (read `value`).
* @fires change - A row opened or closed (read `value`).
*/
export class Accordion extends DsElement {
static styles = [DsElement.styles, styles]
// Layout classes on the element (w-full, max-w-160) land on the stack, as on the React root.
protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('[data-ds="accordion"]'))
static properties = {
multiple: { type: Boolean },
value: { converter: { fromAttribute: (v: string | null) => (v?.trim().startsWith('[') ? JSON.parse(v) : v || null), toAttribute: (v: AccordionValue) => (Array.isArray(v) ? JSON.stringify(v) : v) } },
}
/** Several rows stay open. */
multiple = false
/** The open row's value, or the list of them with `multiple`. */
value: AccordionValue = null
private list() {
return Array.isArray(this.value) ? this.value : this.value ? [this.value] : []
}
/** Whether the row with this value is open (read by the items). */
isOpen(v: string) {
return this.list().includes(v)
}
/** Opens or closes the row with this value (the items' press). */
toggle(v: string) {
const open = this.list()
if (this.multiple) this.commit(open.includes(v) ? open.filter((x) => x !== v) : [...open, v])
else this.commit(open.includes(v) ? null : v)
}
protected updated(changed: PropertyValues<this>) {
super.updated(changed)
if (changed.has('value')) for (const item of this.querySelectorAll<HTMLElement & { requestUpdate(): void }>(tagName('accordion-item'))) item.requestUpdate()
}
render() {
return html`<div data-ds="accordion" class="border-t border-edge"><slot></slot></div>`
}
}
define('accordion', Accordion)import { html } from 'lit'
import { ChevronDown } from 'lucide'
import { accordionOf } from '@/elements/controllers/accordion'
import { DsElement, define, uid } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import styles from 'virtual:tw'
// AccordionItem.tsx as <spyglass-accordion-item>: one row of an accordion: the question as a full-width button (DM Sans
// 16px, soft White that turns full White under the pointer and while open) over a neutral hairline, and the answer
// under it in muted DM Sans 14px. The chevron turns half a circle as the row opens; it never moves on hover. The closed
// answer is inert, so its links leave the tab order. `heading` (React's `title`) or the `title` slot names the row; the
// default slot is the answer.
/**
* @summary One row of an accordion.
* @slot - The answer.
* @slot title - The question, in place of `heading`.
*/
export class AccordionItem extends DsElement {
static styles = [DsElement.styles, styles]
static properties = { value: {}, heading: {}, disabled: { type: Boolean } }
/** The value the accordion opens it by. */
value = ''
/** The question (React's `title`). */
heading?: string
disabled = false
private rowId = uid('accordion')
render() {
const ctx = accordionOf(this)
const open = ctx?.isOpen(this.value) ?? false
return html`<div data-ds="accordion-item" class="border-b border-edge" data-open=${String(open)}>
<h3>
<button id=${`${this.rowId}-head`} type="button" aria-expanded=${String(open)} aria-controls=${`${this.rowId}-body`} ?disabled=${this.disabled} class="flex min-h-control-lg w-full cursor-pointer items-center justify-between gap-6 py-5 text-left type-body text-fg-soft transition-[color] duration-160 ease-standard hover:text-fg aria-expanded:text-fg disabled:cursor-not-allowed disabled:text-fg-faint" @click=${() => ctx?.toggle(this.value)}><slot name="title">${this.heading}</slot>${icon(ChevronDown, 'chevron-down', { size: 16, strokeWidth: 1.5, class: 'ds-accordion-chev shrink-0 text-fg-muted', attrs: { 'aria-hidden': 'true' } })}</button>
</h3>
<div id=${`${this.rowId}-body`} role="region" aria-labelledby=${`${this.rowId}-head`} ?inert=${!open} class="ds-collapse" data-open=${String(open)}>
<div><div class="ds-collapse-body max-w-measure pb-6 type-body text-fg-soft"><slot></slot></div></div>
</div>
</div>`
}
}
define('accordion-item', AccordionItem)/* AccordionItem.tsx's styles, as they are. */
/* The row opens to its content's height (0fr to 1fr) over 320ms and closes in 160ms, on the strong ease-out; the words
fade and settle 4px down, so they never pop. Reduced motion: no height or move, opacity only. */
.ds-collapse { display: grid; grid-template-rows: 0fr; transition: grid-template-rows var(--ds-duration-exit) var(--ds-easing-out); }
.ds-collapse[data-open="true"] { grid-template-rows: 1fr; transition-duration: var(--ds-duration-glide); }
.ds-collapse > div { min-height: 0; overflow: hidden; }
.ds-collapse-body { 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-collapse[data-open="true"] .ds-collapse-body { opacity: 1; transform: none; transition-duration: var(--ds-duration-glide); }
.ds-accordion-chev { transition: rotate var(--ds-duration-glide) var(--ds-easing-in-out); }
[aria-expanded="true"] > .ds-accordion-chev { rotate: 180deg; }
@media (prefers-reduced-motion: reduce) {
.ds-collapse, .ds-collapse[data-open="true"], .ds-accordion-chev { transition: none; }
.ds-collapse-body, .ds-collapse[data-open="true"] .ds-collapse-body { transform: none; transition: opacity var(--ds-duration-micro) var(--ds-easing-standard); }
}import { tagName } from '@/elements/lib/element'
// useAccordion for elements: what a <spyglass-accordion> gives its items (whether a value is open, and the press that
// opens or closes it). An item finds its accordion as its closest ancestor, so accordions nest.
export type AccordionContext = { isOpen: (v: string) => boolean, toggle: (v: string) => void }
/** The accordion around an item, or null outside one (or while it is not defined yet: it renders its items again once
* it is). */
export function accordionOf(item: Element): AccordionContext | null {
const a = item.parentElement?.closest(tagName('accordion')) as (Element & Partial<AccordionContext>) | null
return a && typeof a.isOpen === 'function' ? (a as AccordionContext) : null
}Reference: Derived from the guidelines: Black ground, neutral hairlines, DM Sans for body text. shadcn's accordion for anatomy, ARIA and keys..