import { Meta } from 'storybook/blocks';
<Meta title="Style Guide/Component Patterns" />
Consistent patterns for building and using components throughout the application.
Component Architecture#
Atomic Design Principles#
Our component library follows atomic design methodology:
| Level | Description | Examples |
|---|---|---|
| Tokens | Design primitives | Colors, spacing, typography |
| Primitives | Base UI elements | Button, Input, Card |
| Components | Composed elements | ChatMessage, CitationCard |
| Patterns | Reusable combinations | Form layouts, Card grids |
| Templates | Page structures | Dashboard, Article page |
File Structure#
text
primitives/
├── Button/
│ ├── Button.tsx # Component implementation
│ ├── Button.test.tsx # Unit tests
│ ├── Button.stories.tsx # Storybook stories
│ └── index.ts # Public exports
Component API Patterns#
Props Interface Pattern#
All components use TypeScript interfaces for props:
tsx
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
/** Render as a different element using Slot */
asChild?: boolean;
/** Show loading spinner */
loading?: boolean;
/** Icon before text */
leftIcon?: React.ReactNode;
/** Icon after text */
rightIcon?: React.ReactNode;
}
forwardRef Pattern#
All primitive components forward refs:
tsx
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, ...props }, ref) => {
return (
<button ref={ref} className={cn(buttonVariants({ variant, size }), className)} {...props} />
);
}
);
Button.displayName = 'Button';
Compound Components#
Complex components use compound component pattern:
tsx
// Card with sub-components
<Card>
<CardHeader>
<CardTitle>Title</CardTitle>
<CardDescription>Description</CardDescription>
</CardHeader>
<CardContent>Content here</CardContent>
<CardFooter>Footer actions</CardFooter>
</Card>
// Tabs with compound structure
<Tabs defaultValue="tab1">
<TabsList>
<TabsTrigger value="tab1">Tab 1</TabsTrigger>
<TabsTrigger value="tab2">Tab 2</TabsTrigger>
</TabsList>
<TabsContent value="tab1">Content 1</TabsContent>
<TabsContent value="tab2">Content 2</TabsContent>
</Tabs>
Styling Patterns#
Class Variance Authority (CVA)#
All variant-based styling uses CVA:
tsx
import { cva, type VariantProps } from 'class-variance-authority';
const buttonVariants = cva(
// Base styles (always applied)
'inline-flex items-center justify-center rounded-lg font-semibold transition-colors',
{
variants: {
variant: {
primary: 'bg-primary-600 text-white hover:bg-primary-700',
secondary: 'bg-secondary-600 text-white hover:bg-secondary-700',
outline: 'border-2 border-neutral-300 bg-transparent hover:bg-neutral-100',
ghost: 'bg-transparent hover:bg-neutral-100',
},
size: {
sm: 'h-9 px-3 text-sm',
md: 'h-11 px-4 text-base',
lg: 'h-12 px-6 text-lg',
},
},
defaultVariants: {
variant: 'primary',
size: 'md',
},
}
);
cn Utility#
Use cn() to merge class names safely:
tsx
import { cn } from '@/design-system/utils';
// Merges base styles with conditional and custom classes
<div className={cn(
'base-class',
isActive && 'active-class',
className // allows overrides from props
)} />
Dark Mode#
All components support dark mode through Tailwind's dark: prefix:
tsx
<div className="bg-white dark:bg-neutral-900">
<p className="text-neutral-900 dark:text-neutral-100">
Adapts to theme automatically
</p>
</div>
State Management Patterns#
Controlled vs Uncontrolled#
Components support both patterns:
tsx
// Uncontrolled (internal state)
<Input defaultValue="initial" />
// Controlled (external state)
const [value, setValue] = useState('');
<Input value={value} onChange={(e) => setValue(e.target.value)} />
// Implementation pattern
const Input = ({ value: controlledValue, defaultValue, onChange, ...props }) => {
const [internalValue, setInternalValue] = useState(defaultValue || '');
const value = controlledValue !== undefined ? controlledValue : internalValue;
const handleChange = (e) => {
if (controlledValue === undefined) {
setInternalValue(e.target.value);
}
onChange?.(e);
};
return <input value={value} onChange={handleChange} {...props} />;
};
Context for Complex State#
Use React Context for compound components:
tsx
interface TabsContextValue {
value: string;
onValueChange: (value: string) => void;
}
const TabsContext = createContext<TabsContextValue | null>(null);
function useTabsContext() {
const context = useContext(TabsContext);
if (!context) {
throw new Error('Tabs components must be used within Tabs');
}
return context;
}
Form Patterns#
Input with Validation#
tsx
<Input
label="Email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
error={errors.email}
helperText="We'll never share your email"
/>
Form Layout#
tsx
<form className="space-y-6">
{/* Group related fields */}
<fieldset className="space-y-4">
<legend className="text-lg font-semibold">Personal Information</legend>
<Input label="First Name" />
<Input label="Last Name" />
</fieldset>
{/* Actions aligned right */}
<div className="flex gap-2 justify-end">
<Button variant="outline">Cancel</Button>
<Button type="submit">Save</Button>
</div>
</form>
Modal Patterns#
Basic Modal Usage#
tsx
const [isOpen, setIsOpen] = useState(false);
<Button onClick={() => setIsOpen(true)}>Open Modal</Button>
<Modal open={isOpen} onClose={() => setIsOpen(false)}>
<ModalHeader>
<ModalTitle>Confirm Action</ModalTitle>
<ModalCloseButton onClick={() => setIsOpen(false)} />
</ModalHeader>
<ModalBody>
Are you sure you want to proceed?
</ModalBody>
<ModalFooter>
<Button variant="outline" onClick={() => setIsOpen(false)}>
Cancel
</Button>
<Button onClick={handleConfirm}>Confirm</Button>
</ModalFooter>
</Modal>
Confirmation Dialog Pattern#
tsx
function ConfirmDialog({ open, onClose, onConfirm, title, message }) {
return (
<Modal open={open} onClose={onClose} size="sm">
<ModalBody className="pt-6 text-center">
<WarningIcon className="mx-auto mb-4 text-warning-500" />
<h3 className="text-lg font-semibold mb-2">{title}</h3>
<p className="text-neutral-600">{message}</p>
</ModalBody>
<ModalFooter className="justify-center">
<Button variant="outline" onClick={onClose}>Cancel</Button>
<Button variant="destructive" onClick={onConfirm}>Delete</Button>
</ModalFooter>
</Modal>
);
}
Table Patterns#
Basic Data Table#
tsx
<DataTable
columns={[
{ id: 'name', header: 'Name', accessor: 'name', sortable: true },
{ id: 'email', header: 'Email', accessor: 'email' },
{ id: 'actions', header: '', accessor: (row) => (
<Button size="sm" variant="ghost">Edit</Button>
)}
]}
data={users}
keyExtractor={(row) => row.id}
sortColumn={sortColumn}
sortDirection={sortDirection}
onSort={handleSort}
onRowClick={(row) => openUserDetail(row)}
/>
Table with Selection#
tsx
const [selected, setSelected] = useState(new Set());
<DataTable
columns={columns}
data={data}
keyExtractor={(row) => row.id}
selectedRows={selected}
onSelectRow={(key, checked) => {
setSelected(prev => {
const next = new Set(prev);
checked ? next.add(key) : next.delete(key);
return next;
});
}}
onSelectAll={(checked) => {
setSelected(checked ? new Set(data.map(r => r.id)) : new Set());
}}
/>
Navigation Patterns#
Tab Navigation#
tsx
<Tabs defaultValue="overview" variant="underline">
<TabsList>
<TabsTrigger value="overview">Overview</TabsTrigger>
<TabsTrigger value="analytics">Analytics</TabsTrigger>
<TabsTrigger value="settings">Settings</TabsTrigger>
</TabsList>
<TabsContent value="overview">
<OverviewPanel />
</TabsContent>
<TabsContent value="analytics">
<AnalyticsPanel />
</TabsContent>
<TabsContent value="settings">
<SettingsPanel />
</TabsContent>
</Tabs>
Breadcrumb Navigation#
tsx
<Breadcrumbs
items={[
{ label: 'Home', href: '/' },
{ label: 'Library', href: '/library' },
{ label: 'Buddhism', href: '/library/buddhism' },
{ label: 'Meditation Techniques' }
]}
onItemClick={(item) => router.push(item.href)}
/>
Loading States#
Button Loading#
tsx
<Button loading={isSubmitting} disabled={isSubmitting}>
{isSubmitting ? 'Saving...' : 'Save'}
</Button>
Skeleton Pattern#
tsx
// Define skeleton for component
function CardSkeleton() {
return (
<Card>
<CardContent className="space-y-4">
<div className="h-4 bg-neutral-200 rounded animate-pulse w-3/4" />
<div className="h-4 bg-neutral-200 rounded animate-pulse w-1/2" />
<div className="h-4 bg-neutral-200 rounded animate-pulse w-5/6" />
</CardContent>
</Card>
);
}
// Use during loading
{isLoading ? <CardSkeleton /> : <ActualCard data={data} />}
Error Handling#
Form Errors#
tsx
<Input
label="Username"
state={errors.username ? 'error' : 'default'}
error={errors.username?.message}
/>
Empty States#
tsx
<TableEmpty
colSpan={columns.length}
icon={<SearchIcon className="text-neutral-400" />}
title="No results found"
description="Try adjusting your search criteria"
action={<Button variant="outline" onClick={clearFilters}>Clear Filters</Button>}
/>