Components

Sidebar

The app's rail: Black with a hairline at its edge, the logo at the top, groups named in capitals, the page you are on in White, the account at the foot. It folds to icons with one button. Its body scrolls with fading edges, so no row is cut off.

Install

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

npx spyglass-ds add sidebar
<script type="module" src="/spyglass-ds/elements/sidebar.js"></script>
The app's rail

Usage

The main navigation of the product: search, boards, brands, creators and settings. One per app, at the left.

Never

  • A second level of rows: a page's own sections go in Tabs
  • A spectrum color for the page you are on: it is White, as the primary button
  • Animating the fold: it is pressed many times a day

Adds with it: packages lucide-react

Props

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

<Sidebar>

PropTypeDefault
labelstring

The navigation's name for assistive tech.

'Main'
headReactNode

The logo or workspace, at the top.

footReactNode

The account, at the foot.

collapsibleboolean

Shows the button that folds it to icons.

collapsedboolean

Folded to icons (with onCollapsedChange).

defaultCollapsedbooleanfalse
onCollapsedChange(collapsed: boolean) => void
classNamestring
childrenReactNode

<SidebarLabel>

PropTypeDefault
childrenReactNode

The group's name.

<SidebarLink>

PropTypeDefault
hrefstring
activeboolean

The page you are on.

iconComponentType<{ size?: number, strokeWidth?: number, 'aria-hidden'?: boolean | 'true' }>

A Lucide icon.

statusstring

A count at the end of the row.

asElementType

A router link component in place of <a>.

Examples

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

react/examples/sidebar/App.tsx
'use client'
import { Fragment, useState } from 'react'
import { Bookmark, Compass, Folder, Search, Settings, Store, Users } from 'lucide-react'
import { Logo } from '@/react/components/visuals/Logo'
import { Sidebar } from '@/react/components/ui/Sidebar'
import { SidebarLabel } from '@/react/components/ui/SidebarLabel'
import { SidebarLink } from '@/react/components/ui/SidebarLink'
// The app's rail: the logo and the fold button at the top, a label over each group, the page you are on in White, and
// the account at the foot. Fold it to icons with the button.
const groups = [
  { label: 'Discover', links: [{ label: 'Search', icon: Search }, { label: 'Explore', icon: Compass }, { label: 'Brands', icon: Store, status: '12' }, { label: 'Creators', icon: Users, status: '8' }] },
  { label: 'Boards', links: [{ label: 'Acme hooks', icon: Folder, status: '24' }, { label: 'UGC ideas', icon: Folder, status: '9' }, { label: 'Saved', icon: Bookmark }] },
]

export default function App() {
  const [picked, setPicked] = useState('Search')
  return (
    <div className="flex h-120 overflow-hidden rounded-container border border-edge">
      <Sidebar
        label="App"
        collapsible
        head={<Logo height={20} />}
        foot={(
          <div className="flex flex-col gap-0.5">
            <SidebarLink href="#" icon={Settings} onClick={(e) => e.preventDefault()}>Settings</SidebarLink>
            <div className="flex flex-col px-3 pt-2">
              <span className="type-ui-strong text-fg">Acme Studio</span>
              <span className="type-caption text-fg-muted">Creator plan</span>
            </div>
          </div>
        )}
      >
        {groups.map((group) => (
          <Fragment key={group.label}>
            <SidebarLabel>{group.label}</SidebarLabel>
            {group.links.map((link: { label: string, icon: typeof Search, status?: string }) => (
              <SidebarLink key={link.label} href="#" icon={link.icon} status={link.status} active={picked === link.label} onClick={(e) => { e.preventDefault(); setPicked(link.label) }}>{link.label}</SidebarLink>
            ))}
          </Fragment>
        ))}
      </Sidebar>
      <div className="hidden min-w-0 flex-1 flex-col gap-2 p-8 md:flex">
        <h2 className="type-heading-3 text-fg">{picked}</h2>
        <p className="type-ui text-fg-muted">The only creative search engine.</p>
      </div>
    </div>
  )
}
elements/examples/sidebar/App.html
<!-- The app's rail: the logo and the fold button at the top, a label over each group, the page you are on in White,
     and the account at the foot. Fold it to icons with the button. -->
