View Switcher
The bar of a table's open views, such as Table, List, Board, Chart and Timeline. An “Add view” menu explains each view. Your app decides which views exist, which are open and which can close. The switcher shows exactly what you pass and calls you back.
Installation
pnpm dlx shadcn@latest add https://sprout.tulipfarm.ai/r/view-switcher.jsonCopies View Switcher and the components it uses (Button, Dropdown Menu, and Tabs) into your app, installs the packages, and adds the styles. Then import it from @/components/ui/view-switcher. Needs Tailwind CSS 4 and a components.json from shadcn init.
Install the following dependencies:
pnpm add clsx tailwind-merge @base-ui/react @hugeicons/core-free-icons @hugeicons/reactAdd Sprout base once per app: the
cn()helper and the design tokens.lib/sprout/classes.ts- Design tokens, for your global CSS
Add the components it uses: Button, Dropdown Menu, and Tabs.
Copy and paste the following code into your project.
'use client'; import { Tabs as BaseTabs } from '@base-ui/react/tabs'; import { useEffect, useId, useLayoutEffect, useRef, type ComponentType, type KeyboardEvent, type ReactNode, } from 'react'; import { AddIcon } from '@/lib/sprout/icons/add-icon'; import { CheckIcon } from '@/lib/sprout/icons/check-icon'; import { CloseIcon } from '@/lib/sprout/icons/close-icon'; import { cn } from '@/lib/sprout/classes'; import { Button } from '@/components/ui/button'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; export interface ViewSwitcherView { id: string; label: string; icon: ComponentType<{ size?: number }>; closable?: boolean | undefined; } export interface ViewSwitcherOption extends ViewSwitcherView { description: string; unavailable?: string | undefined; } export interface ViewSwitcherProps { views: ViewSwitcherView[]; value: string; onValueChange: (id: string) => void; options?: ViewSwitcherOption[] | undefined; onAdd?: ((id: string) => void) | undefined; onClose?: ((id: string) => void) | undefined; label?: string | undefined; addLabel?: string | undefined; actions?: ReactNode; panelId?: string | undefined; className?: string | undefined; } export function viewSwitcherTabId(panelId: string, viewId: string) { return `${panelId}-tab-${viewId}`; } const fade = 24; export function ViewSwitcher({ views, value, onValueChange, options, onAdd, onClose, label = 'Views', addLabel = 'Add view', actions, panelId, className, }: ViewSwitcherProps) { const baseId = useId(); const listRef = useRef<HTMLDivElement>(null); const tabs = useRef(new Map<string, HTMLElement>()); const pendingFocus = useRef<{ closed: string; neighbour: string | undefined } | null>(null); const open = new Set(views.map(view => view.id)); const tabId = (id: string) => (panelId ? viewSwitcherTabId(panelId, id) : `${baseId}-tab-${id}`); function close(index: number) { const view = views[index]; if (!view || !view.closable || !onClose) return; const tab = tabs.current.get(view.id); if (tab && tab === document.activeElement) { pendingFocus.current = { closed: view.id, neighbour: (views[index + 1] ?? views[index - 1])?.id }; } onClose(view.id); } function onTabKeyDown(event: KeyboardEvent<HTMLElement>, index: number) { if (event.key !== 'Delete' && event.key !== 'Backspace') return; event.preventDefault(); close(index); } useLayoutEffect(() => { const pending = pendingFocus.current; if (!pending || open.has(pending.closed)) return; pendingFocus.current = null; const target = value !== pending.closed && open.has(value) ? value : pending.neighbour; if (target) tabs.current.get(target)?.focus(); }, [views, value]); useLayoutEffect(() => { const list = listRef.current; const tab = tabs.current.get(value); if (!list || !tab || list.scrollWidth <= list.clientWidth) return; const bounds = list.getBoundingClientRect(); const rect = tab.getBoundingClientRect(); if (rect.left < bounds.left + fade) list.scrollLeft -= bounds.left + fade - rect.left; else if (rect.right > bounds.right - fade) list.scrollLeft += rect.right - (bounds.right - fade); }, [value, views]); useEffect(() => { const list = listRef.current; if (!list) return; const update = () => { const scrolled = Math.abs(list.scrollLeft); const max = list.scrollWidth - list.clientWidth; list.toggleAttribute('data-overflow-start', scrolled > 1); list.toggleAttribute('data-overflow-end', max - scrolled > 1); }; update(); list.addEventListener('scroll', update, { passive: true }); const observer = new ResizeObserver(update); observer.observe(list); for (const child of list.children) observer.observe(child); return () => { list.removeEventListener('scroll', update); observer.disconnect(); }; }, [views]); return ( <div data-slot="view-switcher" className={cn('sprout-view-switcher', className)}> <Tabs className="sprout-view-switcher-tabs" value={open.has(value) ? value : null} onValueChange={next => { if (typeof next === 'string') onValueChange(next); }} > <TabsList ref={listRef} variant="line" activateOnFocus loopFocus={false} aria-label={label} className="sprout-view-switcher-list" > {views.map((view, index) => { const Icon = view.icon; const closable = Boolean(view.closable && onClose); return ( <TabsTrigger key={view.id} value={view.id} id={tabId(view.id)} ref={(node: HTMLElement | null) => { if (node) tabs.current.set(view.id, node); else tabs.current.delete(view.id); }} className="sprout-view-switcher-tab" data-closable={closable || undefined} aria-keyshortcuts={closable ? 'Delete' : undefined} {...(panelId ? { 'aria-controls': panelId } : {})} onKeyDown={event => onTabKeyDown(event, index)} > <span className="sprout-view-switcher-icon" aria-hidden="true"> <Icon size={14} /> </span> <span className="sprout-view-switcher-label">{view.label}</span> {closable && ( <span aria-hidden="true" title={`Close ${view.label}`} data-slot="view-switcher-close" className="sprout-view-switcher-close" onPointerDown={event => { event.preventDefault(); event.stopPropagation(); }} onMouseDown={event => event.preventDefault()} onClick={event => { event.preventDefault(); event.stopPropagation(); close(index); }} > <CloseIcon size="xs" /> </span> )} </TabsTrigger> ); })} <BaseTabs.Indicator className="sprout-view-switcher-indicator" /> </TabsList> </Tabs> {options && ( <DropdownMenu> <DropdownMenuTrigger render={<Button variant="ghost" size="sm" className="sprout-view-switcher-add" />} data-slot="view-switcher-add" > <AddIcon size="sm" aria-hidden="true" data-icon="inline-start" /> <span className="sprout-view-switcher-add-label">{addLabel}</span> </DropdownMenuTrigger> <DropdownMenuContent align="start" size="menu" className="sprout-view-switcher-menu"> <div className="sprout-view-switcher-options"> {options.map(option => ( <ViewOption key={option.id} option={option} baseId={baseId} isOpen={open.has(option.id)} onSelect={() => onAdd?.(option.id)} /> ))} </div> </DropdownMenuContent> </DropdownMenu> )} {actions != null && actions !== false && ( <div data-slot="view-switcher-actions" className="sprout-view-switcher-actions"> {actions} </div> )} </div> ); } function ViewOption({ option, baseId, isOpen, onSelect, }: { option: ViewSwitcherOption; baseId: string; isOpen: boolean; onSelect: () => void; }) { const Icon = option.icon; const unavailable = Boolean(option.unavailable); const titleId = `${baseId}-option-${option.id}-title`; const noteId = `${baseId}-option-${option.id}-note`; const openId = `${baseId}-option-${option.id}-open`; return ( <DropdownMenuItem data-slot="view-switcher-option" className="sprout-view-switcher-option" disabled={unavailable} data-open={isOpen || undefined} aria-labelledby={titleId} aria-describedby={isOpen ? `${openId} ${noteId}` : noteId} onClick={unavailable ? undefined : onSelect} > <span className="sprout-view-switcher-tile" aria-hidden="true"> <Icon size={16} /> </span> <span className="sprout-view-switcher-option-text"> <span id={titleId} className="sprout-view-switcher-option-title"> {option.label} </span> <span id={noteId} className="sprout-view-switcher-option-note" data-kind={unavailable ? 'unavailable' : 'description'} > {option.unavailable || option.description} </span> </span> {isOpen && ( <span className="sprout-view-switcher-check"> <CheckIcon size="md" aria-hidden="true" /> <span id={openId} className="sprout-view-switcher-sr-only"> Already open. </span> </span> )} </DropdownMenuItem> ); }And the files it imports:
lib/sprout/icons/add-icon.tsxlib/sprout/icons/check-icon.tsxlib/sprout/icons/close-icon.tsxlib/sprout/icons/create-icon.tsx
Add the styles to your global CSS, after
@import "tailwindcss".@layer components { .sprout-view-switcher { border-bottom: 1px solid var(--sprout-line); min-width: 0; font-family: var(--sprout-font); align-items: center; gap: 4px; display: flex; container-type: inline-size; } .sprout-view-switcher-tabs.sprout-tabs { flex: 0 auto; min-width: 0; display: flex; } .sprout-view-switcher-list.sprout-tabs-list { --sprout-view-switcher-fade-start: 0px; --sprout-view-switcher-fade-end: 0px; width: auto; max-width: 100%; height: calc(var(--sprout-control-height) + 8px); overscroll-behavior-x: contain; scrollbar-width: none; mask-image: linear-gradient(to right, transparent 0, oklch(0% 0 0) var(--sprout-view-switcher-fade-start), oklch(0% 0 0) calc(100% - var(--sprout-view-switcher-fade-end)), transparent 100%); justify-content: flex-start; gap: 2px; padding: 0 2px; overflow: auto hidden; } .sprout-view-switcher-list::-webkit-scrollbar { display: none; } .sprout-view-switcher-list[data-overflow-start] { --sprout-view-switcher-fade-start: 24px; } .sprout-view-switcher-list[data-overflow-end] { --sprout-view-switcher-fade-end: 24px; } .sprout-view-switcher-list:dir(rtl) { mask-image: linear-gradient(to left, transparent 0, oklch(0% 0 0) var(--sprout-view-switcher-fade-start), oklch(0% 0 0) calc(100% - var(--sprout-view-switcher-fade-end)), transparent 100%); } .sprout-view-switcher-tab.sprout-tabs-trigger { height: calc(var(--sprout-control-height) - 4px); color: var(--sprout-muted); border: 0; flex: none; gap: 6px; padding: 0 8px; } .sprout-view-switcher-tab.sprout-tabs-trigger:after { display: none; } .sprout-view-switcher-tab.sprout-tabs-trigger:focus-visible { outline-offset: -2px; } .sprout-view-switcher-tab.sprout-tabs-trigger[data-active] { color: var(--sprout-text); } .sprout-view-switcher-tab[data-closable] { padding-inline-end: 4px; } @media (hover: hover) { .sprout-view-switcher-tab.sprout-tabs-trigger:hover { background: var(--sprout-hover); color: var(--sprout-text); } .sprout-view-switcher-close:hover { background: var(--sprout-active); color: var(--sprout-text); } .sprout-view-switcher-tab[data-closable] { padding-inline-end: 8px; } .sprout-view-switcher-close { inset-inline-end: 4px; position: absolute; top: 50%; translate: 0 -50%; } .sprout-view-switcher-tab[data-closable]:is(:hover, :focus-visible) .sprout-view-switcher-label { mask-image: linear-gradient(to left, #0000 14px, oklch(0% 0 0) 24px); } .sprout-view-switcher-tab[data-closable]:is(:hover, :focus-visible) .sprout-view-switcher-label:dir(rtl) { mask-image: linear-gradient(to right, #0000 14px, oklch(0% 0 0) 24px); } .sprout-view-switcher-add.sprout-button:hover { color: var(--sprout-text); } } .sprout-view-switcher-icon { flex-shrink: 0; display: inline-flex; } .sprout-view-switcher-tab .sprout-view-switcher-icon svg { width: 14px; height: 14px; } .sprout-view-switcher-close { border-radius: calc(var(--sprout-radius-control) - 2px); width: 16px; height: 16px; color: var(--sprout-muted); opacity: 0; cursor: pointer; flex-shrink: 0; justify-content: center; align-items: center; display: inline-flex; } .sprout-view-switcher-tab .sprout-view-switcher-close svg { pointer-events: none; width: 12px; height: 12px; } .sprout-view-switcher-tab:focus-visible .sprout-view-switcher-close, .sprout-view-switcher-tab:hover .sprout-view-switcher-close { opacity: 1; } @media (hover: none) { .sprout-view-switcher-close { opacity: 1; } } @media (pointer: coarse) { .sprout-view-switcher-close { position: relative; } .sprout-view-switcher-close:after { content: ""; position: absolute; inset: -4px; } } .sprout-view-switcher-indicator { bottom: 0; left: var(--active-tab-left); width: var(--active-tab-width); background: var(--sprout-text); pointer-events: none; border-radius: 2px 2px 0 0; height: 2px; position: absolute; } .sprout-view-switcher-add.sprout-button { color: var(--sprout-muted); flex: none; } .sprout-view-switcher-add.sprout-button[data-popup-open] { color: var(--sprout-text); } .sprout-view-switcher-actions { flex: none; align-items: center; gap: 4px; margin-inline-start: auto; padding-inline-start: 8px; display: flex; } @container (width <= 479px) { .sprout-view-switcher-add-label { clip-path: inset(50%); white-space: nowrap; width: 1px; height: 1px; position: absolute; overflow: hidden; } .sprout-view-switcher-add.sprout-button { padding-inline: 6px; } .sprout-view-switcher-options { grid-template-columns: minmax(0, 1fr); } } .sprout-view-switcher-menu.sprout-dropdown-menu-content { width: min(36rem, var(--available-width)); padding: 6px; container-type: inline-size; } .sprout-view-switcher-options { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 2px; display: grid; } .sprout-view-switcher-option.sprout-dropdown-menu-item { align-items: flex-start; gap: 10px; padding: 8px; } .sprout-view-switcher-tile { border-radius: var(--sprout-radius-control); background: var(--sprout-hover); width: 32px; height: 32px; color: var(--sprout-text); flex-shrink: 0; justify-content: center; align-items: center; display: inline-flex; } .sprout-view-switcher-option[data-highlighted] .sprout-view-switcher-tile { background: var(--sprout-surface); box-shadow: inset 0 0 0 1px var(--sprout-line); } .sprout-view-switcher-option-text { flex: auto; gap: 2px; min-width: 0; padding-top: 1px; display: grid; } .sprout-view-switcher-option-title { font-weight: 500; line-height: 1.25rem; } .sprout-view-switcher-option-note { color: var(--sprout-muted); font-size: var(--sprout-text-xs); overflow-wrap: anywhere; line-height: 1rem; } .sprout-view-switcher-check { color: var(--sprout-text); flex-shrink: 0; align-self: center; display: inline-flex; } .sprout-view-switcher-option.sprout-dropdown-menu-item[data-disabled] { opacity: 1; cursor: not-allowed; } .sprout-view-switcher-option[data-disabled] .sprout-view-switcher-tile { box-shadow: inset 0 0 0 1px var(--sprout-line); color: var(--sprout-muted); background: none; } .sprout-view-switcher-option[data-disabled] .sprout-view-switcher-option-title { color: var(--sprout-muted); } .sprout-view-switcher-option-note[data-kind="unavailable"] { white-space: normal; } .sprout-view-switcher-sr-only { clip-path: inset(50%); white-space: nowrap; width: 1px; height: 1px; position: absolute; overflow: hidden; } @media (forced-colors: active) { .sprout-view-switcher-indicator { background: highlight; } .sprout-view-switcher-tile { border: 1px solid canvastext; } } @media (prefers-reduced-motion: no-preference) { .sprout-view-switcher-indicator { transition: left var(--sprout-motion-normal) var(--sprout-motion-ease), width var(--sprout-motion-normal) var(--sprout-motion-ease); } .sprout-view-switcher-close { transition: opacity var(--sprout-motion-fast) var(--sprout-motion-ease), background-color var(--sprout-motion-fast) var(--sprout-motion-ease); } .sprout-view-switcher-tile { transition: background-color var(--sprout-motion-fast) var(--sprout-motion-ease), box-shadow var(--sprout-motion-fast) var(--sprout-motion-ease); } } }Import it from
@/components/ui/view-switcher. Update the paths if your@/alias points elsewhere.
pnpm add @tulipfarm/sprout@import "tailwindcss";
@import "@tulipfarm/sprout/styles.css";The package keeps the source and ships fixes with each release. Import from @tulipfarm/sprout/view-switcher.
Seed orders
Choose a tab or use the arrow keys. Add a view from the menu. Hover a tab, or focus it and press Delete, to close it. Table stays.
| Order | Stage | Bulbs |
|---|---|---|
| Queen of Night tulips | Growing | 1,200 |
| Apeldoorn tulips | Planting | 800 |
| Tête-à-tête daffodils | Ordered | 450 |
| Pink Impression tulips | Ready | 600 |
| Blue Spike muscari | Growing | 950 |
Usage
import { GridIcon, KanbanIcon, ListIcon } from "@tulipfarm/sprout/icons";
import { ViewSwitcher, viewSwitcherTabId } from "@tulipfarm/sprout/view-switcher";
const options = [
{ id: "table", label: "Table", icon: GridIcon, description: "Rows and columns. Edit, group and sum." },
{ id: "list", label: "List", icon: ListIcon, description: "One item per row for quick reading." },
{ id: "board", label: "Board", icon: KanbanIcon, description: "Cards in lanes, one lane per stage.",
unavailable: hasSingleSelect ? undefined : "Needs a single-select field." },
];
<ViewSwitcher
views={open.map(id => ({ ...byId[id], closable: id !== "table" }))}
value={layout}
onValueChange={setLayout}
options={options}
onAdd={id => { if (!open.includes(id)) openView(id); setLayout(id); }}
onClose={closeView}
panelId="records"
actions={<Button variant="ghost" size="icon-sm" aria-label="View settings">…</Button>}
/>
<div role="tabpanel" id="records" aria-labelledby={viewSwitcherTabId("records", layout)} tabIndex={0}>
{layout === "board" ? <Board … /> : <Table … />}
</div>views:{ id, label, icon, closable? }[]. The tabs, in order.iconis an icon component that takessize, such as one from@tulipfarm/sprout/icons.valueandonValueChange: the active view'sid. Click and arrow keys callonValueChange.options:{ id, label, icon, description, unavailable? }[]. The views in the “Add view” menu. Leave it out to hide the menu.onAdd: called with the chosen option. Options that are already inviewsshow a check. Choosing one still callsonAdd; switch to that view there, as the example does.onClose: called by a tab's close control or the Delete key. Only views markedclosablecan close, and only when you passonClose. Remove the view fromviews, and pick a newvalueif the active view closed.actions: controls at the end of the bar, such as a settings button.panelId: theidof your panel. Every tab points to it witharia-controls. Label the panel withviewSwitcherTabId(panelId, value).labelandaddLabel: the tab list's name, “Views” by default, and the menu button's text, “Add view” by default.
Views that cannot be added
Set unavailable to say why an option cannot be added. The menu shows the reason in place of the description, dims the icon and does not let anyone choose it.
Greenhouse log
This table has no single-select field, so Board says what it needs and cannot be chosen.
| Order | Stage | Bulbs |
|---|---|---|
| Queen of Night tulips | Growing | 1,200 |
| Apeldoorn tulips | Planting | 800 |
| Tête-à-tête daffodils | Ordered | 450 |
| Pink Impression tulips | Ready | 600 |
| Blue Spike muscari | Growing | 950 |
Narrow screens
When the tabs do not fit, they scroll sideways and fade at each edge that hides more tabs. The active tab scrolls into view. “Add view” and actions stay at the end. Under 480px the button shows only its plus icon, and the menu uses one column.
Many views in a narrow space
The tabs scroll sideways with faded edges. The active tab stays in view and Add view stays put.
| Order | Stage | Bulbs |
|---|---|---|
| Queen of Night tulips | Growing | 1,200 |
| Apeldoorn tulips | Planting | 800 |
| Tête-à-tête daffodils | Ordered | 450 |
| Pink Impression tulips | Ready | 600 |
| Blue Spike muscari | Growing | 950 |
Accessibility
The bar is a tablist named by label. It is one tab stop. Left and Right move between tabs and choose them at once; Home and End go to the first and last tab. On a closable tab, Delete (or Backspace) calls onClose. When the tab closes, focus moves to the view your app chose, or else to a neighbour. The close control is for the pointer only, so it is hidden from screen readers; the tab announces the Delete shortcut.
The menu lists options in reading order, and the arrow keys move through them one by one. An unavailable option has aria-disabled and its reason as the description. An open option is described as “Already open”. Escape closes the menu and returns focus to “Add view”.
The underline slides to the active tab over 180ms. It does not move when reduced motion is requested.
Theme tokens
Tabs use --sprout-muted and, when active, --sprout-text with a--sprout-text underline over a --sprout-line rule. Hover uses --sprout-hover. The menu uses the Dropdown Menu surface; icon tiles use --sprout-hover and--sprout-radius-control. Motion uses --sprout-motion-normal,--sprout-motion-fast and --sprout-motion-ease.