# SurgeUI — documentation (4.2.0) --- --- > Accessible, themable Vue 3 component library (npm package `@surgeui/vue`, version 4.2.0): components, layouts and composables with WAI-ARIA keyboard and screen reader support, light/dark themes, RTL and translatable texts (French, English, Arabic). --- --- # Getting Started Modern Vue.js 3 component library with Composition API, designed to create modern and consistent interfaces. ## Resources - **Documentation** - Complete guide with examples and API - **[Storybook](https://surgeui.com/storybook)** - Interactive examples and component playground - **[npm Package](https://www.npmjs.com/package/@surgeui/vue)** ## Features - **Modern Design** - Components with polished and professional design - **TypeScript** - Full TypeScript support for better DX - **Composition API** - Uses Vue 3 Composition API - **Responsive** - Components adapted to all screen sizes - **4 themes** - Default, Ocean, Forest and Sunset, in light and dark mode - **RTL & LTR** - Native support for both text directions - **Accessibility** - WCAG 2.1 AA compliant (focus, keyboard, screen readers, contrast) - **Performance** - Tree-shakable, optimized CSS, transitions respecting `prefers-reduced-motion` ## Accessibility All components follow WCAG 2.1 AA standards: - **Focus Management** - Clear focus indicators and logical tab order - **Keyboard Navigation** - Full keyboard support - **Screen Readers** - Proper ARIA attributes and announcements - **Color Contrast** - WCAG AA compliant contrast ratios (4.5:1 minimum) - **Touch Targets** - Minimum 44px touch targets (`touch-target` mixin) - **Reduced Motion** - Respects `prefers-reduced-motion` - **High Contrast** - Supports `prefers-contrast: high` ## Quick Installation ```bash npm install @surgeui/vue ``` ```vue ``` For the full setup (global import, selective import, plugin options), see the [Installation](https://surgeui.com/en/guide/installation.md) page. --- # Installation ## Prerequisites - Vue.js 3.5+ ## Installation ::: tip New name Since 4.0.0, the package is named `@surgeui/vue` (formerly `@surgeui/ds-vue`). See [Migrating to 4.0](https://surgeui.com/en/guide/migration.md). ::: ::: code-group ```bash [npm] npm install @surgeui/vue ``` ```bash [yarn] yarn add @surgeui/vue ``` ```bash [pnpm] pnpm add @surgeui/vue ``` ::: ::: warning pnpm: minimum release age pnpm can refuse a version published less than `minimumReleaseAge` minutes ago (24 hours by default in pnpm 11). For a new SurgeUI release, wait for that delay or add an exception limited to that version, and remove it afterwards: ```yaml # pnpm-workspace.yaml minimumReleaseAgeExclude: - '@surgeui/vue@4.2.0' # exact version: pnpm 10.19+ ``` ::: ## Configuration ### Global import ```ts // main.ts import { createApp } from 'vue' import SurgeUI from '@surgeui/vue' import '@surgeui/vue/style.css' import App from './App.vue' const app = createApp(App) app.use(SurgeUI) app.mount('#app') ``` ### Selective import ```vue ``` `app.use(SurgeUI)` registers every component: all their JavaScript ends up in the bundle, used or not. To ship only the components you use, see [Importing only what you use](#importing-only-what-you-use). ### Configuration with options ```ts // main.ts import { createApp } from 'vue' import SurgeUI, { locales } from '@surgeui/vue' const app = createApp(App) app.use(SurgeUI, { prefix: 'My', // MyButton, MyInput… locale: locales.en, // Theme tokens (camelCase), applied in both modes theme: { primaryDefault: '#4f46e5', primaryHover: '#4338ca', textPrimary: '#1f2937' } }) ``` ###### options | Option | Description | |--------|-------------| | `prefix` | Component prefix (`Su` by default) | | `theme` | Theme tokens to override, in camelCase (`primaryDefault`, `bgSurface`, `textPrimary`…): set as `--su-custom-*` on ``, for light and dark mode alike. For per-mode values, override the `--su-*` variables in CSS ([Themes](https://surgeui.com/en/theme/index.md)) | | `locale` | Language of default texts: a provided locale (`locales.en`), partial messages, a ref, or `'auto'` to follow `` | | `linkComponent` | Component for `to` links: NuxtLink or your own. Default: RouterLink when registered, otherwise `` | | `components` | Components to register, by name without prefix: `{ Button, Dialog }`. Default: all of them (none with `createSurgeUI`) | ::: tip Older examples The `textPrimaryColor`, `button` and `link` options passed at the root (older examples on this page) are ignored: they belong in `theme`. `theme.button` (`bg`, `color`, `border`, `hoverBg`, `hoverShadow`) styles `variant="custom"` buttons, `theme.link` (`color`, `hoverColor`, `hoverBg`) styles `variant="custom"` links. ::: ### Component language Default component texts (accessible labels, messages, screen reader announcements) are in French. Pass another locale to the plugin (`locales.fr`, `locales.en` or `locales.ar`): ```ts import SurgeUI, { locales } from '@surgeui/vue' app.use(SurgeUI, { locale: locales.en }) ``` With `locale: 'auto'`, the language follows the `lang` attribute of ``, including when it changes without a page reload. A language with no provided translation falls back to English: ```ts app.use(SurgeUI, { locale: 'auto' }) ``` ::: warning Server-side rendering During server-side rendering (Nuxt, Vite SSR), `document` does not exist: `'auto'` gives English on the server, then the page language on the client. Pass the locale explicitly instead, based on the request language. ::: See [useLocale](https://surgeui.com/en/composables/uselocale.md) to customize messages, plug in vue-i18n or switch language at runtime. ### Router links The `to` prop of SuButton, SuLink, SuBreadcrumb (items), SuDropdown (options), SuCommandPalette (commands) and SuTabs (navigation tabs) navigates without reloading the page. The link is rendered by RouterLink when registered (Vue Router, Nuxt), otherwise by a plain ``. The `linkComponent` option sets another component: ```ts import SurgeUI from '@surgeui/vue' import { NuxtLink } from '#components' app.use(SurgeUI, { linkComponent: NuxtLink }) ``` The component receives `to` and the link attributes (classes, `aria-*`, `target`). For your own components, `useLinkComponent()` returns the same component (`linkFor(to)`) and `navigate(to)`. ## Importing only what you use `app.use(SurgeUI)` and `style.css` bring the whole library: about 97 kB of JavaScript and 35 kB of CSS (gzip). To ship only the components you use: ### JavaScript `createSurgeUI()` installs the same plugin (locale, links, toasts, confirmations, theme) without registering every component. Register the ones you need, or import them where they are used: ```ts // main.ts import { createApp } from 'vue' import { createSurgeUI, Button, Dialog } from '@surgeui/vue' createApp(App) .use(createSurgeUI({ locale: 'auto', components: { Button, Dialog } })) .mount('#app') ``` With [unplugin-vue-components](https://github.com/unplugin/unplugin-vue-components), the bundled resolver imports each component where it is used (`` in a template): no list to maintain. ```ts // vite.config.ts import Components from 'unplugin-vue-components/vite' import { SurgeUIResolver } from '@surgeui/vue/resolver' export default defineConfig({ plugins: [vue(), Components({ resolvers: [SurgeUIResolver()] })] }) ``` ```ts // main.ts: the plugin is still useful for the locale, links and toasts app.use(createSurgeUI({ locale: 'auto' })) ``` ### CSS `@surgeui/vue/css/` holds the base (tokens, themes, contrast, utilities) and one stylesheet per component. With the resolver, `importStyle` imports them along with each component, instead of `style.css`: ```ts Components({ resolvers: [SurgeUIResolver({ importStyle: true })] }) // Tailwind 4: the same stylesheets in the surgeui layer Components({ resolvers: [SurgeUIResolver({ importStyle: 'layer' })] }) ``` Without the resolver, import the base, then the stylesheets of the components you use. A stylesheet only holds its own component: `css/manifest.json` lists, for each one, the stylesheets to load in order (Dialog: `Spinner.css`, `Button.css`, `Dialog.css`). ```css @import "@surgeui/vue/css/base.css"; @import "@surgeui/vue/css/Spinner.css"; @import "@surgeui/vue/css/Button.css"; @import "@surgeui/vue/css/Dialog.css"; ``` | Import | CSS (gzip) | |--------|-----------:| | `style.css` (everything) | 35 kB | | `css/base.css` | 5.6 kB | | Base + Button (and Spinner) | 7.3 kB | | Base + Dialog (and Button, Spinner) | 8.2 kB | ::: warning One source only Do not import `style.css` on top of the per-component stylesheets: the rules would be duplicated. ::: ## With Tailwind CSS `style.css` is not in any CSS layer (`@layer`). An unlayered rule beats every layered rule, so Tailwind 4 utilities set on a component (`class="w-full"`) would be ignored whenever SurgeUI sets the same property. Import `style.layer.css` instead: the same stylesheet inside the `surgeui` layer. Place that layer between Tailwind's base and its utilities: ```css /* main.css — Tailwind 4 */ @layer theme, base, surgeui, components, utilities; @import "tailwindcss"; @import "@surgeui/vue/style.layer.css"; ``` Utilities then win over component styles, and component styles win over Tailwind's base (preflight). Tailwind 3 and UnoCSS do not use CSS layers: keep `style.css`, imported after the base and before the utilities. With equal specificity, the last rule wins: ```css /* main.css — Tailwind 3 with postcss-import */ @import "tailwindcss/base"; @import "@surgeui/vue/style.css"; @import "tailwindcss/components"; @import "tailwindcss/utilities"; ``` ::: tip `SuDialog`, `SuCommandPalette` and `SuConfirmDialog` render their `` in ``: utilities set on their containers (`space-y-*`, `divide-*`…) do not reach them. See the [`teleport`](https://surgeui.com/en/components/dialog.md#rendering-in-body) prop. ::: ### Tailwind preset `@surgeui/vue/tailwind.css` (Tailwind 4) turns SurgeUI colors, radii and shadows into utilities, so your pages use the same color source as the components: ```css @layer theme, base, surgeui, components, utilities; @import "tailwindcss"; @import "@surgeui/vue/style.layer.css"; @import "@surgeui/vue/tailwind.css"; ``` ```vue

