# UI State Machine Pattern

## Objective

Replace tangles of independent flags with one named state per interaction.

Explicit states and permitted transitions for the interactions that currently rely on several booleans at once.

## Before You Begin

This feature is being added to an application that already exists and already
works. Do not scaffold a new project, and do not assume a blank slate.

Inspect the codebase first and establish:

- The existing application structure and where code of this kind already lives.
- The framework and version in use.
- The existing design system — colours, spacing, typography, and component conventions.
- Existing UI components you can reuse instead of writing new ones.
- The existing database structure, if this feature needs to persist anything.
- The existing authentication and authorization system, if this feature is user-scoped.
- Dependencies already installed, so you don't add a library that duplicates one.
- The existing test setup and conventions.

Only start writing code once you understand the above. If the application
already implements part of this feature, extend it rather than replacing it.

## Implementation Instructions

1. Find the interactions carrying three or more independent flags — submitting, loading, error, dirty, saved, disabled — and rewrite each as a single value that can only ever hold one named state.
2. Enumerate the permitted transitions rather than the states alone, and reject anything not listed. Most interface bugs of this kind are not a wrong state but a transition nobody expected, such as a response arriving after the user cancelled.
3. Drive every rendered detail from the current state — button label, disabled state, error text, focus — so there is exactly one place to look when the screen and reality disagree.
4. Trigger requests, timers, and navigation as effects of entering a state, and tear them down on leaving it, so a cancelled transition cannot leave a request or a countdown running.
5. This entry owns the shape of the machine. Where an interaction is a request-backed region, hand its states to Async Boundary Component for rendering rather than drawing loading and error treatments here.

## UI and UX Requirements

Match the application's existing design system exactly. Reuse its components,
spacing, and typography. This feature should look like it was always there.

## Responsive Requirements

Works on mobile, tablet, and desktop. Touch targets are large enough to hit on a
phone, and nothing overflows horizontally at 320px.

## Accessibility Requirements

- Fully keyboard navigable.
- Correct semantic elements and ARIA roles.
- Visible focus states.
- Meets WCAG AA contrast.
- Dynamic changes are announced to screen readers.
- Respects prefers-reduced-motion.

## Edge Cases

- Combinations that should never exist — submitting and showing a success message, loading and displaying an error, disabled and pending at once — become unrepresentable once there is a single state value, and that is the point of the change.
- Cancel, retry, and timeout are transitions like any other and must be enumerated. A retry from a failed state and a retry from a timed-out state may need different behaviour, and a cancel arriving mid-request must have a defined destination.
- Effects belong to states, not to arbitrary code paths. A request fired from a click handler rather than from entering a state will keep running after the user has moved on and will write its result into a screen that no longer exists.
- The current state must be readable from the outside for tests and for debugging, without inferring it from rendered text. A test asserting on a spinner's presence is testing the theme, not the behaviour.
- A late response from a superseded transition must be discarded rather than applied, or a slow first attempt will overwrite the result of the retry that replaced it.
- Do not model an entire screen as one machine. Several small machines that each own one interaction are easier to reason about than a single one with forty states.
- Optimistic transitions need a defined path back — the state the interface returns to when the server rejects what it already showed as done.

## Testing

Exercise the feature end to end in the running application. Cover every edge case
above, then run the existing test suite and confirm nothing regressed.

## Acceptance Criteria

- [ ] Each converted interaction holds exactly one named state, with no residual independent boolean flags.
- [ ] Permitted transitions are enumerated and anything outside the list is rejected.
- [ ] Cancel, retry, and timeout are explicit transitions with defined destinations.
- [ ] Requests and timers start on entering a state and are torn down on leaving it.
- [ ] Responses from superseded transitions are discarded rather than applied.
- [ ] The current state is inspectable directly by tests without reading rendered markup.
- [ ] Rendering of request-backed states is delegated to Async Boundary Component.
- [ ] The feature matches the existing design system.
- [ ] No existing functionality is broken.

## Adaptation Rules

- Match the existing design system. Do not introduce a new colour palette,
  spacing scale, or component library.
- Reuse existing components and utilities wherever they fit.
- Follow the naming, file layout, and code style already present.
- Do not upgrade, replace, or remove existing dependencies to make this
  feature fit. Adapt the feature to the app, not the app to the feature.
- Do not break existing functionality. If a change is genuinely required in
  existing code, make the smallest one that works and say so.
- If something in these instructions conflicts with how the application is
  built, follow the application and explain the deviation.

## Final Verification

Before you report the work as done:

1. Re-read the acceptance criteria above and check each one against what you
   actually built.
2. Run the application and exercise the feature end to end.
3. Run the existing test suite and confirm you have broken nothing.
4. Check the feature on mobile, tablet, and desktop widths.
5. Check keyboard navigation and focus handling.
6. Summarize what changed: files added, files modified, and anything you
   deliberately did differently because of how this application is built.

If any acceptance criterion is unmet, fix it before reporting completion.
