# 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
<button id="save-project" type="button" class="focus-btn focus-btn-primary">Save project</button>
```

```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
<button type="button" class="focus-btn focus-theme-toggle" aria-label="Change theme">Theme</button>
```

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
<form id="settings-form" class="focus-card">
  <div class="focus-card-body">
    <h1 class="focus-card-title">Profile settings</h1>
    <div class="focus-form-group">
      <label class="focus-form-label" for="settings-email">Email address</label>
      <input class="focus-input" id="settings-email" type="email" name="email"
        autocomplete="email" aria-describedby="settings-error" required>
    </div>
    <p id="settings-error" class="focus-text-danger" role="alert"></p>
    <button class="focus-btn focus-btn-primary" type="submit">Save settings</button>
    <p id="settings-status" class="focus-mt-2 focus-mb-0" role="status"></p>
  </div>
</form>
```

```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
<div class="project-dashboard">
  <aside class="focus-sidebar" id="project-navigation">
    <nav class="focus-sidebar-nav" aria-label="Project navigation">
      <a class="focus-sidebar-item focus-sidebar-item-active" href="#projects" aria-current="page">Projects</a>
      <a class="focus-sidebar-item" href="/settings">Settings</a>
    </nav>
  </aside>
  <main class="project-content focus-p-3" id="projects">
    <button class="project-nav-toggle focus-btn focus-btn-outline" type="button"
      data-focus-sidebar-mobile="project-navigation" aria-controls="project-navigation"
      aria-expanded="false">Open navigation</button>
    <h1>Projects</h1>
    <div class="focus-form-group">
      <label class="focus-form-label" for="project-filter">Filter by name</label>
      <input class="focus-input" id="project-filter" type="search">
    </div>
    <p id="project-count" role="status"></p>
    <div class="focus-table-responsive" tabindex="0" role="region" aria-label="Project budgets">
      <table class="focus-table focus-table-striped">
        <thead>
          <tr>
            <th scope="col">Project</th>
            <th scope="col" id="project-budget" aria-sort="ascending">
              <button class="focus-btn focus-btn-sm focus-btn-outline" type="button">Budget</button>
            </th>
          </tr>
        </thead>
        <tbody id="project-rows"></tbody>
      </table>
    </div>
  </main>
</div>
```

```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.
