# 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<boolean>. 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.
