Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
4718466
docs: updated documentation of reactive-controllers
Oct 13, 2025
d703c09
Merge branch 'main' into rajdeep/swc-429
Rajdeepc Oct 15, 2025
fb835a8
docs: updated main readme to align with doc standard
Oct 16, 2025
442dfd6
Merge branch 'rajdeep/swc-429' of https://github.com/adobe/spectrum-w…
Oct 16, 2025
fdc8571
docs: updated color controller readme to align with doc standard
Oct 16, 2025
60df8b0
docs: updated dependency controller readme to align with doc standard
Oct 16, 2025
aa88fc4
docs: updated element resolution controller readme to align with doc …
Oct 16, 2025
cc621ec
docs: updated match media controller readme to align with doc standard
Oct 16, 2025
2584cab
docs: updated pending state controller readme to align with doc standard
Oct 16, 2025
a0eb897
docs: updated pending roving tab index controller readme to align wit…
Oct 17, 2025
3dc61ac
Merge branch 'main' into rajdeep/swc-429
Rajdeepc Oct 17, 2025
5ff113f
Merge branch 'main' of https://github.com/adobe/spectrum-web-componen…
Oct 20, 2025
b1e1e41
docs: updated the element resolution example with form field logic
Oct 20, 2025
f31137d
docs: updated element resolution modal overlay example to show the us…
Oct 20, 2025
63ab40f
docs: added new language resolution controller readme
Oct 20, 2025
b3b3459
docs: removed commented code in main readme
Oct 20, 2025
22a5a1c
docs: update docs for the disabled items in robing tab index controller
Oct 20, 2025
7a6c840
docs: removed screen reader section in roving tab index
Oct 20, 2025
38c4ad4
Merge branch 'rajdeep/swc-429' of https://github.com/adobe/spectrum-w…
Oct 20, 2025
746a320
chore: fix up review comments on verbs and script tags
Oct 24, 2025
5bd78cb
chore: added system context controller readme
Oct 24, 2025
6b98e9e
chore: main readme formatting fix
Oct 24, 2025
1811ade
Merge branch 'main' into rajdeep/swc-429
Rajdeepc Oct 26, 2025
9e6283a
Merge branch 'main' into rajdeep/swc-429
Rajdeepc Oct 27, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
334 changes: 323 additions & 11 deletions tools/reactive-controllers/README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,326 @@
## Description
## Overview