Projects

12 active projects

Up to date
``` | Group | Utilities (`bg-`, `text-`, `border-`…) | |-------|----------------------------------------| | Actions | `su-primary`, `su-primary-hover`, `su-primary-active`, `su-on-primary`, `su-secondary`, `su-secondary-hover`, `su-on-secondary`, `su-primary-50` to `su-primary-950` | | Backgrounds | `su-canvas`, `su-surface`, `su-surface-elevated`, `su-overlay`, `su-hover`, `su-active`, `su-selected`, `su-accent`, `su-muted-surface` | | Text | `su-text`, `su-muted`, `su-subtle`, `su-text-disabled`, `su-text-inverse`, `su-link`, `su-link-hover` | | Borders | `su-border`, `su-border-subtle`, `su-border-strong`, `su-border-focus`, `su-ring` | | States | `su-success`, `su-warning`, `su-error`, `su-info`, with `-bg` (tinted background) and `-fg` (text on that background) | | Radii, shadows | `rounded-su-control`, `rounded-su-container`, `shadow-su-control`, `shadow-su-popover` | Values stay the theme variables: the chosen theme, dark mode and high contrast also apply to these utilities. ## Dark mode With [useTheme](https://surgeui.com/en/composables/usetheme.md), the theme and mode are set on `` (`data-theme`, `data-theme-mode`). Without it, Tailwind's `.dark` class is enough: SurgeUI switches to dark when `` has `.dark` and no `data-theme-mode`. See [theme fallbacks](https://surgeui.com/en/theme/index.md#without-attributes-or-with-the-dark-class). ## TypeScript The design system includes complete TypeScript types for imports. ```vue ``` ### Global components With `app.use(SurgeUI)`, ``, ``… are registered globally. For Volar and vue-tsc to check their props, events and slots in templates, add the global types to the `types` list of your tsconfig: ```json // tsconfig.json { "compilerOptions": { "types": ["@surgeui/vue/global"] } } ``` These types cover the default `Su` prefix. With another prefix, declare them yourself: ```ts // surgeui.d.ts import type { SurgeGlobalComponents } from '@surgeui/vue' declare module 'vue' { interface GlobalComponents extends SurgeGlobalComponents<'My'> {} } export {} ``` --- # Migrating to 4.0 Version 4.0.0 publishes the library under a new name, **`@surgeui/vue`**, and removes the APIs deprecated during 3.x. ## New name: @surgeui/vue Only the package name changes in imports: the subpaths, the stylesheets and the types stay the same. | Before | After | |--------|-------| | `@surgeui/ds-vue` | `@surgeui/vue` | | `@surgeui/ds-vue/style.css` | `@surgeui/vue/style.css` | | `@surgeui/ds-vue/style.layer.css` | `@surgeui/vue/style.layer.css` | | `@surgeui/ds-vue/tailwind.css` | `@surgeui/vue/tailwind.css` | | `@surgeui/ds-vue/global` | `@surgeui/vue/global` | | `@surgeui/ds-vue/types` | `@surgeui/vue/types` | `@surgeui/ds-vue@4.0.0` is the last version published under the former name: a relay that depends on `@surgeui/vue@4.0.0` and re-exports it. Imports from `@surgeui/ds-vue` still work in 4.0.0, but later versions are only published as `@surgeui/vue`. ### 1. Replace the dependency ::: code-group ```bash [npm] npm uninstall @surgeui/ds-vue npm install @surgeui/vue ``` ```bash [yarn] yarn remove @surgeui/ds-vue yarn add @surgeui/vue ``` ```bash [pnpm] pnpm remove @surgeui/ds-vue pnpm add @surgeui/vue ``` ::: ### 2. Update the imports Replace `@surgeui/ds-vue` with `@surgeui/vue` in your code, stylesheets and configuration (`tsconfig.json`, `nuxt.config.ts`, `vite.config.ts`…): ```ts // Before import SurgeUI, { locales } from '@surgeui/ds-vue' import '@surgeui/ds-vue/style.css' // After import SurgeUI, { locales } from '@surgeui/vue' import '@surgeui/vue/style.css' ``` In a Git repository, one command does it (GNU sed: Linux, Git Bash; on macOS, write `sed -i ''`): ```bash git grep -l "@surgeui/ds-vue" -- ":(exclude)*lock*" | xargs sed -i "s#@surgeui/ds-vue#@surgeui/vue#g" ``` ### 3. Check `git grep "@surgeui/ds-vue"` should find nothing. Then run your application's build, type check and tests again. ### Both names at once During a gradual migration (monorepo, third-party dependency still on the former name), both packages can be installed together in 4.0.0. The relay re-exports the same module: the plugin, the injection keys and the composables are shared. Two precautions: - keep `@surgeui/vue` at **4.0.0** while `@surgeui/ds-vue` is installed: the relay depends on that exact version, another version would install a second copy; - import the stylesheet **once**, from either name: the relay ships a copy of it, importing both would add it twice to the bundle. ### The former name on npm - **3.3.0**: last full release published as `@surgeui/ds-vue`. - **4.0.0**: first `@surgeui/vue` release; `@surgeui/ds-vue@4.0.0` is a relay, then the former name is marked as deprecated on npm. - **4.0.1 and later**: published as `@surgeui/vue` only. ## Package files The UMD bundle is now named `dist/index.umd.cjs` (previously `dist/index.umd.js`). Imports and `require('@surgeui/vue')` go through the package `exports` field: nothing to change, except a hard-coded path to the old file (` ``` ### Composable Options ```typescript useTheme({ // Override available themes availableThemes: ['default', 'ocean'], // Default theme defaultTheme: 'default', // Default mode (NEW) defaultThemeMode: 'light', // Custom localStorage key storageKey: 'my-app-theme', // Disable persistence persist: false }); ``` ### Changing the Theme #### Change Visual Identity ```vue ``` #### Change Brightness Mode ```vue ``` #### Toggle Light / Dark ```vue ``` #### Cycle Through Themes ```vue ``` ## Components ### ThemeSelector Complete component for theme selection with visual interface. ```vue ``` **Features**: - Visual preview of each theme - Mode selection (light / dark / system) - Contrast selection (normal / high) - Animation configuration (normal / reduced) - Detected system preferences display - Reset button ### ThemeToggle Compact button to quickly toggle between modes. ```vue ``` **Features**: - Dynamic icon based on active mode - Mode label (hidden on mobile) - Transition animation - Cycle through all available themes ## Accessibility ### High Contrast The system automatically supports high contrast mode, essential for accessibility. #### Automatic Detection ```vue ``` #### Manual Configuration ```vue ``` #### High Contrast Mode Behavior - Pure colors (pure black / pure white) - Reinforced borders - Removal of transparency effects - Minimum contrast ratio of 7:1 (WCAG AAA) ### Reduced Motion Respects `prefers-reduced-motion` for users sensitive to movement. ```vue ``` **Effect**: - All transitions become instantaneous (`0ms`) - Animations are disabled - Scale transforms are neutralized ## Usage in Components ### Access Color Tokens Use automatically generated CSS variables: ```vue ``` ### Utility Mixins ```vue ``` ## Advanced Customization with Custom CSS Variables The theme system supports dynamic color customization via **custom CSS variables**. This allows you to override theme colors without creating a complete new theme. ### How it Works The custom variables system uses a **CSS fallback mechanism**: ```scss // Automatically generated for each token --su-primary-default: var(--su-custom-primary-default, #3b82f6); ``` **Flow**: 1. User defines `--su-custom-primary-default: #dc2626` 2. CSS resolves `var(--su-custom-primary-default, ...)` → `#dc2626` 3. All components using `--su-primary-default` receive the new value 4. If no custom is defined, fallback to theme value ### `useCustomTheme` Composable The `useCustomTheme` composable manages custom CSS variables reactively. ```vue ``` ### Usage Examples #### 1. Apply Complete Custom Theme ```vue ``` #### 2. Modify Individual Color ```vue ``` #### 3. Combine Theme, Mode, and Brand Colors ```vue ``` ### Available Custom Variables You can customize any theme token using the `--su-custom-` format: **Text**: - `--su-custom-text-primary` - `--su-custom-text-secondary` - `--su-custom-text-tertiary` - `--su-custom-text-disabled` - `--su-custom-text-inverse` **Backgrounds**: - `--su-custom-bg-canvas` - `--su-custom-bg-surface` - `--su-custom-bg-surface-elevated` - `--su-custom-bg-hover` - `--su-custom-bg-active` - `--su-custom-bg-selected` - `--su-custom-bg-disabled` - `--su-custom-bg-inverse` - `--su-custom-bg-inverse-subtle` **Borders**: - `--su-custom-border-default` - `--su-custom-border-subtle` - `--su-custom-border-strong` - `--su-custom-border-focus` - `--su-custom-border-disabled` - `--su-custom-border-inverse` **Actions**: - `--su-custom-primary-default` - `--su-custom-primary-hover` - `--su-custom-primary-active` - `--su-custom-primary-disabled` - `--su-custom-primary-text` - `--su-custom-secondary-default` - `--su-custom-secondary-hover` - `--su-custom-secondary-active` - `--su-custom-secondary-disabled` - `--su-custom-secondary-text` **States**: - `--su-custom-state-success` - `--su-custom-state-success-bg` - `--su-custom-state-warning` - `--su-custom-state-warning-bg` - `--su-custom-state-error` - `--su-custom-state-error-bg` - `--su-custom-state-info` - `--su-custom-state-info-bg` ### Benefits of This Approach ✅ **Dynamic** - Instant changes without page reload ✅ **Flexible** - Customize partially or completely ✅ **Performant** - No SCSS recompilation, CSS only ✅ **Compatible** - Works with all themes and all modes ✅ **Persistent** - Compatible with localStorage for user preferences ## Create a Custom Theme ### 1. New File Structure (separate light + dark tokens) ``` styles/themes/ ├── _registry.scss ├── _schema.scss ← Required token validation ├── default/ │ ├── _color.scss │ ├── index.scss │ └── tokens/ │ ├── light.scss │ └── dark.scss ├── ocean/ (same structure) ├── forest/ (same structure) ├── sunset/ (same structure) └── custom/ ← Your theme ├── index.scss └── tokens/ ├── light.scss └── dark.scss ``` ### 2. Define Light Tokens ```scss // themes/custom/tokens/light.scss $theme-custom-light: ( 'text-primary': #1a202c, 'text-secondary': #2d3748, 'text-tertiary': #4a5568, 'bg-canvas': #f7fafc, 'bg-surface': #ffffff, 'border-default': #cbd5e0, 'border-focus': #4299e1, 'primary-default': #4299e1, 'primary-hover': #3182ce, 'primary-text': #ffffff, // ... other tokens ); ``` ### 3. Define Dark Tokens ```scss // themes/custom/tokens/dark.scss $theme-custom-dark: ( 'text-primary': #f7fafc, 'text-secondary': #e2e8f0, 'text-tertiary': #a0aec0, 'bg-canvas': #1a202c, 'bg-surface': #2d3748, 'border-default': #4a5568, 'border-focus': #63b3ed, 'primary-default': #63b3ed, 'primary-hover': #4299e1, 'primary-text': #1a202c, // ... other tokens ); ``` ### 4. Register Theme with Both Modes ```scss // themes/custom/index.scss @use '../_registry' as registry; @use './tokens/light' as *; @use './tokens/dark' as *; [data-theme='custom'][data-theme-mode='light'] { @include registry.generate-theme-vars($theme-custom-light); } [data-theme='custom'][data-theme-mode='dark'] { @include registry.generate-theme-vars($theme-custom-dark); } ``` ### 5. Add TypeScript Metadata ```typescript // composables/useTheme.ts const ALL_THEMES: ThemeMetadata[] = [ // ... other themes { id: 'custom', name: 'Custom', description: 'My custom theme', category: 'color', preview: { primary: '#4299e1', background: '#f7fafc', surface: '#ffffff' }, available: themeConfig.themes.includes('custom') } ]; ``` ## API Reference ### `useTheme(options?)` #### Options ```typescript interface UseThemeOptions { availableThemes?: ThemeName[]; defaultTheme?: ThemeName; defaultThemeMode?: ThemeMode; // NEW storageKey?: string; persist?: boolean; } ``` #### Return ```typescript { // Reactive state themeName: Ref; themeMode: Ref; // NEW contrastMode: Ref; motionMode: Ref; // Computed effectiveTheme: ComputedRef; effectiveThemeMode: ComputedRef<'light' | 'dark'>; // NEW effectiveContrast: ComputedRef<'normal' | 'high'>; effectiveMotion: ComputedRef<'normal' | 'reduce'>; systemContrast: ComputedRef<'normal' | 'high'>; systemMotion: ComputedRef<'normal' | 'reduce'>; isDarkMode: ComputedRef; // Data availableThemes: ComputedRef; // Actions setTheme: (theme: ThemeName) => void; setThemeMode: (mode: ThemeMode) => void; // NEW toggleMode: () => void; // NEW cycleTheme: () => void; setContrast: (contrast: ContrastMode) => void; setMotion: (motion: MotionMode) => void; clearConfig: () => void; } ``` ## Practical Examples ### Dashboard with Theme Selector ```vue ``` ### Persistent User Preference ```vue ``` ### Force Theme for a Section ```vue ``` ### Inverted Section with Inversion Tokens ```vue ``` ## Performance ### Built-in Optimizations - **CSS Variables**: Instant theme change without reload - **Dual attributes**: CSS selectors targeted by `[data-theme][data-theme-mode]` - **Lazy loading**: Only configured themes are included in bundle - **Tree-shaking**: Unused themes = 0 bytes - **localStorage**: Persistence without network overhead ### Size Comparison | Configuration | Total Bundle Size | Themes Included | |--------------|-------------------|-----------------| | Minimal | ~200 KB | Default only | | Standard | ~300 KB | Default + 1 color theme | | Complete | ~425 KB | All themes | ### Recommendations ::: tip Corporate Applications Use only `default` to minimize bundle size. ::: ::: tip Creative Applications Include all themes for a rich personalized experience. ::: ::: tip Marketing Sites Choose 1-2 color themes aligned with your brand identity. ::: ## Troubleshooting ### Theme Not Applied Check that: 1. Theme is included in `theme.config.ts` 2. Theme is loaded in `main.scss` 3. `useTheme()` is called in `App.vue` or a parent 4. Both `data-theme` **and** `data-theme-mode` attributes are present on `` ### Colors Not Changing Make sure to use CSS variables: ```scss // ❌ Wrong color: #111827; // ✅ Correct color: var(--su-text-primary); ``` ### Theme Unavailable in Production Check that the theme is in the `themes` list of `theme.config.ts` and imported in the loader. ### Preferences Not Saved Check that `persist: true` is configured and localStorage is accessible (not in private navigation). ### Console Warning "Theme 'dark' is not available" Since 4.0, `setTheme()` only picks the color identity: `setTheme('dark')` and `setTheme('light')` were removed (see [Migrating to 4.0](https://surgeui.com/en/guide/migration.md#removed-apis)). Replace with: ```typescript // Before (removed in 4.0) setTheme('dark') // After setThemeMode('dark') ``` ## Resources - [Color Guide](./colors.md) - [Semantic Tokens](./tokens.md) - [Accessibility](./accessibility.md) - [Complete Examples](./examples.md) --- # Color Guide The color system is organized in three hierarchical levels: raw palettes, semantic tokens, and CSS variables. This architecture ensures cohesion, accessibility, and easy maintenance. ## Color Architecture ### Hierarchical Levels ``` Raw Palettes (foundations) ↓ Semantic Tokens (themes) ↓ CSS Variables (runtime) ``` 1. **Raw Palettes**: Pure colors defined once 2. **Semantic Tokens**: Attribution of contextual meaning to colors 3. **CSS Variables**: Dynamic application based on active theme ## Base Palettes ### Primary (Blue) The main brand color, used for primary actions and key elements. | Shade | Hex | Usage | |-------|-----|-------| | 50 | `#eff6ff` | Very light backgrounds | | 100 | `#dbeafe` | Light backgrounds | | 200 | `#bfdbfe` | Subtle borders | | 300 | `#93c5fd` | Light hover states | | 400 | `#60a5fa` | Dark mode links | | 500 | `#3b82f6` | **Primary color** | | 600 | `#2563eb` | Primary actions | | 700 | `#1d4ed8` | Primary hover | | 800 | `#1e40af` | Active states | | 900 | `#1e3a8a` | Visited links | | 950 | `#172554` | Text on light blue background | **Minimum Contrast**: 600 on white (4.5:1 - AA), 700 recommended (7:1 - AAA) ### Gray (Neutral) Base for texts, backgrounds, and borders. WCAG contrast verified. | Shade | Hex | Contrast on white | Usage | |-------|-----|-------------------|-------| | 50 | `#f9fafb` | - | Light canvas | | 100 | `#f3f4f6` | - | Disabled backgrounds | | 200 | `#e5e7eb` | - | Subtle borders | | 300 | `#d1d5db` | - | Default borders | | 400 | `#9ca3af` | 4.6:1 | Disabled text (AA) | | 500 | `#6b7280` | 4.7:1 | **Tertiary text** (AA) | | 600 | `#4b5563` | 7.3:1 | Strong borders (AAA) | | 700 | `#374151` | 9.3:1 | **Secondary text** (AAA) | | 800 | `#1f2937` | 13.1:1 | Dark surface | | 900 | `#111827` | 16.8:1 | **Primary text** (AAA) | | 950 | `#030712` | 19.4:1 | Dark canvas | ::: tip WCAG Contrast - **AA**: 4.5:1 minimum (normal text) - **AAA**: 7:1 recommended (better readability) ::: ### Success (Green) Positive feedback, validation, operation success. | Shade | Hex | Usage | |-------|-----|-------| | 50 | `#ecfdf5` | Light success background | | 100 | `#d1fae5` | Success background | | 500 | `#10b981` | **Dark success icons** | | 600 | `#059669` | Light success text | | 700 | `#047857` | Success hover | **Example**: Success notifications, validation indicators, active badges. ### Warning (Amber) Warnings, actions requiring attention. | Shade | Hex | Usage | |-------|-----|-------| | 50 | `#fffbeb` | Light warning background | | 100 | `#fef3c7` | Warning background | | 500 | `#f59e0b` | **Dark warning icons** | | 600 | `#d97706` | Light warning text | | 700 | `#b45309` | Warning hover | **Example**: Non-blocking alerts, attention-required sections, update badges. ### Error (Red) Errors, destructive actions, critical states. | Shade | Hex | Usage | |-------|-----|-------| | 50 | `#fef2f2` | Light error background | | 100 | `#fee2e2` | Error background | | 500 | `#ef4444` | **Dark error icons** | | 600 | `#dc2626` | Light error text | | 700 | `#b91c1c` | Error hover | **Example**: Error messages, delete buttons, failure indicators. ### Info (Cyan) Neutral information, contextual help. | Shade | Hex | Usage | |-------|-----|-------| | 50 | `#ecfeff` | Light info background | | 100 | `#cffafe` | Info background | | 500 | `#06b6d4` | **Dark info icons** | | 600 | `#0891b2` | Light info text | | 700 | `#0e7490` | Info hover | **Example**: Tooltips, informational messages, documentation badges. ## Themed Palettes ### Ocean Professional maritime ambiance with cyan dominance and coral accents. **Key Colors**: - Primary: `#f97316` (Coral) - Contrast on ocean background - Background: `#e0f2fe` (Sky Blue) - Accent: `#0891b2` (Cyan) **Use Cases**: Travel applications, analytics dashboards, financial interfaces. ### Forest Natural inspiration with greens and autumn orange. **Key Colors**: - Primary: `#f97316` (Autumn Orange) - Background: `#f7fee7` (Pale Green) - Accent: `#16a34a` (Forest Green) **Use Cases**: Ecological applications, health/wellness, education. ### Sunset Warm palette with pink, violet, and orange. **Key Colors**: - Primary: `#db2777` (Pink) - Background: `#fff7ed` (Peach) - Accent: `#a855f7` (Violet) **Use Cases**: Creative applications, social networks, entertainment. ## Using Colors ### In Components ```vue ``` ### Semantic Colors Always use semantic tokens rather than raw colors: ```scss // ❌ Wrong .button { background: #3b82f6; } // ✅ Correct .button { background-color: var(--su-primary-default); &:hover { background-color: var(--su-primary-hover); } } ``` ### Interactive States State colors are automatically managed: ```vue ``` ## Color Accessibility ### Text Contrast The system guarantees minimum contrast according to WCAG 2.1: | Level | Ratio | Usage | |-------|-------|-------| | AA (minimum) | 4.5:1 | Normal text (16px+) | | AA Large | 3:1 | Large text (18px+ or 14px bold) | | AAA (recommended) | 7:1 | Normal text for better readability | | AAA Large | 4.5:1 | Large text | ### Contrast Verification ```scss // Primary text: ALWAYS AAA (7:1+) .text-primary { color: var(--su-text-primary); // gray-900 on white = 16.8:1 ✓ } // Secondary text: AAA recommended .text-secondary { color: var(--su-text-secondary); // gray-700 on white = 9.3:1 ✓ } // Tertiary text: AA minimum .text-tertiary { color: var(--su-text-tertiary); // gray-500 on white = 4.7:1 ✓ } ``` ### High Contrast Mode In high contrast mode, colors are automatically reinforced: ```scss // Normal mode [data-contrast="normal"] { --su-text-primary: #111827; --su-border-default: #d1d5db; } // High contrast mode [data-contrast="high"] { --su-text-primary: #000000; // Pure black --su-border-default: #000000; // Visible borders everywhere } ``` ### Never Use Color Alone Always combine color with other visual indicators: ```vue ``` ## Transparency and Overlays ### Recommended Overlays ```scss // Dark overlay (modals, dropdowns) .overlay-dark { background-color: rgba(0, 0, 0, 0.5); // 50% black } // Light overlay (on dark background) .overlay-light { background-color: rgba(255, 255, 255, 0.1); // 10% white } // Using variables .modal-backdrop { background-color: var(--su-bg-overlay); // Adapts to theme } ``` ### Hover and Focus States ```scss .button { background-color: var(--su-primary-default); // Hover: darken by 10% &:hover { background-color: color-mix( in srgb, var(--su-primary-default) 90%, black ); } // Or use dedicated token &:hover { background-color: var(--su-primary-hover); } } ``` ## Color-mix and Manipulations ### Lighten / Darken ```scss // Lighten by 20% .lighter { background-color: color-mix( in srgb, var(--su-primary-default) 80%, white ); } // Darken by 20% .darker { background-color: color-mix( in srgb, var(--su-primary-default) 80%, black ); } ``` ### Opacity ```scss // Via rgba (if hex color) .semi-transparent { background-color: rgba(59, 130, 246, 0.5); // 50% opacity } // Via color-mix .semi-transparent-dynamic { background-color: color-mix( in srgb, var(--su-primary-default) 50%, transparent ); } ``` ## Best Practices ### ✅ Do's - Use CSS variables for all colors - Respect semantic tokens - Verify contrast (minimum AA, recommended AAA) - Test in high contrast mode - Combine color + shape + text for information ### ❌ Don'ts - Hard-coded colors in components - Raw palette colors directly - Insufficient contrast (< 4.5:1) - Information only by color - Too many different colors (visual confusion) ## Development Tools ### Browser Extension - **Stark**: Real-time contrast verification - **Colorblindly**: Simulate visual deficiencies - **WAVE**: Complete accessibility audit ### Online - [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/) - [Coolors](https://coolors.co/contrast-checker) - [Color Review](https://color.review/) ### DevTools ```javascript // In browser console const styles = getComputedStyle(document.documentElement); const primary = styles.getPropertyValue('--su-primary-default'); console.log('Primary color:', primary); ``` ## Examples of Custom Palettes ### Corporate Palette ```scss // themes/corporate/_tokens.scss $theme-corporate: ( 'primary-default': #003d82, // Corporate blue 'primary-hover': #002a5c, 'primary-text': #ffffff, 'secondary-default': #f5f5f5, 'secondary-text': #003d82, 'text-primary': #1a1a1a, 'text-secondary': #4a4a4a, 'bg-canvas': #fafafa, 'bg-surface': #ffffff, ); ``` ### Gaming Palette ```scss // themes/gaming/_tokens.scss $theme-gaming: ( 'primary-default': #ff0080, // Neon pink 'primary-hover': #cc0066, 'primary-text': #000000, 'secondary-default': #00ff9f, // Neon green 'secondary-text': #000000, 'text-primary': #ffffff, 'text-secondary': #b3b3b3, 'bg-canvas': #0a0a0f, // Almost black 'bg-surface': #16161f, ); ``` ## FAQ ### Can I add my own colors? Yes! Create a custom theme with your colors. See [Create a Custom Theme](./index.md#create-a-custom-theme). ### How to test color accessibility? Use the DevTools and browser extensions mentioned above. Also test in high contrast mode. ### Do colors change automatically with the theme? Yes, if you use CSS variables (`var(--su-*)`). Hard-coded colors won't adapt. ### What's the difference between primary-600 and primary-default? `primary-600` is a raw palette color. `primary-default` is a semantic token that can point to any color depending on the active theme. ## Resources - [Theme System](./index.md) - [Semantic Tokens](./tokens.md) - [Accessibility](./accessibility.md) - [WCAG 2.1 Guidelines](https://www.w3.org/WAI/WCAG21/quickref/) --- # Semantic Tokens Semantic tokens are the heart of the design system. They transform raw colors into meaningful concepts, enabling perfect consistency and simplified maintenance. ## What is a Semantic Token? A semantic token assigns **contextual meaning** to a technical value. ### Example ```scss // ❌ Technical value (raw color) color: #111827; // ✅ Semantic token (clear intention) color: var(--su-text-primary); ``` **Benefits**: - 🎯 **Clear intention**: "primary text" vs "gray 900" - 🔄 **Adaptability**: Changes automatically with both the theme **and** the mode - 🛠️ **Maintenance**: One place to modify - ♿ **Accessibility**: Built-in contrast guarantees ## Token Architecture ``` Foundations (Raw Palettes) ↓ Semantic Tokens (Meaning) ↓ CSS Variables (Applied via data-theme + data-theme-mode) ↓ Components (Usage) ``` ## Token Categories ### 1. Text Tokens for all text content, with WCAG contrast guaranteed. #### `--su-text-primary` Primary text, maximum contrast (16.8:1 in light mode). ```vue ``` **Usage**: Headings, main text, important content. #### `--su-text-secondary` Secondary text, good contrast (9.3:1 in light mode). ```vue ``` **Usage**: Descriptions, subtitles, metadata. #### `--su-text-tertiary` Tertiary text, minimum AA contrast (4.7:1 in light mode). ```vue ``` **Usage**: Labels, timestamps, auxiliary information. #### `--su-text-disabled` Disabled text, visual indication of unavailability. ```vue ``` **Usage**: Disabled fields, unavailable actions. #### `--su-text-inverse` Text on dark background (or inverted according to theme). ```vue ``` **Usage**: Text on primary buttons, colored banners. #### `--su-text-on-inverse` Text on an inverted background (`--su-bg-inverse`). ```vue ``` **Usage**: Text in sections that contrast with the main background (e.g. a dark hero on a light page). ### 2. Links Specific tokens for hyperlinks. #### `--su-link-default` Default link color. ```vue ``` #### `--su-link-hover` Hover color. ```vue ``` #### `--su-link-visited` Visited links (improves navigation). ```vue ``` #### `--su-link-muted` Secondary, less prominent links. ```vue ``` #### `--su-link-default-rgb` Space-separated RGB value of the default link color, for use with transparency. ```vue ``` **Usage**: Semi-transparent backgrounds based on the link color, badges, indicators. ### 3. Backgrounds Tokens for all backgrounds. #### `--su-bg-canvas` Global app background. ```vue ``` **Usage**: Main page background. #### `--su-bg-surface` Surface for cards, modals, panels. ```vue ``` **Usage**: Cards, modals, dropdown menus. #### `--su-bg-surface-elevated` Elevated surface (with shadow). ```vue ``` **Usage**: Modals, tooltips, floating elements. #### `--su-bg-overlay` Semi-transparent overlay for backdrops. ```vue ``` **Usage**: Modal backgrounds, full-screen menus. #### `--su-bg-hover` Background on hover of interactive elements. ```vue ``` **Usage**: List items, secondary buttons. #### `--su-bg-active` Background in active/pressed state. ```vue ``` **Usage**: Clicked state, pressed buttons. #### `--su-bg-selected` Background for selected elements. ```vue ``` **Usage**: Active tabs, selected items. #### `--su-bg-disabled` Disabled background. ```vue ``` **Usage**: Disabled buttons, disabled fields. #### `--su-bg-inverse` Inverted background - contrasts with the main background of the theme. ```vue ``` **Usage**: Promotional sections, hero banners, highlight areas that need to contrast with the context without forcing a full theme change. #### `--su-bg-inverse-subtle` Secondary inverted background, less pronounced than `--su-bg-inverse`. ```vue ``` **Usage**: Callouts, lightly contrasted information areas. #### `--su-surface-inverse` Surface placed on an inverted background (equivalent of `--su-bg-surface` in an inverted context). ```vue ``` ### 4. Borders Tokens for all borders. #### `--su-border-default` Standard border. ```vue ``` **Usage**: Cards, separators, outlines. #### `--su-border-subtle` Very subtle border. ```vue ``` **Usage**: Light separators, grid lines. #### `--su-border-strong` Reinforced border. ```vue ``` **Usage**: Hover states, highlighted elements. #### `--su-border-focus` Focus border (accessibility). ```vue ``` **Usage**: Focus visible, keyboard navigation. #### `--su-border-disabled` Disabled border. ```vue ``` **Usage**: Disabled fields. #### `--su-border-inverse` Border in an inverted background context. ```vue ``` **Usage**: Separators and outlines on inverted backgrounds. ### 5. States Tokens for state messages and feedbacks. #### Success ```vue ``` **Usage**: Validation, successful operation, active badges. #### Warning ```vue ``` **Usage**: Warnings, actions requiring attention. #### Error ```vue ``` **Usage**: Errors, failures, destructive actions. #### Info ```vue ``` **Usage**: Neutral information, contextual help. ### 6. Primary Actions Tokens for primary buttons and main actions. #### `--su-primary-default` Default state of primary button. ```vue ``` #### `--su-primary-hover` Hover state. ```vue ``` #### `--su-primary-active` Active/pressed state. ```vue ``` #### `--su-primary-disabled` Disabled state. ```vue ``` #### `--su-primary-text` Text on primary button. ```vue ``` ### 7. Secondary Actions Tokens for secondary buttons. ```vue ``` All secondary tokens follow the same pattern as primary tokens. ### 8. Shadows Token for shadow color (adapts to theme). ```vue ``` ## Static Tokens These tokens don't change based on theme. ### Typography ```scss .text { font-family: var(--su-font-family-base); font-size: var(--su-font-size-base); line-height: var(--su-line-height-normal); } ``` **Available**: - `--su-font-family-base`: Main font - `--su-font-family-mono`: Monospace font - `--su-font-size-xs` to `--su-font-size-3xl`: Size scale - `--su-line-height-tight|normal|relaxed`: Line heights ### Spacing ```scss .component { padding: var(--su-spacing-4); margin-bottom: var(--su-spacing-6); gap: var(--su-spacing-2); } ``` **Available**: - `--su-spacing-1`: 0.25rem (4px) - `--su-spacing-2`: 0.5rem (8px) - `--su-spacing-3`: 0.75rem (12px) - `--su-spacing-4`: 1rem (16px) - `--su-spacing-6`: 1.5rem (24px) - `--su-spacing-8`: 2rem (32px) - `--su-spacing-12`: 3rem (48px) ### Border Radius ```scss .card { border-radius: var(--su-radius-lg); } .button { border-radius: var(--su-radius-md); } .avatar { border-radius: var(--su-radius-full); } ``` **Available**: - `--su-radius-sm`: 0.25rem (4px) - `--su-radius-md`: 0.375rem (6px) - `--su-radius-lg`: 0.5rem (8px) - `--su-radius-xl`: 0.75rem (12px) - `--su-radius-full`: 9999px (circle) ### Shadows ```scss .card { box-shadow: var(--su-shadow-sm); } .modal { box-shadow: var(--su-shadow-lg); } ``` **Available**: - `--su-shadow-xs`: Very light shadow - `--su-shadow-sm`: Light shadow - `--su-shadow-md`: Medium shadow - `--su-shadow-lg`: Strong shadow ### Animations ```scss .button { transition-duration: var(--su-duration-normal); transition-timing-function: var(--su-ease-in-out); } ``` **Available**: - `--su-duration-fast`: 150ms (or 0ms if reduced-motion) - `--su-duration-normal`: 200ms (or 0ms if reduced-motion) - `--su-duration-slow`: 300ms (or 0ms if reduced-motion) - `--su-ease-in-out`: cubic-bezier(0.4, 0, 0.2, 1) - `--su-animation-scale`: 1 (or 0 if reduced-motion) ### Focus ```scss .input:focus { outline: var(--su-focus-ring-width) solid var(--su-border-focus); outline-offset: var(--su-focus-ring-offset); } ``` **Available**: - `--su-focus-ring-width`: 2px - `--su-focus-ring-offset`: 2px ## Usage Examples ### Complete Card ```vue ``` ### Alert with State ```vue ``` ### Form Field ```vue ``` ## Best Practices ### ✅ Do's 1. **Always use tokens** rather than raw values 2. **Choose the most semantic token** for the context 3. **Respect hierarchy**: primary > secondary > tertiary 4. **Test all themes and both modes** for consistency 5. **Use mixins** for repetitive patterns 6. **Use `--su-bg-inverse` + `--su-text-on-inverse`** for inverted sections (rather than forcing a theme with `data-theme-mode`) ### ❌ Don'ts 1. **Hard-coded colors**: `color: #111827` ❌ 2. **Non-semantic tokens**: using `primary-600` instead of `primary-default` ❌ 3. **Mix levels**: using raw colors with tokens ❌ 4. **Ignore states**: not managing hover, focus, disabled ❌ 5. **Forget accessibility**: insufficient contrast ❌ ## Extending Tokens ### Add Custom Tokens If you need application-specific tokens: ```scss // In your custom theme - tokens/light.scss $theme-custom-light: ( // Standard tokens 'text-primary': #1a202c, 'bg-surface': #ffffff, // Custom tokens 'brand-highlight': #ff6b6b, 'accent-secondary': #4ecdc4, 'sidebar-bg': #f8f9fa, ); ``` Then use them: ```scss .custom-component { background-color: var(--su-brand-highlight); border-left: 3px solid var(--su-accent-secondary); } ``` ## Inspecting Tokens ### Via DevTools ```javascript // Browser console const root = document.documentElement; const styles = getComputedStyle(root); // See all tokens for (let i = 0; i < styles.length; i++) { const prop = styles[i]; if (prop.startsWith('--su-')) { console.log(prop, ':', styles.getPropertyValue(prop)); } } // See a specific token console.log('Primary:', styles.getPropertyValue('--su-primary-default')); ``` ### Via Vue DevTools ```vue ``` ## Complete Reference Table ### Color Tokens | Token | Light Mode | Dark Mode | Usage | |-------|------------|-----------|-------| | `--su-text-primary` | #111827 (16.8:1) | #f9fafb (17.1:1) | Primary text | | `--su-text-secondary` | #374151 (9.3:1) | #e5e7eb (12.6:1) | Secondary text | | `--su-text-tertiary` | #6b7280 (4.7:1) | #9ca3af (4.5:1) | Tertiary text | | `--su-text-disabled` | #9ca3af | #6b7280 | Disabled text | | `--su-text-inverse` | #f9fafb | #111827 | Inverted text | | `--su-text-on-inverse` | #f9fafb | #111827 | Text on inverted background | | `--su-link-default` | #2563eb | #60a5fa | Default link | | `--su-link-hover` | #1d4ed8 | #93c5fd | Link hover | | `--su-link-visited` | #1e40af | #a855f7 | Visited link | | `--su-link-muted` | #6b7280 | #6b7280 | Muted link | | `--su-link-default-rgb` | 37 99 235 | 96 165 250 | Link RGB for transparency | | `--su-bg-canvas` | #f9fafb | #030712 | Global background | | `--su-bg-surface` | #ffffff | #111827 | Surface / card | | `--su-bg-surface-elevated` | #ffffff | #1f2937 | Elevated surface | | `--su-bg-overlay` | rgba(0,0,0,0.5) | rgba(0,0,0,0.7) | Modal overlay | | `--su-bg-hover` | #f3f4f6 | #1f2937 | Hover background | | `--su-bg-active` | #e5e7eb | #374151 | Active background | | `--su-bg-selected` | #eff6ff | rgba(59,130,246,0.2) | Selected background | | `--su-bg-disabled` | #f3f4f6 | #1f2937 | Disabled background | | `--su-bg-inverse` | #111827 | #f9fafb | Inverted background | | `--su-bg-inverse-subtle` | #1f2937 | #f3f4f6 | Subtle inverted background | | `--su-surface-inverse` | #374151 | #e5e7eb | Surface on inverted background | | `--su-border-default` | #d1d5db | #4b5563 | Standard border | | `--su-border-subtle` | #e5e7eb | #374151 | Subtle border | | `--su-border-strong` | #9ca3af | #6b7280 | Strong border | | `--su-border-focus` | #3b82f6 | #60a5fa | Focus border | | `--su-border-disabled` | #e5e7eb | #374151 | Disabled border | | `--su-border-inverse` | #4b5563 | #d1d5db | Border on inverted background | | `--su-state-success` | #059669 | #4ade80 | Success state | | `--su-state-success-bg` | #ecfdf5 | rgba(74,222,128,0.15) | Success background | | `--su-state-warning` | #d97706 | #facc15 | Warning state | | `--su-state-warning-bg` | #fffbeb | rgba(250,204,21,0.15) | Warning background | | `--su-state-error` | #dc2626 | #f87171 | Error state | | `--su-state-error-bg` | #fef2f2 | rgba(248,113,113,0.15) | Error background | | `--su-state-info` | #0891b2 | #38bdf8 | Info state | | `--su-state-info-bg` | #ecfeff | rgba(56,189,248,0.15) | Info background | | `--su-primary-default` | #2563eb | #3b82f6 | Primary action | | `--su-primary-hover` | #1d4ed8 | #60a5fa | Primary hover | | `--su-primary-active` | #1e40af | #1e40af | Primary active | | `--su-primary-disabled` | #93c5fd | #374151 | Primary disabled | | `--su-primary-text` | #ffffff | #ffffff | Text on primary | | `--su-secondary-default` | #f3f4f6 | #1f2937 | Secondary action | | `--su-secondary-hover` | #e5e7eb | #374151 | Secondary hover | | `--su-secondary-active` | #d1d5db | #4b5563 | Secondary active | | `--su-secondary-disabled` | #f9fafb | #111827 | Secondary disabled | | `--su-secondary-text` | #111827 | #f9fafb | Text on secondary | | `--su-shadow-color` | rgba(0,0,0,0.1) | rgba(0,0,0,0.5) | Shadow color | ### Static Tokens | Token | Value | Description | |-------|-------|-------------| | **Typography** | | | | `--su-font-family-base` | System fonts | Main font | | `--su-font-family-mono` | Monospace | Code font | | `--su-font-size-xs` | 0.75rem (12px) | XS size | | `--su-font-size-sm` | 0.875rem (14px) | Small size | | `--su-font-size-base` | 1rem (16px) | Base size | | `--su-font-size-lg` | 1.125rem (18px) | Large size | | `--su-font-size-xl` | 1.25rem (20px) | XL size | | `--su-font-size-2xl` | 1.5rem (24px) | 2XL size | | `--su-font-size-3xl` | 1.875rem (30px) | 3XL size | | `--su-line-height-tight` | 1.25 | Tight line height | | `--su-line-height-normal` | 1.5 | Normal line height | | `--su-line-height-relaxed` | 1.75 | Relaxed line height | | **Spacing** | | | | `--su-spacing-1` | 0.25rem (4px) | XS spacing | | `--su-spacing-2` | 0.5rem (8px) | S spacing | | `--su-spacing-3` | 0.75rem (12px) | M spacing | | `--su-spacing-4` | 1rem (16px) | Base spacing | | `--su-spacing-6` | 1.5rem (24px) | L spacing | | `--su-spacing-8` | 2rem (32px) | XL spacing | | `--su-spacing-12` | 3rem (48px) | 2XL spacing | | **Border Radius** | | | | `--su-radius-sm` | 0.25rem (4px) | Small radius | | `--su-radius-md` | 0.375rem (6px) | Medium radius | | `--su-radius-lg` | 0.5rem (8px) | Large radius | | `--su-radius-xl` | 0.75rem (12px) | XL radius | | `--su-radius-full` | 9999px | Full radius (circle) | | **Shadows** | | | | `--su-shadow-xs` | 0 1px 2px rgba(...) | Very light shadow | | `--su-shadow-sm` | 0 1px 3px rgba(...) | Light shadow | | `--su-shadow-md` | 0 4px 6px rgba(...) | Medium shadow | | `--su-shadow-lg` | 0 10px 15px rgba(...) | Strong shadow | | **Animations** | | | | `--su-duration-fast` | 150ms (or 0ms) | Fast duration | | `--su-duration-normal` | 200ms (or 0ms) | Normal duration | | `--su-duration-slow` | 300ms (or 0ms) | Slow duration | | `--su-ease-in-out` | cubic-bezier(...) | Default easing | | `--su-animation-scale` | 1 (or 0) | Animation multiplier | | **Focus** | | | | `--su-focus-ring-width` | 2px | Focus ring width | | `--su-focus-ring-offset` | 2px | Focus ring offset | ## Composition Patterns ### Pattern 1: Complete Interactive Component ```vue ``` ### Pattern 2: Inverted Section ```vue ``` ### Pattern 3: Notification System ```vue ``` ## Migrating from Other Systems ### From Tailwind CSS ```scss // Tailwind → Design System // Colors .text-gray-900 → color: var(--su-text-primary) .text-gray-600 → color: var(--su-text-secondary) .text-gray-400 → color: var(--su-text-tertiary) .bg-white → background-color: var(--su-bg-surface) .bg-gray-50 → background-color: var(--su-bg-canvas) .border-gray-300 → border-color: var(--su-border-default) // Spacing .p-4 → padding: var(--su-spacing-4) .m-6 → margin: var(--su-spacing-6) .gap-2 → gap: var(--su-spacing-2) // Radius .rounded → border-radius: var(--su-radius-sm) .rounded-md → border-radius: var(--su-radius-md) .rounded-lg → border-radius: var(--su-radius-lg) .rounded-full → border-radius: var(--su-radius-full) // Typography .text-sm → font-size: var(--su-font-size-sm) .text-base → font-size: var(--su-font-size-base) .text-xl → font-size: var(--su-font-size-xl) ``` ### From Bootstrap ```scss // Bootstrap → Design System // Colors .text-primary → color: var(--su-primary-default) .text-secondary → color: var(--su-text-secondary) .text-muted → color: var(--su-text-tertiary) .bg-light → background-color: var(--su-bg-canvas) .bg-white → background-color: var(--su-bg-surface) // Components .btn-primary → background-color: var(--su-primary-default) .btn-secondary → background-color: var(--su-secondary-default) .alert-success → use --su-state-success tokens .alert-danger → use --su-state-error tokens // Spacing .p-3 → padding: var(--su-spacing-3) .mb-4 → margin-bottom: var(--su-spacing-4) ``` ## Resources - [Color Guide](./colors.md) - [Theme System](./index.md) - [Accessibility](./accessibility.md) - [Complete Examples](./examples.md) - [CSS Custom Properties (MDN)](https://developer.mozilla.org/en-US/docs/Web/CSS/--) --- # Accessibility Accessibility is built into the core of the Design System. All components and tokens respect WCAG 2.1 level AA guidelines, with AAA as a goal when possible. ## Fundamental Principles ### The 4 POUR Principles (WCAG) 1. **Perceivable**: Information must be presented in a perceivable manner 2. **Operable**: Components must be operable by everyone 3. **Understandable**: Information and interface must be understandable 4. **Robust**: Content must be interpretable by various technologies ## Color Contrast ### Conformance Levels | Level | Ratio | Context | Our Guarantee | |-------|-------|---------|----------------| | **AA** | 4.5:1 | Normal text | ✅ Minimum met | | **AA Large** | 3:1 | Large text (18px+) | ✅ Exceeded | | **AAA** | 7:1 | Normal text | ✅ Recommended by default | | **AAA Large** | 4.5:1 | Large text | ✅ Exceeded | ### Contrast Guaranteed by Token ```scss // Light mode --su-text-primary: #111827; // 16.8:1 on white (AAA ✅) --su-text-secondary: #374151; // 9.3:1 on white (AAA ✅) --su-text-tertiary: #6b7280; // 4.7:1 on white (AA ✅) // Dark mode --su-text-primary: #f9fafb; // 17.1:1 on black (AAA ✅) --su-text-secondary: #e5e7eb; // 12.6:1 on black (AAA ✅) --su-text-tertiary: #9ca3af; // 4.5:1 on black (AA ✅) ``` ### Contrast Verification ```vue ``` ### High Contrast Mode The system automatically detects `prefers-contrast: more` and applies adjustments. ```vue ``` **Changes in High Contrast Mode**: - Pure colors (black/white) - Reinforced borders (2px minimum) - Removal of transparencies - Minimum contrast ratio 7:1 #### Enable Manually ```vue ``` ### Verification Tools **Browser Extensions**: - [Stark](https://www.getstark.co/) - Real-time verification - [axe DevTools](https://www.deque.com/axe/devtools/) - Complete audit - [WAVE](https://wave.webaim.org/extension/) - Visual evaluation **Online**: - [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/) - [Contrast Ratio](https://contrast-ratio.com/) ## Keyboard Navigation ### Tab Order Respect logical DOM order for keyboard navigation. ```vue ``` ### Focus Visible The system provides an accessible focus ring automatically. ```vue ``` **Never Remove Focus**: ```scss // ❌ FORBIDDEN button:focus { outline: none; // Makes interface inaccessible } // ✅ If you must customize button:focus-visible { outline: 2px solid var(--su-border-focus); outline-offset: 2px; } ``` ### Skip Links Add skip links for quick navigation. ```vue ``` ### Keyboard Shortcuts Document custom keyboard shortcuts. ```vue ``` ## Screen Readers ### ARIA Landmarks Use semantic HTML elements and ARIA roles. ```vue ``` ### Labels and Descriptions All interactive elements must have an accessible label. ```vue ``` ### Dynamic States Indicate state changes to screen readers. ```vue ``` ### Live Regions For important dynamic updates. ```vue ``` ## Animations and Motion ### Reduced Motion The system automatically respects `prefers-reduced-motion: reduce`. ```vue ``` **Behavior**: - All transition durations → `0ms` - Animations disabled - `--su-animation-scale` → `0` ### Usage in Components ```vue ``` ### Pure CSS Animations ```scss @keyframes slide-in { from { transform: translateX(-100%); } to { transform: translateX(0); } } .slide-element { animation: slide-in var(--su-duration-normal) var(--su-ease-in-out); } // Automatically disable in reduced-motion mode @media (prefers-reduced-motion: reduce) { .slide-element { animation: none; } } ``` ### Essential Animations Some animations communicate important information (loading, progress). Keep them but simplify. ```vue ``` ## Touch Targets ### Minimum Size (WCAG 2.5.5) Interactive elements must have **minimum 44x44px**. ```vue ``` ### Spacing Between Targets Minimum **8px** between adjacent touch elements. ```vue ``` ## Accessible Forms ### Complete Structure ```vue ``` ### Validation accessible ```vue ``` ## Modales et dialogues ### Modal accessible ```vue ``` ### Focus trap Empêchez le focus de sortir de la modale. ```typescript // composables/useFocusTrap.ts export function useFocusTrap(containerRef: Ref) { const focusableSelector = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'; const handleTab = (e: KeyboardEvent) => { if (e.key !== 'Tab' || !containerRef.value) return; const focusables = Array.from( containerRef.value.querySelectorAll(focusableSelector) ) as HTMLElement[]; const first = focusables[0]; const last = focusables[focusables.length - 1]; if (e.shiftKey) { if (document.activeElement === first) { e.preventDefault(); last.focus(); } } else { if (document.activeElement === last) { e.preventDefault(); first.focus(); } } }; onMounted(() => { document.addEventListener('keydown', handleTab); }); onUnmounted(() => { document.removeEventListener('keydown', handleTab); }); } ``` ## Tests d'accessibilité ### Tests automatisés ```bash # Installer axe-core npm install -D @axe-core/vue vitest-axe ``` ```typescript // Button.spec.ts import { describe, it, expect } from 'vitest'; import { mount } from '@vue/test-utils'; import { axe } from 'vitest-axe'; import Button from './Button.vue'; describe('Button', () => { it('devrait être accessible', async () => { const wrapper = mount(Button, { slots: { default: 'Cliquer ici' } }); expect(await axe(wrapper.element)).toHaveNoViolations(); }); it('devrait avoir un label accessible', () => { const wrapper = mount(Button, { slots: { default: 'Cliquer ici' } }); expect(wrapper.text()).toBe('Cliquer ici'); }); }); ``` ### Checklist manuelle - [ ] Navigation complète au clavier - [ ] Focus visible sur tous les éléments - [ ] Contraste minimum AA (4.5:1) - [ ] Labels sur tous les champs - [ ] Textes alternatifs sur les images - [ ] Vidéos avec sous-titres - [ ] Test avec lecteur d'écran (NVDA, JAWS, VoiceOver) - [ ] Zoom à 200% sans perte d'information - [ ] Mode contraste élevé fonctionnel - [ ] Reduced motion respecté ### Outils de test **Automatisés** : - [axe DevTools](https://www.deque.com/axe/devtools/) - [Lighthouse](https://developers.google.com/web/tools/lighthouse) - [Pa11y](https://pa11y.org/) **Lecteurs d'écran** : - **Windows** : NVDA (gratuit), JAWS - **macOS** : VoiceOver (intégré) - **Linux** : Orca - **Mobile** : TalkBack (Android), VoiceOver (iOS) ## Composants accessibles avancés ### Tabs accessibles ```vue ``` ### Accordion accessible ```vue ``` ### Combobox (Autocomplete) ```vue ``` ## Audit et checklist ### Checklist complète WCAG 2.1 AA #### Perceptible - [ ] **1.1.1** Contenu non textuel : Alternatives textuelles pour images - [ ] **1.3.1** Info et relations : Structure sémantique HTML - [ ] **1.3.2** Ordre séquentiel logique : DOM order = visual order - [ ] **1.4.1** Utilisation de la couleur : Ne pas utiliser uniquement la couleur - [ ] **1.4.3** Contraste minimum : 4.5:1 pour texte normal, 3:1 pour texte large - [ ] **1.4.4** Redimensionnement du texte : Zoom 200% sans perte - [ ] **1.4.10** Reflow : Pas de scroll horizontal à 320px - [ ] **1.4.11** Contraste non-textuel : 3:1 pour composants UI - [ ] **1.4.12** Espacement du texte : Supporté sans perte de contenu #### Utilisable - [ ] **2.1.1** Clavier : Toutes les fonctions au clavier - [ ] **2.1.2** Pas de piège au clavier : Possibilité de sortir - [ ] **2.1.4** Raccourcis clavier : Désactivables ou reconfigurables - [ ] **2.4.1** Contournement de blocs : Skip links présents - [ ] **2.4.3** Ordre de focus : Logique et prévisible - [ ] **2.4.6** En-têtes et étiquettes : Descriptifs - [ ] **2.4.7** Focus visible : Toujours visible - [ ] **2.5.1** Gestes du pointeur : Alternatives aux gestes complexes - [ ] **2.5.2** Annulation du pointeur : Possibilité d'annuler - [ ] **2.5.3** Étiquette dans le nom : Nom accessible = label visible - [ ] **2.5.4** Activation par le mouvement : Alternative disponible #### Compréhensible - [ ] **3.1.1** Langue de la page : `lang` défini - [ ] **3.2.1** Au focus : Pas de changement de contexte - [ ] **3.2.2** À la saisie : Pas de changement inattendu - [ ] **3.2.3** Navigation cohérente : Même position des éléments - [ ] **3.2.4** Identification cohérente : Composants identiques - [ ] **3.3.1** Identification des erreurs : Messages clairs - [ ] **3.3.2** Étiquettes ou instructions : Présentes - [ ] **3.3.3** Suggestion d'erreur : Corrections proposées - [ ] **3.3.4** Prévention des erreurs : Confirmation pour actions importantes #### Robuste - [ ] **4.1.1** Analyse syntaxique : HTML valide - [ ] **4.1.2** Nom, rôle, valeur : ARIA correct - [ ] **4.1.3** Messages de statut : Annoncés aux lecteurs d'écran ### Outils d'audit automatisés ```bash # Installation npm install -D @axe-core/cli lighthouse pa11y # Tests axe-core npx axe https://votre-site.com --save results.json # Lighthouse CI npx lighthouse https://votre-site.com --output html --output-path ./report.html # Pa11y npx pa11y https://votre-site.com ``` ### Tests avec lecteurs d'écran **Combinaisons clavier essentielles** : #### NVDA (Windows) - `NVDA + Espace` : Mode navigation / Focus - `H` : Titre suivant - `K` : Lien suivant - `B` : Bouton suivant - `F` : Champ de formulaire suivant - `T` : Tableau suivant #### JAWS (Windows) - `Insert + F7` : Liste des liens - `Insert + F5` : Liste des champs - `Insert + F6` : Liste des titres - `H` : Titre suivant - `F` : Formulaire suivant #### VoiceOver (macOS) - `VO + A` : Lire tout - `VO + Cmd + H` : Titre suivant - `VO + Cmd + L` : Lien suivant - `VO + Cmd + J` : Formulaire suivant - `VO + U` : Rotor (navigation rapide) ### Script de test automatique ```javascript // tests/accessibility.spec.ts import { test, expect } from '@playwright/test'; import { injectAxe, checkA11y } from 'axe-playwright'; test.describe('Accessibility', () => { test('homepage should not have accessibility violations', async ({ page }) => { await page.goto('http://localhost:3000'); await injectAxe(page); await checkA11y(page); }); test('navigation should be keyboard accessible', async ({ page }) => { await page.goto('http://localhost:3000'); // Tab through navigation await page.keyboard.press('Tab'); const firstLink = await page.locator(':focus'); await expect(firstLink).toBeVisible(); // Check focus is visible const outline = await firstLink.evaluate((el) => window.getComputedStyle(el).outline ); expect(outline).not.toBe('none'); }); test('modal should trap focus', async ({ page }) => { await page.goto('http://localhost:3000/modal-test'); // Open modal await page.click('button[aria-label="Open modal"]'); // Tab through modal elements await page.keyboard.press('Tab'); const focusedElement = await page.locator(':focus'); const modalElement = await page.locator('[role="dialog"]'); // Check focus is inside modal const isInsideModal = await focusedElement.evaluate( (el, modal) => modal.contains(el), await modalElement.elementHandle() ); expect(isInsideModal).toBe(true); }); test('form errors should be announced', async ({ page }) => { await page.goto('http://localhost:3000/form'); // Submit empty form await page.click('button[type="submit"]'); // Check error has role="alert" const errorMessage = await page.locator('[role="alert"]'); await expect(errorMessage).toBeVisible(); // Check aria-invalid const invalidInput = await page.locator('[aria-invalid="true"]'); await expect(invalidInput).toBeVisible(); }); }); ``` ## Ressources complémentaires ### Documentation officielle - [WCAG 2.1](https://www.w3.org/WAI/WCAG21/quickref/) - [ARIA Authoring Practices Guide](https://www.w3.org/WAI/ARIA/apg/) - [MDN Web Accessibility](https://developer.mozilla.org/fr/docs/Web/Accessibility) ### Outils - [axe DevTools](https://www.deque.com/axe/devtools/) - Extension navigateur - [WAVE](https://wave.webaim.org/) - Évaluation visuelle - [Lighthouse](https://developers.google.com/web/tools/lighthouse) - Audit complet - [Color Contrast Analyzer](https://www.tpgi.com/color-contrast-checker/) - Desktop app ### Formation - [Web Accessibility by Google (Udacity)](https://www.udacity.com/course/web-accessibility--ud891) - [A11ycasts (YouTube)](https://www.youtube.com/playlist?list=PLNYkxOF6rcICWx0C9LVWWVqvHlYJyqw7g) - [The A11Y Project](https://www.a11yproject.com/) ### Communauté - [WebAIM Forums](https://webaim.org/discussion/) - [A11y Slack](https://web-a11y.slack.com/) ## Liens connexes - [Guide des couleurs](./colors.md) - [Tokens sémantiques](./tokens.md) - [Système de thèmes](./themes.md) - [Exemples complets](./examples.md) --- # Complete Examples Practical and reusable examples to get started quickly with the Design System. ## Complete Dashboard A modern dashboard with theme switcher and navigation. ```vue ``` ## Contact Form Accessible form with complete validation. ```vue ``` ### Different Placements ```vue ``` ### Custom User Menu ```vue ``` ## API ### Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `modelValue` | `boolean` | `undefined` | Controls the open state of the popover (v-model) | | `placement` | `'top' \| 'top-start' \| 'top-end' \| 'bottom' \| 'bottom-start' \| 'bottom-end' \| 'left' \| 'left-start' \| 'left-end' \| 'right' \| 'right-start' \| 'right-end'` | `'bottom'` | Position of the popover relative to the trigger | | `trigger` | `'click' \| 'hover' \| 'focus' \| 'manual'` | `'click'` | Method to trigger the popover | | `showArrow` | `boolean` | `true` | Shows or hides the arrow pointing to the trigger | | `closable` | `boolean` | `false` | Displays a close button in the popover | | `closeOnClickOutside` | `boolean` | `true` | Closes the popover when clicking outside | | `closeOnEscape` | `boolean` | `true` | Closes the popover when pressing Escape key | | `modal` | `boolean` | `false` | Enables modal mode with dark backdrop | | `closeOnBackdropClick` | `boolean` | `true` | Closes the popover when clicking backdrop (modal mode) | | `disabled` | `boolean` | `false` | Disables the popover | | `openDelay` | `number` | `0` | Delay in milliseconds before opening (useful with trigger="hover") | | `closeDelay` | `number` | `0` | Delay in milliseconds before closing (useful with trigger="hover") | | `ariaLabel` | `string` | `undefined` | ARIA label for the popover content | | `ariaLabelledby` | `string` | `undefined` | ID of the element that labels the popover | | `ariaDescribedby` | `string` | `undefined` | ID of the element that describes the popover | | `closeAriaLabel` | `string` | `'Close'` | ARIA label for the close button | ### Accessibility Attributes | Attribute | Element | Description | |-----------|---------|-------------| | `aria-expanded` | Trigger | Indicates whether the popover is open or closed | | `aria-haspopup` | Trigger | Indicates that the element triggers a popover | | `aria-controls` | Trigger | References the ID of the popover content | | `role="dialog"` | Content | Identifies the popover as a dialog box | | `aria-modal` | Content | Indicates whether the popover is modal | | `aria-label` | Content | Provides an accessible label for the popover | | `aria-labelledby` | Content | References the element that labels the popover | | `aria-describedby` | Content | References the element that describes the popover | | `aria-label` | Close button | Provides an accessible label for the close button | ### HTML Validation Attributes | Attribute | Element | Description | |-----------|---------|-------------| | `type="button"` | Close button | Specifies the button type | | `tabindex` | Focusable elements | Manages keyboard navigation order | ### Events | Event | Type | Description | |-------|------|-------------| | `update:modelValue` | `(value: boolean) => void` | Emitted when the open state changes | | `open` | `() => void` | Emitted when the popover opens | | `close` | `() => void` | Emitted when the popover closes | | `after-leave` | `() => void` | Emitted after the closing animation ends | ### Slots | Slot | Props | Description | |------|-------|-------------| | `trigger` | `{ isOpen: boolean }` | Content of the popover trigger | | `default` | `{ close: () => void, isOpen: boolean }` | Main content of the popover | ### Exposed Methods | Method | Type | Description | |--------|------|-------------| | `open` | `() => void` | Opens the popover | | `close` | `() => void` | Closes the popover | | `toggle` | `() => void` | Toggles the open state of the popover | | `updatePosition` | `() => void` | Recalculates the position of the popover | ## Accessibility The Popover component complies with WCAG 2.1 Level AA standards and follows W3C best practices for dialog and popover components. It ensures an accessible user experience for everyone, including people using assistive technologies. ### Accessibility Features - **Complete keyboard navigation**: The popover can be opened with Enter or Space keys, and closed with the Escape key. Navigation inside the popover is done with the Tab key. - **Focus trapping in modal mode**: When modal mode is enabled, focus is trapped inside the popover ([useFocusTrap](https://surgeui.com/en/composables/usefocustrap.md)) and returned to the trigger on close. - **Closing**: Escape and pointer down outside go through [useDismiss](https://surgeui.com/en/composables/usedismiss.md): in a popover containing an open list, Escape only closes the list; inside a SuDialog, Escape closes the popover without closing the dialog. - **Appropriate ARIA attributes**: The component uses `aria-expanded` on the trigger to indicate the open state, `aria-haspopup` to signal the presence of a popover, `aria-controls` to link the trigger to the content, and `role="dialog"` on the content for proper identification by screen readers. - **Accessible labels**: The `ariaLabel`, `ariaLabelledby`, and `ariaDescribedby` props allow providing contextual information to screen readers. The close button has a configurable ARIA label. - **Visual focus indicators**: Focusable elements display a visible outline conforming to accessibility standards, with support for high contrast mode. - **Delay management**: The `openDelay` and `closeDelay` props help avoid accidental openings/closings, particularly useful for users with motor difficulties. - **High contrast mode support**: The component automatically adapts its borders and contrasts in high contrast environments. - **Respect for reduced motion preference**: Animations are automatically disabled for users who have enabled the `prefers-reduced-motion` preference. - **RTL support**: The component automatically adapts to right-to-left languages, reversing element placements and positions. ## Advanced Usage Examples ### Popover with Dynamic Content ```vue ``` ### Popover with Custom Positioning and Recalculation ```vue ``` ### Nested Popovers ```vue ``` ### Popover with Form Validation ```vue ``` ### Popover with Global State Management ```vue ``` --- # Alert The Alert component shows important, contextual messages to the user: confirmations, warnings, errors or general information. ## Usage ### Basic alert ```vue ``` ### Alert types ```vue ``` ### Custom slots ```vue ``` ### Dismissible alert ```vue ``` The alert does not hide itself: remove it in the `dismiss` handler. ## API ### Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `type` | `'success' \| 'warning' \| 'error' \| 'info' \| 'neutral'` | `'info'` | Type (color and icon) | | `title` | `string` | - | Title (`title` slot otherwise) | | `description` | `string` | - | Text (`description` slot otherwise) | | `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Size | | `dismissible` | `boolean` | `false` | Close button | | `dismissLabel` | `string` | - | Accessible name of the close button (translated otherwise) | | `ariaLive` | `'polite' \| 'assertive' \| 'off'` | `'polite'` | Politeness of the screen reader announcement | | `ariaAtomic` | `boolean` | `true` | Reads the whole alert again when it changes | ### Events | Event | Payload | Description | |-------|---------|-------------| | `dismiss` | - | Click on the close button; the page removes the alert | ### Slots | Slot | Description | |------|-------------| | `title` | Replaces the title | | `description` | Replaces the text | | `default` | Extra content under the description (actions, links) | ## Accessibility The Alert component follows WCAG 2.1 AA and W3C best practices. ### Accessibility features - ARIA role: `role="alert"` identifies the element as an alert - Screen reader announcements: `aria-live` with several politeness levels (`assertive` for critical alerts, `polite` for information) - Keyboard: the close button can be reached and activated with the keyboard - Color contrast: colors meet the WCAG AA contrast ratios - RTL support: the layout follows right-to-left languages - Dark mode: theme adapted to the system preference - High contrast: adapted to high contrast settings - Reduced motion: respects the reduced motion preference ## Advanced usage ### Managing a list of alerts ```vue ``` --- # Toast Short-lived notifications: a brief message that confirms an action or reports a problem without interrupting the user. Toasts are created with the `useToast()` composable and rendered by `SuToaster`, placed once in the application. For a message that must stay in the page, use [Alert](https://surgeui.com/en/components/alert.md). ## Usage ### Setup Place `SuToaster` once, at the root of the application. The plugin provides the toast queue to the whole application. ```vue ``` ### Types ```vue ``` ### Action and persistent toast The action button closes the toast after the call. With `duration: 0`, the toast stays until it is closed. ```js toast.show({ title: 'Message archived', action: { label: 'Undo', onClick: () => restore(message) } }) toast.error('Connection lost', { duration: 0 }) toast.dismiss() // closes every toast ``` ### Updating a toast `update(id, options)` changes a visible toast and restarts its timer. `show()` with an existing `id` replaces it entirely. ```js const id = toast.show({ title: 'Exporting…', duration: 0, dismissible: false }) await exportData() toast.update(id, { title: 'Export complete', type: 'success', duration: 4000, dismissible: true }) ``` ## API ### useToast() | Method | Signature | Description | |--------|-----------|-------------| | `show` | `(options \| string) => string` | Shows a toast (a plain string becomes the title); returns its id | | `success` / `error` / `warning` / `info` | `(title, options?) => string` | Typed shortcuts | | `update` | `(id, options) => void` | Changes a visible toast | | `dismiss` | `(id?) => void` | Closes a toast, or all of them without an argument | | `toasts` | `Readonly>` | Current toasts, oldest first | ### Toast options | Option | Type | Default | Description | |--------|------|---------|-------------| | `id` | `string` | generated | A toast with the same id is replaced | | `type` | `'success' \| 'warning' \| 'error' \| 'info' \| 'neutral'` | `'neutral'` | Type (icon, announcement priority) | | `title` | `string` | - | Title | | `description` | `string` | - | Supporting text | | `duration` | `number` | the `SuToaster` one | Display time (ms); `0` = until closed | | `dismissible` | `boolean` | `true` | Close button | | `action` | `{ label: string, onClick: () => void }` | - | Action button | | `announce` | `boolean` | `true` | Announces to screen readers | | `onDismiss` | `(toast) => void` | - | Called when the toast is removed | ### SuToaster props | Prop | Type | Default | Description | |------|------|---------|-------------| | `position` | `'top-start' \| 'top-center' \| 'top-end' \| 'bottom-start' \| 'bottom-center' \| 'bottom-end'` | `'bottom-end'` | Screen corner (full width on mobile). `start` and `end` follow the reading direction (`end`: right in LTR, left in RTL); `left` and `right` are aliases | | `max` | `number` | `3` | Visible toasts; the next ones wait their turn | | `duration` | `number` | `5000` | Default duration (ms) | | `ariaLabel` | `string` | `'Notifications'` | Region name | ### SuToaster slot | Slot | Props | Description | |------|-------|-------------| | `default` | `{ toast, dismiss }` | Custom toast rendering (`SuToast` by default) | ### SuToast props `SuToast` is the stack item, rendered by `SuToaster` (or by its slot). | Prop | Type | Default | Description | |------|------|---------|-------------| | `type` | `'success' \| 'warning' \| 'error' \| 'info' \| 'neutral'` | `'neutral'` | Type (icon) | | `title` | `string` | - | Title (`title` slot otherwise) | | `description` | `string` | - | Extra text (`description` slot otherwise) | | `dismissible` | `boolean` | `true` | Close button | | `duration` | `number` | `5000` | Display time (ms); `0` = until closed | | `paused` | `boolean` | `false` | Pauses the countdown (hover, focus, hidden tab) | | `action` | `{ label: string, onClick: () => void }` | - | Action button | | `dismissLabel` | `string` | - | Accessible name of the close button (translated otherwise) | `SuToast` emits `dismiss` with the reason: `'timeout'`, `'close'` or `'action'`. ## Accessibility - Each toast is announced through `useAnnouncer`: politely, or assertively for an error. The `SuToaster` region is named ("Notifications") but is not a live region, to avoid double readings. - WCAG 2.2.1: timers pause on hover, on focus inside the region and while the tab is hidden. An important message, or one with an action, should be persistent (`duration: 0`). - The stack is shown in the top layer (`popover`), so it stays visible above a modal `SuDialog`. While the dialog is open its buttons cannot be used (the rest of the page is inert), but the announcement goes through the dialog. - The close button is named ("Dismiss notification", customizable with the `toast.dismiss` locale message). --- # PageHeader Header of an application page: breadcrumb or back link, title, description, badges and actions. The actions move below the title when space runs out, based on the available width rather than the screen width. ## Usage ### Title, breadcrumb and actions ```vue ``` The title is an `h1` by default: a page has only one. In the demos above, `level` is set to `2` so they don't compete with this page's title. ### Back link ```vue ``` `back` takes a path or a route: the link goes through RouterLink, or through the plugin `linkComponent` (NuxtLink). ### Tabs below the header The default slot holds what follows the header: tabs, filters… ```vue ``` ## API ### Props | Prop | Type | Default | Description | |------|------|---------|-------------| | `title` | `string` | - | Page title (or `title` slot) | | `description` | `string` | - | Text below the title (or `description` slot) | | `breadcrumb` | `BreadcrumbItem[]` | - | Breadcrumb above the title ([Breadcrumb](https://surgeui.com/en/components/breadcrumb.md)) | | `back` | `string \| RouteLocationRaw` | - | Back link above the title | | `backLabel` | `string` | `'Back'` | Back link text | | `level` | `1 \| 2 \| 3 \| 4 \| 5 \| 6` | `1` | Title level | ### Slots | Slot | Description | |------|-------------| | `breadcrumb` | Replaces the breadcrumb and the back link | | `title` | Title content | | `meta` | Badges, status… next to the title | | `description` | Description content | | `actions` | Page action buttons | | `default` | Below the header: tabs, filters… | ## Accessibility - One `h1` per page: set `level` when the header is not the page's own. - The breadcrumb is a named navigation (`