UserHappyDesign system
Storybook

Componentization audit

Original documentation preserved from the source revision.

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.css defines a Tailwind v4 theme and customer palette roles.
  • design/canon.json records part of the cross-platform palette policy.
  • palette tests prevent some color regressions and ratchet other color debt.
  • design-docs contains Storybook stories and a small set of components.
  • src/components/pulse-wizard-v3/ui.tsx contains feature-local buttons, fields, a segmented control, and cards.
  • src/components/report-editor/styles.ts centralizes several class strings for one feature.
  • lucide-react is 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 style attributes or JSX style props. 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-react imports 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-editor work 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:

  1. src/ui (or the ratified equivalent) is the only production source for reusable visual primitives.
  2. Storybook imports those production components; duplicate components under design-docs/src/components are removed.
  3. Feature source contains zero raw native interactive controls.
  4. Feature source contains zero JSX style props and web HTML contains zero hand-authored style attributes or <style> blocks.
  5. Feature source contains zero raw SVG markup and zero direct icon-library imports.
  6. Feature source contains zero hardcoded color values and zero arbitrary visual Tailwind values.
  7. Every reusable button, field, overlay, status, surface, typography, and layout recipe maps to a named component or semantic class.
  8. Customer and Cortex themes pass visual regression, contrast, keyboard, focus, and responsive QA.
  9. A structural CI gate rejects every prohibited pattern without a grandfathered baseline.
  10. 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

  1. Storybook-only primitives

    design-docs/src/components defines ButtonFilled, ButtonOutline, PillOption, SegmentToggle, StepIndicator, CheckBadge, and TaskHighlight. Their visual rules are authored with inline style objects. They cannot be the target library in their current form.

  2. Pulse-wizard primitives

    src/components/pulse-wizard-v3/ui.tsx defines PrimaryButton, OutlineButton, QuietButton, FieldShell, CounterStepper, SegmentedToggle, SelectableCard, and SearchInput. This is the best pilot because production and Storybook already both import it, but it is feature-scoped and embeds literal visual values.

  3. Report-editor recipes

    src/components/report-editor/styles.ts shares INPUT_CLASSES, ADD_BUTTON, and ICON_BUTTON. This reduces copying within one feature, but strings are not semantic components and cannot enforce accessible structure or icon usage.

  4. Status components

    src/components/Badge.tsx and src/components/help/HelpStatusBadge.tsx implement separate badge systems and include raw color-family choices. They need one semantic Badge/StatusBadge API.

Token and theme drift

  • src/index.css and design-docs/src/tokens.css both define design tokens with different names and incomplete overlap.
  • Storybook adds more Tailwind theme definitions in onboarding-tailwind.css and pulse-wizard-v3-tailwind.css.
  • design-docs/src/tokens.css explicitly records a body-font divergence from the app.
  • customer code mixes semantic tokens such as text-text-muted with literal forms such as text-[#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, and Building2 are the most frequently imported Lucide implementation names.
  • Google marks are independently embedded in Login.tsx and Profile.tsx with different view boxes/path data.
  • Layout.tsx embeds a custom help glyph; AppFooter.tsx embeds the tagline wordmark; SentimentIcon.tsx embeds sentiment paths; NotFound.tsx embeds an illustration.
  • These custom assets are legitimate, but they need named ownership in src/ui/icons, src/ui/brand, or src/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/src has 56 inline style props across 14 finding files.
  • public/docs/userjourneys-embed/index.html has 662 inline style attributes.
  • public/docs/confetti-celebration-embed/index.html has four <style> blocks and 18 controls.
  • release/drift report embeds contain authored <style> blocks and inline styles.
  • qa and ops server-rendered views contain inline style attributes, <style> blocks, raw controls, and raw SVG.
  • worker/lib/email.ts contains 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.destructive with rest, hover, pressed, focus, and disabled states;
  • status.info, status.success, status.warning, status.danger with 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 style props, 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

  1. Approve this scope and record an ADR covering semantic HTML, the external behavior primitive choice, Tailwind's final role, email output, and generated documentation.
  2. Add a TypeScript-AST audit script and a Vitest/CI wrapper.
  3. Record the current per-file baseline for raw controls, style props, raw SVG, direct icon imports, literal colors, arbitrary visual values, and hand-rolled overlays.
  4. Add the rules to repo-level AGENTS.md so 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

  1. Complete semantic color, type, spacing, radius, shadow, control, icon, and motion roles.
  2. Make the production token CSS the only source imported by app and Storybook.
  3. Remove duplicate token declarations from design-docs.
  4. Introduce customer and Cortex semantic theme roots.
  5. 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:

  1. typography and layout;
  2. Icon, brand marks, and illustrations;
  3. Button, IconButton, and LinkButton;
  4. Field, text controls, selection controls, and search;
  5. badges, alerts, progress, skeletons, and empty states;
  6. cards, panels, toolbars, and tables;
  7. 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

  1. Move the useful API from pulse-wizard-v3/ui.tsx into src/ui.
  2. Update CreatePulseV3 and its Storybook flow to consume the production library.
  3. Extract GoogleMark, the UserHappy brand mark, custom help glyph, footer wordmark, and sentiment graphics into named library assets.
  4. Migrate Login/Profile buttons and fields to prove customer/Cortex theming and third-party brand handling.
  5. 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

  1. After the current report-editor work is stable, replace styles.ts strings with field, button, icon-button, card, and table components.
  2. Migrate shared shells and components: Layout, AppFooter, PageHeader, badges, progress, dialogs, help panels, participant preview, and export UI.
  3. Replace all hand-rolled dialogs and menus with the overlay library.
  4. Migrate DetailedReport chart/progress rendering to semantic report components with no style props.

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:

  1. customer dashboard, reports, results, sessions, and participant flows;
  2. team, profile, help, and public/auth routes;
  3. Cortex shell, team, customers, connect, environments, and inbox;
  4. high-density CortexPulses and CortexReportBuilder;
  5. Panels.tsx last, 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

  1. Generate public documentation embeds from shared React components or author them with linked semantic CSS classes; remove authored inline styling and <style> blocks.
  2. Give Ops and QA server views shared semantic render helpers and an external stylesheet.
  3. Convert email templates to semantic email components/tokens. Inline CSS may exist only in generated/delivered HTML and golden fixtures.
  4. 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

  1. Delete all grandfathered counts.
  2. Hard-fail CI on raw controls outside src/ui, style props, raw SVG outside asset modules, direct icon imports, literal visual values, and duplicate token definitions.
  3. Add a dependency-boundary test so features can import only src/ui/index.ts.
  4. Make the component inventory and visual regression suite required CI.
  5. 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
Email 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:

  1. add the structural ratchet and ADR;
  2. consolidate token imports for app and Storybook;
  3. build Icon, Button, IconButton, Field, TextField, Textarea, Select, Card, Dialog, and basic layout primitives;
  4. migrate pulse-wizard-v3, Login, and Profile;
  5. extract Google/UserHappy/help/footer/sentiment assets;
  6. 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.

Source: docs/ux-reviews/2026-08-10-ui-componentization-audit-and-plan.md