# Focus UI: complete user guides > All Focus UI user guides in one file for AI agents. Generated from the individual guides listed in https://focus-ui.de/llms.txt. # Focus UI user guides Focus UI is a browser UI kit: plain CSS plus optional browser JavaScript. Focus UI supplies layout, styles, and documented browser interactions. Your application owns data, validation rules, requests, authorization, and persistence. Server-side validation still applies when using client-side helpers. ## First use 1. Resolve the current release and matching integrity hashes using the CDN assets section of the [agent index](https://focus-ui.de/llms.txt), or download and self-host that release. The example below is pinned and verified for v2.2.0. The [API guide](https://focus-ui.de/ai/API.md) lists version requirements. 2. Build one screen with existing Focus UI classes and native HTML controls. 3. Implement list/filter, create/edit, archive confirmation, and save/error feedback in your browser code. 4. Decide where records persist. An in-memory list is a prototype; durable shared data needs an application backend. ```html ``` ## Choose a path - CSS-only page: read [Design](https://focus-ui.de/ai/DESIGN.md) for composition and [Styling](https://focus-ui.de/ai/STYLING.md) for available classes and tokens. - Interactive component: start with [Components](https://focus-ui.de/ai/COMPONENTS.md), then check initialization and teardown in the [API](https://focus-ui.de/ai/API.md). - Framework integration: follow [Frameworks](https://focus-ui.de/ai/FRAMEWORKS.md) for client-side loading and mount/unmount. - Complete workflow: copy the async settings form or mobile dashboard in [Recipes](https://focus-ui.de/ai/RECIPES.md). ## Reference | Guide | Use it for | | --- | --- | | [STYLING.md](https://focus-ui.de/ai/STYLING.md) | Existing classes, utilities, and theme tokens | | [QUICKSTART.md](https://focus-ui.de/ai/QUICKSTART.md) | A minimal page setup | | [MIGRATION.md](https://focus-ui.de/ai/MIGRATION.md) | Replacing parts of Bootstrap/Tailwind interfaces | Use `window.FocusUI` from the browser bundle or named imports from a self-hosted ESM build. The runtime needs a browser DOM. This project does not provide an npm package or maintained React/Vue wrappers. # Quick Start with Focus UI Get started in 5 minutes. ## 1. Install ### Via CDN Choose a release using the CDN assets section of the [agent index](https://focus-ui.de/llms.txt). The following example is pinned and verified for v2.2.0. ```html ``` ## 2. Your First Component ```html ``` ## 3. JavaScript components Load the browser bundle once. The declarative dialog controls bind automatically when the document is ready. ```html ``` ## 4. Form submission Follow the [async settings form](https://focus-ui.de/ai/RECIPES.md#async-settings-form) for named fields, native validation, and feedback tied to the server response. See the [API](https://focus-ui.de/ai/API.md#lifecycle) for explicit initialization and cleanup. ## Next Steps - Browse [Templates](https://focus-ui.de/layout/templates) - Read [API Reference](https://focus-ui.de/ai/API.md) - See [All Components](https://focus-ui.de/ai/COMPONENTS.md) # Building applications with Focus UI Use Focus UI when you want a compact, familiar interface in plain HTML or a framework application. A small admin panel, project tracker, or client portal is a suitable first use case. Start with a real workflow: list records → filter → edit → confirm → show success/error feedback. ## Load the library For new installs, follow the CDN assets section of the [agent index](https://focus-ui.de/llms.txt) or self-host the selected release. This example is pinned and verified for v2.2.0. ```html ``` Load application JavaScript after the library (a following deferred script works). With self-hosted ESM, use named exports from your local `focus-ui.esm.js`. The runtime requires a browser DOM; initialize it on the client in SSR applications. No npm package, default npm import, or React/Vue component wrapper is promised. ## Compose a page Use a container, responsive row/columns, and card sections. Existing layout classes include `focus-row`, `focus-col-12`, `focus-col-md-6`, `focus-d-flex`, and `focus-gap-4`. Do not invent `focus-grid-cols-2` or unprefixed Bootstrap utilities. ```html

Projects

Active projects

