Sidebars are one of the most complex components to build. They are central to any application and often contain a lot of moving parts.
We now have a solid foundation to build on top of. Composable. Themeable. Customizable.
Installation
Copy and paste the following code into your project.
/**
* Sidebar: an application's side navigation, collapsible to icons or off
* canvas, and a sheet on a phone. Tier 2 for the parts with state (the
* provider, the sidebar, its trigger and rail, and the inset beside it) and
* Tier 1 for everything inside, which is markup with classes, as in shadcn.
*
* shadcn parity:
* SidebarProvider (defaultOpen, open)
* → <ui-sidebar-provider default-open="false" open>
* Sidebar (side, variant, collapsible)
* → <ui-sidebar side="left" | "right" variant="sidebar" | "floating" | "inset"
* collapsible="offcanvas" | "icon" | "none">
* SidebarTrigger / SidebarRail / SidebarInset
* → <ui-sidebar-trigger> / <ui-sidebar-rail> / <ui-sidebar-inset>
* SidebarHeader / Footer / Content / Separator / Input
* → <div data-slot="sidebar-header" data-sidebar="header" class=${sidebarHeaderClass()}>
* and so on (sidebarInputClass() on an <input>)
* SidebarGroup / GroupLabel / GroupAction / GroupContent
* → sidebarGroupClass() / sidebarGroupLabelClass() / sidebarGroupActionClass() /
* sidebarGroupContentClass()
* SidebarMenu / MenuItem → <ul class=${sidebarMenuClass()}> / <li class=${sidebarMenuItemClass()}>
* SidebarMenuButton (variant, size, isActive)
* → <a data-slot="sidebar-menu-button" data-sidebar="menu-button" data-size
* data-active class=${sidebarMenuButtonClass({ variant, size })}>
* (sidebarMenuButtonVariants is the same helper under shadcn's name)
* SidebarMenuAction showOnHover / MenuBadge / MenuSkeleton
* → sidebarMenuActionClass({ showOnHover }) / sidebarMenuBadgeClass() /
* sidebarMenuSkeleton({ showIcon })
* SidebarMenuSub / SubItem / SubButton (size, isActive)
* → sidebarMenuSubClass() / sidebarMenuSubItemClass() /
* sidebarMenuSubButtonClass({ size })
* useSidebar() → the provider: open, state, isMobile, openMobile, toggle(), setOpen()
* onOpenChange → `ui-open-change` ({ detail: { open } }) on the provider
*
* The open state is kept in the `sidebar_state` cookie, as in shadcn, so a
* page can read it on the server and render `default-open` to match, with no
* flash. Ctrl+B (Cmd+B on a Mac) toggles it. Below 768px the sidebar opens
* as a sheet from its side instead, `--sidebar-width-mobile` wide (18rem
* when no ancestor sets it, shadcn's SIDEBAR_WIDTH_MOBILE).
*
* For a collapsed icon sidebar, wrap a menu button in a `<ui-tooltip>` whose
* content carries `hidden group-data-[collapsible=icon]:block`, so the label
* shows only when the text does not.
*
* A11y (handled by the elements, plus your part): the trigger is named
* "Toggle Sidebar", the inset is the page's `main` landmark, and on a phone
* the sheet is a modal dialog named "Sidebar" with Escape and focus return.
* Your part: put the menu in a `<nav aria-label>`, mark the current page's
* button `data-active="true"` and `aria-current="page"`, and give a
* collapsed icon button a name (its text stays in the markup, hidden by the
* width, so a screen reader still reads it).
*
* @example
* ```html
* <ui-sidebar-provider>
* <ui-sidebar collapsible="icon">
* <div data-slot="sidebar-content" data-sidebar="content" class=${sidebarContentClass()}>
* <nav aria-label="Main" data-slot="sidebar-group" data-sidebar="group" class=${sidebarGroupClass()}>
* <ul data-slot="sidebar-menu" data-sidebar="menu" class=${sidebarMenuClass()}>
* <li data-slot="sidebar-menu-item" data-sidebar="menu-item" class=${sidebarMenuItemClass()}>
* <a href="/inbox" data-slot="sidebar-menu-button" data-sidebar="menu-button" data-active="true"
* aria-current="page" class=${sidebarMenuButtonClass()}><span>Inbox</span></a>
* </li>
* </ul>
* </nav>
* </div>
* <ui-sidebar-rail></ui-sidebar-rail>
* </ui-sidebar>
* <ui-sidebar-inset>
* <header class="flex h-12 items-center px-4"><ui-sidebar-trigger></ui-sidebar-trigger></header>
* </ui-sidebar-inset>
* </ui-sidebar-provider>
* ```
*/
import { WebComponent, html, prop, signal } from '@webjsdev/core';
import { cn, takeAuthoredClass } from '../lib/utils.ts';
import { buttonClass } from './button.ts';
import { inputClass } from './input.ts';
import { separatorClass } from './separator.ts';
import { skeletonClass } from './skeleton.ts';
import './sheet.ts';
const COOKIE = 'sidebar_state';
const COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const MOBILE_QUERY = '(max-width: 767px)';
const PROVIDER = 'ui-sidebar-provider';
// --------------------------------------------------------------------------
// Class helpers (Tier 1)
// --------------------------------------------------------------------------
/** The provider's wrapper (the element applies them). */
export function sidebarWrapperClass(): string {
return 'group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar';
}
/** The header. */
export function sidebarHeaderClass(): string {
return 'gap-2 p-2 flex flex-col';
}
/** The footer. */
export function sidebarFooterClass(): string {
return 'gap-2 p-2 flex flex-col';
}
/** A separator in the sidebar, on a separator element. */
export function sidebarSeparatorClass(): string {
return cn(separatorClass(), 'mx-2 bg-sidebar-border w-auto');
}
/** The search field in the sidebar, on an <input>. */
export function sidebarInputClass(): string {
return cn(inputClass(), 'h-8 w-full bg-background shadow-none');
}
/** The scrolling content. */
export function sidebarContentClass(): string {
return 'gap-2 flex min-h-0 flex-1 flex-col overflow-auto group-data-[collapsible=icon]:overflow-hidden';
}
/** A group. */
export function sidebarGroupClass(): string {
return 'p-2 relative flex w-full min-w-0 flex-col';
}
/** A group's label. */
export function sidebarGroupLabelClass(): string {
return 'h-8 rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0 flex shrink-0 items-center outline-hidden [&>svg]:shrink-0';
}
/** A group's action button. */
export function sidebarGroupActionClass(): string {
return 'absolute top-3.5 end-3 w-5 rounded-md p-0 text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 flex aspect-square items-center justify-center outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 md:after:hidden [&>svg]:shrink-0';
}
/** A group's content. */
export function sidebarGroupContentClass(): string {
return 'w-full';
}
/** A menu (<ul>). */
export function sidebarMenuClass(): string {
return 'gap-1 flex w-full min-w-0 flex-col';
}
/** A menu item (<li>). */
export function sidebarMenuItemClass(): string {
return 'group/menu-item relative';
}
const MENU_BUTTON_VARIANTS = {
default: 'hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
outline: 'bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]',
} as const;
const MENU_BUTTON_SIZES = {
default: 'h-8 text-sm',
sm: 'h-7 text-xs',
lg: 'h-12 text-sm group-data-[collapsible=icon]:p-0!',
} as const;
export type SidebarMenuButtonVariant = keyof typeof MENU_BUTTON_VARIANTS;
export type SidebarMenuButtonSize = keyof typeof MENU_BUTTON_SIZES;
/** A menu button (an <a> or a <button>); mark the current one `data-active="true"`. */
export function sidebarMenuButtonClass(opts: { variant?: SidebarMenuButtonVariant; size?: SidebarMenuButtonSize } & { className?: string } = {}): string {
return cn(
'gap-2 rounded-md p-2 text-start text-sm ring-sidebar-ring transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pe-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground peer/menu-button group/menu-button flex w-full items-center overflow-hidden outline-hidden disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate',
MENU_BUTTON_VARIANTS[opts.variant ?? 'default'],
MENU_BUTTON_SIZES[opts.size ?? 'default'],
opts.className,
);
}
/** shadcn's name for {@link sidebarMenuButtonClass}. Like cva, it merges a `className`. */
export function sidebarMenuButtonVariants(opts: { variant?: SidebarMenuButtonVariant; size?: SidebarMenuButtonSize; className?: string } = {}): string {
return sidebarMenuButtonClass(opts);
}
/** A menu item's action button; `showOnHover` hides it until the item is hovered or focused. */
export function sidebarMenuActionClass(opts: { showOnHover?: boolean } = {}): string {
return cn(
'absolute end-1 w-5 rounded-md p-0 text-sidebar-foreground ring-sidebar-ring peer-hover/menu-button:text-sidebar-accent-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 peer-data-[size=sm]/menu-button:top-1 peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 flex items-center justify-center outline-hidden transition-transform group-data-[collapsible=icon]:hidden after:absolute after:-inset-2 md:after:hidden [&>svg]:shrink-0',
opts.showOnHover ? 'group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground aria-expanded:opacity-100 md:opacity-0' : '',
);
}
/** A menu item's badge. */
export function sidebarMenuBadgeClass(): string {
return 'pointer-events-none absolute end-1 h-5 min-w-5 rounded-md px-1 text-xs font-medium text-sidebar-foreground peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground peer-data-[size=sm]/menu-button:top-1 peer-data-[size=default]/menu-button:top-1.5 peer-data-[size=lg]/menu-button:top-2.5 flex items-center justify-center tabular-nums select-none group-data-[collapsible=icon]:hidden';
}
/**
* A loading placeholder for a menu item. `width` is the text bar's width
* (shadcn picks a random one, which would differ between server and client).
*/
export function sidebarMenuSkeleton(opts: { showIcon?: boolean; width?: string } = {}) {
return html`<div data-slot="sidebar-menu-skeleton" data-sidebar="menu-skeleton" class="h-8 gap-2 rounded-md px-2 flex items-center">${opts.showIcon
? html`<div data-sidebar="menu-skeleton-icon" class=${cn(skeletonClass(), 'size-4 rounded-md')}></div>`
: ''}<div data-sidebar="menu-skeleton-text" style=${`--skeleton-width: ${opts.width ?? '70%'}`} class=${cn(skeletonClass(), 'h-4 max-w-(--skeleton-width) flex-1')}></div></div>`;
}
/** A submenu (<ul>). */
export function sidebarMenuSubClass(): string {
return 'mx-3.5 translate-x-px rtl:-translate-x-px gap-1 border-s border-sidebar-border px-2.5 py-0.5 group-data-[collapsible=icon]:hidden flex min-w-0 flex-col';
}
/** A submenu item (<li>). */
export function sidebarMenuSubItemClass(): string {
return 'group/menu-sub-item relative';
}
/** A submenu button (an <a>); `size` is "sm" or "md", set as `data-size`. */
export function sidebarMenuSubButtonClass(): string {
return 'h-7 gap-2 rounded-md px-2 text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:text-sidebar-accent-foreground data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground data-[size=sm]:text-xs data-[size=md]:text-sm flex min-w-0 -translate-x-px items-center overflow-hidden outline-hidden group-data-[collapsible=icon]:hidden disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:shrink-0';
}
// --------------------------------------------------------------------------
// <ui-sidebar-provider>
// --------------------------------------------------------------------------
function providerOf(el: Element): UiSidebarProvider | null {
return (typeof el.closest === 'function' ? el.closest(PROVIDER) : null) as UiSidebarProvider | null;
}
export class UiSidebarProvider extends WebComponent({
defaultOpen: prop(String, { attribute: 'default-open' }),
open: prop(Boolean, { reflect: true }),
}) {
readonly #openMobile = signal(false);
get openMobile() { return this.#openMobile.get(); }
set openMobile(v) { this.#openMobile.set(v); }
readonly #isMobile = signal(false);
get isMobile() { return this.#isMobile.get(); }
set isMobile(v) { this.#isMobile.set(v); }
_query: MediaQueryList | null = null;
_parsed = false;
constructor() {
super();
this.defaultOpen = 'true';
this.open = false;
}
/** "expanded" or "collapsed", as shadcn's `state`. */
get state(): 'expanded' | 'collapsed' {
return this.open ? 'expanded' : 'collapsed';
}
willUpdate(changedProperties: Map<string, unknown>): void {
super.willUpdate?.(changedProperties);
if (this._parsed) return;
this._parsed = true;
// An `open` attribute wins; otherwise default-open decides.
if (!this.hasAttribute?.('open')) this.open = this.defaultOpen !== 'false';
}
connectedCallback(): void {
super.connectedCallback?.();
window.addEventListener('keydown', this._onKeyDown);
if (typeof matchMedia === 'function') {
this._query = matchMedia(MOBILE_QUERY);
this.isMobile = this._query.matches;
this._query.addEventListener('change', this._onQuery);
}
}
disconnectedCallback(): void {
window.removeEventListener('keydown', this._onKeyDown);
this._query?.removeEventListener('change', this._onQuery);
super.disconnectedCallback?.();
}
render() {
return html`<div
data-slot="sidebar-wrapper"
style="--sidebar-width: 16rem; --sidebar-width-icon: 3rem"
class=${sidebarWrapperClass()}
><slot></slot></div>`;
}
updated(changedProperties: Map<string, unknown>): void {
super.updated?.(changedProperties);
// `isMobile` and `openMobile` are signals, so a part that reads them
// re-renders on its own; only the `open` property needs the nudge.
if (changedProperties.has('open')) {
for (const part of Array.from(this.querySelectorAll<WebComponent>('ui-sidebar, ui-sidebar-trigger, ui-sidebar-rail'))) {
if (providerOf(part) === this) part.requestUpdate?.();
}
}
}
/** Open or close the desktop sidebar, keeping the choice in the cookie. */
setOpen(open: boolean): void {
if (open === this.open) return;
this.open = open;
if (typeof document !== 'undefined') document.cookie = `${COOKIE}=${open}; path=/; max-age=${COOKIE_MAX_AGE}`;
this.dispatchEvent(new CustomEvent('ui-open-change', { bubbles: true, detail: { open } }));
}
/** Open or close the phone sheet. */
setOpenMobile(open: boolean): void {
this.openMobile = open;
}
/** Toggle the sheet on a phone, the sidebar otherwise. */
toggle(): void {
if (this.isMobile) this.setOpenMobile(!this.openMobile);
else this.setOpen(!this.open);
}
_onQuery = (e: MediaQueryListEvent): void => {
this.isMobile = e.matches;
};
_onKeyDown = (e: KeyboardEvent): void => {
if (e.key === 'b' && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
this.toggle();
}
};
}
UiSidebarProvider.register('ui-sidebar-provider');
// --------------------------------------------------------------------------
// <ui-sidebar>
// --------------------------------------------------------------------------
export class UiSidebar extends WebComponent({
side: prop<'left' | 'right'>(String),
variant: prop<'sidebar' | 'floating' | 'inset'>(String),
collapsible: prop<'offcanvas' | 'icon' | 'none'>(String),
}) {
_authored: string | null = null;
constructor() {
super();
this.side = 'left';
this.variant = 'sidebar';
this.collapsible = 'offcanvas';
}
_host(attrs: Record<string, string | null>, cls: string): void {
if (typeof this.setAttribute !== 'function') return;
this.setAttribute('class', cn(cls, this._authored));
for (const [k, v] of Object.entries(attrs)) {
if (v === null) this.removeAttribute(k);
else this.setAttribute(k, v);
}
}
// The sidebar's state and its group / peer markers sit on its own host:
// the inset beside it styles itself with peer-data-*, which needs a real
// sibling, and everything inside reads group-data-*.
render() {
this._authored = takeAuthoredClass(this);
const provider = providerOf(this);
const side = this.side === 'right' ? 'right' : 'left';
const floating = this.variant === 'floating' || this.variant === 'inset';
if (this.collapsible === 'none') {
this._host({ 'data-slot': 'sidebar', 'data-state': null, 'data-collapsible': null, 'data-variant': null, 'data-side': null },
'flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground');
return html`<slot></slot>`;
}
if (provider?.isMobile) {
this._host({ 'data-slot': null, 'data-state': null, 'data-collapsible': null, 'data-variant': null, 'data-side': null }, 'contents');
return html`<ui-sheet ?open=${!!provider.openMobile} @ui-open-change=${(e: CustomEvent) => {
if (e.target === e.currentTarget) provider.setOpenMobile(!!e.detail?.open);
}}><ui-sheet-content
side=${side}
show-close-button="false"
data-sidebar="sidebar"
data-slot="sidebar"
data-mobile="true"
style="--sidebar-width: var(--sidebar-width-mobile, 18rem)"
class="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground"
><h2 data-slot="sheet-title" class="sr-only">Sidebar</h2><p data-slot="sheet-description" class="sr-only">Displays the mobile sidebar.</p><div class="flex h-full w-full flex-col"><slot></slot></div></ui-sheet-content></ui-sheet>`;
}
const state = provider?.state ?? 'expanded';
this._host({
'data-slot': 'sidebar',
'data-state': state,
'data-collapsible': state === 'collapsed' ? this.collapsible : '',
'data-variant': this.variant,
'data-side': side,
}, 'group peer hidden text-sidebar-foreground md:block');
return html`<div
data-slot="sidebar-gap"
class=${cn(
'transition-[width] duration-200 ease-linear relative w-(--sidebar-width) bg-transparent group-data-[collapsible=offcanvas]:w-0 group-data-[side=right]:rotate-180',
floating ? 'group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]' : 'group-data-[collapsible=icon]:w-(--sidebar-width-icon)',
)}
></div><div
data-slot="sidebar-container"
data-side=${side}
class=${cn(
'fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear data-[side=left]:left-0 data-[side=left]:group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)] data-[side=right]:right-0 data-[side=right]:group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)] md:flex',
floating ? 'p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]' : 'group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l',
)}
><div data-sidebar="sidebar" data-slot="sidebar-inner" class="bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm flex size-full flex-col"><slot></slot></div></div>`;
}
}
UiSidebar.register('ui-sidebar');
// --------------------------------------------------------------------------
// <ui-sidebar-trigger> and <ui-sidebar-rail>
// --------------------------------------------------------------------------
export class UiSidebarTrigger extends WebComponent {
render() {
return html`<button
type="button"
data-sidebar="trigger"
data-slot="sidebar-trigger"
class=${cn(buttonClass({ variant: 'ghost', size: 'icon-sm' }), 'size-7')}
@click=${() => providerOf(this)?.toggle()}
><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" class="cn-rtl-flip rtl:rotate-180"><rect width="18" height="18" x="3" y="3" rx="2"></rect><path d="M9 3v18"></path></svg><span class="sr-only">Toggle Sidebar</span></button>`;
}
}
UiSidebarTrigger.register('ui-sidebar-trigger');
export class UiSidebarRail extends WebComponent {
render() {
return html`<button
type="button"
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
tabindex="-1"
title="Toggle Sidebar"
class="hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2 in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize [[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar [[data-side=left][data-collapsible=offcanvas]_&]:-right-2 [[data-side=right][data-collapsible=offcanvas]_&]:-left-2"
@click=${() => providerOf(this)?.toggle()}
></button>`;
}
}
UiSidebarRail.register('ui-sidebar-rail');
// --------------------------------------------------------------------------
// <ui-sidebar-inset>
// --------------------------------------------------------------------------
export class UiSidebarInset extends WebComponent {
_authored: string | null = null;
// The inset is the sidebar's following sibling, so peer-data-* reaches it
// only on its own host, which is also the page's main landmark.
render() {
this._authored = takeAuthoredClass(this);
if (typeof this.setAttribute === 'function') {
this.setAttribute('class', cn('bg-background md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ms-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ms-2 relative flex w-full flex-1 flex-col', this._authored));
this.setAttribute('data-slot', 'sidebar-inset');
this.setAttribute('role', 'main');
}
return html`<slot></slot>`;
}
}
UiSidebarInset.register('ui-sidebar-inset');
Update the import paths to match your project setup.
Usage
import { html } from '@webjsdev/core';
import type { LayoutProps } from '@webjsdev/core';
import { appSidebar } from '#components/app-sidebar.ts';
// Registers the sidebar's elements.
import '#components/ui/sidebar.ts';
export default function Layout({ children }: LayoutProps) {
return html`
<ui-sidebar-provider>
${appSidebar()}
<ui-sidebar-inset>
<ui-sidebar-trigger></ui-sidebar-trigger>
${children}
</ui-sidebar-inset>
</ui-sidebar-provider>
`;
}
import { html } from '@webjsdev/core';
import {
sidebarContentClass,
sidebarFooterClass,
sidebarGroupClass,
sidebarHeaderClass,
} from '#components/ui/sidebar.ts';
export function appSidebar() {
return html`
<ui-sidebar>
<div data-slot="sidebar-header" data-sidebar="header" class=${sidebarHeaderClass()}></div>
<div data-slot="sidebar-content" data-sidebar="content" class=${sidebarContentClass()}>
<div data-slot="sidebar-group" data-sidebar="group" class=${sidebarGroupClass()}></div>
<div data-slot="sidebar-group" data-sidebar="group" class=${sidebarGroupClass()}></div>
</div>
<div data-slot="sidebar-footer" data-sidebar="footer" class=${sidebarFooterClass()}></div>
</ui-sidebar>
`;
}
appSidebar() is a fragment helper rather than an element, so the server renders the whole sidebar into the page and a reader without JavaScript still gets every link.
Composition
Use the following composition to build a sidebar layout:
<ui-sidebar-provider>
├── <ui-sidebar>
│ ├── sidebarHeaderClass()
│ ├── sidebarContentClass()
│ │ ├── sidebarGroupClass()
│ │ │ ├── sidebarGroupLabelClass()
│ │ │ ├── sidebarGroupActionClass()
│ │ │ ├── sidebarGroupContentClass()
│ │ │ └── sidebarMenuClass()
│ │ │ ├── sidebarMenuItemClass()
│ │ │ │ ├── sidebarMenuButtonClass()
│ │ │ │ ├── sidebarMenuActionClass()
│ │ │ │ └── sidebarMenuBadgeClass()
│ │ │ └── sidebarMenuItemClass()
│ │ │ ├── sidebarMenuButtonClass()
│ │ │ └── sidebarMenuSubClass()
│ │ │ ├── sidebarMenuSubItemClass()
│ │ │ └── sidebarMenuSubItemClass()
│ │ └── sidebarGroupClass()
│ │ └── sidebarMenuClass()
│ │ ├── sidebarMenuItemClass()
│ │ └── sidebarMenuItemClass()
│ ├── sidebarFooterClass()
│ └── <ui-sidebar-rail>
├── <ui-sidebar-inset>
└── <ui-sidebar-trigger>
Structure
<ui-sidebar-provider>holds the open state, the cookie and the keyboard shortcut, and every part inside reads it.<ui-sidebar>is the main collapsible sidebar panel.sidebarHeaderClass()styles the header, sticky at the top. Use it for branding, titles, or workspace switchers.sidebarFooterClass()styles the footer, sticky at the bottom. Use it for user menus, settings, or actions.sidebarContentClass()styles the scrollable region between the header and footer.sidebarGroupClass()groups related navigation with an optional label, action, and content area.sidebarMenuClass()/sidebarMenuItemClass()build the menu structure for links, badges, actions, and nested submenus.<ui-sidebar-rail>is a thin strip along the sidebar's edge that toggles it.<ui-sidebar-inset>wraps the main content when using theinsetvariant, and is the page'smainlandmark.<ui-sidebar-trigger>is a button that toggles the sidebar open or collapsed.
<ui-sidebar>
sidebarHeaderClass()
(Sticky)
sidebarContentClass()
(Scrollable)
sidebarGroupClass()
sidebarGroupClass()
sidebarFooterClass()
(Sticky)
SidebarProvider
The <ui-sidebar-provider> element holds the sidebar's state for every part inside it. You should always wrap your application in a <ui-sidebar-provider>.
Props
Width
If you have a single sidebar in your application, the widths are set where the provider and the phone sheet render, in components/ui/sidebar.ts. Edit them there.
// The provider's wrapper: the desktop width and the collapsed icon width.
style="--sidebar-width: 16rem; --sidebar-width-icon: 3rem"
// The sheet content on a phone: --sidebar-width-mobile, else 18rem.
style="--sidebar-width: var(--sidebar-width-mobile, 18rem)"
For multiple sidebars in your application, set --sidebar-width and --sidebar-width-mobile in the style of each <ui-sidebar>. The sidebar's gap and panel read the first, and the phone sheet the second. --sidebar-width-mobile can also go on the provider, for every sidebar inside it.
<ui-sidebar-provider>
<ui-sidebar style="--sidebar-width: 20rem; --sidebar-width-mobile: 20rem"></ui-sidebar>
</ui-sidebar-provider>
Keyboard Shortcut
To trigger the sidebar, you use the cmd+b keyboard shortcut on Mac and ctrl+b on Windows. The key is in the provider's keydown handler.
_onKeyDown = (e: KeyboardEvent): void => {
if (e.key === 'b' && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
this.toggle();
}
};
Sidebar
The main <ui-sidebar> element renders a collapsible sidebar. Below 768px it opens as a sheet from its side instead.
Props
Note: If you use the inset variant, remember to wrap your main content in a <ui-sidebar-inset> element.
<ui-sidebar-provider>
<ui-sidebar variant="inset"></ui-sidebar>
<ui-sidebar-inset>
${children}
</ui-sidebar-inset>
</ui-sidebar-provider>
useSidebar
The provider element is the sidebar's state. From a component inside it, reach it with closest() and read or call the members below.
import type { UiSidebarProvider } from '#components/ui/sidebar.ts';
const sidebar = this.closest<UiSidebarProvider>('ui-sidebar-provider');
const { state, open, openMobile, isMobile } = sidebar;
sidebar.setOpen(false);
sidebar.setOpenMobile(true);
sidebar.toggle();
SidebarHeader
Use sidebarHeaderClass() to add a sticky header to the sidebar.
<ui-sidebar>
<div data-slot="sidebar-header" data-sidebar="header" class=${sidebarHeaderClass()}>
<ul data-slot="sidebar-menu" data-sidebar="menu" class=${sidebarMenuClass()}>
<li data-slot="sidebar-menu-item" data-sidebar="menu-item" class=${sidebarMenuItemClass()}>
<ui-dropdown-menu>
<ui-dropdown-menu-trigger>
<button type="button" data-slot="sidebar-menu-button" data-sidebar="menu-button" class=${sidebarMenuButtonClass()}>
Select Workspace
${ChevronDownIcon('ml-auto')}
</button>
</ui-dropdown-menu-trigger>
<ui-dropdown-menu-content class="w-(--radix-dropdown-menu-trigger-width)">
<ui-dropdown-menu-item>
<span>Acme Inc</span>
</ui-dropdown-menu-item>
</ui-dropdown-menu-content>
</ui-dropdown-menu>
</li>
</ul>
</div>
</ui-sidebar>
SidebarFooter
Use sidebarFooterClass() to add a sticky footer to the sidebar.
<ui-sidebar>
<div data-slot="sidebar-footer" data-sidebar="footer" class=${sidebarFooterClass()}>
<ul data-slot="sidebar-menu" data-sidebar="menu" class=${sidebarMenuClass()}>
<li data-slot="sidebar-menu-item" data-sidebar="menu-item" class=${sidebarMenuItemClass()}>
<button type="button" data-slot="sidebar-menu-button" data-sidebar="menu-button" class=${sidebarMenuButtonClass()}>
${UserIcon()} Username
</button>
</li>
</ul>
</div>
</ui-sidebar>
SidebarContent
sidebarContentClass() styles the element that wraps the content of the sidebar. This is where you add your groups. It is scrollable.
<ui-sidebar>
<div data-slot="sidebar-content" data-sidebar="content" class=${sidebarContentClass()}>
<div data-slot="sidebar-group" data-sidebar="group" class=${sidebarGroupClass()}></div>
<div data-slot="sidebar-group" data-sidebar="group" class=${sidebarGroupClass()}></div>
</div>
</ui-sidebar>
SidebarGroup
Use sidebarGroupClass() to create a section within the sidebar.
A group has a label (sidebarGroupLabelClass()), a content area (sidebarGroupContentClass()) and an optional action (sidebarGroupActionClass()).
<div data-slot="sidebar-group" data-sidebar="group" class=${sidebarGroupClass()}>
<div data-slot="sidebar-group-label" data-sidebar="group-label" class=${sidebarGroupLabelClass()}>Application</div>
<button type="button" data-slot="sidebar-group-action" data-sidebar="group-action" class=${sidebarGroupActionClass()}>
${PlusIcon()} <span class="sr-only">Add Project</span>
</button>
<div data-slot="sidebar-group-content" data-sidebar="group-content" class=${sidebarGroupContentClass()}></div>
</div>
To make a group collapsible, build it on a native <details> with the collapsible helpers, its <summary> as the label. It opens and closes with no JavaScript.
<details open data-slot="collapsible" class=${cn(collapsibleClass(), 'group/collapsible')}>
<summary data-slot="sidebar-group-label" data-sidebar="group-label" class=${cn(sidebarGroupLabelClass(), 'cursor-pointer list-none [&::-webkit-details-marker]:hidden')}>
Help
${ChevronDownIcon('ml-auto transition-transform group-open/collapsible:rotate-180')}
</summary>
<div data-slot="collapsible-content" class=${collapsibleContentClass()}>
<div data-slot="sidebar-group-content" data-sidebar="group-content" class=${sidebarGroupContentClass()}></div>
</div>
</details>
SidebarMenu
sidebarMenuClass() goes on the <ul> of a menu within a group, and sidebarMenuItemClass() on each <li>.
sidebarMenuClass() on the <ul>
sidebarMenuItemClass() on each <li>
sidebarMenuButtonClass()sidebarMenuButtonClass()sidebarMenuButtonClass()sidebarMenuButtonClass()sidebarMenuActionClass()
<ul data-slot="sidebar-menu" data-sidebar="menu" class=${sidebarMenuClass()}>
${projects.map((project) => html`
<li data-slot="sidebar-menu-item" data-sidebar="menu-item" class=${sidebarMenuItemClass()}>
<a href=${project.url} data-slot="sidebar-menu-button" data-sidebar="menu-button" class=${sidebarMenuButtonClass()}>
${project.icon()}
<span>${project.name}</span>
</a>
</li>
`)}
</ul>
SidebarMenuButton
sidebarMenuButtonClass() styles a menu button within a menu item.
Put it on whatever element the item needs: an <a> for a link, a <button> for an action, the <summary> of a <details> for a collapsible item. It takes variant (default or outline) and size (default, sm or lg); set data-size to the same size.
Mark the current page's button data-active="true", and give it aria-current="page" too.
<a href="#" data-slot="sidebar-menu-button" data-sidebar="menu-button" data-active="true" aria-current="page" class=${sidebarMenuButtonClass()}>Home</a>
SidebarMenuAction
sidebarMenuActionClass() styles a menu action within a menu item. Pass showOnHover: true to keep it hidden until the item is hovered or focused.
<li data-slot="sidebar-menu-item" data-sidebar="menu-item" class=${sidebarMenuItemClass()}>
<a href="#" data-slot="sidebar-menu-button" data-sidebar="menu-button" class=${sidebarMenuButtonClass()}>
${HomeIcon()}
<span>Home</span>
</a>
<button type="button" data-slot="sidebar-menu-action" data-sidebar="menu-action" class=${sidebarMenuActionClass()}>
${PlusIcon()} <span class="sr-only">Add Project</span>
</button>
</li>
SidebarMenuSub
sidebarMenuSubClass() styles a submenu within a menu item.
<li data-slot="sidebar-menu-item" data-sidebar="menu-item" class=${sidebarMenuItemClass()}>
<a href="#" data-slot="sidebar-menu-button" data-sidebar="menu-button" class=${sidebarMenuButtonClass()}></a>
<ul data-slot="sidebar-menu-sub" data-sidebar="menu-sub" class=${sidebarMenuSubClass()}>
<li data-slot="sidebar-menu-sub-item" data-sidebar="menu-sub-item" class=${sidebarMenuSubItemClass()}>
<a href="#" data-slot="sidebar-menu-sub-button" data-sidebar="menu-sub-button" data-size="md" class=${sidebarMenuSubButtonClass()}></a>
</li>
</ul>
</li>
SidebarMenuBadge
sidebarMenuBadgeClass() styles a badge within a menu item.
<li data-slot="sidebar-menu-item" data-sidebar="menu-item" class=${sidebarMenuItemClass()}>
<a href="#" data-slot="sidebar-menu-button" data-sidebar="menu-button" class=${sidebarMenuButtonClass()}></a>
<div data-slot="sidebar-menu-badge" data-sidebar="menu-badge" class=${sidebarMenuBadgeClass()}>24</div>
</li>
SidebarMenuSkeleton
sidebarMenuSkeleton() renders a loading placeholder for a menu item. It returns the markup itself, and takes showIcon and the text bar's width (a fixed width, since a random one would differ between the server and the browser).
<ul data-slot="sidebar-menu" data-sidebar="menu" class=${sidebarMenuClass()}>
${Array.from({ length: 5 }, (_, index) => html`
<li data-slot="sidebar-menu-item" data-sidebar="menu-item" class=${sidebarMenuItemClass()}>
${sidebarMenuSkeleton({ width: `${60 + index * 6}%` })}
</li>
`)}
</ul>
SidebarTrigger
Use <ui-sidebar-trigger> to render a button that toggles the sidebar. It is named "Toggle Sidebar".
For a trigger of your own, write a component that calls the provider's toggle(). A page never runs in the browser, so the click handler has to live in a component.
import { WebComponent, html } from '@webjsdev/core';
import type { UiSidebarProvider } from '#components/ui/sidebar.ts';
class CustomTrigger extends WebComponent {
render() {
return html`<button type="button" @click=${() => this.closest<UiSidebarProvider>('ui-sidebar-provider')?.toggle()}>Toggle Sidebar</button>`;
}
}
CustomTrigger.register('custom-trigger');
SidebarRail
The <ui-sidebar-rail> element renders a rail within a sidebar. This rail can be used to toggle the sidebar.
<ui-sidebar>
<div data-slot="sidebar-header" data-sidebar="header" class=${sidebarHeaderClass()}></div>
<div data-slot="sidebar-content" data-sidebar="content" class=${sidebarContentClass()}>
<div data-slot="sidebar-group" data-sidebar="group" class=${sidebarGroupClass()}></div>
</div>
<div data-slot="sidebar-footer" data-sidebar="footer" class=${sidebarFooterClass()}></div>
<ui-sidebar-rail></ui-sidebar-rail>
</ui-sidebar>
Controlled Sidebar
The provider keeps its own state, and you drive it from outside: write open or call setOpen() to change it, and listen for ui-open-change to follow it.
const sidebar = document.querySelector<UiSidebarProvider>('ui-sidebar-provider');
sidebar.addEventListener('ui-open-change', (e) => {
console.log('open', e.detail.open);
});
sidebar.setOpen(false);
The choice is kept in the sidebar_state cookie, so a layout can read it on the server and render default-open to match, with no flash.
'use server';
import { cookies } from '@webjsdev/server';
export async function sidebarOpen() {
return cookies().get('sidebar_state')?.value !== 'false';
}
<ui-sidebar-provider default-open=${String(await sidebarOpen())}>
Theming
We use the following CSS variables to theme the sidebar.
:root {
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.439 0 0);
}
Styling
Here are some tips for styling the sidebar based on different states.
<ui-sidebar collapsible="icon">
<div data-slot="sidebar-content" data-sidebar="content" class=${sidebarContentClass()}>
<div data-slot="sidebar-group" data-sidebar="group" class=${cn(sidebarGroupClass(), 'group-data-[collapsible=icon]:hidden')}></div>
</div>
</ui-sidebar>
<li data-slot="sidebar-menu-item" data-sidebar="menu-item" class=${sidebarMenuItemClass()}>
<a href="#" data-slot="sidebar-menu-button" data-sidebar="menu-button" class=${sidebarMenuButtonClass()}></a>
<button type="button" data-slot="sidebar-menu-action" data-sidebar="menu-action" class=${cn(sidebarMenuActionClass(), 'peer-data-[active=true]/menu-button:opacity-100')}></button>
</li>
RTL
To enable RTL support, see the RTL configuration guide. Put dir="rtl" on an ancestor and give the sidebar side="right".
Changelog
RTL Support
Right-to-left support takes five things, and the kit's sidebar ships with all of them:
No dir prop to add.
The direction comes from the dir attribute on an ancestor, and the phone sheet inherits it.
The container carries data-side.
<ui-sidebar> sets data-side on itself and on its container.
The container is positioned by data attributes.
The container's classes use data-[side=left]: and data-[side=right]: selectors, with no ternary on the side.
The rail is positioned physically.
<ui-sidebar-rail> uses -right-4 / left-0 with ltr: and rtl: translates.
The trigger's icon flips.
<ui-sidebar-trigger>'s icon carries rtl:rotate-180.
So a right-to-left sidebar is the direction on an ancestor and the side:
<div dir="rtl">
<ui-sidebar-provider>
<ui-sidebar side="right"></ui-sidebar>
</ui-sidebar-provider>
</div>
The sidebar will correctly position itself and handle interactions in both LTR and RTL layouts.