<div class="flex h-120 overflow-hidden rounded-container border border-edge">
  <spyglass-sidebar id="app-rail" label="App" collapsible>
    <spyglass-logo slot="head" height="20"></spyglass-logo>
    <spyglass-sidebar-label>Discover</spyglass-sidebar-label>
    <spyglass-sidebar-link href="#" active><i data-lucide="search" slot="icon" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Search</spyglass-sidebar-link>
    <spyglass-sidebar-link href="#"><i data-lucide="compass" slot="icon" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Explore</spyglass-sidebar-link>
    <spyglass-sidebar-link href="#" status="12"><i data-lucide="store" slot="icon" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Brands</spyglass-sidebar-link>
    <spyglass-sidebar-link href="#" status="8"><i data-lucide="users" slot="icon" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Creators</spyglass-sidebar-link>
    <spyglass-sidebar-label>Boards</spyglass-sidebar-label>
    <spyglass-sidebar-link href="#" status="24"><i data-lucide="folder" slot="icon" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Acme hooks</spyglass-sidebar-link>
    <spyglass-sidebar-link href="#" status="9"><i data-lucide="folder" slot="icon" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>UGC ideas</spyglass-sidebar-link>
    <spyglass-sidebar-link href="#"><i data-lucide="bookmark" slot="icon" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Saved</spyglass-sidebar-link>
    <div slot="foot" class="flex flex-col gap-0.5">
      <spyglass-sidebar-link href="#" data-static><i data-lucide="settings" slot="icon" data-size="16" data-stroke-width="1.5" aria-hidden="true"></i>Settings</spyglass-sidebar-link>
      <div class="flex flex-col px-3 pt-2">
        <span class="type-ui-strong text-fg">Acme Studio</span>
        <span class="type-caption text-fg-muted">Creator plan</span>
      </div>
    </div>
  </spyglass-sidebar>
  <div class="hidden min-w-0 flex-1 flex-col gap-2 p-8 md:flex">
    <h2 id="app-page" class="type-heading-3 text-fg">Search</h2>
    <p class="type-ui text-fg-muted">The only creative search engine.</p>
  </div>
</div>
<script type="module">
  const rail = document.getElementById('app-rail')
  const links = rail.querySelectorAll('spyglass-sidebar-link:not([data-static])')
  for (const link of rail.querySelectorAll('spyglass-sidebar-link')) {
    link.addEventListener('click', (event) => {
      event.preventDefault()
      if (link.hasAttribute('data-static')) return
      for (const l of links) l.active = l === link
      document.getElementById('app-page').textContent = link.textContent.trim()
    })
  }
</script>

Source

react/components/ui/Sidebar.tsx
'use client'
import { createContext, useContext, type HTMLAttributes, type ReactNode } from 'react'
import { PanelLeftClose, PanelLeftOpen } from 'lucide-react'
import { useControllable } from '@/react/hooks/useControllable'
import { cn } from '@/react/lib/cn'

// The app's rail: Black with a hairline at its edge, 256px wide. `head` holds the logo or the workspace (56px, over a
// hairline), SidebarLabel names each group in capitals, a SidebarLink per page (the page you are on in White), and
// `foot` the account. `collapsible` adds a button that folds it to 64px of icons (the labels stay for assistive tech);
// it folds at once, no motion, as something pressed many times a day should. `collapsed` with `onCollapsedChange`
// controls it. Other attributes land on the <nav>.
export interface SidebarProps extends Omit<HTMLAttributes<HTMLElement>, 'children'> {
  /** The navigation's name for assistive tech. */
  label?: string
  /** The logo or workspace, at the top. */
  head?: ReactNode
  /** The account, at the foot. */
  foot?: ReactNode
  /** Shows the button that folds it to icons. */
  collapsible?: boolean
  /** Folded to icons (with onCollapsedChange). */
  collapsed?: boolean
  defaultCollapsed?: boolean
  onCollapsedChange?: (collapsed: boolean) => void
  className?: string
  children?: ReactNode
}

/** Whether the sidebar around a link or label is folded to icons. */
export const SidebarContext = createContext(false)
export const useSidebarCollapsed = () => useContext(SidebarContext)

