UI componentization audit and elimination plan
Date: 2026-08-10
Status: proposed migration plan; implementation has not started
Scope snapshot: the current shared checkout, including uncommitted report-editor work; dev was 19 commits behind origin/dev when scanned
Goal
Make every UserHappy web surface consume one semantic design system and component library so that:
- interactive controls are never hand-styled at a call site;
- visual recipes do not live in JSX or HTML;
- the same semantic action always uses the same button treatment;
- the same semantic icon always resolves to the same SVG, size, and stroke treatment;
- design tokens, component implementations, and Storybook examples have one production source of truth;
- new uncomponentized UI cannot enter the repository unnoticed.
Context
The repository has useful foundations, but they are not yet a component system:
src/index.cssdefines a Tailwind v4 theme and customer palette roles.design/canon.jsonrecords part of the cross-platform palette policy.- palette tests prevent some color regressions and ratchet other color debt.
design-docscontains Storybook stories and a small set of components.src/components/pulse-wizard-v3/ui.tsxcontains feature-local buttons, fields, a segmented control, and cards.src/components/report-editor/styles.tscentralizes several class strings for one feature.lucide-reactis the prevailing general icon source.
Those pieces do not enforce a shared API. Storybook's early primitives use inline style props, the pulse wizard owns a second button implementation, and most screens still style native controls directly.
Constraints
- Preserve semantic HTML. A
main,section, heading, paragraph, list, or table is not debt merely because it is native HTML. It becomes design-system debt when a feature call site owns its reusable visual treatment. - Native interactive elements (
button,input,select,textarea) must only be emitted inside the component library. Feature code consumes semantic components. - No authored
styleattributes or JSXstyleprops. Dynamic progress, charts, and geometry must use semantic HTML attributes (value,max, SVG geometry attributes), finite component variants, or a library-owned rendering implementation. - No raw SVG markup and no direct
lucide-reactimports outside the icon/illustration library. - No raw color, radius, shadow, typography, or control-state recipe at feature call sites.
- Customer, Cortex/staff, and status treatments remain intentionally distinct, but are implemented as semantic theme overrides rather than per-page class forks.
- Transactional email is a rendering exception only at build output: email clients may require inlined CSS, but authored templates must consume email components/tokens and generate the inline output.
- Existing unrelated work must not be overwritten. In particular, the current uncommitted
src/components/report-editorwork should land or move to an isolated worktree before its migration tranche begins.
Done when
All of the following are true in the current tree, not merely planned:
src/ui(or the ratified equivalent) is the only production source for reusable visual primitives.- Storybook imports those production components; duplicate components under
design-docs/src/componentsare removed. - Feature source contains zero raw native interactive controls.
- Feature source contains zero JSX
styleprops and web HTML contains zero hand-authoredstyleattributes or<style>blocks. - Feature source contains zero raw SVG markup and zero direct icon-library imports.
- Feature source contains zero hardcoded color values and zero arbitrary visual Tailwind values.
- Every reusable button, field, overlay, status, surface, typography, and layout recipe maps to a named component or semantic class.
- Customer and Cortex themes pass visual regression, contrast, keyboard, focus, and responsive QA.
- A structural CI gate rejects every prohibited pattern without a grandfathered baseline.
- Browser QA proves representative customer, participant, staff, public-auth, and operational flows at desktop and mobile widths.
Verification required
- unit and interaction tests for every library primitive and state;
- accessibility checks for roles, names, focus movement, Escape behavior, disabled behavior, and keyboard-only use;
- Storybook coverage for every variant, state, and theme;
- screenshot comparison for representative routes in both customer and Cortex themes;
- repository-wide structural audit with a zero baseline;
- focused feature tests after each migration tranche, then the full web test/build suite;
- final Browser QA against a running build, not screenshots alone.
Current-state inventory
The inventory used the TypeScript parser over non-test TSX in src and design-docs/src, plus a text scan of server-rendered and static HTML sources. Counts include the current uncommitted report-editor files and will need to be regenerated after the branch is synchronized.
Current guard verification is not fully green. Running
npx vitest run src/__tests__/paletteCanon.test.ts src/__tests__/canonPropagation.test.ts src/__tests__/cortexMonochrome.test.ts
passed the canon-propagation and Cortex-monochrome suites, but the palette ratchet failed on the already-modified src/pages/CortexReportBuilder.tsx: its non-canon hex count increased from 5 to 10 (#f0eeec, #fff8f2, #b34700, and #fbfaf8). This plan does not update that baseline or alter the in-progress file.
Production React surface
Scanned: 120 non-test src/**/*.tsx files.
| Finding | Current evidence | Why it matters |
|---|---|---|
| Raw native controls | 453 across 78 files | Control behavior and styling are owned by features rather than a library. |
| Raw buttons | 268 | Button states, sizing, icon spacing, and focus behavior can drift. |
| Raw inputs | 134 | Field layout, errors, labels, focus, and disabled states can drift. |
| Raw selects | 24 | Styling and keyboard behavior are repeated. |
| Raw textareas | 27 | Field behavior and resize treatment are repeated. |
| Distinct control class recipes | 286 | The repository has local recipes rather than a bounded variant API. |
| Distinct button recipes | 199 | Existing approval to unify buttons has not become an enforced system. |
| Styled intrinsic elements to review | 3,107 | This is the migration population, not a claim that every semantic element needs a React wrapper. |
JSX style props |
65 across 18 files | CSS is authored in rendered markup. |
| Arbitrary Tailwind value matches | 2,603 across 89 files | Tokens and component variants are bypassed at call sites. |
| Hex literal matches in TSX source | 2,202 | Palette values are still copied into components and screens. |
| Raw SVG roots | 11 across 10 files | SVG source and treatment are not centralized. |
| Direct Lucide imports | 341 imported symbols across 71 files | Glyph choice is tied to implementation names, not semantic product roles. |
| Hand-rolled dialogs | 17 instances across 12 files | Overlay focus, dismissal, layering, and styling are repeated. |
| Hand-rolled menus | 4 instances | Menu behavior and presentation are repeated. |
The largest interactive-control hotspots are:
| File | Raw controls | Inline styles | Styled intrinsic elements |
|---|---|---|---|
src/pages/Panels.tsx |
61 | 7 | 267 |
src/pages/CortexPulses.tsx |
25 | 8 | 142 |
src/pages/Team.tsx |
19 | 0 | 119 |
src/pages/CortexCustomers.tsx |
17 | 0 | 81 |
src/pages/CortexReportBuilder.tsx |
16 | 0 | 112 |
src/pages/Profile.tsx |
14 | 0 | 104 |
src/components/cortex/CortexOnboardingWizard.tsx |
14 | 0 | 64 |
src/components/TaskCompletionPulse.tsx |
13 | 0 | 61 |
src/pages/PulseSessions.tsx |
12 | 0 | 70 |
src/components/PromptLabRail.tsx |
12 | 0 | 45 |
src/components/DetailedReport.tsx is the largest inline-style hotspot with 15 style props. src/pages/SentimentDemo.tsx has 13. These include shadows, measurements, opacity, gaps, and data-driven widths that need explicit semantic replacements rather than a blanket search-and-replace.
Existing component islands
Storybook-only primitives
design-docs/src/componentsdefinesButtonFilled,ButtonOutline,PillOption,SegmentToggle,StepIndicator,CheckBadge, andTaskHighlight. Their visual rules are authored with inlinestyleobjects. They cannot be the target library in their current form.Pulse-wizard primitives
src/components/pulse-wizard-v3/ui.tsxdefinesPrimaryButton,OutlineButton,QuietButton,FieldShell,CounterStepper,SegmentedToggle,SelectableCard, andSearchInput. This is the best pilot because production and Storybook already both import it, but it is feature-scoped and embeds literal visual values.Report-editor recipes
src/components/report-editor/styles.tssharesINPUT_CLASSES,ADD_BUTTON, andICON_BUTTON. This reduces copying within one feature, but strings are not semantic components and cannot enforce accessible structure or icon usage.Status components
src/components/Badge.tsxandsrc/components/help/HelpStatusBadge.tsximplement separate badge systems and include raw color-family choices. They need one semanticBadge/StatusBadgeAPI.
Token and theme drift
src/index.cssanddesign-docs/src/tokens.cssboth define design tokens with different names and incomplete overlap.- Storybook adds more Tailwind theme definitions in
onboarding-tailwind.cssandpulse-wizard-v3-tailwind.css. design-docs/src/tokens.cssexplicitly records a body-font divergence from the app.- customer code mixes semantic tokens such as
text-text-mutedwith literal forms such astext-[#565352]. - Cortex uses page-level monochrome class forks. A semantic theme should choose the colors while the component API stays the same.
- the palette tests guard colors, not component ownership, SVG identity, focus behavior, typography, spacing, radius, or shadows.
Icon and illustration drift
Plus,Trash2,X,Loader2,ChevronDown, andBuilding2are the most frequently imported Lucide implementation names.- Google marks are independently embedded in
Login.tsxandProfile.tsxwith different view boxes/path data. Layout.tsxembeds a custom help glyph;AppFooter.tsxembeds the tagline wordmark;SentimentIcon.tsxembeds sentiment paths;NotFound.tsxembeds an illustration.- These custom assets are legitimate, but they need named ownership in
src/ui/icons,src/ui/brand, orsrc/ui/illustrations, not page-local SVG. - Icon-only buttons are currently assembled locally, so glyph size, stroke width, accessible name, hit target, and disabled state are not centrally guaranteed.
Other authored web surfaces
The React app is not the complete web footprint:
design-docs/srchas 56 inline style props across 14 finding files.public/docs/userjourneys-embed/index.htmlhas 662 inline style attributes.public/docs/confetti-celebration-embed/index.htmlhas four<style>blocks and 18 controls.- release/drift report embeds contain authored
<style>blocks and inline styles. qaandopsserver-rendered views contain inline style attributes,<style>blocks, raw controls, and raw SVG.worker/lib/email.tscontains 172 inline style attributes. These should be generated from email components/tokens; the delivered email HTML remains an explicitly tested output exception.
Static/generated documentation and transactional email must be classified in the architecture decision so the zero gate measures authored source correctly rather than silently ignoring those surfaces.
Target architecture
1. One token source
Use one role-based token graph shared by the app and Storybook. Complete design/canon.json (or supersede it through an explicit ADR) with semantic roles, then generate or import one CSS token file.
Required semantic roles include:
surface.page,surface.card,surface.subtle,surface.overlay;text.heading,text.body,text.muted,text.inverse,text.link;border.default,border.strong,border.focus;action.primary,action.secondary,action.quiet,action.destructivewith rest, hover, pressed, focus, and disabled states;status.info,status.success,status.warning,status.dangerwith text, surface, border, and icon roles;- typography, spacing, radius, elevation, motion, control height, and icon size roles.
Components consume semantic roles only. Raw swatches remain available to the token build but are not an application API.
Use a theme attribute at the shell boundary, for example data-theme="customer" and data-theme="cortex". Cortex overrides semantic roles to monochrome; feature components do not branch on host names to select visual classes.
2. One production component library
Create a deliberately bounded production library under src/ui:
src/ui/
actions/ Button, IconButton, LinkButton
fields/ Field, TextField, Textarea, Select, Checkbox, RadioGroup, SearchField
feedback/ Alert, Badge, StatusBadge, Progress, Skeleton, EmptyState, Spinner
layout/ Page, Container, Stack, Inline, Cluster, Grid, Divider
overlays/ Dialog, Drawer, Popover, Menu, Tooltip
surfaces/ Card, Panel, Toolbar, DataTable
typography/ Heading, Text, Label, Code
icons/ Icon registry and custom product icons
brand/ UserHappy marks and third-party provider marks
illustrations/ Named, non-interactive illustrations
styles/ tokens.css, components.css, themes.css
index.ts Public API only
The exact folder name is less important than the import boundary: features import only the public src/ui API. Raw elements and third-party behavior primitives stay private to the library.
Use semantic variants, not color names:
<Button intent="primary">Send pulse</Button>
<Button intent="destructive">Delete account</Button>
<IconButton icon="action.close" label="Close dialog" />
<TextField label="Email" error={emailError} />
<StatusBadge status="processing" />
Do not expose orange, navy, rounded-lg, or arbitrary className escape hatches as the normal API. A tightly controlled layout className may be allowed during migration, then removed or limited by the structural gate.
Composite overlays and selection widgets should use one accessible behavior layer inside src/ui rather than repeating ARIA and focus logic in features. Ratify the specific headless dependency in the ADR; feature code must not import it directly.
3. Semantic icon registry
Only src/ui/icons imports lucide-react or owns SVG path data. The public API maps product meaning to one glyph:
type IconName =
| 'action.add'
| 'action.close'
| 'action.delete'
| 'action.download'
| 'navigation.dashboard'
| 'navigation.pulses'
| 'status.success'
| 'status.warning'
<Icon name="action.add" size="control" /> owns aria-hidden, stroke width, fill policy, and size. <IconButton> requires a label and owns the hit target. Brand marks and illustrations use separate named components because they are not interchangeable UI glyphs.
This permits the underlying SVG to change once without editing consumers and prevents one meaning from drifting across Check, CheckCircle, and CheckCircle2 at call sites.
4. CSS ownership
- CSS lives in the library's CSS files, not
styleprops, HTML style attributes, or feature-local visual recipes. - Component classes use semantic names such as
.uh-button,.uh-button--primary, and.uh-field--invalid. - Feature code may retain semantic structure and approved layout composition. Repeated layout becomes a layout component.
- Dynamic progress uses
<progress value max>; indeterminate state is a component variant. - Charts use SVG geometry attributes owned by chart components, not CSS width calculations in pages.
- Animation values live in CSS keyframes and semantic motion tokens.
- Third-party widget selectors remain in CSS files behind a library adapter.
Migration plan
Each tranche should be a separate, reviewable PR or isolated worktree. Counts are ratcheted down after each merge; no tranche may increase another category.
Phase 0 — Ratify policy and add the baseline gate
- Approve this scope and record an ADR covering semantic HTML, the external behavior primitive choice, Tailwind's final role, email output, and generated documentation.
- Add a TypeScript-AST audit script and a Vitest/CI wrapper.
- Record the current per-file baseline for raw controls,
styleprops, raw SVG, direct icon imports, literal colors, arbitrary visual values, and hand-rolled overlays. - Add the rules to repo-level
AGENTS.mdso Codex implementations use the library by default.
Exit gate: CI fails on any increase and prints actionable file/line diagnostics.
Phase 1 — Consolidate tokens and themes
- Complete semantic color, type, spacing, radius, shadow, control, icon, and motion roles.
- Make the production token CSS the only source imported by app and Storybook.
- Remove duplicate token declarations from
design-docs. - Introduce customer and Cortex semantic theme roots.
- Extend the existing palette tests from swatch policing to role validation.
Exit gate: changing a token updates app and Storybook; representative customer and Cortex stories render without feature-level color forks.
Phase 2 — Build the primitive library
Build and test, in dependency order:
- typography and layout;
Icon, brand marks, and illustrations;Button,IconButton, andLinkButton;Field, text controls, selection controls, and search;- badges, alerts, progress, skeletons, and empty states;
- cards, panels, toolbars, and tables;
- dialog, drawer, popover, menu, tooltip, tabs, and segmented/radio controls.
Every component needs Storybook stories for themes, sizes, interaction states, keyboard use, focus, disabled, loading, error, and responsive behavior before migration begins.
Exit gate: the library covers the current recipe inventory with a small semantic variant set; it does not reproduce 199 button variants.
Phase 3 — Pilot on the pulse wizard and identity surfaces
- Move the useful API from
pulse-wizard-v3/ui.tsxintosrc/ui. - Update
CreatePulseV3and its Storybook flow to consume the production library. - Extract
GoogleMark, the UserHappy brand mark, custom help glyph, footer wordmark, and sentiment graphics into named library assets. - Migrate Login/Profile buttons and fields to prove customer/Cortex theming and third-party brand handling.
- Delete the duplicate Storybook-only button/field components.
Exit gate: no raw controls, inline styles, raw SVG, direct Lucide imports, or hardcoded visual values remain in the pilot surfaces.
Phase 4 — Migrate high-leverage shared features
- After the current report-editor work is stable, replace
styles.tsstrings with field, button, icon-button, card, and table components. - Migrate shared shells and components:
Layout,AppFooter,PageHeader, badges, progress, dialogs, help panels, participant preview, and export UI. - Replace all hand-rolled dialogs and menus with the overlay library.
- Migrate
DetailedReportchart/progress rendering to semantic report components with nostyleprops.
Exit gate: shared components contain no prohibited patterns and downstream pages lose local recipes as a consequence.
Phase 5 — Migrate application routes by risk cluster
Use route-level Browser QA after every cluster:
- customer dashboard, reports, results, sessions, and participant flows;
- team, profile, help, and public/auth routes;
- Cortex shell, team, customers, connect, environments, and inbox;
- high-density
CortexPulsesandCortexReportBuilder; Panels.tsxlast, after fields, tables, cards, dialogs, menus, and icon buttons are proven.
Exit gate per route: zero prohibited patterns, focused tests green, keyboard pass complete, desktop/mobile visual comparison approved.
Phase 6 — Migrate static, Ops, QA, and email sources
- Generate public documentation embeds from shared React components or author them with linked semantic CSS classes; remove authored inline styling and
<style>blocks. - Give Ops and QA server views shared semantic render helpers and an external stylesheet.
- Convert email templates to semantic email components/tokens. Inline CSS may exist only in generated/delivered HTML and golden fixtures.
- Label historical design evidence that is intentionally immutable; keep it outside the executable-source gate.
Exit gate: all executable authored web source meets the policy, and exceptions are generated artifacts with tests proving their origin.
Phase 7 — Remove baselines and make zero permanent
- Delete all grandfathered counts.
- Hard-fail CI on raw controls outside
src/ui,styleprops, raw SVG outside asset modules, direct icon imports, literal visual values, and duplicate token definitions. - Add a dependency-boundary test so features can import only
src/ui/index.ts. - Make the component inventory and visual regression suite required CI.
- Run full build/test and Browser QA across the route matrix.
Exit gate: every Done when item has direct current-state evidence.
Recommended verification matrix
| Layer | Automated evidence | Human/Browser evidence |
|---|---|---|
| Tokens | role graph, contrast checks, no duplicate definitions | customer/Cortex theme comparison |
| Buttons/fields | interaction tests, accessible names, states | focus ring, hit target, copy length, mobile keyboard |
| Icons | registry boundary, snapshot of name-to-glyph map | visual weight and semantic appropriateness |
| Overlays | focus trap/return, Escape, outside dismissal, ARIA | keyboard-only and screen-size checks |
| Reports/charts | semantic values and no inline CSS | zero/large values, narrow layout, print/export |
| Route migration | structural zero checks plus focused tests | desktop/mobile route screenshots and core tasks |
| Ops/QA/docs | no authored inline styles, linked asset checks | authenticated operational flows |
| component render and golden output | major-client preview; generated inline CSS allowed |
Immediate next implementation slice
The safest first implementation slice is Phases 0–3 limited to the pulse wizard and identity assets:
- add the structural ratchet and ADR;
- consolidate token imports for app and Storybook;
- build
Icon,Button,IconButton,Field,TextField,Textarea,Select,Card,Dialog, and basic layout primitives; - migrate
pulse-wizard-v3, Login, and Profile; - extract Google/UserHappy/help/footer/sentiment assets;
- verify in Storybook, unit tests, build, and Browser at mobile/desktop widths in customer and Cortex themes.
Do not begin the report-editor tranche in the current shared checkout until its uncommitted work is stabilized. Use an isolated worktree for the first migration PR so the shared checkout remains untouched beyond this planning document.