diff --git a/skills/radix-ui-design-system/SKILL.md b/skills/radix-ui-design-system/SKILL.md new file mode 100644 index 00000000..6aaf1ca0 --- /dev/null +++ b/skills/radix-ui-design-system/SKILL.md @@ -0,0 +1,847 @@ +--- +name: radix-ui-design-system +description: Build accessible design systems with Radix UI primitives. Headless component customization, theming strategies, and compound component patterns for production-grade UI libraries. +risk: safe +source: self +--- + +# Radix UI Design System + +Build production-ready, accessible design systems using Radix UI primitives with full customization control and zero style opinions. + +## Overview + +Radix UI provides unstyled, accessible components (primitives) that you can customize to match any design system. This skill guides you through building scalable component libraries with Radix UI, focusing on accessibility-first design, theming architecture, and composable patterns. + +**Key Strengths:** +- **Headless by design**: Full styling control without fighting defaults +- **Accessibility built-in**: WAI-ARIA compliant, keyboard navigation, screen reader support +- **Composable primitives**: Build complex components from simple building blocks +- **Framework agnostic**: Works with React, but styles work anywhere + +## When to Use This Skill + +- Creating a custom design system from scratch +- Building accessible UI component libraries +- Implementing complex interactive components (Dialog, Dropdown, Tabs, etc.) +- Migrating from styled component libraries to unstyled primitives +- Setting up theming systems with CSS variables or Tailwind +- Need full control over component behavior and styling +- Building applications requiring WCAG 2.1 AA/AAA compliance + +## Do not use this skill when + +- You need pre-styled components out of the box (use shadcn/ui, Mantine, etc.) +- Building simple static pages without interactivity +- The project doesn't use React 16.8+ (Radix requires hooks) +- You need components for frameworks other than React + +--- + +## Core Principles + +### 1. Accessibility First + +Every Radix primitive is built with accessibility as the foundation: + +- **Keyboard Navigation**: Full keyboard support (Tab, Arrow keys, Enter, Escape) +- **Screen Readers**: Proper ARIA attributes and live regions +- **Focus Management**: Automatic focus trapping and restoration +- **Disabled States**: Proper handling of disabled and aria-disabled + +**Rule**: Never override accessibility features. Enhance, don't replace. + +### 2. Headless Architecture + +Radix provides **behavior**, you provide **appearance**: + +```tsx +// ❌ Don't fight pre-styled components + + +// ✅ Radix gives you behavior, you add styling + + + + +``` + +### 3. Composition Over Configuration + +Build complex components from simple primitives: + +```tsx +// Primitive components compose naturally + + + Tab 1 + Tab 2 + + Content 1 + Content 2 + +``` + +--- + +## Getting Started + +### Installation + +```bash +# Install individual primitives (recommended) +npm install @radix-ui/react-dialog @radix-ui/react-dropdown-menu + +# Or install multiple at once +npm install @radix-ui/react-{dialog,dropdown-menu,tabs,tooltip} + +# For styling (optional but common) +npm install clsx tailwind-merge class-variance-authority +``` + +### Basic Component Pattern + +Every Radix component follows this pattern: + +```tsx +import * as Dialog from '@radix-ui/react-dialog'; + +export function MyDialog() { + return ( + + {/* Trigger the dialog */} + + Open + + + {/* Portal renders outside DOM hierarchy */} + + {/* Overlay (backdrop) */} + + + {/* Content (modal) */} + + Title + Description + + {/* Your content here */} + + + Close + + + + + ); +} +``` + +--- + +## Theming Strategies + +### Strategy 1: CSS Variables (Framework-Agnostic) + +**Best for**: Maximum portability, SSR-friendly + +```css +/* globals.css */ +:root { + --color-primary: 220 90% 56%; + --color-surface: 0 0% 100%; + --radius-base: 0.5rem; + --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1); +} + +[data-theme="dark"] { + --color-primary: 220 90% 66%; + --color-surface: 222 47% 11%; +} +``` + +```tsx +// Component.tsx + +``` + +### Strategy 2: Tailwind + CVA (Class Variance Authority) + +**Best for**: Tailwind projects, variant-heavy components + +```tsx +// button.tsx +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '@/lib/utils'; + +const buttonVariants = cva( + // Base styles + "inline-flex items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/90", + destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90", + outline: "border border-input bg-background hover:bg-accent", + ghost: "hover:bg-accent hover:text-accent-foreground", + }, + size: { + default: "h-10 px-4 py-2", + sm: "h-9 rounded-md px-3", + lg: "h-11 rounded-md px-8", + icon: "h-10 w-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +); + +interface ButtonProps extends VariantProps { + children: React.ReactNode; +} + +export function Button({ variant, size, children }: ButtonProps) { + return ( + + {children} + + ); +} +``` + +### Strategy 3: Stitches (CSS-in-JS) + +**Best for**: Runtime theming, scoped styles + +```tsx +import { styled } from '@stitches/react'; +import * as Dialog from '@radix-ui/react-dialog'; + +const StyledContent = styled(Dialog.Content, { + backgroundColor: '$surface', + borderRadius: '$md', + padding: '$6', + + variants: { + size: { + small: { width: '300px' }, + medium: { width: '500px' }, + large: { width: '700px' }, + }, + }, + + defaultVariants: { + size: 'medium', + }, +}); +``` + +--- + +## Component Patterns + +### Pattern 1: Compound Components with Context + +**Use case**: Share state between primitive parts + +```tsx +// Select.tsx +import * as Select from '@radix-ui/react-select'; +import { CheckIcon, ChevronDownIcon } from '@radix-ui/react-icons'; + +export function CustomSelect({ items, placeholder, onValueChange }) { + return ( + + + + + + + + + + + + {items.map((item) => ( + + {item.label} + + + + + ))} + + + + + ); +} +``` + +### Pattern 2: Polymorphic Components with `asChild` + +**Use case**: Render as different elements without losing behavior + +```tsx +// ✅ Render as Next.js Link but keep Radix behavior + + Open Settings + + +// ✅ Render as custom component + + }>Action + +``` + +**Why `asChild` matters**: Prevents nested button/link issues in accessibility tree. + +### Pattern 3: Controlled vs Uncontrolled + +```tsx +// Uncontrolled (Radix manages state) + + Tab 1 + + +// Controlled (You manage state) +const [activeTab, setActiveTab] = useState('tab1'); + + + Tab 1 + +``` + +**Rule**: Use controlled when you need to sync with external state (URL, Redux, etc.). + +### Pattern 4: Animation with Framer Motion + +```tsx +import * as Dialog from '@radix-ui/react-dialog'; +import { motion, AnimatePresence } from 'framer-motion'; + +export function AnimatedDialog({ open, onOpenChange }) { + return ( + + + + {open && ( + <> + + + + + + + {/* Content */} + + + > + )} + + + + ); +} +``` + +--- + +## Common Primitives Reference + +### Dialog (Modal) + +```tsx + {/* State container */} + {/* Opens dialog */} + {/* Renders in portal */} + {/* Backdrop */} + {/* Modal content */} + {/* Required for a11y */} + {/* Required for a11y */} + {/* Closes dialog */} + + + +``` + +### Dropdown Menu + +```tsx + + + + + + + + + + + {/* Nested menus */} + + + + + + +``` + +### Tabs + +```tsx + + + + + + + + +``` + +### Tooltip + +```tsx + + + + + + Tooltip text + + + + + +``` + +### Popover + +```tsx + + + + + Content + + + + + +``` + +--- + +## Accessibility Checklist + +### Every Component Must Have: + +- [ ] **Focus Management**: Visible focus indicators on all interactive elements +- [ ] **Keyboard Navigation**: Full keyboard support (Tab, Arrows, Enter, Esc) +- [ ] **ARIA Labels**: Meaningful labels for screen readers +- [ ] **Color Contrast**: WCAG AA minimum (4.5:1 for text, 3:1 for UI) +- [ ] **Error States**: Clear error messages with `aria-invalid` and `aria-describedby` +- [ ] **Loading States**: Proper `aria-busy` during async operations + +### Dialog-Specific: +- [ ] `Dialog.Title` is present (required for screen readers) +- [ ] `Dialog.Description` provides context +- [ ] Focus trapped inside modal when open +- [ ] Escape key closes dialog +- [ ] Focus returns to trigger on close + +### Dropdown-Specific: +- [ ] Arrow keys navigate items +- [ ] Type-ahead search works +- [ ] First/last item wrapping behavior +- [ ] Selected state indicated visually and with ARIA + +--- + +## Best Practices + +### ✅ Do This + +1. **Always use `asChild` to avoid wrapper divs** + ```tsx + + Open + + ``` + +2. **Provide semantic HTML** + ```tsx + + + {/* content */} + + + ``` + +3. **Use CSS variables for theming** + ```css + .dialog-content { + background: hsl(var(--surface)); + color: hsl(var(--on-surface)); + } + ``` + +4. **Compose primitives for complex components** + ```tsx + function CommandPalette() { + return ( + + + {/* Radix Combobox inside Dialog */} + + + ); + } + ``` + +### ❌ Don't Do This + +1. **Don't skip accessibility parts** + ```tsx + // ❌ Missing Title and Description + + Content + + ``` + +2. **Don't fight the primitives** + ```tsx + // ❌ Overriding internal behavior + e.stopPropagation()}> + ``` + +3. **Don't mix controlled and uncontrolled** + ```tsx + // ❌ Inconsistent state management + + ``` + +4. **Don't ignore keyboard navigation** + ```tsx + // ❌ Disabling keyboard behavior + e.preventDefault()}> + ``` + +--- + +## Real-World Examples + +### Example 1: Command Palette (Combo Dialog) + +```tsx +import * as Dialog from '@radix-ui/react-dialog'; +import { Command } from 'cmdk'; + +export function CommandPalette() { + const [open, setOpen] = useState(false); + + useEffect(() => { + const down = (e: KeyboardEvent) => { + if (e.key === 'k' && (e.metaKey || e.ctrlKey)) { + e.preventDefault(); + setOpen((open) => !open); + } + }; + document.addEventListener('keydown', down); + return () => document.removeEventListener('keydown', down); + }, []); + + return ( + + + + + + + + No results found. + + Calendar + Search Emoji + + + + + + + ); +} +``` + +### Example 2: Dropdown Menu with Icons + +```tsx +import * as DropdownMenu from '@radix-ui/react-dropdown-menu'; +import { DotsHorizontalIcon } from '@radix-ui/react-icons'; + +export function ActionsMenu() { + return ( + + + + + + + + + + + Edit + + + Duplicate + + + + Delete + + + + + ); +} +``` + +### Example 3: Form with Radix Select + React Hook Form + +```tsx +import * as Select from '@radix-ui/react-select'; +import { useForm, Controller } from 'react-hook-form'; + +interface FormData { + country: string; +} + +export function CountryForm() { + const { control, handleSubmit } = useForm(); + + return ( + console.log(data))}> + ( + + + + + + + + + + United States + Canada + United Kingdom + + + + + )} + /> + Submit + + ); +} +``` + +--- + +## Troubleshooting + +### Problem: Dialog doesn't close on Escape key + +**Cause**: `onEscapeKeyDown` event prevented or `open` state not synced + +**Solution**: +```tsx + + {/* Don't prevent default on escape */} + +``` + +### Problem: Dropdown menu positioning is off + +**Cause**: Parent container has `overflow: hidden` or transform + +**Solution**: +```tsx +// Use Portal to render outside overflow container + + + +``` + +### Problem: Animations don't work + +**Cause**: Portal content unmounts immediately + +**Solution**: +```tsx +// Use forceMount + AnimatePresence + + + {open && } + + +``` + +### Problem: TypeScript errors with `asChild` + +**Cause**: Type inference issues with polymorphic components + +**Solution**: +```tsx +// Explicitly type your component + + Open + +``` + +--- + +## Performance Optimization + +### 1. Code Splitting + +```tsx +// Lazy load heavy primitives +const Dialog = lazy(() => import('@radix-ui/react-dialog')); +const DropdownMenu = lazy(() => import('@radix-ui/react-dropdown-menu')); +``` + +### 2. Portal Container Reuse + +```tsx +// Create portal container once + + {/* All tooltips share portal container */} + ... + ... + +``` + +### 3. Memoization + +```tsx +// Memoize expensive render functions +const SelectItems = memo(({ items }) => ( + items.map((item) => ) +)); +``` + +--- + +## Integration with Popular Tools + +### shadcn/ui (Built on Radix) + +shadcn/ui is a collection of copy-paste components built with Radix + Tailwind. + +```bash +npx shadcn-ui@latest init +npx shadcn-ui@latest add dialog +``` + +**When to use shadcn vs raw Radix**: +- Use shadcn: Quick prototyping, standard designs +- Use raw Radix: Full customization, unique designs + +### Radix Themes (Official Styled System) + +```tsx +import { Theme, Button, Dialog } from '@radix-ui/themes'; + +function App() { + return ( + + Click me + + ); +} +``` + +--- + +## Related Skills + +- `@tailwind-design-system` - Tailwind + Radix integration patterns +- `@react-patterns` - React composition patterns +- `@frontend-design` - Overall frontend architecture +- `@accessibility-compliance` - WCAG compliance testing + +--- + +## Resources + +### Official Documentation +- [Radix UI Docs](https://www.radix-ui.com/primitives) +- [Radix Colors](https://www.radix-ui.com/colors) - Accessible color system +- [Radix Icons](https://www.radix-ui.com/icons) - Icon library + +### Community Resources +- [shadcn/ui](https://ui.shadcn.com) - Component collection +- [Radix UI Discord](https://discord.com/invite/7Xb99uG) - Community support +- [CVA Documentation](https://cva.style/docs) - Variant management + +### Examples +- [Radix Playground](https://www.radix-ui.com/primitives/docs/overview/introduction#try-it-out) +- [shadcn/ui Source](https://github.com/shadcn-ui/ui) - Production examples + +--- + +## Quick Reference + +### Installation +```bash +npm install @radix-ui/react-{primitive-name} +``` + +### Basic Pattern +```tsx + + + + + + +``` + +### Key Props +- `asChild` - Render as child element +- `defaultValue` - Uncontrolled default +- `value` / `onValueChange` - Controlled state +- `open` / `onOpenChange` - Open state +- `side` / `align` - Positioning + +--- + +**Remember**: Radix gives you **behavior**, you give it **beauty**. Accessibility is built-in, customization is unlimited. diff --git a/skills/radix-ui-design-system/examples/README.md b/skills/radix-ui-design-system/examples/README.md new file mode 100644 index 00000000..0d2d2daa --- /dev/null +++ b/skills/radix-ui-design-system/examples/README.md @@ -0,0 +1,63 @@ +# Radix UI Design System - Skill Examples + +This folder contains practical examples demonstrating how to use Radix UI primitives to build accessible, customizable components. + +## Examples + +### `dialog-example.tsx` + +Demonstrates Dialog (Modal) component patterns: +- **BasicDialog**: Standard modal with form +- **ControlledDialog**: Externally controlled modal state + +**Key Concepts**: +- Portal rendering outside DOM hierarchy +- Overlay (backdrop) handling +- Accessibility requirements (Title, Description) +- Custom styling with CSS + +### `dropdown-example.tsx` + +Complete dropdown menu implementation: +- **CompleteDropdown**: Full-featured menu with all Radix primitives + - Regular items + - Separators and labels + - Checkbox items + - Radio groups + - Sub-menus +- **ActionsMenu**: Simple actions menu for data tables/cards + +**Key Concepts**: +- Compound component architecture +- Keyboard navigation +- Item indicators (checkboxes, radio buttons) +- Nested sub-menus + +## Usage + +```tsx +import { BasicDialog } from './examples/dialog-example'; +import { CompleteDropdown } from './examples/dropdown-example'; + +function App() { + return ( + <> + + + > + ); +} +``` + +## Styling + +These examples use CSS classes. You can: +1. Copy the CSS from each file +2. Replace with Tailwind classes +3. Use CSS-in-JS (Stitches, Emotion, etc.) + +## Learn More + +- [Main SKILL.md](../SKILL.md) - Complete guide +- [Component Template](../templates/component-template.tsx) - Boilerplate +- [Radix UI Docs](https://www.radix-ui.com/primitives) diff --git a/skills/radix-ui-design-system/examples/dialog-example.tsx b/skills/radix-ui-design-system/examples/dialog-example.tsx new file mode 100644 index 00000000..befb7daa --- /dev/null +++ b/skills/radix-ui-design-system/examples/dialog-example.tsx @@ -0,0 +1,128 @@ +import * as Dialog from '@radix-ui/react-dialog'; +import { Cross2Icon } from '@radix-ui/react-icons'; +import './dialog.css'; + +/** + * Example: Basic Dialog Component + * + * Demonstrates: + * - Compound component pattern + * - Portal rendering + * - Accessibility features (Title, Description) + * - Custom styling with CSS + */ +export function BasicDialog() { + return ( + + + + Open Dialog + + + + + {/* Overlay (backdrop) */} + + + {/* Content (modal) */} + + {/* Title - Required for accessibility */} + + Edit Profile + + + {/* Description - Recommended for accessibility */} + + Make changes to your profile here. Click save when you're done. + + + {/* Form Content */} + + + + Name + + + + + + + Email + + + + + + + + Cancel + + + + Save Changes + + + + + {/* Close button */} + + + + + + + + + ); +} + +/** + * Example: Controlled Dialog + * + * Use when you need to: + * - Sync dialog state with external state + * - Programmatically open/close dialog + * - Track dialog open state + */ +export function ControlledDialog() { + const [open, setOpen] = React.useState(false); + + const handleSave = () => { + // Your save logic here + console.log('Saving...'); + setOpen(false); // Close after save + }; + + return ( + + + + Open Controlled Dialog + + + + + + + Controlled Dialog + + This dialog's state is managed externally. + + + Dialog is {open ? 'open' : 'closed'} + + Save and Close + + + + ); +} diff --git a/skills/radix-ui-design-system/examples/dropdown-example.tsx b/skills/radix-ui-design-system/examples/dropdown-example.tsx new file mode 100644 index 00000000..668543f1 --- /dev/null +++ b/skills/radix-ui-design-system/examples/dropdown-example.tsx @@ -0,0 +1,162 @@ +import * as DropdownMenu from '@radix-ui/react-dropdown-menu'; +import { + HamburgerMenuIcon, + DotFilledIcon, + CheckIcon, + ChevronRightIcon, +} from '@radix-ui/react-icons'; +import './dropdown.css'; + +/** + * Example: Complete Dropdown Menu + * + * Features: + * - Items, separators, labels + * - Checkbox items + * - Radio group items + * - Sub-menus + * - Keyboard navigation + */ +export function CompleteDropdown() { + const [bookmarksChecked, setBookmarksChecked] = React.useState(true); + const [urlsChecked, setUrlsChecked] = React.useState(false); + const [person, setPerson] = React.useState('pedro'); + + return ( + + + + + + + + + + {/* Regular items */} + + New Tab ⌘+T + + + New Window ⌘+N + + + New Private Window ⇧+⌘+N + + + {/* Sub-menu */} + + + More Tools + + + + + + + + Save Page As… ⌘+S + + + Create Shortcut… + + + Name Window… + + + + Developer Tools + + + + + + + + {/* Checkbox items */} + + + + + Show Bookmarks ⌘+B + + + + + + Show Full URLs + + + + + {/* Radio group */} + + People + + + + + + + Pedro Duarte + + + + + + Colm Tuite + + + + + + + + ); +} + +/** + * Example: Simple Actions Menu + * + * Common use case for data tables, cards, etc. + */ +export function ActionsMenu({ onEdit, onDuplicate, onDelete }) { + return ( + + + + + + + + + + + Edit + + + Duplicate + + + + Delete + + + + + ); +} diff --git a/skills/radix-ui-design-system/templates/component-template.tsx b/skills/radix-ui-design-system/templates/component-template.tsx new file mode 100644 index 00000000..4210e4ab --- /dev/null +++ b/skills/radix-ui-design-system/templates/component-template.tsx @@ -0,0 +1,148 @@ +/** + * Radix UI Component Template + * + * This template provides a starting point for creating + * custom components with Radix UI primitives. + * + * Replace [PRIMITIVE] with actual primitive name: + * Dialog, DropdownMenu, Select, Tabs, Tooltip, etc. + */ + +import * as [PRIMITIVE] from '@radix-ui/react-[primitive]'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '@/lib/utils'; + +// ============================================================================ +// Variants Definition (using CVA) +// ============================================================================ + +const [component]Variants = cva( + // Base styles (always applied) + "base-styles-here", + { + variants: { + // Define your variants + variant: { + default: "default-styles", + secondary: "secondary-styles", + destructive: "destructive-styles", + }, + size: { + sm: "small-size-styles", + md: "medium-size-styles", + lg: "large-size-styles", + }, + }, + defaultVariants: { + variant: "default", + size: "md", + }, + } +); + +// ============================================================================ +// TypeScript Interfaces +// ============================================================================ + +interface [Component]Props + extends React.ComponentPropsWithoutRef, + VariantProps { + // Add custom props here +} + +// ============================================================================ +// Component Implementation +// ============================================================================ + +export function [Component]({ + variant, + size, + className, + children, + ...props +}: [Component]Props) { + return ( + <[PRIMITIVE].Root {...props}> + {/* Trigger */} + <[PRIMITIVE].Trigger asChild> + + {children} + + [PRIMITIVE].Trigger> + + {/* Portal (if needed) */} + <[PRIMITIVE].Portal> + {/* Overlay (for Dialog, etc.) */} + <[PRIMITIVE].Overlay className="overlay-styles" /> + + {/* Content */} + <[PRIMITIVE].Content className="content-styles"> + {/* Required accessibility parts */} + <[PRIMITIVE].Title className="title-styles"> + Title + [PRIMITIVE].Title> + + <[PRIMITIVE].Description className="description-styles"> + Description + [PRIMITIVE].Description> + + {/* Your content */} + + {/* ... */} + + + {/* Close button */} + <[PRIMITIVE].Close asChild> + Close + [PRIMITIVE].Close> + [PRIMITIVE].Content> + [PRIMITIVE].Portal> + [PRIMITIVE].Root> + ); +} + +// ============================================================================ +// Sub-components (if needed) +// ============================================================================ + +[Component].[SubComponent] = function [SubComponent]({ + className, + ...props +}: React.ComponentPropsWithoutRef) { + return ( + <[PRIMITIVE].[SubComponent] + className={cn("subcomponent-styles", className)} + {...props} + /> + ); +}; + +// ============================================================================ +// Usage Example +// ============================================================================ + +/* +import { [Component] } from './[component]'; + +function App() { + return ( + <[Component] variant="default" size="md"> + Trigger Content + [Component] + ); +} +*/ + +// ============================================================================ +// Accessibility Checklist +// ============================================================================ + +/* +[ ] Keyboard navigation works (Tab, Arrow keys, Enter, Esc) +[ ] Focus visible on all interactive elements +[ ] Screen reader announces all states +[ ] ARIA attributes are correct +[ ] Color contrast meets WCAG AA (4.5:1 for text) +[ ] Focus trapped when needed (modals) +[ ] Focus restored after close +*/
Dialog is {open ? 'open' : 'closed'}