export function Sidebar({ label = 'Main', head, foot, collapsible, collapsed: given, defaultCollapsed = false, onCollapsedChange, className, children, ...rest }: SidebarProps) {
  const [collapsed, setCollapsed] = useControllable(given, defaultCollapsed, onCollapsedChange)
  const Icon = collapsed ? PanelLeftOpen : PanelLeftClose
  return (
    <nav data-ds="sidebar" aria-label={label} data-collapsed={collapsed || undefined} className={cn('flex h-full shrink-0 flex-col border-r border-edge bg-surface', collapsed ? 'w-16' : 'w-rail', className)} {...rest}>
      {(head || collapsible) && (
        <div className={cn('flex h-14 shrink-0 items-center gap-2 border-b border-edge px-3', collapsed ? 'justify-center' : 'justify-between')}>
          {head && !collapsed && <div className="flex min-w-0 flex-1 items-center pl-1">{head}</div>}
          {collapsible && (
            <button type="button" className="inline-flex size-control-md shrink-0 cursor-pointer items-center justify-center rounded-control text-fg-muted transition-[background-color,color] duration-160 ease-standard hover:bg-action-ghost-hover hover:text-fg" aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'} aria-expanded={!collapsed} onClick={() => setCollapsed(!collapsed)}>
              <Icon size={16} strokeWidth={1.5} aria-hidden="true" />
            </button>
          )}
        </div>
      )}
      <SidebarContext.Provider value={collapsed}>
        <div className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto p-3 fade-y">{children}</div>
      </SidebarContext.Provider>
      {foot && <div className={cn('shrink-0 border-t border-edge p-3', collapsed && 'hidden')}>{foot}</div>}
    </nav>
  )
}

export default Sidebar
react/components/ui/SidebarLabel.tsx
'use client'
import type { ReactNode } from 'react'
import { useSidebarCollapsed } from '@/react/components/ui/Sidebar'

// A group's name in the Sidebar: DM Sans Medium in capitals at 6%, muted, 16px over it. Folded to icons, a hairline
// takes its place and the name stays for assistive tech.
export interface SidebarLabelProps {
  /** The group's name. */
  children?: ReactNode
}

export function SidebarLabel({ children }: SidebarLabelProps) {
  const collapsed = useSidebarCollapsed()
  return (
    <div data-ds="sidebar-label" className="pt-4 pb-2 first:pt-1">
      {collapsed ? <div className="mx-2 border-t border-edge" aria-hidden="true" /> : null}
      <p className={collapsed ? 'sr-only' : 'px-3 type-label text-fg-muted'}>{children}</p>
    </div>
  )
}

export default SidebarLabel
react/components/ui/SidebarLink.tsx
'use client'
import type { AnchorHTMLAttributes, ComponentType, ElementType } from 'react'
import { useSidebarCollapsed } from '@/react/components/ui/Sidebar'
import { cn } from '@/react/lib/cn'

// One page in the Sidebar: a 40px row (44px on phones) with its 16px icon, the label and a count at the end, the brand
// corner. The page you are on is White with Black type, as the primary button; the others are soft gray and fill on
// hover. Folded to icons, the row is a 40px square and the label stays for assistive tech. `as` renders a router link
// component instead of an anchor; other props (onClick) land on the link.
export interface SidebarLinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
  href?: string
  /** The page you are on. */
  active?: boolean
  /** A Lucide icon. */
  icon?: ComponentType<{ size?: number, strokeWidth?: number, 'aria-hidden'?: boolean | 'true' }>
  /** A count at the end of the row. */
  status?: string
  /** A router link component in place of <a>. */
  as?: ElementType
}