Your project list
``` Cards already have padding and a hover effect; check their behavior before adding wrappers or extra padding. Use `focus-table` for tabular information and real form controls for editing. Interactive helpers do not replace application state, persistence, or server validation. ## Preserve the style Use blue primary buttons for the principal action, secondary buttons for alternatives, and danger only for destructive actions. Keep neutral surfaces and use semantic alerts/toasts for feedback. Use existing spacing utilities and token values; keep dense screens readable with clear headings and one principal action per section. The default typeface is Source Sans Pro with system fallbacks. Load a font yourself if needed. Icons in several components/examples use Font Awesome; it is not bundled. Provide it separately or use options such as `icon: false` for Toast. Do not rely on icons alone to explain an action. For theme selection use `FocusUI.Theme.set('light' | 'dark' | 'auto')`. The root attribute is `data-focus-theme`, not `data-theme`; auto removes it and follows the OS. Theme changes use localStorage. If overriding colors, override related hover/background/border/text tokens and test both themes. ```css /* Load application overrides after Focus UI. */ :root { --focus-font-family: system-ui, sans-serif; --focus-radius-md: 0.5rem; } ``` ## Interactions and accessibility The browser bundle initializes supported data attributes on DOM ready. After adding markup dynamically, call `FocusUI.init()`; Searchbar, Tables, and TOC have separate initialization APIs. Prefer direct component methods with framework event handlers so the framework owns the element lifecycle. Never combine an inline handler and data attribute for the same action. Use `Modal.confirm()` for simple confirmations and handle cancellation: ```js try { await FocusUI.Modal.confirm({ title: 'Archive project?', message: 'You can restore it later.', confirmText: 'Archive' }) // Persist the change here, then report the actual result. FocusUI.Toast.show({ type: 'success', message: 'Project archived', icon: false }) } catch { // User cancelled (or the operation failed; distinguish this in application code). } ``` Supply meaningful labels, visible focus, native button types, and heading hierarchy. CSS-only styling does not implement focus trapping, menu navigation, or dialogs. Check keyboard access and contrast in your actual application; the kit's tests do not certify your screen. Test narrow layouts and reduced motion. Keep messages as plain text and use server validation for submitted data. ## Reference order 1. [API.md](https://focus-ui.de/ai/API.md): exact signatures and options. 2. [COMPONENTS.md](https://focus-ui.de/ai/COMPONENTS.md): required markup structure. 3. [STYLING.md](https://focus-ui.de/ai/STYLING.md): available classes and token families. 4. [RECIPES.md](https://focus-ui.de/ai/RECIPES.md): composition ideas; verify them against the current API. 5. [FRAMEWORKS.md](https://focus-ui.de/ai/FRAMEWORKS.md): client integration sketches. When documentation disagrees, inspect `src/lib/` in the source repository. Generated docs templates at `layout/templates/` are useful starting points, but application-specific logic belongs in your project. # Component patterns Use these small patterns as a starting point. Browse the [generated page references](https://focus-ui.de/ai/pages.md) for complete examples. See the [API guide](https://focus-ui.de/ai/API.md) for release boundaries. Focus UI does not provide application persistence, authorization or framework state management. ## Actions and feedback ```html Active ``` Loading is application state: disable the button, replace its text and restore it in a finally block. There is no focus-btn-loading class. Toast.show takes one config object; catch dialog cancellation before performing the application action. ## Cards and forms Static cards stay still on hover. Cards that are links or buttons, and cards with `focus-card-clickable`, get border and shadow feedback with fine pointers that support hover. They also lift when reduced motion is off. The modifier adds styling only; use a link or button for a keyboard-accessible action. ```html

Project details

``` ```js FocusUI.Forms.onSubmit('#project-form', { '[name="name"]': { required: true, minLength: 2 } }, values => { // Submit to your backend and handle success/failure. console.log(values.name) }) ``` Use associated labels and explicit error messages. Client validation is not server validation. For controlled framework forms, keep state and submit handling in the framework. ## Tables ```html
Projects
Status
ExampleActive
``` Static tables need no JavaScript. Optional sorting requires explicit initialization. Since v2.3.0, an empty `focus-table-sort-icon` element in a sortable header receives a built-in indicator without an icon font. A native button in the header dispatches the same click on Enter or Space. For currency or dates, sort typed values before formatting as shown in the [dashboard recipe](https://focus-ui.de/ai/RECIPES.md#mobile-project-dashboard). The v2.1.1 API supports Tables.init/destroy; v2.0.0 uses makeSortable. Keep framework-owned rows sorted through framework state. ## Information display recipes These patterns use existing Focus UI classes and application CSS. They do not add library components. ### Details Use a native description list for terms and values. The rows stack below 576px, and long values wrap. Remove the border rule to omit dividers. The monospace stack is application CSS. ```css .recipe-detail-row { display: grid; gap: var(--focus-spacing-xs); padding-block: var(--focus-spacing-sm); } .recipe-detail-row dt { color: var(--focus-color-text-muted); } .recipe-detail-row dd { min-width: 0; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; } .recipe-detail-row + .recipe-detail-row { border-block-start: 1px solid var(--focus-color-border); } .recipe-mono { font-family: Consolas, Monaco, "Courier New", monospace; } @media (min-width: 576px) { .recipe-detail-row { grid-template-columns: minmax(8rem, 1fr) minmax(0, 2fr); gap: var(--focus-spacing-base); } } ``` ```html
Endpoint
https://gateway.example.com/api/v1/health/check?region=eu-central&environment=production
Requests today
1,248,635
Owner
Platform operations
``` ### Status summaries Cards and badges make a status summary. The card grid fits cards to the available width. Use text in badges so state does not depend on color, and use links for actions. ```html

Availability

99.98%

Healthy

Last 30 days

Requests

1,248,635

Last 24 hours

View request details

``` ### Task progress Use a native ordered list for a non-interactive progress indicator. State remains visible as text, and the current item uses `aria-current="step"`. The example stacks below 768px and uses application CSS for the layout. An application owns state changes. ```css .recipe-steps { display: grid; gap: var(--focus-spacing-base); padding: 0; margin: 0; list-style: none; } .recipe-step { display: flex; align-items: start; gap: var(--focus-spacing-sm); min-width: 0; } .recipe-step-mark { flex: 0 0 2rem; width: 2rem; height: 2rem; display: grid; place-items: center; border: 1px solid var(--focus-color-border); border-radius: var(--focus-radius-circle); font-weight: var(--focus-font-weight-semibold); } .recipe-step-complete .recipe-step-mark { background: var(--focus-color-success-bg); color: var(--focus-color-success-text); } .recipe-step-current .recipe-step-mark { background: var(--focus-color-primary); color: var(--focus-color-black); } .recipe-step-error .recipe-step-mark { background: var(--focus-color-danger-bg); color: var(--focus-color-danger-text); } .recipe-step-label { display: block; font-weight: var(--focus-font-weight-semibold); overflow-wrap: anywhere; } .recipe-step-state { display: block; color: var(--focus-color-text-muted); font-size: var(--focus-font-size-sm); } @media (min-width: 768px) { .recipe-steps { grid-template-columns: repeat(4, minmax(0, 1fr)); } } ``` ```html

Set up a service

  1. DetailsComplete
  2. Choose a planCurrent step
  3. Review configuration and accessNeeds attention
  4. ConfirmUpcoming
``` ### Numbered status items Use native buttons for items that open details. Each accessible name includes the number and state; symbols and a visible key also convey state. This example wraps and writes a selected item to a status line. The CSS and click behavior belong to the application. Replace the detail action as needed. ```css .recipe-cells { display: grid; grid-template-columns: repeat(auto-fit, minmax(4rem, 1fr)); gap: var(--focus-spacing-sm); } .recipe-cell.focus-btn { min-width: 0; min-height: 3rem; display: flex; justify-content: center; align-items: center; gap: var(--focus-spacing-xs); color: var(--focus-color-text); border-color: var(--focus-color-border); } .recipe-cell-key { display: flex; flex-wrap: wrap; gap: var(--focus-spacing-sm); margin-block-start: var(--focus-spacing-base); } ``` ```html

Service checks

✓ Healthy! Attention× Error- Pending

Select a check to see details.

``` ```js const checks = document.querySelector('.recipe-cells') const detail = document.querySelector('#check-detail') checks.addEventListener('click', event => { const button = event.target.closest('button[data-detail]') if (button && checks.contains(button)) detail.textContent = button.dataset.detail }) ``` ## Dropdown ```html
``` The data attribute binds the toggle. Menu actions still require application handlers. Add and synchronize accessible expanded-state behavior when integrating a custom menu; the library does not supply a complete ARIA menu keyboard pattern. ## Tabs ```html
Details content
Activity content
``` Hover feedback on tabs and other interactive components is limited to devices whose primary input supports hover and a fine pointer. Touch interaction retains selected and keyboard focus states. Buttons/panels share data-tab; HTML IDs serve accessible relationships. Scope Tabs.switch to a container when IDs repeat. Test keyboard navigation; native button activation alone is not the full arrow-key tab pattern. ## Existing modal ```html ``` Add `hidden` to an overlay to keep it hidden until opened. Modal stacking and toast progress use JavaScript style-property assignments, so test these features under your application's Content Security Policy. Pass either the overlay or its nested modal to the API. Call Modal.open('#edit-project') and Modal.close('#edit-project'). The library manages focus trapping/restoration. For simple confirmation or text input, use the promise helpers instead of recreating their markup. ## Navigation recipes These examples use existing Focus UI classes plus application-owned CSS and JavaScript. Replace example links and icons with your own. They do not add library APIs. ### Mobile bottom navigation Include `` in the document head for safe-area insets. Place the drawer outside transformed ancestors and stacking contexts that could cover it. Load the Focus UI JavaScript with its normal automatic initialization so the More button opens the drawer and receives synchronized expanded state. Escape or the backdrop closes it and restores focus. This example is visible through 768px, matching the existing mobile sidebar boundary. The fixed height reserves room for two-line labels and the safe area; adjust both heights together for your labels, text scaling and device. The active link uses text weight and a border as well as color. ```css .recipe-bottom-nav { display: none; } @media (max-width: 768px) { .recipe-drawer:not(.focus-sidebar-open) { visibility: hidden; } .recipe-page { padding-block-end: calc(5rem + env(safe-area-inset-bottom, 0px)); } .recipe-bottom-nav { position: fixed; inset: auto 0 0; z-index: var(--focus-z-fixed); display: flex; height: calc(5rem + env(safe-area-inset-bottom, 0px)); padding-block-end: env(safe-area-inset-bottom, 0px); background: var(--focus-color-surface); border-block-start: 1px solid var(--focus-color-border); } .recipe-bottom-nav a, .recipe-bottom-nav button { flex: 1 1 0; min-width: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; color: var(--focus-color-text); background: transparent; border: 0; font: inherit; font-size: var(--focus-font-size-sm); text-align: center; overflow-wrap: anywhere; cursor: pointer; } .recipe-bottom-nav [aria-current="page"] { border-block-start: 3px solid var(--focus-color-primary); font-weight: var(--focus-font-weight-semibold); } .recipe-bottom-nav :focus-visible { outline: 2px solid var(--focus-color-primary); outline-offset: -2px; } } @media (min-width: 769px) { .recipe-drawer { display: none; } } ``` ```html

Overview

Application content

``` ### Flat desktop sidebar rail This flat example keeps an accessible name on every icon link when its visible label is hidden. The toggle and state are owned by the application; there is no persistence or nested-group behavior. The rail control is hidden at mobile widths, where the separate mobile button opens the sidebar drawer. For nested navigation, retain the expanded sidebar or provide another accessible way to reach every destination. The example uses the current physical sidebar behavior in RTL. ```css @media (min-width: 769px) { .recipe-rail-mobile-toggle { display: none; } .recipe-rail[data-recipe-expanded="false"] { width: 4.5rem; } .recipe-rail[data-recipe-expanded="false"] .recipe-rail-label { display: none; } .recipe-rail[data-recipe-expanded="false"] .focus-sidebar-item { justify-content: center; } } @media (max-width: 768px) { .recipe-rail-toggle { display: none; } .recipe-rail:not(.focus-sidebar-open) { visibility: hidden; } } ``` ```html ``` ```js const rail = document.querySelector('#flat-sidebar') const railToggle = document.querySelector('#rail-toggle') railToggle.addEventListener('click', () => { const expanded = railToggle.getAttribute('aria-expanded') === 'true' railToggle.setAttribute('aria-expanded', String(!expanded)) rail.dataset.recipeExpanded = String(!expanded) railToggle.textContent = expanded ? 'Expand navigation' : 'Collapse navigation' }) ``` ## Navigation and other components Since v2.2.0, `Sidebar.open`, `close`, and `toggle` manage the mobile drawer backdrop and focus. Clicking the backdrop or pressing Escape closes the drawer; resizing to desktop or destroying its scope releases the overlay. A transformed ancestor can constrain the backdrop to that ancestor; place the drawer outside transformed containers. Use the API when changing visibility so the backdrop and focus stay in sync. Ancestor stacking contexts can also place the drawer and backdrop behind other page layers. Sidebar collapse markup has paired data-collapse-id and collapse-... IDs; copy the current sidebar example rather than inventing sidebar-link/submenu class names. Navbar search requires Searchbar.init and application-supplied results. Icons are separate assets; Font Awesome is not bundled. Since v2.3.0, add `focus-sidebar-collapse-icon` to a decorative, down-facing custom icon (for example, an SVG with `aria-hidden="true"` and `focusable="false"`). Existing `fa-chevron-down` markup continues to work. Add `focus-sidebar-item-icon` to a decorative inline SVG directly inside a `focus-sidebar-item` to use the sidebar item icon spacing and colors. Give the link a visible text label and set `aria-hidden="true"` and `focusable="false"` on the SVG. The following links open the published component references. ### Navigation - [Navbar](https://focus-ui.de/components/navigation/navbar): Navigation headers - [Sidebar](https://focus-ui.de/components/navigation/sidebar): Side navigation panels - [Breadcrumbs](https://focus-ui.de/components/navigation/breadcrumbs): Navigation hierarchy - [Pagination](https://focus-ui.de/components/navigation/pagination): Page navigation - [Table of Contents](https://focus-ui.de/components/navigation/toc): Auto-generated navigation from page headings - [Tabs](https://focus-ui.de/components/navigation/tabs): Tabbed content panels - [Searchbar](https://focus-ui.de/components/navigation/searchbar): Search input with results dropdown - [Dropdowns](https://focus-ui.de/components/navigation/dropdowns): Toggleable context menus ### Forms & Inputs - [Forms](https://focus-ui.de/components/forms-inputs/forms): Input fields and controls - [Buttons](https://focus-ui.de/components/forms-inputs/buttons): Interactive action triggers - [Toggle Switch](https://focus-ui.de/components/forms-inputs/toggle): iOS-style on/off toggle switches ### Feedback - [Alerts](https://focus-ui.de/components/feedback/alerts): Contextual feedback messages - [Toasts](https://focus-ui.de/components/feedback/toasts): Notification popups. Since v2.3.0, default icons are built in; `icon: false` disables them and a custom icon class retains the `fa` class. - [Modals](https://focus-ui.de/components/feedback/modals): Dialog windows. Since v2.3.0, the generated delete confirmation includes a built-in warning icon. - [Progress](https://focus-ui.de/components/feedback/progress): Progress indicators - [Spinners](https://focus-ui.de/components/feedback/spinners): Loading indicators - [Tooltip](https://focus-ui.de/components/feedback/tooltip): Contextual hints on hover or focus. Add `focus-tooltip-multiline` to wrap longer text. Its width fits the content up to `--focus-tooltip-max-width` (250px by default) and is capped by the viewport width. CSS-only tooltips do not automatically shift or flip. For top or bottom placement near a viewport edge, add `focus-tooltip-align-left` or `focus-tooltip-align-right` to align the bubble with that edge of its trigger. Leave enough space for side placements. v2.2.0 adds `FocusUI.Tooltip.init(root)` (unavailable in v2.1.1), which opts existing tooltips in that root into viewport positioning. Retain its destroy handle and call `destroy()` before unmounting; initialize again after adding tooltips. The preferred side can flip or move to a perpendicular side, and arrows shift toward the trigger. A touch tap opens the tooltip until an outside tap without blocking the tap action. Oversized bubbles and clipping ancestors can still clip. Force-shown tooltips are positioned automatically only during pointer, focus or touch activation; otherwise they use CSS positioning. - [Skeleton](https://focus-ui.de/components/feedback/skeleton): Loading placeholders for content ### Content - [Avatar](https://focus-ui.de/components/content/avatar): User profile images and initials - [Badges](https://focus-ui.de/components/content/badges): Small count and labeling - [Callouts](https://focus-ui.de/components/content/callouts): Highlighted information boxes - [Cards](https://focus-ui.de/components/content/cards): Flexible content containers - [Code](https://focus-ui.de/components/content/code): Code snippets with copy - [Dividers](https://focus-ui.de/components/content/dividers): Visual separators and section dividers - [Hero](https://focus-ui.de/components/content/hero): Landing page hero sections - [Preview](https://focus-ui.de/components/content/preview): Component demos and full page previews - [Tables](https://focus-ui.de/components/content/tables): Tabular data display # Focus UI — Styling Guide CSS classes, theming, and customization. --- ## CSS Class Naming All Focus UI classes use the `focus-` prefix to avoid conflicts. ``` focus-{component}[-{variant}][-{modifier}] ``` Examples: - `focus-btn` — Button base - `focus-btn-primary` — Primary variant - `focus-btn-lg` — Large modifier - `focus-card-clickable` — Clickable card modifier --- ## CSS Custom Properties (Variables) Focus UI uses CSS variables for theming. Override them to customize. **Naming pattern:** `--focus-color-{name}` for colors, `--focus-{category}-{name}` for other tokens. ### Primary & Secondary Colors ```css :root { --focus-color-primary: #007bff; --focus-color-primary-hover: #0056b3; --focus-color-primary-light: #80bdff; --focus-color-primary-dark: #004085; --focus-color-primary-bg: #cfe2ff; --focus-color-primary-border: #b6d4fe; --focus-color-primary-text: #004085; --focus-color-secondary: #6c757d; --focus-color-secondary-hover: #5a6268; } ``` ### Semantic Colors ```css :root { --focus-color-success: #28a745; --focus-color-success-hover: #218838; --focus-color-success-bg: #d4edda; --focus-color-success-text: #155724; --focus-color-danger: #dc3545; --focus-color-danger-hover: #c82333; --focus-color-danger-bg: #f8d7da; --focus-color-danger-text: #721c24; --focus-color-warning: #ffc107; --focus-color-warning-hover: #e0a800; --focus-color-warning-bg: #fff3cd; --focus-color-warning-text: #000000; --focus-color-info: #17a2b8; --focus-color-info-hover: #138496; --focus-color-info-bg: #d1ecf1; --focus-color-info-text: #0c5460; } ``` `--focus-color-warning-text` sets the foreground on solid warning surfaces such as badges. Override `--focus-color-warning-alert-text` to customize tinted warning alerts. By default, alerts use `--focus-color-warning-text` in light mode and `#fcd34d` in dark mode. ### Accent Colors ```css :root { --focus-color-purple: #6f42c1; --focus-color-teal: #20c997; --focus-color-orange: #fd7e14; --focus-color-pink: #e83e8c; } ``` ### Text Colors ```css :root { --focus-color-text: #495057; --focus-color-text-muted: #6c757d; --focus-color-text-light: #999999; --focus-color-text-dark: #333333; } ``` ### Background Colors ```css :root { --focus-color-bg: #f4f6f9; --focus-color-bg-light: #fafbfc; --focus-color-card-bg: #ffffff; --focus-color-surface: #ffffff; --focus-color-hover: rgba(0, 0, 0, 0.04); } ``` ### Border Colors ```css :root { --focus-color-border: #ced4da; --focus-color-border-light: #e9ecef; --focus-color-border-dark: #dee2e6; } ``` ### Spacing ```css :root { --focus-spacing-xs: 0.25rem; /* 4px */ --focus-spacing-sm: 0.5rem; /* 8px */ --focus-spacing-md: 0.75rem; /* 12px */ --focus-spacing-base: 1rem; /* 16px */ --focus-spacing-lg: 1.5rem; /* 24px */ --focus-spacing-xl: 2rem; /* 32px */ --focus-spacing-2xl: 3rem; /* 48px */ } ``` ### Typography ```css :root { --focus-font-family: 'Source Sans Pro', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; --focus-font-size-xs: 0.75rem; /* 12px */ --focus-font-size-sm: 0.85rem; /* 13.6px */ --focus-font-size-base: 0.95rem; /* 15.2px */ --focus-font-size-md: 1rem; /* 16px */ --focus-font-size-lg: 1.1rem; /* 17.6px */ --focus-font-size-xl: 1.25rem; /* 20px */ --focus-font-weight-normal: 400; --focus-font-weight-medium: 500; --focus-font-weight-semibold: 600; --focus-font-weight-bold: 700; --focus-line-height-tight: 1.25; --focus-line-height-normal: 1.4; --focus-line-height-relaxed: 1.5; } ``` Table headers, sidebar section headings, TOC titles, code labels, dropdown headers and avatar initials use the case you write. Set `--focus-label-text-transform: uppercase` on `:root` or a component scope to display them in uppercase. ### Border Radius ```css :root { --focus-radius-sm: 0.25rem; /* 4px */ --focus-radius-md: 0.5rem; /* 8px */ --focus-radius-lg: 0.75rem; /* 12px */ --focus-radius-xl: 1rem; /* 16px */ --focus-radius-pill: 12px; --focus-radius-circle: 50%; } ``` ### Shadows ```css :root { --focus-shadow-xs: 0 1px 2px rgba(0, 0, 0, 0.05); --focus-shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.1); --focus-shadow-md: 0 4px 8px rgba(0, 0, 0, 0.15); --focus-shadow-lg: 0 4px 12px rgba(0, 0, 0, 0.15); --focus-shadow-xl: 0 8px 16px rgba(0, 0, 0, 0.2); --focus-shadow-focus: 0 0 0 0.2rem var(--focus-color-primary-lighter); } ``` ### Transitions ```css :root { --focus-transition-fast: 0.15s ease; --focus-transition-base: 0.2s ease; --focus-transition-slow: 0.3s ease; } ``` ### Z-Index Layers ```css :root { --focus-z-dropdown: 1000; --focus-z-sticky: 1020; --focus-z-fixed: 1030; --focus-z-modal-backdrop: 1040; --focus-z-modal: 1050; --focus-z-popover: 1060; --focus-z-tooltip: 1070; } ``` --- ## Dark Mode Focus UI supports dark mode via: 1. **System preference** (automatic) 2. **Manual toggle** via JavaScript 3. **Data attribute** on `` ### How Dark Mode Works ```css /* System light and explicit light share a palette. */ :root, [data-focus-theme="light"] { --focus-color-bg: #f4f6f9; --focus-color-text: #495057; --focus-color-card-bg: #ffffff; } /* Dark mode via system preference */ @media (prefers-color-scheme: dark) { :root:where(:not([data-focus-theme="light"])) { --focus-color-bg: #111827; --focus-color-text: #e5e7eb; --focus-color-card-bg: #1f2937; } } /* Dark mode via attribute (overrides system) */ [data-focus-theme="dark"] { --focus-color-bg: #111827; --focus-color-text: #e5e7eb; --focus-color-card-bg: #1f2937; } ``` ### Controlling Dark Mode ```javascript // Toggle between light/dark/auto FocusUI.Theme.toggle() // Set specific theme FocusUI.Theme.set('dark') FocusUI.Theme.set('light') FocusUI.Theme.set('auto') // Follow system preference // Get current theme FocusUI.Theme.get() // 'light' | 'dark' | 'auto' FocusUI.Theme.getEffective() // 'light' | 'dark' (resolves auto) ``` Inside a navbar, `.focus-theme-toggle` follows the navbar variant's colors, including `.focus-navbar-light` when the page uses a dark theme. ### Custom Dark Mode Colors Override in your CSS: ```css [data-focus-theme="dark"] { --focus-color-primary: #60a5fa; /* Lighter blue for dark mode */ --focus-color-bg: #0f172a; /* Custom dark background */ } ``` --- ## Customizing Components ### Method 1: Override Variables ```css :root { --focus-color-primary: #8b5cf6; /* Purple instead of blue */ --focus-radius-md: 0; /* Square corners */ } ``` ### Method 2: Override Classes ```css .focus-btn { font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; } .focus-card { border: 2px solid var(--focus-color-primary); } ``` ### Method 3: Extend with Custom Classes ```css .focus-btn-gradient { background: linear-gradient(to right, #8b5cf6, #ec4899); border: none; } ``` --- ## Utility Classes Reference ### Spacing (margin/padding) | Class | CSS | |-------|-----| | `focus-m-{0-5}` | `margin` | | `focus-p-{0-5}` | `padding` | | `focus-mt-{0-5}` | `margin-top` | | `focus-mb-{0-5}` | `margin-bottom` | ### Display | Class | CSS | |-------|-----| | `focus-d-none` | `display: none` | | `focus-d-block` | `display: block` | | `focus-d-inline` | `display: inline` | | `focus-d-inline-block` | `display: inline-block` | | `focus-d-flex` | `display: flex` | | `focus-d-grid` | `display: grid` | | `focus-d-table-cell` | `display: table-cell` | ### Flexbox | Class | CSS | |-------|-----| | `focus-flex-row` | `flex-direction: row` | | `focus-flex-column` | `flex-direction: column` | | `focus-flex-wrap` | `flex-wrap: wrap` | | `focus-justify-start` | `justify-content: flex-start` | | `focus-justify-center` | `justify-content: center` | | `focus-justify-end` | `justify-content: flex-end` | | `focus-justify-between` | `justify-content: space-between` | | `focus-align-start` | `align-items: flex-start` | | `focus-align-center` | `align-items: center` | | `focus-align-end` | `align-items: flex-end` | | `focus-gap-{1-5}` | `gap` | ### Text | Class | CSS | |-------|-----| | `focus-text-left` | `text-align: left` | | `focus-text-center` | `text-align: center` | | `focus-text-right` | `text-align: right` | | `focus-text-sm` | `font-size: var(--focus-font-size-sm)` | | `focus-text-lg` | `font-size: var(--focus-font-size-lg)` | | `focus-text-xl` | `font-size: var(--focus-font-size-xl)` | | `focus-font-bold` | `font-weight: 700` | | `focus-text-primary` | `color: var(--focus-color-primary)` | | `focus-text-muted` | `color: var(--focus-color-text-muted)` | | `focus-text-white` | `color: white` | ### Background | Class | CSS | |-------|-----| | `focus-bg-primary` | `background-color: var(--focus-color-primary)` | | `focus-bg-secondary` | `background-color: var(--focus-color-secondary)` | | `focus-bg-success` | `background-color: var(--focus-color-success)` | | `focus-bg-danger` | `background-color: var(--focus-color-danger)` | | `focus-bg-warning` | `background-color: var(--focus-color-warning)` | | `focus-bg-white` | `background-color: white` | ### Borders | Class | CSS | |-------|-----| | `focus-border` | `border: 1px solid var(--focus-color-border)` | | `focus-border-0` | `border: none` | | `focus-rounded` | `border-radius: var(--focus-radius-sm)` | | `focus-rounded-lg` | `border-radius: var(--focus-radius-lg)` | | `focus-rounded-circle` | `border-radius: var(--focus-radius-circle)` | ### Width/Height | Class | CSS | |-------|-----| | `focus-w-100` | `width: 100%` | | `focus-h-100` | `height: 100%` | | `focus-w-auto` | `width: auto` | ### Position | Class | CSS | |-------|-----| | `focus-position-relative` | `position: relative` | | `focus-position-absolute` | `position: absolute` | | `focus-position-fixed` | `position: fixed` | --- ## Z-Index Layers Focus UI uses these z-index values: | Layer | Z-Index | Components | |-------|---------|------------| | Dropdown | 1000 | Dropdown menus | | Sticky | 1020 | Sticky headers | | Fixed | 1030 | Fixed elements | | Modal backdrop | 1040 | Modal overlay | | Modal | 1050 | Modal dialog | | Popover | 1060 | Popovers | | Tooltip | 1070 | Tooltips | --- ## Document scrolling Since v2.2.0, the reset lets the document scroll vertically and clips horizontal page overflow. Sticky elements follow the nearest scroll container. Avoid adding overflow to an ancestor unless that container should control scrolling. Keep interactive content within the viewport, or give wide content its own scrollable container. For an app wrapper that previously relied on `height: 100%` under `body`, use `focus-min-vh-100` to fill at least the viewport. --- ## Responsive Breakpoints Focus UI is mobile-first. Default breakpoints: | Breakpoint | Min Width | |------------|-----------| | `sm` | 576px | | `md` | 768px | | `lg` | 992px | | `xl` | 1200px | Display utilities include `focus-d-{sm|md|lg|xl}-table-cell`. Apply `focus-d-none focus-d-md-table-cell` to both the header and each data cell to hide a column below 768px. Hidden cells are unavailable to assistive technology at that width. Use `focus-table-responsive` to contain any remaining table overflow. Add `tabindex="0"`, `role="region"` and a descriptive label to the wrapper so keyboard users can reach and scroll it. The wrapper stays in the tab order even when all columns fit. The tables reference includes a seven-column example. Some utilities support responsive prefixes: ```html
Hidden on mobile, visible on tablet+
``` --- ## Best Practices 1. **Use CSS variables** for theming instead of overriding classes directly 2. **Prefer utility classes** for one-off styling 3. **Create custom component classes** for reusable patterns 4. **Test dark mode** when customizing colors 5. **Use semantic color names** (primary, danger) not literal colors ## Pointer feedback Interactive hover styling follows the primary input. It applies when that input is a fine pointer and supports hover. Selected and keyboard focus states work independently of hover. ## Multiline tooltip sizing Set `--focus-tooltip-max-width` to customize the maximum width of a multiline tooltip. It defaults to `15.625rem`, and the bubble also respects the viewport width cap. Choose a placement with enough room around the trigger. ## Content Security Policy The library has a Chromium regression check for representative component markup and selected JavaScript component interactions under a self-only script and style policy. Components also set some style properties through JavaScript. Test your own workflows and browser policies, including external assets and application handlers; the regression check does not cover every integration. See the [CSP guide](https://focus-ui.de/security/csp). ## Semantic text and filled control colors Use `--focus-color-primary-foreground` for primary text on neutral surfaces. The success, danger, warning and info families also provide `-foreground` tokens, with light and dark defaults. These are separate from the tinted alert `-text` tokens. Setting an existing base color such as `--focus-color-primary` still changes filled controls, but no longer changes semantic text. Set the matching `-foreground` token as well when customizing text. Set `--focus-color-primary-foreground-hover` for link hover text. Filled buttons, badges, avatars, active pagination and pill tabs accept `--focus-color--solid` and `--focus-color-on--solid`. When the solid token is unset, the component uses the existing base color, including overrides on a themed container. Button hover backgrounds use `--focus-color--solid-hover`, falling back to the existing hover token. Primary buttons also accept `--focus-color-on-primary-solid-hover` because their default hover background uses a light foreground. Warning controls continue to fall back to `--focus-color-warning-text`. Check every foreground and background pair after customization. ```css [data-focus-theme="dark"] { --focus-color-primary-foreground: #93c5fd; --focus-color-primary-solid: #1d4ed8; --focus-color-on-primary-solid: #ffffff; --focus-color-primary-solid-hover: #1e40af; --focus-color-on-primary-solid-hover: #ffffff; } ``` ## Right-to-left layouts Set `dir="rtl"` on the document or an appropriate container and test with real translated content. Complete mirrored support is not guaranteed. The development build has Chromium coverage for navbar and breadcrumb keyboard order, mixed Arabic and Latin labels, mobile sidebar focus and Escape, and physical toast positions at 375px and 1280px while rendering light, dark and forced-light themes. These checks do not independently verify theme-specific styling or contrast. Table alignment, mixed-script sorting using a button in the header, table-of-contents links and basic form focus and validation have separate coverage. Additional RTL fixtures exercise a mixed-text alert, toggle, dropdown, confirm dialog and tooltip, and sample static content and pagination. RTL tests also cover theme toggle, search result arrow/Enter navigation and horizontal tab arrow behavior. Select focus and programmatic selection, radio Space, textarea focus and static physical tooltip placement have separate coverage. For keyboard activation of sorting, use a native button inside each sortable table header. Explicit `text-right` table alignment stays physical right in RTL. Dismissible alert controls remain on the physical right, and the default toggle thumb starts on the physical left. Static tooltip left/right placements remain physical. A Chromium test checks a managed tooltip flipping from left to right at the viewport edge and dismissing on an outside tap in RTL at 375px. Other collision and touch scenarios remain untested in RTL. Progress direction and untested variants need application review. Search result navigation changes an active class while focus stays in the input; screen-reader announcement is unverified. Native select popup keyboard selection was not verified locally. The search input icon and its padding remain on the physical left in both directions. The mobile sidebar opens from the physical left in both directions; its active marker, text alignment and nested indentation also use physical properties. Breadcrumb chevrons point the same physical direction in RTL and LTR. Toast left and right placement modifiers and the toast accent border are physical, and `focus-dropdown-menu-right` remains physical right. These sidebar, breadcrumb and toast positioning characteristics also exist in v2.1.1. Mobile sidebar backdrop and focus behavior differs between v2.1.1 and the development build. In development source, horizontal tab arrows follow the visual direction: ArrowLeft moves left in RTL and ArrowRight moves right. Vertical tabs keep Up/Down navigation. Navbar search uses physical-right alignment on desktop and fixed left/right insets on narrow screens. Test other variants, browsers and assistive technologies for your application. # Browser JavaScript API This reference describes v2.3.0 and calls out older release boundaries where relevant. For new installs, use the [release index](https://cdn.focus-ui.de/versions.json) and the CDN assets section of the [agent index](https://focus-ui.de/llms.txt) to select matching assets and integrity hashes, or download and self-host the selected release. This repository does not publish an npm package. Use `window.FocusUI` after loading the UMD bundle, or named imports from a downloaded `focus-ui.esm.js`. The [declarations](https://focus-ui.de/ai/focus-ui.d.ts) describe the supported argument shapes; implementation and tests are authoritative. Browser DOM access is required. The v2.1.1 release includes the documented `Tables.init/destroy` methods and named keyboard utility exports. Published v2.0.0 predates these additions; with that release, use `Tables.makeSortable` and do not rely on newer APIs listed here. ## Lifecycle The browser bundle runs `FocusUI.init()` on DOM readiness. Call it again to discover newly inserted declarative markup, such as dropdown triggers or theme buttons, without duplicating bindings. The root method returns `void`. Call the component's own initializer for Searchbar, Tables, TOC, and optional tooltip positioning. Sidebar and Code also support explicit initialization. Retain a component handle where documented and use its cleanup or the documented component teardown before unmounting. Your application owns data, network requests and their cancellation. | Component | Methods | Notes | | --- | --- | --- | | Modal | `open(element, options?)`, `close(element)` | Pass the `.focus-modal-overlay` or its nested `.focus-modal`. Add `hidden` to the overlay to hide it until opened. Open options: `focusTrap`, `closeOnEsc`, `closeOnOverlay`. Overlay closing defaults to false. Since v2.3.0, removing an open modal releases its listeners and hides its remaining overlay when no other dialog uses it. | | Modal helpers | `confirm(config)`, `deleteConfirm(config)`, `prompt(config)` | Return promises. Confirm/delete resolve true; prompt resolves a string. All reject on cancellation. Catch cancellation in event handlers. The top dialog owns Escape/focus; closing restores the previous layer. Generated inputs and close buttons are labelled. Since v2.3.0, the delete confirmation warning icon is built in. Background content is inert while the default focus trap is active. Closing a generated dialog through `Modal.close` or removing its host cancels the promise and releases that state. | | Tooltip | `init(root?)`, `destroy(root?)` | Available since v2.2.0; unavailable in v2.1.1. Opt in to viewport-aware positioning for the tooltips present in a root. Init returns a destroy handle, or null for a missing root. Destroy before removing the root. | | Toast | `show(config)`, `close(element)`, `getContainer(position?)` | One config object: type, title, message, duration, position, icon, progress. Since v2.3.0, default icons are built in; `icon: false` removes the icon and a custom class retains the `fa` class. Duration 0 keeps it open. `show` returns the toast element. `getContainer` is mainly for internal use; advanced integrations can get or create the body-level container for a position (default `top-right`). Supported positions: `top-right`, `top-left`, `bottom-right`, `bottom-left`, `top-center`, `bottom-center`. | | Alert | `show(config)`, `close(element)`, `dismiss(element)` | Config: type, message, dismissible, container. `dismiss` aliases close. | | Tabs | `init(container?)`, `destroy(container)`, `switch(tabId, container?)`, `activate(button)` | Auto-init includes keyboard navigation and linked ARIA state. Since v2.3.0, horizontal arrows follow the tab list direction, while vertical tabs use Up/Down. Button and panel share literal `data-tab` values. Scope repeated IDs to a container. Destroy removes click/key handlers and retains markup/state; init binds them again. These lifecycle methods are included in v2.1.1; they are not available in published v2.0.0. | | Dropdown | `open(element)`, `close(element)`, `toggle(element)` | Pass the `.focus-dropdown` container. Auto-initialized toggles support Up/Down, menus support Home/End and Escape, and `aria-expanded` follows state. Tab leaves the disclosure normally. Removing an open dropdown closes it and releases the document click handler. Arbitrary content retains its native semantics. | | Sidebar | `init(container?, options?)`, `destroy(container?)`, `open/close/toggle(element)` | Init options: accordion (default true), scope (`sidebar` or `section`), expandActiveGroup. Open/close/toggle control sidebar visibility. Since v2.2.0 it also manages the mobile backdrop and focus. Collapsible handlers are delegated to their scope; repeated init discovers new controls and keeps the original options. Explicit nested scopes take ownership. Destroy stops that scope, even under document auto-init; init re-enables it. Detached explicit hosts are cleaned automatically. Since v2.3.0, a stale destroy handle cannot destroy a later registration. Collapsed groups are inert so hidden links cannot receive keyboard focus. Non-native collapse controls support Enter/Space and linked ARIA state. Missing or invalid selectors return null from init. | | Sidebar groups | `expand/collapse/toggleItem(element)` | Legacy item class API; current collapse controls use `data-collapse-id` with matching `collapse-...` panel IDs. Use the rendered sidebar page as the markup reference. | | Searchbar | `init(element, options?)`, `destroy/open/close/toggle(element)` | Init returns an API with destroy. Removing an initialized searchbar releases its listeners. Initialize it again after remounting. Since v2.3.0, a stale destroy handle cannot destroy a later registration. Options include globalShortcut, shortcutKey, shortcutModifier, showShortcutBadge, escapeToClose, resultNavigation and focusOnOpen. Search results are supplied by your application. | | Tables | `init(element, options?)`, `destroy(element)` | Click sortable `[data-sort]` headers to sort; init returns a destroy API. `makeSortable` is a supported compatibility alias. Options: headerSelector, bodySelector, sort icons, onSort. Since v2.3.0, a destroyed handle cannot affect a later instance. Since v2.3.0, empty `focus-table-sort-icon` containers receive built-in indicators without an icon font. Custom icon strings use the restricted empty `i` element format; other strings are rendered as text. Put a native button in each sortable header for Enter and Space. For formatted dates or currency, sort typed application data before rendering. | | TOC | `init(selector, options?)`, `update(selector)`, `destroy(selector)` | Init returns update/destroy API or null. Since v2.3.0, handles operate only on their own registration; a handle remains valid across updates until it is destroyed or replaced by a new init. Destroy before unmounting; detached TOCs do not clean up automatically. Since v2.3.0, TOCs can share headings: the most recently initialized or updated smooth-scroll TOC sets the offset until it is destroyed; original inline margins return after the last owner is destroyed, overwriting application edits made while the TOC owned them. In v2.2.0, avoid sharing headings because margin restoration is not coordinated. Options: contentSelector, headingSelector, title, scrollOffset, smoothScroll, activeClass, includeLevel. Default heading levels are 2/3. Supply stable heading IDs. | | Code | `init()`, `copy(element)` | Pass a `.focus-code` block to copy; returns Promise. Clipboard availability depends on browser permissions and a secure context. | | Theme | `get()`, `set(mode)`, `apply(mode)`, `toggle()`, `getEffective()`, `init()` | Modes: light, dark, auto. `getEffective` resolves auto to light/dark. Persistence uses localStorage. | | Forms | `validate(input, rules?)`, `check(input, rules?)`, `validateForm(form, fieldRules?)` | Validate returns `{valid,message}`; check applies state and returns boolean. Rules: required, email, minLength, maxLength, RegExp pattern, match selector, synchronous custom function. | | Forms state/submission | `setState(input, valid, message?)`, `clearState(input)`, `onSubmit(form, rules, onValid, onInvalid?)` | Values use named fields and flatten FormData to an object. Read FormData directly with `getAll` for repeated names. State helpers apply visual state; supply associated error messages and focus handling in the application. `onSubmit` adds a submit listener; v2.2.0 returns an idempotent cleanup function, or `undefined` if the form is not found. See the release boundary below. Validation is synchronous. The helper invokes callbacks without awaiting them; the application handles pending state and request errors. | The `onSubmit` cleanup return was added in v2.2.0 and is not in v2.1.1, where the method returns `void`. Callers may ignore the return for compatibility; use optional cleanup when a shared caller can run against both versions. Dispose before repeating setup or unmounting. It removes only that registration: it does not deduplicate other registrations, cancel a running callback or request, or clear validation state or form values. ```js const disposeSubmit = FocusUI.Forms.onSubmit('#projectForm', { '[name=title]': { required: true } }, data => console.log('Submit:', data)) ``` Before registering again or unmounting the form, call the saved disposer: ```js disposeSubmit?.() ``` ## Dialog configuration Confirm config: title, message, confirmText, cancelText, variant (primary, secondary, success, danger, warning, info). Delete confirmation uses entityName instead of variant. Prompt uses placeholder, defaultValue, type (text or textarea), required instead of variant. ```js try { await FocusUI.Modal.confirm({ title: 'Archive project?', message: 'You can restore it later.' }) // Perform the application action here. } catch { // User cancelled; leave application data unchanged. } const toast = FocusUI.Toast.show({ type: 'success', message: 'Saved', duration: 3000 }) // To close early: FocusUI.Toast.close(toast) ``` ## Named utilities The ESM and UMD named exports include `version`, `init`, `getElement`, `addListener`, `trapFocus`, `isMac`, `getShortcutText`, and `matchesShortcut`. `addListener` and `trapFocus` return cleanup functions. The default ESM export contains the component objects, services, version, and init; import utilities by name. See [DESIGN.md](https://focus-ui.de/ai/DESIGN.md) for application composition and [COMPONENTS.md](https://focus-ui.de/ai/COMPONENTS.md) for CSS/HTML examples. Use the documented markup and check classes against the CSS file for your selected release. # Application recipes Use a pinned published release or a local build. These snippets use the browser global after the library loads; move JavaScript to your application script for CSP-conscious integration. Server routes below are application placeholders, not a backend supplied by Focus UI. ## First consumer: client/project tracker Build one small screen: a labelled search field filters active project rows; New/Edit opens an application-owned form; Save validates, disables while pending, then reports the actual result; Archive asks for confirmation before the archive request. Use native controls and existing classes such as `focus-input`, `focus-btn`, `focus-table`, and `focus-card`. Keep records and filter state in your application. For a prototype, use in-memory sample records; add `localStorage` only when single-browser persistence is enough. Shared or sensitive client data belongs behind an authorized server API. Use ordinary input and submit handlers for filtering and editing. Keep dynamic values as text (`textContent` or DOM properties), not HTML strings. A minimal save shape is: ```js async function saveProject(form, button) { const values = Object.fromEntries(new FormData(form)) button.disabled = true const oldText = button.textContent button.textContent = 'Saving…' try { const response = await fetch('/api/projects', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(values) }) if (!response.ok) throw new Error('Save failed') FocusUI.Toast.show({ type: 'success', message: 'Project saved', icon: false }) } catch { FocusUI.Toast.show({ type: 'danger', message: 'Could not save. Try again.', icon: false }) } finally { button.disabled = false button.textContent = oldText } } ``` Call it from the form's `submit` event after preventing default submission. Validate on the server too. Keep labels associated with fields, let Tab reach every action, preserve a visible focus indicator, and test the filter/form/table at phone width. If the table needs horizontal scrolling, use a responsive wrapper or render a compact mobile list; the library does not choose that application behavior. ## Confirm, then archive Catch cancellation separately from request failures. Fetch does not reject merely because the server returns an HTTP error. ```js async function archiveProject(id) { try { await FocusUI.Modal.confirm({ title: 'Archive project?', message: 'You can restore it later.' }) } catch { return // User cancelled. } try { const response = await fetch(`/api/projects/${encodeURIComponent(id)}/archive`, { method: 'POST' }) if (!response.ok) throw new Error('Archive failed') FocusUI.Toast.show({ type: 'success', message: 'Archived' }) } catch { FocusUI.Toast.show({ type: 'danger', message: 'Could not archive. Try again.' }) } } ``` Add server-side authorization/validation and your application's CSRF/session handling. Client confirmation is a user interaction, not access control. ## Loading button ```html ``` ```js const button = document.querySelector('#save-project') button.addEventListener('click', async () => { button.disabled = true button.textContent = 'Saving…' try { const response = await fetch('/api/projects', { method: 'POST' }) if (!response.ok) throw new Error('Save failed') FocusUI.Toast.show({ type: 'success', message: 'Saved' }) } catch { FocusUI.Toast.show({ type: 'danger', message: 'Could not save' }) } finally { button.disabled = false button.textContent = 'Save project' } }) ``` ## Tabs and dropdowns Use `.focus-tab-list`, `.focus-tab` and `.focus-tab-panel`; each button/panel pair shares `data-tab`. Add the active classes to the initial pair. Use semantic tab roles and labels, then test keyboard interaction. See [COMPONENTS.md](https://focus-ui.de/ai/COMPONENTS.md) for the complete structure. Do not invent `focus-tab-link` or `focus-tab-content` classes. For a dropdown, place a button with `data-focus-dropdown` inside `.focus-dropdown`, followed by `.focus-dropdown-menu`. The browser initializer binds that attribute; a styled button by itself is insufficient. Add `aria-haspopup` and keep expanded state synchronized when your application supplies custom behavior. ## Theme ```html ``` The library binds `.focus-theme-toggle`. Do not also add an inline toggle handler, which would toggle twice. Theme modes are light/dark/auto. Storage denial falls back to session state in v2.2.0. ## Async settings form Copy the HTML into the page and the JavaScript into a separate deferred `settings.js` script. Load the assets from [Quickstart](https://focus-ui.de/ai/QUICKSTART.md). This example uses native constraint validation and a persistent error region. The application endpoint must validate and authorize each request. Adapt the URL, payload, and any CSRF protection to your server. ```html

Profile settings

``` ```js const form = document.querySelector('#settings-form') const email = form.elements.namedItem('email') const button = form.querySelector('button[type="submit"]') const error = document.querySelector('#settings-error') const status = document.querySelector('#settings-status') let saving = false function clearError() { email.removeAttribute('aria-invalid') error.textContent = '' } email.addEventListener('input', () => { clearError() status.textContent = '' }) form.addEventListener('submit', async event => { event.preventDefault() if (saving) return clearError() const data = Object.fromEntries(new FormData(form)) saving = true button.disabled = true email.readOnly = true status.textContent = 'Saving settings…' let invalidEmail = false try { const response = await fetch('/api/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) if (response.ok) { status.textContent = 'Settings saved.' } else { status.textContent = '' // This example endpoint reserves 422 for a rejected email. invalidEmail = response.status === 422 error.textContent = invalidEmail ? 'The server rejected this email address. Check it and try again.' : 'Could not save settings. Try again.' if (invalidEmail) email.setAttribute('aria-invalid', 'true') } } catch { status.textContent = '' error.textContent = 'Could not reach the server. Try again.' } finally { saving = false button.disabled = false email.readOnly = false if (invalidEmail) email.focus() } }) ``` When native validation fails, the browser reports the first invalid field and blocks the `submit` event. If you use `novalidate` with `Forms.onSubmit`, supply equivalent error associations, announcements, and focus yourself. The Forms helper does synchronous validation; the application still manages the request and waits for success before announcing it. ## Mobile project dashboard Use the same sidebar for desktop navigation and the mobile drawer. Load Focus UI CSS and the browser bundle using [Quickstart](https://focus-ui.de/ai/QUICKSTART.md), then add this CSS after the library and run the JavaScript from a deferred application script. Keep sample records in application state, or replace them with results from your own endpoint. ```css .project-dashboard { display: flex; } .project-dashboard > .focus-sidebar { flex-shrink: 0; } .project-content { flex: 1; min-width: 0; } .project-nav-toggle { display: none; } @media (max-width: 768px) { .project-nav-toggle { display: inline-flex; } .project-dashboard > .focus-sidebar:not(.focus-sidebar-open) { visibility: hidden; } } ``` ```html

Projects

Project
``` ```js const projects = [ { name: 'Atlas', budget: 100 }, { name: 'Beacon', budget: 9 } ] const currency = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) const filter = document.querySelector('#project-filter') const budget = document.querySelector('#project-budget') const rows = document.querySelector('#project-rows') const count = document.querySelector('#project-count') let direction = 1 function renderProjects() { const query = filter.value.trim().toLowerCase() const matches = projects.filter(project => project.name.toLowerCase().includes(query)) matches.sort((a, b) => direction * (a.budget - b.budget)) rows.replaceChildren() for (const project of matches) { const row = rows.insertRow() row.insertCell().textContent = project.name row.insertCell().textContent = currency.format(project.budget) } budget.setAttribute('aria-sort', direction === 1 ? 'ascending' : 'descending') count.textContent = matches.length ? `Projects shown: ${matches.length}` : 'No matching projects.' } filter.addEventListener('input', renderProjects) budget.querySelector('button').addEventListener('click', () => { direction *= -1 renderProjects() }) renderProjects() ``` This example sorts numeric budgets before formatting them. For dates, store timestamps and sort those before formatting. When loading records remotely, update the status region while loading and show a persistent error with a retry control if the request fails. # Framework integration Focus UI supplies browser CSS and JavaScript, not React/Vue packages or maintained wrappers. Download a release and serve its files under your application's `/vendor/` path, or use a pinned CDN version. Load CSS once at the application root. Import browser modules only on the client. ## React Use normal `className` markup and call library APIs from event handlers. For components with initialization APIs, initialize after mount and destroy before unmount: ```jsx import { useEffect, useRef } from 'react' // In a client-only module; /vendor contains downloaded Focus UI assets. import { Tables } from '/vendor/focus-ui.esm.js' export function ProjectTable() { const ref = useRef(null) useEffect(() => { const api = Tables.init(ref.current) return () => api?.destroy() }, []) return
Project
Example
} ``` Keep React responsible for application state. Sorting DOM rows directly is suitable for static/uncontrolled tables; for React-managed data, sort state yourself and use Focus UI's CSS. Apply the same boundary to dynamically inserted dialogs and toasts. ## Vue Use `ref`, `onMounted` and `onBeforeUnmount` to retain the element and returned initialization API. Initialize after mount; destroy before unmount. Use `class` for styling and Vue event handlers for application actions. Keep table sorting in Vue state when Vue owns the rows. ## SSR and other frameworks Server-render the CSS markup, then initialize browser behavior during client hydration. Do not import Focus UI's DOM-dependent entry point in server code. No SSR-safe runtime export is promised. Existing modal markup must use `.focus-modal-overlay` around `.focus-modal`, with `.focus-modal-body` and optional `.focus-modal-footer`; see [QUICKSTART.md](https://focus-ui.de/ai/QUICKSTART.md). # Migrate a screen to Focus UI Replace one complete workflow at a time. A client/project tracker makes a useful first slice: show active projects, filter by name or status, create and edit a record, confirm archiving, and report save success or failure. Keep the current app's data model and authorization rules. ## Map what the screen does Use these as starting points for matching intent. They are selected examples, not a complete conversion table; verify the markup and available classes in [STYLING.md](https://focus-ui.de/ai/STYLING.md) and [COMPONENTS.md](https://focus-ui.de/ai/COMPONENTS.md). | Existing pattern | Focus UI starting point | | --- | --- | | Bootstrap `.container`, `.row`, `.col-md-6` | `focus-container`, `focus-row`, `focus-col-md-6` | | Bootstrap `.btn.btn-primary` | `focus-btn focus-btn-primary` | | Bootstrap `.card` and card sections | `focus-card` with `focus-card-header`, `focus-card-body`, optional `focus-card-footer` | | Bootstrap `.form-control` | Native input with `focus-input`; pair it with a visible label | | Bootstrap `.table` | `focus-table`; add `Tables.init()` only for supported sorting | | Tailwind `flex`, `gap-4`, `p-4` | `focus-d-flex`, `focus-gap-4`, `focus-p-4` | | Tailwind button styling | `focus-btn` plus a semantic variant such as `focus-btn-primary` or `focus-btn-secondary` | | Tailwind card surface | `focus-card` and its documented sections | Do not mechanically prefix class names or translate every utility. Focus UI has its own layout, spacing, component markup, and tokens; retain small application-specific CSS where there is no direct equivalent. Its reset and base rules affect global elements, so check the host page for conflicts when both libraries are loaded. ## What Focus UI doesn't cover Focus UI supplies presentation and selected browser interactions, not application state, durable storage, authorization, server validation, or complete framework components. Keep state and requests in your application, use its authorized server API for shared data, and retain small application CSS or an existing component library where a pattern has no direct counterpart. Use native controls and application handlers for behavior the library does not provide. ## Move behavior with the markup Start with a semantic table or list and native filter/form controls. Keep filtering and the project's create/edit state in your application. On save, disable the submit button while the request is pending, restore it in `finally`, and show feedback only after the result is known. `Toast.show({ type, message })` accepts one configuration object. Handle failed HTTP responses explicitly; `fetch()` does not reject for an HTTP error status. Use `Modal.confirm()` before archiving and catch its rejection so cancellation leaves the record untouched. Confirmation is not authorization: validate and authorize the archive on the server. Keep keyboard operation native where possible: labelled inputs, buttons for actions, visible focus, and a logical heading order. Test the actual screen at narrow widths; a table may need a scroll wrapper or a different mobile presentation. For a prototype, seed records in memory and say so in the UI. `localStorage` can preserve one browser's data, but it is not shared, access-controlled, or a replacement for a server. The library does not supply storage, routes, validation policy, or backend behavior. ## Check one slice before expanding Verify empty and filtered results, invalid input, pending/success/error states, archive cancel/confirm, keyboard use, narrow screens, and light/dark themes. Remove old handlers for migrated controls so one action has one owner. In a framework, let that framework own application state and initialize/destroy Focus UI behavior with the component lifecycle; see [FRAMEWORKS.md](https://focus-ui.de/ai/FRAMEWORKS.md). These lifecycle examples target v2.2.0; v2.0.0 does not contain all of those APIs. See [API.md](https://focus-ui.de/ai/API.md) for the version boundary.