Components
Tabs
Views of one thing, one at a time. The default is a segmented control: a #262626 track, the current view a White block with a Black label. Line tabs sit over a hairline with a 2px White line under the current one.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add tabs<script type="module" src="/spyglass-ds/elements/tabs.js"></script>Usage
Two to six views of the same thing: kinds of creative in a search, a board's sections. Arrow keys move between tabs; the panel follows.
Never
- Actions: use Button
- More than six views: use a Select or a menu
- Bold or a color on the current tab: the White block or the White line marks it
- A sliding or bouncing indicator
Props
The web component takes the same as attributes or properties (<spyglass-tabs>); title is heading there.
<Tabs>
| Prop | Type | Default |
|---|---|---|
options | readonly TabOption<T>[] The tabs: values, or { value, label, disabled }. | |
label | string The tab list's name for assistive tech. | |
value | T | |
defaultValue | T | |
onValueChange | (value: T) => void | |
variant | TabsVariant default (a segmented control) or line (labels over a hairline). | 'default' |
panels | Partial<Record<T, ReactNode>> The panel for each tab, by value. | |
className | string |
Examples
The same example in React and as web components; both render identically.
import { Tabs } from '@/react/components/ui/Tabs'
// What to search: a segmented control over the panel for each kind of creative.
export default function Segmented() {
return (
<Tabs
className="w-96 max-w-full"
label="Creative type"
options={[{ value: 'ads', label: 'Ads' }, { value: 'posts', label: 'Posts' }, { value: 'products', label: 'Product shots' }]}
defaultValue="ads"
panels={{
ads: <div className="rounded-container bg-surface-raised p-6"><p className="type-ui-strong text-fg">Ads</p><p className="mt-1 type-ui text-fg-muted">Paid creative from every brand you track.</p></div>,
posts: <div className="rounded-container bg-surface-raised p-6"><p className="type-ui-strong text-fg">Posts</p><p className="mt-1 type-ui text-fg-muted">Organic posts and creator content.</p></div>,
products: <div className="rounded-container bg-surface-raised p-6"><p className="type-ui-strong text-fg">Product shots</p><p className="mt-1 type-ui text-fg-muted">Stills of the product, as posted.</p></div>,
}}
/>
)
}<!-- What to search: a segmented control over the panel for each kind of creative. -->
<spyglass-tabs class="w-96 max-w-full" label="Creative type" value="ads" options='[{"value":"ads","label":"Ads"},{"value":"posts","label":"Posts"},{"value":"products","label":"Product shots"}]'>
<div slot="ads" class="rounded-container bg-surface-raised p-6"><p class="type-ui-strong text-fg">Ads</p><p class="mt-1 type-ui text-fg-muted">Paid creative from every brand you track.</p></div>
<div slot="posts" class="rounded-container bg-surface-raised p-6"><p class="type-ui-strong text-fg">Posts</p><p class="mt-1 type-ui text-fg-muted">Organic posts and creator content.</p></div>
<div slot="products" class="rounded-container bg-surface-raised p-6"><p class="type-ui-strong text-fg">Product shots</p><p class="mt-1 type-ui text-fg-muted">Stills of the product, as posted.</p></div>
</spyglass-tabs>import { Tabs } from '@/react/components/ui/Tabs'
// A board's sections as line tabs, one of them not ready yet.
export default function Line() {
return (
<Tabs
className="w-full max-w-lg"
variant="line"
label="Board sections"
options={[{ value: 'creatives', label: 'Creatives' }, { value: 'brands', label: 'Brands' }, { value: 'notes', label: 'Notes' }, { value: 'export', label: 'Export', disabled: true }]}
defaultValue="creatives"
panels={{
creatives: <p className="type-ui text-fg-muted">48 creatives, newest first.</p>,
brands: <p className="type-ui text-fg-muted">12 brands on this board.</p>,
notes: <p className="type-ui text-fg-muted">No notes yet.</p>,
}}
/>
)
}<!-- A board's sections as line tabs, one of them not ready yet. -->
<spyglass-tabs class="w-full max-w-lg" variant="line" label="Board sections" value="creatives" options='[{"value":"creatives","label":"Creatives"},{"value":"brands","label":"Brands"},{"value":"notes","label":"Notes"},{"value":"export","label":"Export","disabled":true}]'>
<p slot="creatives" class="type-ui text-fg-muted">48 creatives, newest first.</p>
<p slot="brands" class="type-ui text-fg-muted">12 brands on this board.</p>
<p slot="notes" class="type-ui text-fg-muted">No notes yet.</p>
</spyglass-tabs>Source
'use client'
import { useId, useRef, type KeyboardEvent, type ReactNode } from 'react'
import { useControllable } from '@/react/hooks/useControllable'
import { cn } from '@/react/lib/cn'
// Views of one thing, one at a time. `variant` default is a segmented control: a #262626 track with the brand corner,
// the current view a White block with a Black DM Sans Medium label, the rest muted and White under the pointer. `line`
// is for a page's sections: labels 24px apart over a #363636 hairline, the current one White with a 2px White line
// under it. Colors change over 160ms; nothing slides. Arrow keys move between tabs and select (Home and End for the
// ends); Tab moves into the panel. Pass `panels` (content by value) to draw the current panel under the list. The
// value is `value` with `onValueChange` (or `defaultValue` alone).
export type TabOption<T extends string> = T | { value: T, label: string, disabled?: boolean }
export type TabsVariant = 'default' | 'line'
export interface TabsProps<T extends string> {
/** The tabs: values, or { value, label, disabled }. */
options: readonly TabOption<T>[]
/** The tab list's name for assistive tech. */
label: string
value?: T
defaultValue?: T
onValueChange?: (value: T) => void
/** default (a segmented control) or line (labels over a hairline). */
variant?: TabsVariant
/** The panel for each tab, by value. */
panels?: Partial<Record<T, ReactNode>>
className?: string
}
const norm = <T extends string>(o: TabOption<T>) => (typeof o === 'string' ? { value: o, label: o, disabled: false } : { disabled: false, ...o })
const LIST: Record<TabsVariant, string> = {
default: 'inline-flex h-control-md w-fit max-w-full items-center gap-1 rounded-control bg-surface-raised p-1',
line: 'flex items-center gap-6 border-b border-edge',
}
const TAB: Record<TabsVariant, string> = {
default: 'inline-flex h-full flex-1 cursor-pointer items-center justify-center rounded-ds-sm px-3 type-ui-strong whitespace-nowrap transition-[background-color,color] duration-160 ease-standard disabled:cursor-not-allowed disabled:text-fg-faint',
line: '-mb-px inline-flex h-control-md cursor-pointer items-center border-b-2 type-ui-strong whitespace-nowrap transition-[border-color,color] duration-160 ease-standard disabled:cursor-not-allowed disabled:text-fg-faint',
}
const ON: Record<TabsVariant, string> = { default: 'bg-action-primary text-action-primary-fg', line: 'border-action-primary text-fg' }
const OFF: Record<TabsVariant, string> = { default: 'text-fg-muted hover:not-disabled:text-fg', line: 'border-transparent text-fg-muted hover:not-disabled:text-fg' }
/** The id-safe form of a value. */
const slug = (v: string) => v.replace(/[^\w-]/g, '-')
export function Tabs<T extends string>({ options, label, value, defaultValue, onValueChange, variant = 'default', panels, className }: TabsProps<T>) {
const opts = options.map(norm)
const [current, setCurrent] = useControllable<T | undefined>(value, defaultValue ?? opts.find((o) => !o.disabled)?.value, (v) => v !== undefined && onValueChange?.(v))
const base = `tabs-${useId().replace(/:/g, '')}`
const list = useRef<HTMLDivElement | null>(null)
const v = LIST[variant] ? variant : 'default'
function onKeyDown(event: KeyboardEvent) {
const enabled = opts.filter((o) => !o.disabled)
const at = enabled.findIndex((o) => o.value === current)
let next: number
if (event.key === 'ArrowRight') next = (at + 1) % enabled.length
else if (event.key === 'ArrowLeft') next = (at - 1 + enabled.length) % enabled.length
else if (event.key === 'Home') next = 0
else if (event.key === 'End') next = enabled.length - 1
else return
event.preventDefault()
const pick = enabled[next]
if (!pick) return
setCurrent(pick.value)
list.current?.querySelector<HTMLElement>(`#${base}-tab-${slug(pick.value)}`)?.focus()
}
const panel = current !== undefined ? panels?.[current] : undefined
return (
<div data-ds="tabs" className={cn('flex flex-col gap-4', className)}>
<div ref={list} role="tablist" aria-label={label} className={LIST[v]} onKeyDown={onKeyDown}>
{opts.map((o) => (
<button
key={o.value}
id={`${base}-tab-${slug(o.value)}`}
type="button"
role="tab"
aria-selected={current === o.value}
aria-controls={panels?.[o.value] !== undefined ? `${base}-panel-${slug(o.value)}` : undefined}
tabIndex={current === o.value ? 0 : -1}
disabled={o.disabled}
className={cn(TAB[v], current === o.value ? ON[v] : OFF[v])}
onClick={() => setCurrent(o.value)}
>
{o.label}
</button>
))}
</div>
{panel !== undefined && current !== undefined && (
<div id={`${base}-panel-${slug(current)}`} role="tabpanel" tabIndex={0} aria-labelledby={`${base}-tab-${slug(current)}`}>{panel}</div>
)}
</div>
)
}
export default Tabs'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, nothing } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { DsElement, define, HostLayoutController, uid } from '@/elements/lib/element'
import styles from 'virtual:tw'
// Tabs.tsx as <spyglass-tabs>: views of one thing, one at a time. `variant` default is the segmented control (a
// #262626 track, the current view a White block with a Black label); `line` is labels over a hairline with a 2px
// White line under the current one. Colors change over 160ms; nothing slides. Arrow keys move and select (Home, End);
// Tab moves into the panel. `options` is a JSON list; each panel is a child with slot="<value>" (React's `panels`),
// drawn under the list while its tab is current. `value` with the native `input` and `change` events.
export type TabOption = string | { value: string, label: string, disabled?: boolean }
const norm = (o: TabOption) => (typeof o === 'string' ? { value: o, label: o, disabled: false } : { disabled: false, ...o })
const LIST = {
default: 'inline-flex h-control-md w-fit max-w-full items-center gap-1 rounded-control bg-surface-raised p-1',
line: 'flex items-center gap-6 border-b border-edge',
} as const
const TAB = {
default: 'inline-flex h-full flex-1 cursor-pointer items-center justify-center rounded-ds-sm px-3 type-ui-strong whitespace-nowrap transition-[background-color,color] duration-160 ease-standard disabled:cursor-not-allowed disabled:text-fg-faint',
line: '-mb-px inline-flex h-control-md cursor-pointer items-center border-b-2 type-ui-strong whitespace-nowrap transition-[border-color,color] duration-160 ease-standard disabled:cursor-not-allowed disabled:text-fg-faint',
} as const
const ON = { default: 'bg-action-primary text-action-primary-fg', line: 'border-action-primary text-fg' } as const
const OFF = { default: 'text-fg-muted hover:not-disabled:text-fg', line: 'border-transparent text-fg-muted hover:not-disabled:text-fg' } as const
const slug = (v: string) => v.replace(/[^\w-]/g, '-')
/**
* @summary Views of one thing: a segmented control or line tabs, with their panels.
* @slot <value> - The panel for the tab with that value.
* @fires input - The tab changed (read `value`).
* @fires change - The tab changed (read `value`).
*/
export class Tabs extends DsElement {
static styles = [DsElement.styles, styles]
protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('[data-ds="tabs"]'))
static properties = { value: { reflect: true }, options: { type: Array }, label: {}, variant: { reflect: true } }
/** The current tab's value (the first enabled one when empty). */
value = ''
/** Values, or { value, label, disabled } (a JSON attribute or the property). */
options: TabOption[] = []
/** The tab list's name for assistive tech. */
label = ''
/** default (a segmented control) or line. */
variant: keyof typeof LIST = 'default'
private base = uid('tabs')
private get current() {
const opts = this.options.map(norm)
return this.value || opts.find((o) => !o.disabled)?.value || ''
}
private onKeyDown(event: KeyboardEvent) {
const enabled = this.options.map(norm).filter((o) => !o.disabled)
const at = enabled.findIndex((o) => o.value === this.current)
let next: number
if (event.key === 'ArrowRight') next = (at + 1) % enabled.length
else if (event.key === 'ArrowLeft') next = (at - 1 + enabled.length) % enabled.length
else if (event.key === 'Home') next = 0
else if (event.key === 'End') next = enabled.length - 1
else return
event.preventDefault()
const pick = enabled[next]
if (!pick) return
this.commit(pick.value)
void this.updateComplete.then(() => this.renderRoot.querySelector<HTMLElement>(`#${this.base}-tab-${slug(pick.value)}`)?.focus())
}
render() {
const v = LIST[this.variant] ? this.variant : 'default'
const opts = this.options.map(norm)
const current = this.current
const has = (value: string) => this.hasSlot(value)
return html`<div data-ds="tabs" class="flex flex-col gap-4">
<div role="tablist" aria-label=${this.label} class=${LIST[v]} @keydown=${this.onKeyDown}>${opts.map((o) => html`<button
id=${`${this.base}-tab-${slug(o.value)}`}
type="button"
role="tab"
aria-selected=${String(current === o.value)}
aria-controls=${ifDefined(has(o.value) ? `${this.base}-panel-${slug(o.value)}` : undefined)}
tabindex=${current === o.value ? '0' : '-1'}
?disabled=${o.disabled}
class=${`${TAB[v]} ${current === o.value ? ON[v] : OFF[v]}`}
@click=${() => this.commit(o.value)}
>${o.label}</button>`)}</div>
${current && has(current) ? html`<div id=${`${this.base}-panel-${slug(current)}`} role="tabpanel" tabindex="0" aria-labelledby=${`${this.base}-tab-${slug(current)}`}><slot name=${current}></slot></div>` : nothing}
</div>`
}
}
define('tabs', Tabs)Reference: Derived from the brand guidelines (no tabs in the brand assets): the primary button's White fill and Black label for the current view, the plan card's fill for the track, the neutral steps for the hairline.