export function SidebarLink({ href, active, icon: Icon, status, as: Link = 'a', className, children, ...rest }: SidebarLinkProps) {
  const collapsed = useSidebarCollapsed()
  return (
    <Link
      data-ds="sidebar-link"
      href={href}
      aria-current={active ? 'page' : undefined}
      className={cn(
        'flex h-row shrink-0 cursor-pointer items-center gap-3 rounded-control type-ui -outline-offset-2 transition-[background-color,color] duration-160 ease-standard max-md:h-control-touch',
        collapsed ? 'w-row justify-center px-0' : 'px-3',
        active ? 'bg-action-primary text-action-primary-fg' : 'text-fg-soft hover:bg-action-ghost-hover hover:text-fg',
        className,
      )}
      {...rest}
    >
      {Icon && <span className={cn('flex shrink-0', active ? 'text-action-primary-fg' : 'text-fg-muted')}><Icon size={16} strokeWidth={1.5} aria-hidden="true" /></span>}
      <span className={collapsed ? 'sr-only' : 'min-w-0 flex-1 truncate'}>{children}</span>
      {status && !collapsed && <span className={cn('type-caption tabular-nums', active ? 'text-action-primary-fg' : 'text-fg-muted')}>{status}</span>}
    </Link>
  )
}

export default SidebarLink
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
}
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(' ')
}
elements/components/ui/sidebar.ts
import { html, nothing, type PropertyValues } from 'lit'
import { PanelLeftClose, PanelLeftOpen } from 'lucide'
import { DsElement, define, HostLayoutController, tagName } from '@/elements/lib/element'
import { icon } from '@/elements/lib/icon'
import styles from 'virtual:tw'

// Sidebar.tsx as <spyglass-sidebar>: the app's rail, Black with a hairline at its edge, 256px wide. The `head` slot
// holds the logo or the workspace (56px, over a hairline), <spyglass-sidebar-label> names each group, a
// <spyglass-sidebar-link> per page (the page you are on in White), and the `foot` slot the account. `collapsible` adds a
// button that folds it to 64px of icons, at once; `collapsed` (reflected) with `collapsed-change`.

/**
 * @summary The app's navigation rail, with groups of links.
 * @slot - Labels and links.
 * @slot head - The logo or the workspace.
 * @slot foot - The account.
 * @fires collapsed-change - It folded or unfolded (detail.value).
 */
export class Sidebar extends DsElement {
	static styles = [DsElement.styles, styles]
	protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('nav'))
	static properties = { label: {}, collapsible: { type: Boolean }, collapsed: { type: Boolean, reflect: true } }

	/** The navigation's name for assistive tech. */
	label = 'Main'
	/** Shows the button that folds it to icons. */
	collapsible = false
	/** Folded to icons. */
	collapsed = false

	protected updated(changed: PropertyValues) {
		super.updated(changed)
		// The links and labels draw themselves from the sidebar's state.
		if (changed.has('collapsed')) for (const el of this.querySelectorAll<DsElement>(`${tagName('sidebar-link')}, ${tagName('sidebar-label')}`)) el.requestUpdate()
	}

	render() {
		const head = this.hasSlot('head')
		const Icon = this.collapsed ? PanelLeftOpen : PanelLeftClose
		return html`<nav data-ds="sidebar" aria-label=${this.label} ?data-collapsed=${this.collapsed} class=${`flex h-full shrink-0 flex-col border-r border-edge bg-surface ${this.collapsed ? 'w-16' : 'w-rail'}`}>
			${head || this.collapsible
				? html`<div class=${`flex h-14 shrink-0 items-center gap-2 border-b border-edge px-3 ${this.collapsed ? 'justify-center' : 'justify-between'}`}>
					${head && !this.collapsed ? html`<div class="flex min-w-0 flex-1 items-center pl-1"><slot name="head"></slot></div>` : nothing}
					${this.collapsible ? html`<button type="button" class="inline-flex size-control-md shrink-0 cursor-pointer items-center justify-center rounded-control text-fg-muted transition-[background-color,color] duration-160 ease-standard hover:bg-action-ghost-hover hover:text-fg" aria-label=${this.collapsed ? 'Expand sidebar' : 'Collapse sidebar'} aria-expanded=${String(!this.collapsed)} @click=${() => this.commit(!this.collapsed, 'collapsed')}>${icon(Icon, this.collapsed ? 'panel-left-open' : 'panel-left-close', { size: 16, strokeWidth: 1.5, attrs: { 'aria-hidden': 'true' } })}</button>` : nothing}
				</div>`
				: nothing}
			<div class="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto p-3 fade-y"><slot></slot></div>
			${this.hasSlot('foot') ? html`<div class=${`shrink-0 border-t border-edge p-3 ${this.collapsed ? 'hidden' : ''}`}><slot name="foot"></slot></div>` : nothing}
		</nav>`
	}
}