[Reactive controllers](https://lit.dev/docs/composition/controllers/) are a tool for code reuse and composition within [Lit](https://lit.dev), a core dependency of Spectrum Web Components. Reactive controllers can be reused across components to reduce both code complexity and size, and to deliver a consistent user experience. These reactive controllers are used by the Spectrum Web Components library and are published to NPM for you to leverage in your projects as well.
[Reactive controllers](https://lit.dev/docs/composition/controllers/) are a powerful tool for code reuse and composition within [Lit](https://lit.dev), a core dependency of Spectrum Web Components. They enable you to extract common behaviors into reusable packages that can be shared across multiple components, reducing code complexity and size while delivering a consistent user experience.

### Reactive controllers
### Usage

- [ColorController](../color-controller)
- [ElementResolutionController](../element-resolution)
- FocusGroupController
- LanguageResolutionController
- [MatchMediaController](../match-media)
- [RovingTabindexController](../roving-tab-index)
- [PendingStateController](../pending-state)
- SystemContextResolutionController
```bash
yarn add @spectrum-web-components/reactive-controllers
```

Reactive controllers are instantiated in your component and automatically hook into the component's lifecycle:

```typescript
import { LitElement, html } from 'lit';
import { MatchMediaController } from '@spectrum-web-components/reactive-controllers/src/MatchMedia.js';

class MyComponent extends LitElement {
// Create controller instance
darkMode = new MatchMediaController(this, '(prefers-color-scheme: dark)');

render() {
// Use controller state in render
return html`
<div class=${this.darkMode.matches ? 'dark' : 'light'}>Content</div>
`;
}
}
```

### Controller lifecycle

Reactive controllers implement the `ReactiveController` interface with the following optional lifecycle methods:

- **`hostConnected()`**: Called when the host element is connected to the DOM
- **`hostDisconnected()`**: Called when the host element is disconnected from the DOM
- **`hostUpdate()`**: Called before the host's `update()` method
- **`hostUpdated()`**: Called after the host's `update()` method

Controllers can also call `host.requestUpdate()` to trigger an update cycle on the host element.

### Creating your own controllers

You can create custom reactive controllers by implementing the `ReactiveController` interface:

```typescript
import { ReactiveController, ReactiveElement } from 'lit';

export class MyController implements ReactiveController {
private host: ReactiveElement;

constructor(host: ReactiveElement) {
this.host = host;
// Register this controller with the host
this.host.addController(this);
}

hostConnected() {
// Called when host is connected to DOM
}

hostDisconnected() {
// Called when host is disconnected from DOM
}
}
```

### Available controllers

#### ColorController

Manages and validates color values in various color spaces (RGB, HSL, HSV, Hex). Provides conversion between formats and state management for color-related interactions.

**Use cases:**

- Color pickers and selectors
- Color input validation
- Color format conversion
- Theme customization UIs

**Key features:**

- Multiple color format support (hex, RGB, HSL, HSV)
- Color validation
- Format preservation
- Undo/redo support

[Learn more →](../color-controller)

---

#### DependencyManagerController

Manages the availability of custom element dependencies, enabling lazy loading patterns and progressive enhancement strategies.

**Use cases:**

- Code splitting and lazy loading
- Progressive enhancement
- Route-based component loading
- Conditional feature loading

**Key features:**

- Tracks custom element registration
- Reactive loading state
- Multiple dependency management
- Works with dynamic imports

[Learn more →](../dependency-manager)

---

#### ElementResolutionController

Maintains an active reference to another element in the DOM tree, automatically tracking changes and updating when the DOM mutates.

**Use cases:**

- Accessible label associations
- Focus trap management
- Form validation connections
- Dynamic element relationships

**Key features:**

- Automatic DOM observation
- ID selector optimization
- Shadow DOM support
- Reactive updates

[Learn more →](../element-resolution)

---

#### FocusGroupController

Base controller for managing keyboard focus within groups of elements. Extended by `RovingTabindexController` with tabindex management capabilities.

**Use cases:**

- Custom composite widgets
- Keyboard navigation patterns
- Focus management

**Key features:**

- Arrow key navigation
- Configurable direction modes
- Focus entry points
- Element enter actions

**Note:** This controller is typically not used directly. Use `RovingTabindexController` instead for most use cases.

---

#### LanguageResolutionController

Resolves and tracks the language/locale context of the host element, responding to changes in the `lang` attribute up the DOM tree.

**Use cases:**

- Internationalization (i18n)
- Localized content
- RTL/LTR text direction
- Locale-specific formatting

**Key features:**

- Automatic language detection
- Locale change tracking
- Supports Shadow DOM
- Bubbles up DOM tree

---

#### MatchMediaController

Binds CSS media queries to reactive elements, automatically updating when queries match or unmatch.

**Use cases:**

- Responsive design
- Dark mode detection
- Mobile/desktop layouts
- Print styles
- Accessibility preferences (prefers-reduced-motion, etc.)

**Key features:**

- Multiple media query support
- Reactive updates
- Predefined queries (DARK_MODE, IS_MOBILE)
- Event-driven

[Learn more →](../match-media)

---

#### PendingStateController

Manages pending/loading states for interactive elements, providing visual feedback and accessible state communication.

**Use cases:**

- Async button actions
- Form submission states
- Loading indicators
- Progress feedback

**Key features:**

- Automatic ARIA label management
- Progress circle rendering
- Label caching and restoration
- Disabled state awareness

**Note:** Currently used primarily by Button component. May be deprecated in future versions.

[Learn more →](../pending-state)

---

#### RovingTabindexController

Implements the W3C ARIA roving tabindex pattern for keyboard navigation in composite widgets, managing `tabindex` attributes and arrow key navigation.

**Use cases:**

- Toolbars
- Tab lists
- Menus
- Radio groups
- Listboxes
- Grids

**Key features:**

- Arrow key navigation (with Home/End support)
- Automatic tabindex management
- Flexible direction modes (horizontal, vertical, both, grid)
- Skips disabled elements
- WCAG compliant

[Learn more →](../roving-tab-index)

---

#### SystemContextResolutionController

Resolves and tracks system-level context like color scheme and scale preferences from Spectrum theme providers.

**Use cases:**

- Theme integration
- Scale-aware components
- System preference detection
- Spectrum theme consumption

**Key features:**

- Automatic theme context resolution
- Color scheme tracking
- Scale preference tracking
- Works with Spectrum theme providers
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add a page for this one with examples.


<!-- ### Best practices
#### Composition over inheritance
Use reactive controllers to share behavior across components instead of extending base classes:
```typescript
// Good: Composition with controllers
class ButtonA extends LitElement {
pending = new PendingStateController(this);
}
class ButtonB extends LitElement {
pending = new PendingStateController(this);
}
// Avoid: Inheritance
class BaseButton extends LitElement {
// shared pending logic
}
class ButtonA extends BaseButton {}
class ButtonB extends BaseButton {}
```
#### Keep controllers focused
Each controller should have a single responsibility:
```typescript
// Good: Focused controllers
darkMode = new MatchMediaController(this, '(prefers-color-scheme: dark)');
isMobile = new MatchMediaController(this, '(max-width: 768px)');
// Avoid: One controller doing too much
```
#### Clean up resources
Always clean up in `hostDisconnected()`:
```typescript
hostConnected() {
window.addEventListener('resize', this.handleResize);
}
hostDisconnected() {
window.removeEventListener('resize', this.handleResize);
}
```
#### Request updates appropriately
Only call `host.requestUpdate()` when state that affects rendering changes:
```typescript
set value(newValue: string) {
if (newValue === this._value) return;
this._value = newValue;
this.host.requestUpdate(); // Only when value actually changes
}
``` -->
Loading
Loading