Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
docs: make the UI/UX guide a standing rule for every interface change
spacesdriveaebdec6cdc41
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 064161f..519474f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -33,6 +33,12 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Changed+- The app and the public site follow the Laws of UX and WCAG 2.2 AA (#132, ADR-047): reading text and inputs are 16 px, controls are 44 px on touch screens, every page has its own tab title, focus moves to the page heading after navigation, and tabs, searches, filters, sort and page live in the address so Back, refresh and shared links keep the view+- Field errors show under the field and keep what was typed; error toasts stay until closed; a failed load shows what failed with Try again instead of an empty list+- Small deletes act at once with an Undo toast for 8 seconds; removing an account or deleting everything confirms with a choice that needs no press and hold+- `/upload` is now `/publish` and `/reels` is now `/instagram`; the old addresses redirect+- Public site: a plain headline ("YouTube, Instagram and Reddit analytics in one dashboard") and buttons that name what they do, comment automation named on the home page and in the Product menu, a Pause animations control for the looping previews, keyboard and screen reader fixes (white focus on red bands, the phone docs menu as a real dialog, announced search results and copy status, focus on the new page heading, focusable code and table scroll boxes, an outline on phones), and a real 404 status for unknown paths+- An unknown address shows a Page not found page with links back, the sidebar lists Your accounts and Categories before Manage with a Show all toggle, Help sits in the top bar, and the theme switch and second Refresh left the top bar- The README recordings are animated WebP instead of GIF: 8.3 MB for all seven instead of 35.5 MB, so the repository page loads in a fraction of the time, with smoother motion and full colour (#129)- Connecting an Instagram account that is already connected renews its token instead of answering that it is already added, so a revoked token can be fixed without removing the account (#89)- The Worker's publishing cron runs every 5 minutes instead of 15; posts still publish on the quarter hour, and the other runs check the reply queue (#89, #100)diff --git a/CLAUDE.md b/CLAUDE.mdindex c8ed6a4..953288c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -71,10 +71,11 @@ Before implementing any feature or fix, read these documents in this exact order4. `docs/architecture/OVERVIEW.md` - system topology and request flow5. `docs/guidelines/TYPESCRIPT.md` - code standards and typing rules (always apply)6. `docs/guidelines/CODE_STYLE.md` - how code reads here: layer shapes, comments, naming, messages, tests (always apply; its checklist runs before every commit)-7. Relevant architecture doc - backend, frontend, site, database, or cloudflare-8. Relevant feature guide - if one exists in `docs/features/`-9. Relevant engineering guideline - if the task touches a specific layer-10. `ROADMAP.md` - if the task is a planned item, link its issue there+7. `docs/guidelines/UI_UX.md` - the UI and UX rules: Laws of UX, WCAG 2.2 AA, every state, the reference dashboard patterns (always apply when the task touches anything people see or use, in the app or the site, however small; its checklist runs before every such commit)+8. Relevant architecture doc - backend, frontend, site, database, or cloudflare+9. Relevant feature guide - if one exists in `docs/features/`+10. Relevant engineering guideline - if the task touches a specific layer+11. `ROADMAP.md` - if the task is a planned item, link its issue thereFor MCP usage, read `docs/mcp/OVERVIEW.md` before using any MCP server.@@ -122,6 +123,7 @@ docs/AUTOMATION.md Comment webhook, keyword rules, reply queue, limits and failure handlingguidelines/CODE_STYLE.md How code reads: the shapes to copy per layer, comments, naming, messages, tests, pre-commit checklist+ UI_UX.md UI and UX rules for every interface change: sources, how to work a UI task, laws, states, reference dashboard patterns, checks, checklistTYPESCRIPT.md Compiler settings, typing rules, where types live, code style, comments policyREACT.md Component rules, hooks, JSX conventionsHONO.md Route handlers, middleware, context usage@@ -180,6 +182,7 @@ Read `docs/WRITING_STANDARDS.md` for the full specification. The non-negotiable- One comment per non-obvious logic block, maximum - never restate what the code does- Every page must feel like it belongs to the same application: consistent padding, cards, skeletons, toasts, icons- All styling goes through the design tokens in `frontend/src/index.css` and the shared components listed in `docs/architecture/frontend/DESIGN_SYSTEM.md`; no hex or Tailwind palette colours in components+- The interface follows the Laws of UX and WCAG 2.2 AA (ADR-047): keyboard and screen reader access, 16 px reading text, 44 px touch targets, view state in the address, every data state designed (loading, empty, error, partial, stale), one primary action per view; the rules are in `docs/architecture/frontend/DESIGN_SYSTEM.md` (Rules)- Brand assets (logos, fonts, tokens, guidelines) live in `frontend/public/` (the public site keeps copies in `site/public/brand/` and `site/public/fonts/`, and `docs/brand-notes.md` records what it takes from the kit); sentence case in UI copy, no exclamation marks---@@ -207,7 +210,7 @@ Read `docs/guidelines/CODE_STYLE.md` before writing code and run its checklist b- Match the nearest existing file of the same kind before inventing a shape: open a sibling and copy its imports, exports, naming and comment density- One job per file and per layer: route tables map, controllers translate HTTP, services decide, repositories query, components render, `lib/` helpers compute; services are `createXService(deps)` factories with an `XService` and an `XDeps` interface- Comments explain why in one lowercase line above the code; never restate the code, reference a task, or write JSDoc or multi-line blocks; a constant with a number in it gets its reason-- Backend failures are typed errors from `lib/errors.ts` with a message a person can act on; frontend failures are toasts that start with what failed (`Couldn't save the password.`) and add the reason; success toasts confirm in past tense (`Password saved`)+- Backend failures are typed errors from `lib/errors.ts` with a message a person can act on; a field the person can fix shows its error under the field (`FieldRow error`), a failed load shows `ErrorState`, and a failed request is a toast that starts with what failed (`Couldn't save the password.`) and adds the reason; success toasts confirm in past tense (`Password saved`)- Formatting follows the file: 4 spaces in `backend/`, 2 elsewhere, single quotes, semicolons, trailing commas- Pure logic goes in a plain `.ts` helper (`lib/`) so Node can test it; markup used twice becomes a component; copy that changes by mode lives in a typed table- `scripts/` stays free of npm packages but may import a `backend/lib/` helper that imports nothing at runtime, so both schedulers share one set of rules (`scheduledPublishing.ts`)@@ -296,6 +299,8 @@ This is not optional for features that touch new UI patterns, new APIs, or new i**Open the issue first.** No task starts without a GitHub issue, and no task is reported as done while its issue is still open. See Issue Tracking above and `docs/workflows/ISSUES.md`.+**Apply the UI/UX guide to every interface change.** Any task that adds or changes something people see or use, in `frontend/` or `site/`, follows `docs/guidelines/UI_UX.md`, including small updates such as a new button, message or column: name the users, tasks and states, pick the laws that apply, reuse the design system, design every state, and run its checks and checklist before committing. With the ProfileBox MCP available, also load the `ui-ux-design-intelligence` system for the task (`get_system_instructions_for_task`). WCAG 2.2 AA is the floor; the project's design system and brand win over any reference.+**Always read before writing.** Read every file you will modify. Read all files in the same directory that might be affected. Read sibling files to understand conventions before adding new ones.**Match the existing pattern.** This project has established conventions for route tables, controllers, services, repositories, validators, context hooks and api.ts methods. Find the nearest existing example and follow it exactly before introducing anything new.@@ -410,6 +415,7 @@ When anything changes, update every relevant docs file from the table below. The| Release tagged | `CHANGELOG.md` (convert Unreleased to version number with date), a GitHub Release page for the tag (`docs/workflows/GIT.md`, Release notes) || Any planned feature added or changed | `ROADMAP.md` || Writing or design rule changed | `docs/WRITING_STANDARDS.md`, this file (Writing and Design Standards section) |+| UI or UX rule changed (a law applied differently, a new state rule, a reference pattern adopted) | `docs/guidelines/UI_UX.md`, `docs/architecture/frontend/DESIGN_SYSTEM.md` (Rules), this file (AI Operating Rules) || Code style or a layer's shape changed (a new pattern to copy, a naming, comment or message rule) | `docs/guidelines/CODE_STYLE.md`, the guideline it details (`TYPESCRIPT.md`, `REACT.md`, `HONO.md`, `NAMING.md`), this file (Code Style section) || MCP usage rule changed | `docs/mcp/OVERVIEW.md`, this file (MCP Usage Rules section) || Engineering standard changed | `docs/philosophy/ARCHITECTURE.md`, this file (Engineering Standards section) |diff --git a/DECISIONS.md b/DECISIONS.mdindex 1b4ed67..e761f7e 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -1012,3 +1012,31 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts- The tree is a snapshot, so it is right only after `db:push` and `db:schema`; the test catches a missing object, not a changed column.- The tree is exported from the linked database, so a self-hoster refreshing it needs the CLI linked to their project.- Changing only the comments of applied files leaves their SQL byte for byte the same, which the CLI does not compare, so production is unaffected.++## ADR-047: The interface follows the Laws of UX and WCAG 2.2 AA, with 16 px reading text++**Date:** 2026-11-04+**Status:** Accepted++**Decision:** The app and the public site follow the UI/UX Design Intelligence system: the Laws of UX, WCAG 2.2 AA, heuristic evaluation and its guidelines for dashboards, forms, interaction, navigation, responsive layouts and data views (#132). An audit of both found 131 problems, and they were fixed in one change. The owner made four calls where the system and earlier choices differed:+- Reading text (page descriptions, help, settings copy) and inputs are 16 px. Tables, navigation, chips and labels stay at the measured 14 px.+- The automation rule editor is a page with its own address, not a dialog.+- Small, frequent deletes (stop tracking, delete a rule, remove a scheduled post record) act at once with an Undo toast. Removing an account and deleting everything still confirm, with a way to confirm that needs no press and hold.+- `/upload` became `/publish` and `/reels` became `/instagram`, with redirects, so the address matches the label.++**Context:** The design reference chose 14 px body text for density, and errors were shown in toasts that closed after four seconds. Several pages lost their view on refresh, showed a failed load as an empty list, and showed cached data as current. A code audit against the system's checklists found these, with a severity for each.++**Why:** WCAG 2.2 AA is a floor, not a preference: errors tied to fields, status messages announced, keyboard and touch targets, and colour never the only signal. The laws are used as reasons where their evidence fits the task, for example Fitts's Law for touch targets and Working Memory for keeping view state and exact values visible.++**Alternatives considered:**+- Keeping 14 px everywhere. It reads well on a desktop monitor, but help text at 12 to 13 px was hard to read and 16 px is the web default for reading.+- Keeping the rule editor as a dialog with a discard warning. A 15-field form with a preview and a test is long work, and a page gives it Back, a shareable address and room on a phone.+- Hold-to-confirm for every delete. Frequent confirmations teach people to push through them, and voice-control and switch users often cannot hold.++**Site specifics:** the public site's previews loop for as long as they are on screen, so it has its own Pause animations control (a `data-motion` attribute on the root, saved in `localStorage`), as WCAG 2.2.2 requires beyond the operating system's reduced-motion setting. Unknown paths get a real 404: the build writes `dist/404.html`, and `_redirects` rewrites `/docs` and `/docs/*` to `index.html` because a top-level `404.html` turns off Pages' single-page fallback.++**Trade-offs:**+- The app is a little less dense where reading text sits.+- A mistyped docs address still answers 200, and a new top-level page on the site needs a rewrite line.+- A delete reaches the server 8 seconds late; leaving the page sends any waiting delete at once.+- Old `/upload` and `/reels` links keep working only through the redirects.diff --git a/docs/WRITING_STANDARDS.md b/docs/WRITING_STANDARDS.mdindex 243aebd..1fbc50d 100644--- a/docs/WRITING_STANDARDS.md+++ b/docs/WRITING_STANDARDS.md@@ -90,6 +90,7 @@ Write from the user's perspective, not the system's internals.- Error messages explain what went wrong and what to do: "Instagram token expired - reconnect your account" not "Authentication error"- No apologies in error messages- No vague messages like "Something went wrong"+- A link that opens a new tab carries a screen-reader-only "(opens in a new tab)"---@@ -115,10 +116,10 @@ Maintain:- One `PageHeader` per page; the app shell provides page padding- Consistent vertical rhythm (`flex flex-col gap-6` between sections)- Consistent containers (`SurfaceBox`, `MetricBox`) and design tokens only, no palette colours-- Consistent loading states (`PageSkeleton`, `Skeleton`), empty states (`EmptyState`) and error display (toasts via `showToast`)+- Consistent loading states (`PageSkeleton`, `Skeleton`), empty states (`EmptyState`), field errors under their field (`FieldRow error`), load failures in place (`ErrorState`) and request failures in toasts (`showToast`)- Consistent icon usage (Lucide, 1.75 stroke)- Consistent button variants (default for the main action, outline for secondary, ghost for tertiary)-- Destructive actions confirmed with `ConfirmDialog` and `hold`+- Small, frequent deletes act at once with an Undo toast (`deleteWithUndo`); removing an account and deleting everything confirm with `ConfirmDialog`, with a way to confirm that needs no press and hold- Sentence case in all UI copy, and no exclamation marksSee `docs/architecture/frontend/DESIGN_SYSTEM.md` and `docs/design-reference.md`.diff --git a/docs/architecture/frontend/DESIGN_SYSTEM.md b/docs/architecture/frontend/DESIGN_SYSTEM.mdindex 27f0877..9f933c8 100644--- a/docs/architecture/frontend/DESIGN_SYSTEM.md+++ b/docs/architecture/frontend/DESIGN_SYSTEM.md@@ -15,9 +15,9 @@ All tokens live in `frontend/src/index.css`: raw values on `:root` and `.dark`,| Brand | `bg-brand`, `hover:bg-brand-hover`, `bg-brand-soft`, `text-brand-text`, `text-on-brand` | Red as text is always `text-brand-text` || Status | `success`, `warning`, `danger`, `info`, each with `-soft` | Errors share the brand red, so they always carry an icon and the word "Error" || Charts | `var(--chart-1)` to `var(--chart-5)` via `lib/chart.ts` `SERIES` | Brand series order; platforms map to series in `lib/accounts.ts` |-| Type | `font-heading` (Sora), `font-sans` (Manrope), `font-mono` (JetBrains Mono); `text-display`, `text-page-title`, `text-section`, `text-body`, `text-small`, `text-caption` | Fonts are self-hosted from `frontend/public/fonts` and preloaded in `index.html` |+| Type | `font-heading` (Sora), `font-sans` (Manrope), `font-mono` (JetBrains Mono); `text-display`, `text-page-title`, `text-metric`, `text-section`, `text-body`, `text-small`, `text-caption` | Reading text (page descriptions, help, settings copy) and inputs are `text-body`, 16 px with a 1.5 line height; tables, navigation, chips and labels use `text-sm` (14 px); nothing readable is below `text-caption` (12 px). Paragraphs of help keep `max-w-prose`. Fonts are self-hosted from `frontend/public/fonts` and preloaded in `index.html` || Radius | `rounded-row` 10, `rounded-control` 10, `rounded-field` 12, `rounded-card` 16, `rounded-panel` 24, `rounded-dialog` 24, `rounded-pill` | Buttons, inputs and chips are rounded rectangles; badges keep the brand capsule |-| Sizes | `h-(--control-h-sm)` 32, `h-(--control-h)` 36, `h-(--control-h-lg)` 40, `--nav-row-h` 32, `--topbar-h` 50, `--sidebar-w` 256 | |+| Sizes | `h-(--control-h-sm)` 32, `h-(--control-h)` 36, `h-(--control-h-lg)` 40, `--nav-row-h` 32, `--topbar-h` 50, `--sidebar-w` 256 | On a touch screen (`pointer: coarse`) controls and nav rows grow to 44 px (small controls to 40) so a finger can hit them; `--focus-clearance` keeps a focused element clear of the sticky top bar || Motion | `duration-(--duration-fast)` 75ms, `--duration-base` 150ms, `--duration-overlay` 200ms, `animate-fold-in` 220ms | `prefers-reduced-motion` collapses all motion |`TabsList` has three variants: `default` (underline tabs), `segmented` (a pill control) and `none` (no list styling, for layouts such as the Overview metric tiles that style each trigger themselves).@@ -31,7 +31,7 @@ Shared components live in `frontend/src/components/`. Reach for these before wri| Component | Use it for ||---|---|| `PageHeader` | The one title block per page: optional back link, eyebrow, avatar media, description and actions |-| `SurfaceBox` | Any grouped content. Optional title row with `subheader` and `secondary` actions |+| `SurfaceBox` | Any grouped content. Optional title row with `subheader` and `secondary` actions. The title is an `h2` (pass `headingLevel="h3"` inside a section), and a `Table` inside takes its accessible name from it || `MetricBox` | A single metric: icon, label, tabular value, one line of context. `highlight` marks the page's lead metric || `SectionHeader` | A heading between groups of boxes || `ListRow`, `RankNumber` | Dense clickable rows and mono rank numbers |@@ -43,8 +43,12 @@ Shared components live in `frontend/src/components/`. Reach for these before wri| `ChartPanel` | A titled Recharts container with an empty state || `MetricAreaChart` | A single-series area chart || `ChoiceCard` | Large selectable cards in creation flows |-| `DetailPanel`, `FieldRow` | The settings side panel of a working surface, and label plus hint plus control rows |-| `ConfirmDialog` | Confirmation. Pass `hold` for destructive actions |+| `DetailPanel`, `FieldRow` | The settings side panel of a working surface, and label plus hint plus control plus error rows. `FieldRow` wires `hint` and `error` to its control (`aria-describedby`, `aria-invalid`), marks `optional` fields, and renders a `fieldset` with `group` |+| `ConfirmDialog` | Confirmation for removing an account and deleting everything. Pass `hold`; it also offers a way to confirm without holding |+| `deleteWithUndo` (`lib/undoToast.ts`) | Small, frequent deletes: hide the item, show an Undo toast for 8 seconds, then send the delete |+| `Num` | A rounded figure (12.4K) with the exact value on hover and for screen readers |+| `RelativeTime` | "2h ago" in a `<time>` with the exact date and time on hover and for screen readers; dates older than a month show as dates |+| `LiveStatus` | A status line that stays mounted, so result counts and progress are announced || `HoldToConfirmButton` | Press and hold (pointer or Space or Enter) to confirm; a click never fires it || `CommandPalette` | Ctrl+K or Cmd+K search over pages, accounts, categories and actions || `EmptyState`, `ErrorState`, `LoadingState`, `PageSkeleton` | Every data view needs all of these |@@ -66,8 +70,21 @@ Shared components live in `frontend/src/components/`. Reach for these before wri## Rules+The interface follows the UI/UX Design Intelligence system: the Laws of UX, WCAG 2.2 AA and its practical guidelines (ADR-047). How to work a UI task, the full rules, the reference dashboard patterns and the checks are in `docs/guidelines/UI_UX.md`; the rules below are the short version.++- WCAG 2.2 AA is the floor: every action works by keyboard with a visible focus ring, every control has a name that contains its visible label, colour is never the only signal (status, trend, links in text, chart series), and status changes are announced (`LiveStatus`, `role="alert"` for a message that appears after an action; static `Alert` notes stay silent).+- Each page has a title in the browser tab (detail pages name the item with `useDocumentTitle(name)`), focus moves to the `PageHeader` heading after navigation (add no other focus target), and the view (tab, search, filters, sort, page, layout) lives in the address through `useUrlState`, so Back, refresh and a shared link show the same view.+- One primary (default) button per view. An empty state's action replaces the header action, it does not repeat it.+- Every data view designs loading, empty, error, partial failure and stale states, and says how old cached data is. Refreshing keeps the data on screen with a progress bar; skeletons are only for the first load.+- Metric tiles say what period they cover, show the exact value behind a rounded one, and colour a change by whether it is good, with the direction in words for screen readers.+- Charts have a one-line summary and a table of the same data; a chart never mixes two units on one axis.+- Field errors appear under the field and keep the input; buttons stay enabled and explain what is missing when pressed; leaving a form with unsaved work asks first.+- Help text and descriptions are short, in the user's words, and next to the thing they explain.+- Dialogs become full-width bottom sheets below `sm`. Link-styled buttons are always underlined, and a link that opens a new tab says so to screen readers.+- `cn()` knows the token text sizes and radii, so a size and a colour class never cancel each other; add any new `--text-*` or `--radius-*` token to `lib/utils.ts`.+- One `PageHeader` per page. Gaps between page sections are `gap-6`, or `gap-8` on pages with large sections.-- Destructive actions go through `ConfirmDialog` with `hold`.+- Small deletes use `deleteWithUndo`; removing an account and deleting everything go through `ConfirmDialog` with `hold`.- Every async action disables its trigger, shows a spinner or progress, and ends in a toast that names what happened.- Sentence case in all UI copy. No exclamation marks. Errors say what happened and what to do.- Lucide icons at 1.75 stroke. 18px in navigation, 16px in controls. (The public site in `site/` uses Solar icons instead; see `docs/architecture/site/SITE.md`.)diff --git a/docs/guidelines/CODE_STYLE.md b/docs/guidelines/CODE_STYLE.mdindex 83c1c80..f55dc72 100644--- a/docs/guidelines/CODE_STYLE.md+++ b/docs/guidelines/CODE_STYLE.md@@ -91,7 +91,7 @@ The layers are in `docs/architecture/backend/REQUEST_PIPELINE.md`; the recipes aMessages are UI copy. Follow `docs/WRITING_STANDARDS.md` (UI Copy) and `docs/guidelines/ERROR_HANDLING.md`.- Backend: throw the typed error whose code matches the failure (`ValidationError`, `NotFoundError`, `RateLimitedError`, `NotConfiguredError`, `UpstreamError`), with a message a person can act on: `'This address has received the most codes allowed today. Use the latest code you received, or try again tomorrow.'` A missing secret names the secret: `'Email sending is not set up: the RESEND_API_KEY and EMAIL_FROM Worker secrets are required'`.-- Frontend failures: a toast that starts with what failed and adds the reason: `` `Couldn't save the password. ${reason}` ``. Map provider error codes to plain sentences in a `lib/` helper (`lib/authErrors.ts`) and keep the provider's own message when it already says what to do.+- Frontend failures: a field the person can fix shows its message under the field through `FieldRow error`; a request failure is a toast that starts with what failed and adds the reason: `` `Couldn't save the password. ${reason}` ``; a failed load shows `ErrorState`, never an empty state. See `docs/guidelines/ERROR_HANDLING.md`. Map provider error codes to plain sentences in a `lib/` helper (`lib/authErrors.ts`) and keep the provider's own message when it already says what to do.- Frontend success: confirm what happened in past tense, sentence case, no exclamation mark: `'Password saved'`, `'New code sent'`.- Never reveal more than the user should know: the password reset message reads `If an account uses <email>, a code is on its way.` because the server does not say whether the account exists.@@ -150,6 +150,7 @@ Rules in `docs/workflows/TESTING.md`.## Before Every Commit- [ ] The new file looks like its nearest sibling: imports, exports, naming, comments+- [ ] Interface changes pass the checklist in `docs/guidelines/UI_UX.md`- [ ] Comments only explain why; no restated code, no task references- [ ] Errors are typed (backend) or toasts with a reason (frontend), and every message says what to do- [ ] No `any`, enums, `@ts-ignore`, hex colours, emoji, em dashes or exclamation marksdiff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.mdindex 0da5b8f..4e970af 100644--- a/docs/guidelines/ERROR_HANDLING.md+++ b/docs/guidelines/ERROR_HANDLING.md@@ -109,9 +109,22 @@ It also maps Hono's own `HTTPException` (such as a malformed JSON body) by statu`authHookErrorHandler`, in the same file, is used only by `routes/authHookRoutes.ts` (`router.onError`). It logs and maps statuses exactly like `errorHandler`, but writes the body Supabase Auth reads from a hook, `{ "error": { "http_code": 429, "message": "..." } }`; Supabase passes the message to the sign-in page, so it is written for the person signing in or up; for the daily cap the page shows its own wording (`emailErrorNotice` in `frontend/src/lib/authErrors.ts`).+### Where the Frontend Shows a Failure++Put the message next to its cause, so it is still there when the person looks for it (WCAG 3.3.1, 3.3.3):++| Failure | Where it shows |+|---|---|+| A field the person can fix (empty, wrong format, too short, a date in the past) | Under the field, through `FieldRow error`, which sets `aria-invalid` and `aria-describedby`; on submit, focus moves to the first invalid field. Validators return the field and the message, not only a message |+| A load that failed | `ErrorState` with Try again in place of the content, or an inline `Alert` above the last good data; never an empty state |+| Part of a load that failed (one channel of five) | An inline `Alert` naming what did not load, with Retry, above the results that did |+| A request that failed after submit (network, server, a platform refusing) | A toast; error toasts stay until closed |++A toast is never the only copy of an error the person has to act on. Success toasts confirm in past tense and close on their own.+### Frontend API Calls-Catch in the component or handler, show a toast, and handle loading state:+Catch in the component or handler, show a toast for a request failure, and handle loading state:```tsxconst [loading, setLoading] = useState(false);diff --git a/docs/guidelines/UI_UX.md b/docs/guidelines/UI_UX.mdnew file mode 100644index 0000000..d57cd11--- /dev/null+++ b/docs/guidelines/UI_UX.md@@ -0,0 +1,136 @@+# UI and UX++How every change to the interface is designed, built and checked. It applies to any task that adds or changes something people see or use, in the app (`frontend/`) or the public site (`site/`): a page, a component, a state, a flow, copy, motion or layout. Small updates count too: a new button, a changed message, a new table column.++Read this page before writing interface code, and run its checklist before every commit that touches the interface.++## Sources, in priority order++1. **People can finish their tasks safely, including people with disabilities.** WCAG 2.2 AA is the floor, never a trade-off.+2. **This project's design system.** `docs/architecture/frontend/DESIGN_SYSTEM.md` (tokens, components, page patterns, Rules), `docs/design-reference.md` (where each value comes from), `docs/brand-notes.md` (the site), `docs/WRITING_STANDARDS.md` (copy). Brand colours, type, logo and icons never change for a UX reason.+3. **The UI/UX Design Intelligence system:** the 30 Laws of UX with their evidence, WCAG 2.2, heuristic evaluation, and guides for dashboards, forms, interaction, navigation, responsive layouts and data views (ADR-047). The owner keeps it as the ProfileBox system `ui-ux-design-intelligence`. With the ProfileBox MCP, load it with `get_system_instructions_for_task`, giving it the task, and read single files with `get_system_file`. This page carries its rules as they apply here, so the work does not stop without it.+4. **The reference dashboard patterns** at the end of this page: structure and behaviour only, never another product's brand.++When two sources disagree, the higher one wins. Say so in the pull request.++## How to work a UI task++1. **Users and tasks.** Who uses the screen, how often, on what device, and what must never go wrong (a reply sent twice, a post published to the wrong account). If you don't know, write down your assumption.+2. **Primary tasks and states.** Name the 3 to 5 things people do here, and every state the screen can be in: loading, empty (first use and no results), error, partial failure, stale, success, too much content, no permission.+3. **Principles.** Pick the 4 to 8 laws that fit, with the selector below, and note the trade-off of each. One line per non-obvious decision in the pull request: decision, law, trade-off.+4. **Reuse first.** The components in `DESIGN_SYSTEM.md` before new markup; a new pattern only when no existing one does the job, and then it becomes a shared component.+5. **Build it real.** Concrete components, values, copy and states; never a control that only looks like it works. A missing backend operation is shown as unavailable with the reason, never faked.+6. **Consistency.** Same job, same component, same label, same place as on every other page.+7. **Remove.** For each element, ask what breaks if it goes. If nothing breaks, remove it.+8. **Check.** Run the checks and the checklist below, fix what fails, then commit.++### Which laws apply++| Situation | Lean on |+|---|---|+| Many options, menus, settings | Hick's Law, Choice Overload; then Chunking and Tesler's Law (let the system choose) |+| A dense screen where people miss things | Selective Attention, Von Restorff Effect, Cognitive Load |+| Layout, grouping, cards, forms | Law of Proximity, Law of Common Region, Law of Similarity |+| People must remember or compare | Working Memory, Chunking |+| Navigation and labels | Jakob's Law, Mental Model |+| Buttons and touch targets | Fitts's Law |+| Waiting, loading, slow platforms | Doherty Threshold, Goal-Gradient Effect, Peak-End Rule |+| Multi-step flows and setup | Goal-Gradient Effect, Paradox of the Active User |+| Forms and data entry | Postel's Law, Tesler's Law |+| Errors and recovery | Peak-End Rule, Postel's Law |+| Scope and simplification | Occam's Razor, Pareto Principle |++Don't cite these as rules: "7 plus or minus 2" as a menu limit, the 400 ms figure, Zeigarnik as a reason to nag, "fewer options is always better", "a beautiful design is a usable one".++## The rules++### Thinking++- Design the primary task first; secondary tasks get a path, not the prime space.+- Push work the system can do into the system: defaults, inference, formatting (Tesler's Law). Don't ask for a page ID the app could look up, or for milliseconds when people think in seconds.+- People start without reading. Teach in empty states and inline hints, not in tours (Paradox of the Active User).+- Never use a bias against the user: no fake urgency, no hidden costs, no pre-ticked extras, no hard cancellation.++### Visual++- Group with spacing first, then a `SurfaceBox`, then lines. Gaps between groups are larger than gaps inside them (`gap-6` or `gap-8` between sections, `gap-3` or `gap-4` inside).+- Hierarchy by position, size, weight, contrast, then colour. One primary (default) button per view; an empty state's action replaces the header action, it does not repeat it.+- Emphasis only where it means something (Von Restorff): one `highlight` metric per row, one accent per view.+- Type: reading text and inputs at `text-body` (16 px, 1.5 line height); tables, navigation, chips and labels at `text-sm` (14 px); nothing readable below `text-caption` (12 px); help paragraphs in `max-w-prose`; numbers tabular and right-aligned in tables.+- Colour only through tokens. Text at least 4.5:1, large text and UI parts at least 3:1. Compute the ratio, don't estimate it (see Checking the work). Colour is never the only signal: pair status with an icon and a word, trends with a sign, links in text with an underline, chart series with a label or shape.++### Interaction++- Feedback at once: a pressed or busy state under 100 ms, a skeleton or spinner after about a second (`Spinner` already waits 300 ms so fast answers don't flash), real progress with a way to stop or leave beyond about 10 seconds.+- Design every state. Refreshing keeps the data on screen with a progress bar; skeletons are only for the first load. A failed load shows `ErrorState` with Try again, never an empty state. Cached data says how old it is.+- Errors say what failed and what to do, sit next to their cause, and keep the input. A field the person can fix gets `FieldRow error`; a failed request gets a toast; a toast is never the only copy of an error the person must act on (see `docs/guidelines/ERROR_HANDLING.md`).+- Buttons stay enabled except while busy; pressing one with something missing shows what is missing.+- Accept messy input and store clean data (Postel's Law): trim, ignore case, accept `@name`, `u/name`, full profile URLs, `1,234` and `12.5k`, a link without `https://`. Then show the clean value.+- Small, frequent deletes act at once with `deleteWithUndo`. Removing an account or deleting everything confirms with `ConfirmDialog`, naming the object and the consequence, with a way to confirm that needs no press and hold.+- Leaving a form with unsaved work asks first; long forms keep a draft.+- Dialogs only for short tasks that must interrupt. Focus goes in, stays in, Escape closes, focus returns. Long work gets a page.+- Motion explains a change. It lasts 150 to 300 ms, never blocks input, and stops under `prefers-reduced-motion`. Nothing loops while idle unless people can pause it (WCAG 2.2.2).++### Navigation and layout++- Each page has its own tab title (`useDocumentTitle` for detail pages), focus moves to its heading after navigation, and the current place is marked (`aria-current`).+- View state lives in the address (`useUrlState`, `useUrlChoice`, `useUrlPage`): tabs, search, filters, sort, page, layout. Typing replaces the history entry; a tab or page change adds one.+- One label per destination, the same in the sidebar, the page title, buttons and the command palette.+- Page anatomy stays the same everywhere: `PageHeader` (title, short description, the primary action on the right), then filters, then content.++### Accessibility++- Native elements first (`button`, `a href`, `label`, `table`, `fieldset`); ARIA only when nothing native fits, and composite widgets follow the WAI-ARIA keyboard patterns (arrow keys inside a radio group or tabs).+- Every control has an accessible name that contains its visible label, and row actions name their row ("Edit rule Giveaway").+- Status changes are announced without moving focus (`LiveStatus`; `role="alert"` only for a message that appears after an action).+- Targets are at least 24 by 24 px, 44 px on touch screens (the tokens grow under `pointer: coarse`). Nothing works on hover only.+- The layout reflows at 320 px wide and at 200 percent zoom; wide tables scroll inside their box, which the keyboard can reach.++### Data views and dashboards++- Each element answers a question someone asks. The top row holds the few figures that matter, each with its period and a comparison, colouring a change by whether it is good.+- Rounded figures offer the exact value (`Num`); relative times offer the date (`RelativeTime`).+- Charts have a one-line summary and a table of the same data, and never put two units on one axis.+- Libraries share one toolbar: search, filters shown as removable chips with Clear all, sort, a result count, and a no-results state that repeats the query.+- A part that failed says so above the parts that loaded, with Retry.++## Reference dashboard patterns++The Activepieces platform dashboard was studied on 4 Nov 2026 in a signed-in browser, using read-only actions only. Its 27 pages were measured with Chrome DevTools, the same way `docs/design-reference.md` records the ElevenLabs reference. Take its structure and behaviour where Twiligent has no pattern of its own. Never take its colours, logo, typeface or wording, and never change a Twiligent token to match it.++| Pattern | What the reference does | How it maps here |+|---|---|---|+| List page | Header, then filter chips (36 px, dashed border, icon plus field name, chosen values as small badges after a hairline), then a table card, then "Rows per page" and Previous / Next under it on the right, disabled at the ends | Library pages: `SearchField`, `FilterChips`, a table in `SurfaceBox`, `Pager`; active filters as removable chips |+| Settings page | Cards with a header row; each row has the label and a one-line description on the left and the control on the right; Cancel and Save in a sticky bottom bar, Save disabled until something changes | Settings sections with `FieldRow`; a page with explicit Save shows unsaved changes and warns before leaving |+| Status page | Rows of a 36 px icon tile, a title, one line of description, and a status dot with a word on the right | Account health and automation status: icon plus word, never a dot alone |+| Empty state | The table keeps its header; a 36 px muted tile with the icon, a title, one muted line, centred in the table area | `EmptyState` inside the same `SurfaceBox` |+| Loading | Rounded bars the height of a row inside the table card until the data arrives | Skeleton rows in the table's own layout |+| Dialog | Fades in and grows from 95 percent in 200 ms over a dimmed overlay; focus inside; Escape closes and leaves nothing behind | `Dialog` and `ConfirmDialog`; a bottom sheet below `sm` |+| Menus and popovers | Open in 150 ms with a short fade and zoom | `select.tsx`, `popover.tsx`, `dropdown-menu.tsx` |+| Sidebar group | A muted 12 px label, 32 px rows, a quarter-turn chevron in 200 ms when sub-rows open by height | The sidebar's groups and the Show all toggle |+| Icon motion | On hovering a row (not the icon), the icon's parts move once and settle by about 300 ms: tiles scale, a figure slides, a plug pulls apart, a piece tilts; nothing moves at rest or under reduced motion | Optional for sidebar icons: CSS on the Lucide parts, one run per hover or keyboard focus, `prefers-reduced-motion` turns it off |+| Motion timing | 150 ms for colour, size and buttons (`cubic-bezier(0.4, 0, 0.2, 1)`); 200 ms for chevrons and opening sections (`cubic-bezier(0.22, 1, 0.36, 1)`) | `--duration-base` (150 ms) and `--duration-overlay` (200 ms) already match |++## Checking the work++- **Contrast:** with Node 22, `node "A:/Profile Box/systems/ui-ux-design-intelligence/scripts/contrast.mjs" "#fg" "#bg"` on the owner's machine. It exits with code 1 when a pair fails, so don't chain it with `&&`. Elsewhere, any WCAG contrast calculator.+- **Keyboard:** complete each primary task without a mouse. Focus is always visible, never hidden under the top bar, and returns to the opener after a dialog or menu closes.+- **Screen reader:** where possible, NVDA with Chrome or VoiceOver with Safari. Check names, headings, announced counts and errors.+- **Width and zoom:** 320, 375, 768 and 1280 px, and 200 percent zoom. The page never scrolls sideways.+- **Automated:** axe or Lighthouse on each changed page in both themes, through the Chrome DevTools MCP when it is available. A clean scan is not a pass on its own.+- **Reduced motion and touch:** turn on reduced motion, and use a touch emulation for the 44 px targets.+- **Audits:** a review or audit records each problem with where, the law or criterion, a severity from 0 to 4, an evidence label (`heuristic` for code reading, `walkthrough`, `automated`, `usability-test`) and the fix, as the system's `evaluation/issue-template.md` does. Findings from reading code are predictions; say "likely".++## Checklist before a commit that touches the interface++- [ ] Primary tasks and every state (loading, empty, no results, error, partial, stale, success) are designed+- [ ] One primary action per view; the same job uses the same component and label as elsewhere+- [ ] Reading text 16 px, nothing below 12 px, help in `max-w-prose`, only token colours and sizes+- [ ] Keyboard path complete, focus visible and moved where it should be, names contain the visible labels+- [ ] Colour is never the only signal; contrast computed for any new colour pair+- [ ] Field errors under the field, request failures in a toast, failed loads in `ErrorState`; input kept+- [ ] View state in the address; Back and refresh keep the view+- [ ] Works at 320 px and 200 percent zoom; targets 24 px, 44 px on touch; nothing hover-only+- [ ] Motion 150 to 300 ms, stops under reduced motion; nothing loops without a pause+- [ ] Nothing fake: every control does what it shows, or says why it can't+- [ ] `DESIGN_SYSTEM.md` updated if a shared component or rule changeddiff --git a/docs/workflows/FEATURE_DEVELOPMENT.md b/docs/workflows/FEATURE_DEVELOPMENT.mdindex 19b8f20..9866923 100644--- a/docs/workflows/FEATURE_DEVELOPMENT.md+++ b/docs/workflows/FEATURE_DEVELOPMENT.md@@ -69,6 +69,9 @@ Determine:- What new frontend pages or components are needed- What security implications exist+**Step 9b - Design the interface (any UI change)**+Follow `docs/guidelines/UI_UX.md`: name the users, the 3 to 5 primary tasks and every state (loading, empty, no results, error, partial, stale, success), pick the laws that apply with their trade-offs, and choose the shared components that carry them. Record the non-obvious decisions in the pull request.+**Step 10 - Identify reuse opportunities**Before creating new patterns, check:- Is there a repository method that almost does what you need? Extend it.diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex 96d54bf..dab31c3 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -296,16 +296,20 @@ Open browser DevTools -> Console. Navigate through all changed pages.### 7. Accessibility Verification-For any new UI:+For any new or changed UI, run the checks in `docs/guidelines/UI_UX.md` (Checking the work). At least:- Tab through all interactive elements - all must be reachable- Press Enter on buttons - they should activate- Press Space on buttons and checkboxes - they should activate- Check for visible focus ring on focused elements- Use Chrome's built-in Accessibility tab (DevTools -> Elements -> Accessibility) to verify ARIA structure+- Run axe or Lighthouse on the changed pages in both themes+- Confirm focus moves to the page heading after navigation and back to the opener after a dialog closes+- Turn on reduced motion and check that nothing moves or loops### 8. Responsive Layout VerificationResize the browser to test at:+- 320px (the WCAG reflow width, also 1280px at 400 percent zoom)- 375px (iPhone SE - smallest common mobile)- 768px (tablet)- 1280px (laptop)