import { Meta } from 'storybook/blocks'; # 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 ``` 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, VariantProps { /** 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( ({ className, variant, size, ...props }, ref) => { return ( ); } ); Button.displayName = 'Button'; ``` ### Compound Components Complex components use compound component pattern: ```tsx // Card with sub-components Title Description Content here Footer actions // Tabs with compound structure Tab 1 Tab 2 Content 1 Content 2 ``` ## 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 ``` ### Dark Mode All components support dark mode through Tailwind's `dark:` prefix: ```tsx Adapts to theme automatically ``` ## State Management Patterns ### Controlled vs Uncontrolled Components support both patterns: ```tsx // Uncontrolled (internal state) // Controlled (external state) const [value, setValue] = useState(''); 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 ; }; ``` ### Context for Complex State Use React Context for compound components: ```tsx interface TabsContextValue { value: string; onValueChange: (value: string) => void; } const TabsContext = createContext(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 setEmail(e.target.value)} error={errors.email} helperText="We'll never share your email" /> ``` ### Form Layout ```tsx {/* Group related fields */} Personal Information {/* Actions aligned right */} Cancel Save ``` ## Modal Patterns ### Basic Modal Usage ```tsx const [isOpen, setIsOpen] = useState(false); setIsOpen(true)}>Open Modal setIsOpen(false)}> Confirm Action setIsOpen(false)} /> Are you sure you want to proceed? setIsOpen(false)}> Cancel Confirm ``` ### Confirmation Dialog Pattern ```tsx function ConfirmDialog({ open, onClose, onConfirm, title, message }) { return ( {title} {message} Cancel Delete ); } ``` ## Table Patterns ### Basic Data Table ```tsx ( Edit )} ]} 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()); 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 Overview Analytics Settings ``` ### Breadcrumb Navigation ```tsx router.push(item.href)} /> ``` ## Loading States ### Button Loading ```tsx {isSubmitting ? 'Saving...' : 'Save'} ``` ### Skeleton Pattern ```tsx // Define skeleton for component function CardSkeleton() { return ( ); } // Use during loading {isLoading ? : } ``` ## Error Handling ### Form Errors ```tsx ``` ### Empty States ```tsx } title="No results found" description="Try adjusting your search criteria" action={Clear Filters} /> ```
Adapts to theme automatically
{message}