define('sidebar', Sidebar)
elements/components/ui/sidebar-label.ts
import { html } from 'lit'
import { DsElement, define, tagName } from '@/elements/lib/element'
import styles from 'virtual:tw'

// SidebarLabel.tsx as <spyglass-sidebar-label>: a group's name in the sidebar, DM Sans Medium in capitals at 6%,
// muted, 16px over it. Folded to icons, a hairline takes its place and the name stays for assistive tech.

/**
 * @summary A group's name in the sidebar.
 * @slot - The name.
 */
export class SidebarLabel extends DsElement {
	static styles = [DsElement.styles, styles]

	render() {
		const collapsed = !!(this.closest(tagName('sidebar')) as (Element & { collapsed?: boolean }) | null)?.collapsed
		// The first in the sidebar's body (the head and foot slots' content aside), as :first-child is in React's.
		let prev = this.previousElementSibling
		while (prev?.hasAttribute('slot')) prev = prev.previousElementSibling
		const first = !prev
		return html`<div data-ds="sidebar-label" class=${first ? 'pt-1 pb-2' : 'pt-4 pb-2'}>${collapsed ? html`<div class="mx-2 border-t border-edge" aria-hidden="true"></div>` : ''}<p class=${collapsed ? 'sr-only' : 'px-3 type-label text-fg-muted'}><slot></slot></p></div>`
	}
}

define('sidebar-label', SidebarLabel)
elements/components/ui/sidebar-link.ts
import { html, nothing } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { DsElement, define, HostLayoutController, tagName } from '@/elements/lib/element'
import styles from 'virtual:tw'

// SidebarLink.tsx as <spyglass-sidebar-link>: one page in the sidebar, a 40px row (44px on phones) with its icon (an
// <i data-lucide> in the `icon` slot), the label and a count (`status`) at the end. The page you are on (`active`) is
// White with Black type; the others are soft gray and fill on hover. Folded to icons, the row is a 40px square.

/**
 * @summary One page in the sidebar.
 * @slot - The label.
 * @slot icon - A Lucide icon.
 */
export class SidebarLink extends DsElement {
	static styles = [DsElement.styles, styles]
	protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('a'))
	static properties = { href: {}, active: { type: Boolean, reflect: true }, status: {} }

	href?: string
	/** The page you are on. */
	active = false
	/** A count at the end of the row. */
	status?: string

	render() {
		const collapsed = !!(this.closest(tagName('sidebar')) as (Element & { collapsed?: boolean }) | null)?.collapsed
		const classes = [
			'flex h-row shrink-0 cursor-pointer items-center gap-3 rounded-control type-ui -outline-offset-2 transition-[background-color,color] duration-160 ease-standard max-md:h-control-touch',
			collapsed ? 'w-row justify-center px-0' : 'px-3',
			this.active ? 'bg-action-primary text-action-primary-fg' : 'text-fg-soft hover:bg-action-ghost-hover hover:text-fg',
		].join(' ')
		return html`<a data-ds="sidebar-link" href=${ifDefined(this.href)} aria-current=${ifDefined(this.active ? 'page' : undefined)} class=${classes}>${this.hasSlot('icon') ? html`<span class=${`flex shrink-0 ${this.active ? 'text-action-primary-fg' : 'text-fg-muted'}`}><slot name="icon"></slot></span>` : nothing}<span class=${collapsed ? 'sr-only' : 'min-w-0 flex-1 truncate'}><slot></slot></span>${this.status && !collapsed ? html`<span class=${`type-caption tabular-nums ${this.active ? 'text-action-primary-fg' : 'text-fg-muted'}`}>${this.status}</span>` : nothing}</a>`
	}
}

define('sidebar-link', SidebarLink)

Reference: Derived from the brand guidelines (no app rail in the brand assets): Black ground, DM Sans labels in capitals at 6%, the White primary fill for the current page, the brand corner.