Files
ims/docs/superpowers/plans/2026-09-30-modernist-design-system-restyle.md
T

1909 lines
76 KiB
Markdown

# Modernist Design System Restyle Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Restyle the whole IMS app to the Modernist design system, and leave guardrails so future development stays on-system.
**Architecture:** Declare the Modernist tokens in `app/globals.css` with Tailwind v4 `@theme static`, remapping the existing `gray-*` and `blue-*` palettes and zeroing all radii so existing utility classes restyle automatically. A small codemod removes dead `rounded-*` classes and swaps `bg-white` and gray borders. Thin shared components (`Button`, `Tag`, `StatusTag`, `PriorityTag`, `Field`, `Card`, `Modal`) cover what token remapping cannot (flush-left labels, status colors). A gate script (`npm run check:design`) fails on off-system classes.
**Tech Stack:** Next.js 16.3.7 (App Router), React 19, Tailwind CSS v4 (`@tailwindcss/postcss`), `lucide-react`, Archivo via `next/font/google`, vitest 4 + jsdom + `@testing-library/react`.
**Spec:** `docs/superpowers/specs/2026-09-30-modernist-design-system-design.md`
## Global Constraints
- Design source of truth: `design-system/_ds/modernist-6062679c-a4aa-42a4-9043-28fea370dda9/readme.md` and `styles.css`. `design-system/IMS Admin.dc.html` (Geist, teal, 12px radius) is NOT implemented.
- Take every color, font, spacing, radius and shadow from tokens (`var(--color-*)`, `var(--font-*)`, `var(--space-*)`, `var(--radius-*)`, `var(--shadow-*)`). Never hard-code a hex, font name, or px value the tokens already carry.
- Zero corner radius anywhere. `rounded-full` is kept only for circular avatars and radio dots.
- Strong 2px rules (`var(--color-divider)`) between major sections. Do not soften into hairlines.
- Button labels are flush left, including labels inside wide buttons. Never center button labels or hero copy.
- Icons: Lucide (`lucide-react`). Fonts: Archivo (variable font) for headings and body.
- Light ground only (`--color-bg` #f3f2f2, `--color-text` #201e1d, accent #ec3013). No dark mode.
- Body-size text in the accent uses `accent-700`, never the accent itself (accent on ground is 3:1, for chrome and large text only).
- Interactive states are themed: hover tint, pressed step from the accent ramp, `:focus-visible { outline: 2px solid var(--color-accent); outline-offset: 2px; }`. Disabled controls drop to 45% opacity.
- Status mapping (approved): needs attention or overdue or open or reported or severity 4 to 5 = `tag-accent`; in progress (triaged, investigating, CAPA pending, verification, in_progress, pending_verification) = `tag-outline`; done (closed, verified, completed) and low or informational = `tag-neutral`. Status is never color alone: keep the text label and add a Lucide icon.
- Incident evidence photos and thumbnails stay full color. `.grayscale` is for decorative or brand photography only.
- No database, API, auth or routing changes. PDFs (JKKP 6/7/8, incident report) and email templates are out of scope.
- Deployment: build locally only, NEVER run `next build` or `npm ci` on the server. Server path `/srv/apps/ims/app` (`/var/www/ims` is a symlink). Never overwrite or delete `.env*` files. Restart with `sudo systemctl restart ims`. Never restart if `.next/BUILD_ID` is missing. Do not deploy without the user's go-ahead.
## File Structure
**Create**
- `tests/design/tokens.test.ts` — contract test for the token sheet in `globals.css`
- `scripts/modernist-codemod.mjs` — `transformSource()` plus CLI that rewrites class names
- `tests/scripts/modernist-codemod.test.ts` — unit tests for the codemod
- `components/ui/button.tsx`, `tag.tsx`, `status-tag.tsx`, `field.tsx`, `card.tsx` — shared components
- `tests/components/ui/*.test.tsx` — tests for each shared component
- `scripts/check-design-gates.mjs` — gate script, exposed as `npm run check:design`
- `tests/scripts/check-design-gates.test.ts` — tests for the gate rules
**Modify**
- `app/globals.css` — tokens, theme remap, base layer
- `app/layout.tsx` — Archivo replaces Geist
- `package.json` — `lucide-react`, `check:design` script
- `components/ui/modal.tsx`, `components/layout/sidebar.tsx`, `components/notifications/bell.tsx`, `app/(protected)/layout.tsx`
- 11 files holding status, priority or severity color maps (listed in Task 6)
- All remaining TSX files flagged by the gate script (Task 7)
- `CLAUDE.md`, plus memory file `ims-design-system.md` and `MEMORY.md` index (Task 8)
---
### Task 1: Tokens, theme remap, and Archivo font
**Files:**
- Create: `tests/design/tokens.test.ts`
- Modify: `app/globals.css` (full rewrite), `app/layout.tsx`, `package.json` (via npm install)
**Interfaces:**
- Consumes: nothing.
- Produces: Tailwind utilities `bg-ground`, `bg-surface`, `text-ink`, `bg-accent`, `text-accent`, `border-divider`, `bg-accent-100…900`, `bg-neutral-100…900`; CSS vars `--color-bg`, `--color-surface`, `--color-text`, `--color-accent`, `--color-divider`, `--shadow-sm|md|lg`, `--font-sans`; `gray-*` remapped to the neutral ramp and `blue-*` remapped to the accent ramp; every `rounded-*` size resolves to 0.
- [ ] **Step 1: Create a working branch and install Lucide**
```bash
cd /Users/yapweeihan/Projects/IMS.nosync
git checkout -b feat/modernist-restyle
npm install lucide-react
```
Expected: `lucide-react` appears under `dependencies` in `package.json`. Leave the untracked `design-system/*` files and the deleted `design-system/ims-admin/MASTER.md` alone; they are handled in Task 8.
- [ ] **Step 2: Write the failing token contract test**
Create `tests/design/tokens.test.ts`:
```ts
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'fs'
import path from 'path'
const css = readFileSync(path.resolve(__dirname, '../../app/globals.css'), 'utf8')
describe('Modernist tokens in globals.css', () => {
it.each([
['--color-bg', '#f3f2f2'],
['--color-surface', '#eae9e9'],
['--color-text', '#201e1d'],
['--color-accent', '#ec3013'],
['--color-accent-700', '#ae1800'],
['--color-neutral-900', '#2d2b2b'],
])('declares %s as %s', (name, value) => {
expect(css).toMatch(new RegExp(`${name}:\\s*${value}`, 'i'))
})
it.each(['xs', 'sm', 'md', 'lg', 'xl', '2xl', '3xl', '4xl'])('zeroes --radius-%s', size => {
expect(css).toMatch(new RegExp(`--radius-${size}:\\s*0px`))
})
it('remaps the gray ramp onto the neutral ramp', () => {
expect(css).toMatch(/--color-gray-100:\s*var\(--color-neutral-200\)/)
expect(css).toMatch(/--color-gray-900:\s*var\(--color-text\)/)
})
it('remaps the blue ramp onto the accent ramp', () => {
expect(css).toMatch(/--color-blue-600:\s*var\(--color-accent\)/)
expect(css).toMatch(/--color-blue-700:\s*var\(--color-accent-700\)/)
})
it('maps shadows onto the Modernist elevation tokens', () => {
expect(css).toMatch(/--shadow-2xl:\s*var\(--shadow-lg\)/)
})
it('uses Archivo through the next/font variable', () => {
expect(css).toMatch(/--font-sans:\s*var\(--font-archivo\)/)
})
it('has no dark mode block', () => {
expect(css).not.toContain('prefers-color-scheme')
})
it('styles keyboard focus with the 2px accent ring', () => {
expect(css).toMatch(/:focus-visible\s*\{[^}]*outline:\s*2px solid var\(--color-accent\)/)
})
})
```
- [ ] **Step 3: Run the test to verify it fails**
Run: `npx vitest run tests/design/tokens.test.ts`
Expected: FAIL (most assertions, because `globals.css` still has the old tokens).
- [ ] **Step 4: Rewrite `app/globals.css`**
Replace the whole file with:
```css
@import "tailwindcss";
/* Modernist tokens. Source of truth: the Modernist styles.css under design-system/_ds.
Static emits every variable so plain CSS can use var(--color-*) too. */
@theme static {
--color-bg: #f3f2f2;
--color-surface: #eae9e9;
--color-text: #201e1d;
--color-accent: #ec3013;
--color-accent-2: #e15b47;
--color-divider: color-mix(in srgb, #201e1d 40%, transparent);
/* Utility-friendly aliases: bg-ground, text-ink */
--color-ground: var(--color-bg);
--color-ink: var(--color-text);
--color-neutral-100: #f8f4f4;
--color-neutral-200: #eae7e7;
--color-neutral-300: #d7d3d3;
--color-neutral-400: #bab6b6;
--color-neutral-500: #9b9797;
--color-neutral-600: #7d7979;
--color-neutral-700: #605d5d;
--color-neutral-800: #444141;
--color-neutral-900: #2d2b2b;
--color-accent-100: #fff2ef;
--color-accent-200: #ffe0d9;
--color-accent-300: #ffc4b8;
--color-accent-400: #ff9783;
--color-accent-500: #ff563c;
--color-accent-600: #dd2b0f;
--color-accent-700: #ae1800;
--color-accent-800: #7c1405;
--color-accent-900: #4d170e;
--color-accent-2-100: #fff2ef;
--color-accent-2-200: #ffe0da;
--color-accent-2-300: #ffc4b9;
--color-accent-2-400: #ff9784;
--color-accent-2-500: #ef6853;
--color-accent-2-600: #c94b39;
--color-accent-2-700: #9e3526;
--color-accent-2-800: #71261b;
--color-accent-2-900: #471d16;
/* Existing gray-* utilities render on the neutral ramp. */
--color-gray-50: var(--color-neutral-100);
--color-gray-100: var(--color-neutral-200);
--color-gray-200: var(--color-neutral-300);
--color-gray-300: var(--color-neutral-400);
--color-gray-400: var(--color-neutral-500);
--color-gray-500: var(--color-neutral-600);
--color-gray-600: var(--color-neutral-700);
--color-gray-700: var(--color-neutral-800);
--color-gray-800: var(--color-neutral-900);
--color-gray-900: var(--color-text);
--color-gray-950: var(--color-text);
/* Existing blue-* utilities render on the accent ramp. 600 is the canonical
accent; 700 and darker are safe for body-size text. */
--color-blue-50: var(--color-accent-100);
--color-blue-100: var(--color-accent-100);
--color-blue-200: var(--color-accent-200);
--color-blue-300: var(--color-accent-300);
--color-blue-400: var(--color-accent-400);
--color-blue-500: var(--color-accent-500);
--color-blue-600: var(--color-accent);
--color-blue-700: var(--color-accent-700);
--color-blue-800: var(--color-accent-800);
--color-blue-900: var(--color-accent-900);
--color-blue-950: var(--color-accent-900);
/* Zero corner radius, everywhere. */
--radius: 0px;
--radius-xs: 0px;
--radius-sm: 0px;
--radius-md: 0px;
--radius-lg: 0px;
--radius-xl: 0px;
--radius-2xl: 0px;
--radius-3xl: 0px;
--radius-4xl: 0px;
/* Elevation, tuned to the ground. */
--shadow-sm: 0 1px 2px color-mix(in srgb, #2d2b2b 14%, transparent);
--shadow-md: 0 3px 10px color-mix(in srgb, #2d2b2b 16%, transparent);
--shadow-lg: 0 12px 32px color-mix(in srgb, #2d2b2b 22%, transparent);
--shadow-xl: var(--shadow-lg);
--shadow-2xl: var(--shadow-lg);
--font-sans: var(--font-archivo), system-ui, sans-serif;
--font-heading: var(--font-archivo), system-ui, sans-serif;
}
@layer base {
html {
background: var(--color-bg);
}
body {
background: var(--color-bg);
color: var(--color-text);
font-family: var(--font-sans);
font-size: 15px;
line-height: 1.55;
}
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-heading);
font-weight: 800;
line-height: 1.12;
letter-spacing: -0.015em;
}
:focus {
outline: none;
}
:focus-visible {
outline: 2px solid var(--color-accent);
outline-offset: 2px;
}
::selection {
background: color-mix(in srgb, var(--color-accent) 30%, transparent);
}
input,
textarea,
select {
color: var(--color-text);
}
input::placeholder,
textarea::placeholder {
color: color-mix(in srgb, var(--color-text) 55%, transparent);
}
button:disabled,
input:disabled,
select:disabled,
textarea:disabled {
opacity: 0.45;
cursor: not-allowed;
}
}
.grayscale {
filter: grayscale(1) contrast(1.08);
}
```
- [ ] **Step 5: Swap Geist for Archivo in `app/layout.tsx`**
Replace the font imports and instances. The top of the file becomes:
```tsx
import type { Metadata } from 'next'
import { Archivo } from 'next/font/google'
import './globals.css'
import { I18nProvider } from '@/lib/i18n/context'
import { getLocale, loadMessages } from '@/lib/i18n/server'
const archivo = Archivo({
variable: '--font-archivo',
subsets: ['latin'],
})
```
(Omitting `weight` loads the variable font, so every weight from 400 to 800 renders exactly.) Change the `<html>` element's className to:
```tsx
className={`${archivo.variable} h-full antialiased`}
```
Delete the `geistSans` and `geistMono` constants and their usages. Confirm nothing else uses them: `grep -rn "font-geist\|geistMono\|geistSans" app components` must print nothing (if `font-mono` is used somewhere, it now falls back to the Tailwind default monospace stack, which is fine).
- [ ] **Step 6: Run the token test, then verify the compiled CSS**
Run: `npx vitest run tests/design/tokens.test.ts`
Expected: PASS (all).
Run the production build and inspect the emitted CSS:
```bash
npm run build 2>&1 | tail -5
grep -ho '\.rounded-xl{[^}]*}' .next/static/chunks/*.css | head -2
grep -ho '\-\-radius-xl:[^;}]*' .next/static/chunks/*.css | head -1
grep -ho '\-\-color-blue-600:[^;}]*' .next/static/chunks/*.css | head -1
grep -ho '\.rounded{[^}]*}' .next/static/chunks/*.css | head -1
```
Expected:
- build succeeds,
- `.rounded-xl{border-radius:var(--radius-xl)}` and `--radius-xl:0px`,
- `--color-blue-600:var(--color-accent)`.
- Check the bare `.rounded{...}` output: if it is a literal such as `0.25rem` rather than a var resolving to 0, add `--radius: 0px;` to the `@theme static` block and rebuild. The codemod in Task 2 removes bare `rounded` anyway, so this is belt and braces.
- [ ] **Step 7: Commit**
```bash
git add app/globals.css app/layout.tsx package.json package-lock.json tests/design/tokens.test.ts
git commit -m "feat(design): add Modernist tokens, theme remap and Archivo font
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
```
---
### Task 2: Class-name codemod
**Files:**
- Create: `scripts/modernist-codemod.mjs`, `tests/scripts/modernist-codemod.test.ts`
- Modify: every `app/**/*.tsx` and `components/**/*.tsx` whose `className` matches a rule (written by the script)
**Interfaces:**
- Consumes: Task 1 utilities `bg-surface`, `border-divider`, `shadow-lg`.
- Produces: `export function transformSource(src: string): string` (pure, idempotent), and a CLI `node scripts/modernist-codemod.mjs [--dry]` that prints `changed N files`.
Rules, applied only inside `className=` attribute values (`"…"`, `'…'`, `{"…"}`, `{'…'}`, `` {`…`} ``):
1. Remove `rounded`, `rounded-{xs|sm|md|lg|xl|2xl|3xl|4xl|none}` and side forms (`rounded-t-lg`, `rounded-br`, …), including variant prefixes (`hover:rounded-lg`). Keep `rounded-full`.
2. `bg-white` becomes `bg-surface` (variants and `/opacity` kept).
3. `border-gray-100|200|300` becomes `border-divider`; `divide-gray-100|200|300` becomes `divide-divider`.
4. `shadow-xl` and `shadow-2xl` become `shadow-lg`.
5. Drop a now-empty `className=""` attribute and collapse repeated spaces.
- [ ] **Step 1: Write the failing tests**
Create `tests/scripts/modernist-codemod.test.ts`:
```ts
import { describe, it, expect } from 'vitest'
import { transformSource } from '../../scripts/modernist-codemod.mjs'
const t = (s: string): string => transformSource(s)
describe('modernist codemod', () => {
it('removes rounded-* sizes but keeps rounded-full', () => {
expect(t('<div className="rounded-xl p-4 rounded-full" />')).toBe('<div className="p-4 rounded-full" />')
expect(t('<div className="p-4 rounded" />')).toBe('<div className="p-4" />')
expect(t('<div className="rounded-t-lg border" />')).toBe('<div className="border" />')
})
it('removes variant-prefixed rounded classes whole', () => {
expect(t('<a className="hover:rounded-lg px-2" />')).toBe('<a className="px-2" />')
})
it('swaps bg-white for bg-surface, keeping variants and opacity', () => {
expect(t('<div className="bg-white p-2" />')).toBe('<div className="bg-surface p-2" />')
expect(t('<div className="hover:bg-white/80" />')).toBe('<div className="hover:bg-surface/80" />')
})
it('swaps light gray borders and dividers for the divider token', () => {
expect(t('<div className="border border-gray-200" />')).toBe('<div className="border border-divider" />')
expect(t('<ul className="divide-y divide-gray-100" />')).toBe('<ul className="divide-y divide-divider" />')
})
it('leaves dark gray borders alone', () => {
expect(t('<div className="border-gray-500" />')).toBe('<div className="border-gray-500" />')
})
it('swaps heavy shadows for shadow-lg', () => {
expect(t('<div className="shadow-2xl" />')).toBe('<div className="shadow-lg" />')
expect(t('<div className="shadow-xl" />')).toBe('<div className="shadow-lg" />')
expect(t('<div className="shadow-sm" />')).toBe('<div className="shadow-sm" />')
})
it('handles template literals with conditionals', () => {
const src = '<div className={`rounded-lg p-2 ${on ? \'bg-white rounded-md\' : \'bg-gray-50\'}`} />'
expect(t(src)).toBe('<div className={`p-2 ${on ? \'bg-surface\' : \'bg-gray-50\'}`} />')
})
it('drops a className that becomes empty', () => {
expect(t('<div className="rounded-lg" />')).toBe('<div />')
})
it('does not touch text outside className', () => {
const src = '<p>The corners are rounded and bg-white is a word.</p>'
expect(t(src)).toBe(src)
})
it('is idempotent', () => {
const once = t('<div className="rounded-xl bg-white border-gray-200 shadow-2xl" />')
expect(t(once)).toBe(once)
})
})
```
- [ ] **Step 2: Run the tests to verify they fail**
Run: `npx vitest run tests/scripts/modernist-codemod.test.ts`
Expected: FAIL ("Cannot find module" for the script).
- [ ] **Step 3: Write the codemod**
Create `scripts/modernist-codemod.mjs`:
```js
import { readdirSync, readFileSync, writeFileSync, statSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const CLASS_ATTR =
/className=(?:"[^"]*"|'[^']*'|\{"[^"]*"\}|\{'[^']*'\}|\{`(?:[^`\\]|\\.)*`\})/g
const ROUNDED =
/(?<![\w:-])(?:[\w-]+:)*rounded(?:-(?:t|b|l|r|tl|tr|bl|br|s|e))?(?:-(?:xs|sm|md|lg|xl|2xl|3xl|4xl|none))?(?![\w-])/g
function transformClassAttr(attr) {
let out = attr
out = out.replace(ROUNDED, '')
out = out.replace(/(?<![\w-])bg-white(?![\w-])/g, 'bg-surface')
out = out.replace(/(?<![\w-])border-gray-(?:100|200|300)(?![\w-])/g, 'border-divider')
out = out.replace(/(?<![\w-])divide-gray-(?:100|200|300)(?![\w-])/g, 'divide-divider')
out = out.replace(/(?<![\w-])shadow-(?:xl|2xl)(?![\w-])/g, 'shadow-lg')
out = out.replace(/(["'])([^"'`$]*)\1/g, (_, q, body) => q + body.trim().replace(/ {2,}/g, ' ') + q)
out = out.replace(/^(className=\{`)\s+/, '$1').replace(/\s+(`\})$/, '$1')
return out
}
export function transformSource(src) {
const next = src.replace(CLASS_ATTR, transformClassAttr)
return next.replace(/ className=(?:""|''|\{""\}|\{''\}|\{``\})/g, '')
}
function walk(dir, files = []) {
for (const name of readdirSync(dir)) {
const full = path.join(dir, name)
if (statSync(full).isDirectory()) walk(full, files)
else if (full.endsWith('.tsx')) files.push(full)
}
return files
}
function main() {
const dry = process.argv.includes('--dry')
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
let changed = 0
for (const dir of ['app', 'components']) {
for (const file of walk(path.join(root, dir))) {
const before = readFileSync(file, 'utf8')
const after = transformSource(before)
if (after !== before) {
changed++
if (!dry) writeFileSync(file, after)
}
}
}
console.log(`${dry ? 'would change' : 'changed'} ${changed} files`)
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main()
```
Note on the whitespace cleanup: only string-literal bodies and the attribute's outer backtick delimiters are trimmed, so spaces around `?` and `:` inside `${...}` survive.
- [ ] **Step 4: Run the tests to verify they pass**
Run: `npx vitest run tests/scripts/modernist-codemod.test.ts`
Expected: PASS (9 tests). If the template-literal case fails, check that `CLASS_ATTR` still matches the whole `` {`...`} `` span including the nested `${...}` (nested backticks are not supported and are not present in this codebase).
- [ ] **Step 5: Dry-run, then apply**
```bash
node scripts/modernist-codemod.mjs --dry
```
Expected: `would change N files` with N between 40 and 62. If N is 0 or above 62, stop and debug the regexes before writing.
```bash
node scripts/modernist-codemod.mjs
git diff --stat | tail -3
```
Expected: only `.tsx` files under `app/` and `components/` changed; diff is deletions of `rounded-*` plus one-word swaps.
- [ ] **Step 6: Verify nothing broke**
```bash
npx vitest run 2>&1 | tail -8
npm run build 2>&1 | tail -6
grep -rhoE '(^|[\s"'"'"'`:])rounded(-(xs|sm|md|lg|xl|2xl|3xl|4xl|t|b|l|r|tl|tr|bl|br))*[\s"'"'"'`]' app components --include='*.tsx' | sort | uniq -c | sort -rn | head
```
Expected: all tests pass (the suite has no class-name assertions), the build passes, and the last command prints only leftovers that sit outside `className` (for example constants such as `const base = '...'`). List any leftovers and fix them by hand in this task: delete the `rounded-*` token, keep `rounded-full`.
- [ ] **Step 7: Commit**
```bash
git add scripts/modernist-codemod.mjs tests/scripts/modernist-codemod.test.ts app components
git commit -m "refactor(design): drop rounded classes, swap bg-white and gray borders for tokens
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
```
### Task 3: Shared UI primitives
**Files:**
- Create: `components/ui/cx.ts`, `components/ui/button.tsx`, `components/ui/tag.tsx`, `components/ui/status-tag.tsx`, `components/ui/field.tsx`, `components/ui/card.tsx`, `components/ui/table-styles.ts`
- Test: `tests/components/ui/primitives.test.tsx`
**Interfaces:**
- Consumes: Task 1 utilities (`bg-accent`, `bg-surface`, `text-ink`, `border-divider`, `accent-*`, `neutral-*`).
- Produces (later tasks import these exactly):
- `cx(...parts: Array<string | false | null | undefined>): string`
- `Button({ variant?: 'primary' | 'secondary' | 'ghost' | 'icon', block?: boolean } & ButtonHTMLAttributes)`; default `type="button"`
- `Tag({ variant: 'accent' | 'neutral' | 'outline', children })`
- `statusTone(status: string): 'accent' | 'outline' | 'neutral'`, `StatusTag({ status: string, children?: ReactNode })`, `PriorityTag({ priority: string, children?: ReactNode })`
- `Field({ label, htmlFor, children })`, `Input`, `Textarea`, `Select` (native elements sharing `INPUT_CLASS`)
- `Card({ kicker?, title?, meta?, children? })`
- `TABLE`, `TH`, `TR`, `TD` class-string constants from `table-styles.ts`
- [ ] **Step 1: Write the failing tests**
Create `tests/components/ui/primitives.test.tsx`:
```tsx
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import { Button } from '@/components/ui/button'
import { Tag } from '@/components/ui/tag'
import { StatusTag, PriorityTag, statusTone } from '@/components/ui/status-tag'
import { Field, Input } from '@/components/ui/field'
import { Card } from '@/components/ui/card'
import { TABLE, TH, TR, TD } from '@/components/ui/table-styles'
describe('Button', () => {
it('renders a primary accent button that is type=button and flush left', () => {
render(<Button variant="primary">Save</Button>)
const btn = screen.getByRole('button', { name: 'Save' })
expect(btn.getAttribute('type')).toBe('button')
expect(btn.className).toContain('bg-accent')
expect(btn.className).toContain('justify-start')
expect(btn.className).not.toContain('justify-center')
})
it('block buttons span the row and stay flush left', () => {
render(<Button block>Go</Button>)
const btn = screen.getByRole('button', { name: 'Go' })
expect(btn.className).toContain('w-full')
expect(btn.className).toContain('justify-start')
})
it('icon buttons are square and centered', () => {
render(<Button variant="icon" aria-label="Close" />)
const btn = screen.getByRole('button', { name: 'Close' })
expect(btn.className).toContain('w-9')
expect(btn.className).toContain('justify-center')
})
it('never uses a rounded class', () => {
render(<Button variant="secondary">x</Button>)
expect(screen.getByRole('button').className).not.toMatch(/rounded/)
})
})
describe('Tag', () => {
it.each([
['accent', 'bg-accent-100'],
['neutral', 'bg-neutral-100'],
['outline', 'border-accent'],
] as const)('%s variant carries %s', (variant, cls) => {
render(<Tag variant={variant}>Label</Tag>)
expect(screen.getByText('Label').className).toContain(cls)
})
})
describe('statusTone', () => {
it.each([
['reported', 'accent'],
['triaged', 'outline'],
['investigating', 'outline'],
['capa_pending', 'outline'],
['verification', 'outline'],
['closed', 'neutral'],
['open', 'accent'],
['in_progress', 'outline'],
['overdue', 'accent'],
['pending_verification', 'outline'],
['verified', 'neutral'],
['reopened', 'accent'],
['something_else', 'neutral'],
])('%s maps to %s', (status, tone) => {
expect(statusTone(status)).toBe(tone)
})
})
describe('StatusTag', () => {
it('shows a humanized text label plus an icon, never color alone', () => {
const { container } = render(<StatusTag status="capa_pending" />)
expect(screen.getByText('CAPA Pending')).toBeTruthy()
expect(container.querySelector('svg')).not.toBeNull()
})
it('accepts a label override', () => {
render(<StatusTag status="overdue">Late</StatusTag>)
expect(screen.getByText('Late')).toBeTruthy()
})
})
describe('PriorityTag', () => {
it.each([
['high', 'bg-accent-100'],
['med', 'border-accent'],
['low', 'bg-neutral-100'],
])('%s priority uses %s', (priority, cls) => {
const { container } = render(<PriorityTag priority={priority} />)
expect(container.firstElementChild?.className).toContain(cls)
})
})
describe('Field and Input', () => {
it('associates the label with the input', () => {
render(
<Field label="Email" htmlFor="email">
<Input id="email" />
</Field>,
)
const input = screen.getByLabelText('Email')
expect(input.className).toContain('bg-surface')
expect(input.className).toContain('border-divider')
})
})
describe('Card', () => {
it('renders kicker, title, body and meta on the surface fill', () => {
const { container } = render(
<Card kicker="Open" title="Forklift" meta="Due Friday">
Body text
</Card>,
)
expect(screen.getByText('Open')).toBeTruthy()
expect(screen.getByText('Forklift')).toBeTruthy()
expect(screen.getByText('Body text')).toBeTruthy()
expect(screen.getByText('Due Friday')).toBeTruthy()
expect(container.firstElementChild?.className).toContain('bg-surface')
})
})
describe('table styles', () => {
it('uses a 2px header rule and 1px row rules', () => {
expect(TH).toContain('border-b-2')
expect(TH).toContain('border-divider')
expect(TD).toContain('border-b')
expect(TR).toContain('hover:bg-ink/4')
expect(TABLE).toContain('w-full')
})
})
```
- [ ] **Step 2: Run the tests to verify they fail**
Run: `npx vitest run tests/components/ui/primitives.test.tsx`
Expected: FAIL (modules not found).
- [ ] **Step 3: Write the primitives**
`components/ui/cx.ts`:
```ts
export const cx = (...parts: Array<string | false | null | undefined>): string =>
parts.filter(Boolean).join(' ')
```
`components/ui/button.tsx`:
```tsx
import type { ButtonHTMLAttributes } from 'react'
import { cx } from './cx'
type Variant = 'primary' | 'secondary' | 'ghost' | 'icon'
const BASE =
'inline-flex items-center gap-1.5 text-left font-extrabold text-sm leading-tight ' +
'border border-transparent cursor-pointer transition-colors ' +
'disabled:opacity-45 disabled:cursor-not-allowed'
const VARIANTS: Record<Variant, string> = {
primary: 'justify-start bg-accent text-ground px-3.5 py-2 hover:bg-accent-600 active:bg-accent-700',
secondary: 'justify-start border-divider text-ink px-3.5 py-2 hover:bg-ink/7 active:bg-ink/15',
ghost: 'justify-start text-accent-700 px-1 py-2 hover:bg-accent/10 active:bg-accent/20',
icon: 'justify-center w-9 h-9 p-0 text-ink hover:bg-ink/7 active:bg-ink/15',
}
type Props = ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: Variant
block?: boolean
}
export function Button({ variant = 'primary', block = false, className, type = 'button', ...rest }: Props) {
return <button type={type} className={cx(BASE, VARIANTS[variant], block && 'w-full', className)} {...rest} />
}
```
`components/ui/tag.tsx`:
```tsx
import type { ReactNode } from 'react'
import { cx } from './cx'
export type TagVariant = 'accent' | 'neutral' | 'outline'
const VARIANTS: Record<TagVariant, string> = {
accent: 'bg-accent-100 text-accent-800',
neutral: 'bg-neutral-100 text-neutral-800',
outline: 'border border-accent text-accent-700',
}
export function Tag({ variant, children, className }: { variant: TagVariant; children: ReactNode; className?: string }) {
return (
<span
className={cx(
'inline-flex items-center gap-1 text-[11px] font-medium tracking-wide px-2.5 py-[3px] whitespace-nowrap',
VARIANTS[variant],
className,
)}
>
{children}
</span>
)
}
```
`components/ui/status-tag.tsx`:
```tsx
import type { ReactNode } from 'react'
import {
AlarmClock,
BadgeCheck,
Circle,
CircleAlert,
CircleCheck,
ClipboardList,
ListChecks,
Loader,
RotateCcw,
Search,
type LucideIcon,
} from 'lucide-react'
import { Tag, type TagVariant } from './tag'
const TONES: Record<string, TagVariant> = {
reported: 'accent',
triaged: 'outline',
investigating: 'outline',
capa_pending: 'outline',
verification: 'outline',
closed: 'neutral',
open: 'accent',
in_progress: 'outline',
overdue: 'accent',
pending_verification: 'outline',
verified: 'neutral',
reopened: 'accent',
}
const ICONS: Record<string, LucideIcon> = {
reported: CircleAlert,
triaged: ListChecks,
investigating: Search,
capa_pending: ClipboardList,
verification: BadgeCheck,
closed: CircleCheck,
open: Circle,
in_progress: Loader,
overdue: AlarmClock,
pending_verification: BadgeCheck,
verified: CircleCheck,
reopened: RotateCcw,
}
export function statusTone(status: string): TagVariant {
return TONES[status] ?? 'neutral'
}
function humanize(value: string): string {
return value
.split('_')
.map(w => (w === 'capa' ? 'CAPA' : w.charAt(0).toUpperCase() + w.slice(1)))
.join(' ')
}
export function StatusTag({ status, children }: { status: string; children?: ReactNode }) {
const Icon = ICONS[status]
return (
<Tag variant={statusTone(status)}>
{Icon && <Icon size={12} strokeWidth={2} aria-hidden />}
{children ?? humanize(status)}
</Tag>
)
}
const PRIORITY_TONES: Record<string, TagVariant> = { high: 'accent', med: 'outline', low: 'neutral' }
export function PriorityTag({ priority, children }: { priority: string; children?: ReactNode }) {
return <Tag variant={PRIORITY_TONES[priority] ?? 'neutral'}>{children ?? humanize(priority)}</Tag>
}
```
`components/ui/field.tsx`:
```tsx
import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes, TextareaHTMLAttributes } from 'react'
import { cx } from './cx'
export const INPUT_CLASS =
'w-full min-h-9 px-2.5 py-1.5 text-sm text-ink caret-accent bg-surface border border-divider ' +
'hover:border-ink/45 focus-visible:border-accent focus-visible:outline-offset-0 ' +
'disabled:opacity-45 disabled:cursor-not-allowed'
export function Field({ label, htmlFor, children }: { label: string; htmlFor: string; children: ReactNode }) {
return (
<div>
<label htmlFor={htmlFor} className="block text-xs mb-[5px] text-ink/70">
{label}
</label>
{children}
</div>
)
}
export function Input({ className, ...rest }: InputHTMLAttributes<HTMLInputElement>) {
return <input className={cx(INPUT_CLASS, className)} {...rest} />
}
export function Textarea({ className, ...rest }: TextareaHTMLAttributes<HTMLTextAreaElement>) {
return <textarea className={cx(INPUT_CLASS, 'min-h-[90px] resize-y', className)} {...rest} />
}
export function Select({ className, ...rest }: SelectHTMLAttributes<HTMLSelectElement>) {
return <select className={cx(INPUT_CLASS, className)} {...rest} />
}
```
`components/ui/card.tsx`:
```tsx
import type { ReactNode } from 'react'
export function Card({
kicker,
title,
meta,
children,
}: {
kicker?: ReactNode
title?: ReactNode
meta?: ReactNode
children?: ReactNode
}) {
return (
<div className="flex flex-col gap-2 p-3 bg-surface">
{kicker && <span className="text-[10px] tracking-[0.1em] uppercase text-accent-700">{kicker}</span>}
{title && <h3 className="text-[17px] leading-tight font-extrabold">{title}</h3>}
{children && <div className="flex-1 text-[13px] opacity-80">{children}</div>}
{meta && <div className="flex items-center gap-1.5 text-[11px] text-ink/50">{meta}</div>}
</div>
)
}
```
`components/ui/table-styles.ts`:
```ts
export const TABLE = 'w-full border-collapse text-sm'
export const TH =
'text-left text-[11px] uppercase tracking-[0.08em] text-ink/60 px-2 py-2 border-b-2 border-divider'
export const TR = 'hover:bg-ink/4'
export const TD = 'px-2 py-2 border-b border-divider'
```
- [ ] **Step 4: Run the tests to verify they pass**
Run: `npx vitest run tests/components/ui/primitives.test.tsx`
Expected: PASS. If a Lucide import fails to resolve (for example `CircleAlert` or `CircleCheck` in an older `lucide-react`), use the legacy names `AlertCircle` and `CheckCircle2` and keep the `ICONS` keys unchanged.
- [ ] **Step 5: Type-check and commit**
```bash
npx tsc --noEmit 2>&1 | head -5
git add components/ui tests/components/ui
git commit -m "feat(design): add Modernist UI primitives (Button, Tag, StatusTag, Field, Card, table styles)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
```
Expected: `tsc` prints nothing.
---
### Task 4: Restyle Modal
**Files:**
- Modify: `components/ui/modal.tsx` (full rewrite)
- Test: `tests/components/ui/modal.test.tsx`
**Interfaces:**
- Consumes: `lucide-react` `X`.
- Produces: same exported `Modal({ open, onClose, title, children, footer?, width? })` API as today, so no caller changes.
- [ ] **Step 1: Write the failing test**
Create `tests/components/ui/modal.test.tsx`:
```tsx
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { Modal } from '@/components/ui/modal'
describe('Modal (Modernist dialog)', () => {
it('renders nothing when closed', () => {
const { container } = render(
<Modal open={false} onClose={() => {}} title="T">
body
</Modal>,
)
expect(container.firstChild).toBeNull()
})
it('renders a dialog with title, body and footer on the surface fill', () => {
render(
<Modal open onClose={() => {}} title="Confirm" footer={<span>actions</span>}>
body text
</Modal>,
)
const dialog = screen.getByRole('dialog')
expect(dialog).toBeTruthy()
expect(screen.getByText('Confirm')).toBeTruthy()
expect(screen.getByText('body text')).toBeTruthy()
expect(screen.getByText('actions')).toBeTruthy()
expect(dialog.innerHTML).toContain('bg-surface')
expect(dialog.innerHTML).toContain('shadow-lg')
})
it('has no rounded corners and uses a 2px title rule', () => {
render(
<Modal open onClose={() => {}} title="T">
x
</Modal>,
)
const html = screen.getByRole('dialog').innerHTML
expect(html).not.toMatch(/rounded/)
expect(html).toContain('border-b-2')
})
it('closes from the X button and on Escape', () => {
const onClose = vi.fn()
render(
<Modal open onClose={onClose} title="T">
x
</Modal>,
)
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
fireEvent.keyDown(document, { key: 'Escape' })
expect(onClose).toHaveBeenCalledTimes(2)
})
})
```
- [ ] **Step 2: Run the test to verify it fails**
Run: `npx vitest run tests/components/ui/modal.test.tsx`
Expected: FAIL (`bg-surface`, `shadow-lg` or `border-b-2` missing, or `rounded` still present).
- [ ] **Step 3: Rewrite `components/ui/modal.tsx`**
Read the current file first (the Task 2 codemod already edited it), then replace it entirely with:
```tsx
'use client'
import { useEffect } from 'react'
import { X } from 'lucide-react'
interface ModalProps {
open: boolean
onClose: () => void
title: string
children: React.ReactNode
footer?: React.ReactNode
width?: 'sm' | 'md' | 'lg'
}
export function Modal({ open, onClose, title, children, footer, width = 'md' }: ModalProps) {
useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [open, onClose])
if (!open) return null
const maxW = { sm: 'max-w-sm', md: 'max-w-md', lg: 'max-w-lg' }[width]
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4" role="dialog" aria-modal="true">
<div className="absolute inset-0 bg-neutral-900/50" onClick={onClose} />
<div className={`relative w-full ${maxW} bg-surface shadow-lg`}>
<div className="flex items-center justify-between px-6 py-4 border-b-2 border-divider">
<h2 className="text-xl font-extrabold text-ink">{title}</h2>
<button
onClick={onClose}
aria-label="Close"
className="inline-flex w-9 h-9 items-center justify-center text-ink cursor-pointer transition-colors hover:bg-ink/7 active:bg-ink/15"
>
<X size={18} strokeWidth={2} aria-hidden />
</button>
</div>
<div className="px-6 py-5">{children}</div>
{footer && (
<div className="px-6 py-4 border-t border-divider flex justify-end gap-2">
{footer}
</div>
)}
</div>
</div>
)
}
```
- [ ] **Step 4: Run the test to verify it passes**
Run: `npx vitest run tests/components/ui/modal.test.tsx`
Expected: PASS (4 tests).
- [ ] **Step 5: Commit**
```bash
git add components/ui/modal.tsx tests/components/ui/modal.test.tsx
git commit -m "feat(design): restyle Modal as a flat Modernist dialog
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
```
---
### Task 5: Shell (sidebar, mobile nav, bell, protected layout)
**Files:**
- Modify: `components/layout/sidebar.tsx` (full rewrite), `components/notifications/bell.tsx`, `app/(protected)/layout.tsx`
- Test: `tests/components/layout/sidebar.test.tsx`
**Interfaces:**
- Consumes: `lucide-react` icons; Task 1 utilities.
- Produces: unchanged `Sidebar({ role, userName, userEmail })` and `NotificationBell()` APIs.
- [ ] **Step 1: Write the failing sidebar test**
Create `tests/components/layout/sidebar.test.tsx`:
```tsx
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
vi.mock('next/navigation', () => ({
usePathname: () => '/hse/capa',
useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }),
}))
vi.mock('@/components/notifications/bell', () => ({ NotificationBell: () => null }))
import { Sidebar } from '@/components/layout/sidebar'
describe('Sidebar (Modernist shell)', () => {
it('renders the role nav with Lucide icons instead of inline paths', () => {
const { container } = render(<Sidebar role="hse" userName="Ada Lovelace" userEmail="" />)
expect(screen.getAllByText('Dashboard').length).toBeGreaterThan(0)
expect(screen.getAllByText('CAPA').length).toBeGreaterThan(0)
expect(container.querySelectorAll('svg.lucide').length).toBeGreaterThan(4)
})
it('marks the active link in the accent with an aria-current', () => {
render(<Sidebar role="hse" userName="Ada" userEmail="" />)
const active = screen.getAllByRole('link', { name: /CAPA/ }).find(a => a.getAttribute('aria-current') === 'page')
expect(active).toBeTruthy()
expect(active?.className).toContain('text-accent-700')
expect(active?.className).toContain('border-accent')
})
it('is flat: a 2px divider rule, ground fill and no rounded corners except the avatar', () => {
const { container } = render(<Sidebar role="hse" userName="Ada" userEmail="" />)
const aside = container.querySelector('aside')
expect(aside?.className).toContain('border-r-2')
expect(aside?.className).toContain('bg-ground')
const rounded = container.innerHTML.match(/rounded[\w-]*/g) ?? []
expect(rounded.every(r => r === 'rounded-full')).toBe(true)
})
it('keeps the version label', () => {
render(<Sidebar role="hse" userName="Ada" userEmail="" />)
expect(screen.getByText('v1.2.2')).toBeTruthy()
})
})
```
- [ ] **Step 2: Run the test to verify it fails**
Run: `npx vitest run tests/components/layout/sidebar.test.tsx`
Expected: FAIL (no `svg.lucide`, no `aria-current`, old classes).
- [ ] **Step 3: Rewrite `components/layout/sidebar.tsx`**
Read the current file first, then replace it entirely. The nav data, exact-match rule and logout behavior are unchanged.
```tsx
'use client'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import {
AlignLeft,
CircleCheck,
ClipboardList,
LayoutDashboard,
LogOut,
Plus,
Settings,
User,
Users,
} from 'lucide-react'
import { NotificationBell } from '@/components/notifications/bell'
interface NavItem {
label: string
href: string
icon: React.ReactNode
}
interface SidebarProps {
role: string
userName: string
userEmail: string
}
const IconGrid = () => <AlignLeft size={20} aria-hidden />
const IconList = () => <ClipboardList size={20} aria-hidden />
const IconCheck = () => <CircleCheck size={20} aria-hidden />
const IconChart = () => <LayoutDashboard size={20} aria-hidden />
const IconSettings = () => <Settings size={20} aria-hidden />
const IconUsers = () => <Users size={20} aria-hidden />
const IconPlus = () => <Plus size={20} aria-hidden />
const IconLogout = () => <LogOut size={16} aria-hidden />
const IconUser = () => <User size={16} aria-hidden />
const NAV_ITEMS: Record<string, NavItem[]> = {
reporter: [
{ label: 'My Reports', href: '/reporter', icon: <IconList /> },
{ label: 'New Incident', href: '/report', icon: <IconPlus /> },
],
supervisor: [
{ label: 'Overview', href: '/supervisor', icon: <IconGrid /> },
{ label: 'Incidents', href: '/supervisor/incidents', icon: <IconList /> },
],
hse: [
{ label: 'Dashboard', href: '/hse/dashboard', icon: <IconChart /> },
{ label: 'Incidents', href: '/hse/incidents', icon: <IconList /> },
{ label: 'CAPA', href: '/hse/capa', icon: <IconCheck /> },
{ label: 'Settings', href: '/hse/settings', icon: <IconSettings /> },
],
management: [
{ label: 'Dashboard', href: '/management', icon: <IconChart /> },
],
capa_owner: [
{ label: 'My CAPAs', href: '/capa-owner', icon: <IconCheck /> },
],
admin: [
{ label: 'Admin', href: '/admin', icon: <IconUsers /> },
{ label: 'Dashboard', href: '/hse/dashboard', icon: <IconChart /> },
{ label: 'Incidents', href: '/hse/incidents', icon: <IconList /> },
{ label: 'CAPA', href: '/hse/capa', icon: <IconCheck /> },
{ label: 'Management', href: '/management', icon: <IconGrid /> },
{ label: 'Settings', href: '/hse/settings', icon: <IconSettings /> },
],
}
const EXACT_ROOTS = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
function isActivePath(href: string, pathname: string): boolean {
return EXACT_ROOTS.includes(href) ? pathname === href : pathname.startsWith(href)
}
function initials(name: string): string {
return name
.split(' ')
.map(w => w[0] ?? '')
.join('')
.toUpperCase()
.slice(0, 2)
}
function useNavItems(role: string): NavItem[] {
return NAV_ITEMS[role] ?? NAV_ITEMS.reporter
}
const LINK_BASE = 'flex items-center gap-3 px-3 py-2 text-sm border-l-2 transition-colors'
const LINK_ACTIVE = 'border-accent text-accent-700 font-extrabold bg-accent-100/50'
const LINK_IDLE = 'border-transparent text-ink/70 font-medium hover:bg-ink/7 hover:text-ink'
function NavLink({ item, pathname }: { item: NavItem; pathname: string }) {
const active = isActivePath(item.href, pathname)
return (
<Link
href={item.href}
aria-current={active ? 'page' : undefined}
className={`${LINK_BASE} ${active ? LINK_ACTIVE : LINK_IDLE}`}
>
<span className={active ? 'text-accent-700' : 'text-ink/50'}>{item.icon}</span>
{item.label}
</Link>
)
}
export function Sidebar({ role, userName, userEmail }: SidebarProps) {
const pathname = usePathname()
const router = useRouter()
const items = useNavItems(role)
const mobileItems = items.slice(0, 4)
const logout = async () => {
await fetch('/api/auth/logout', { method: 'POST' })
router.push('/login')
router.refresh()
}
const displayName = userName || userEmail || 'User'
const roleLabel = role.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
const accountActive = pathname === '/account'
return (
<>
{/* Desktop sidebar */}
<aside className="hidden sm:flex fixed left-0 top-0 h-full w-60 bg-ground border-r-2 border-divider flex-col z-40">
<div className="flex items-center justify-between px-4 py-4 border-b-2 border-divider">
<span className="text-lg font-extrabold tracking-tight text-ink">IMS</span>
<NotificationBell />
</div>
<nav className="flex-1 overflow-y-auto py-3">
{items.map(item => (
<NavLink key={item.href} item={item} pathname={pathname} />
))}
</nav>
<div className="border-t-2 border-divider py-3">
<div className="flex items-center gap-2 px-4 py-2 mb-1">
<div className="w-8 h-8 rounded-full bg-accent flex items-center justify-center text-ground text-xs font-extrabold flex-shrink-0">
{initials(displayName)}
</div>
<div className="min-w-0">
<p className="text-sm font-extrabold text-ink truncate">{displayName}</p>
<p className="text-xs text-ink/60 truncate">{roleLabel}</p>
</div>
</div>
<Link
href="/account"
aria-current={accountActive ? 'page' : undefined}
className={`${LINK_BASE} ${accountActive ? LINK_ACTIVE : LINK_IDLE}`}
>
<span className={accountActive ? 'text-accent-700' : 'text-ink/50'}>
<IconUser />
</span>
Account
</Link>
<button
onClick={logout}
className={`${LINK_BASE} ${LINK_IDLE} w-full text-left cursor-pointer`}
>
<span className="text-ink/50"><IconLogout /></span>
Logout
</button>
<div className="mt-3 pt-3 border-t border-divider px-4">
<p className="text-xs text-ink/50">v1.2.2</p>
</div>
</div>
</aside>
{/* Mobile bottom tab bar */}
<nav className="sm:hidden fixed bottom-0 left-0 right-0 bg-ground border-t-2 border-divider flex z-40 safe-area-pb">
{mobileItems.map(item => {
const active = isActivePath(item.href, pathname)
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? 'page' : undefined}
className={`flex-1 flex flex-col items-center gap-1 py-2 text-[10px] font-extrabold transition-colors ${
active ? 'text-accent-700' : 'text-ink/55'
}`}
>
{item.icon}
<span className="leading-none">{item.label}</span>
</Link>
)
})}
{items.length <= 4 && (
<button
onClick={logout}
className="flex-1 flex flex-col items-center gap-1 py-2 text-[10px] font-extrabold text-ink/55 cursor-pointer"
>
<IconLogout />
<span className="leading-none">Logout</span>
</button>
)}
</nav>
</>
)
}
```
- [ ] **Step 4: Restyle the notification bell**
Open `components/notifications/bell.tsx` and make these edits (the file is otherwise unchanged):
1. Add `import { Bell } from 'lucide-react'` under the existing imports.
2. Replace the toggle `<button …>…</button>` element (the one holding the 🔔 span and the unread badge) with:
```tsx
<button
onClick={() => setOpen(o => !o)}
aria-label={`Notifications${unread > 0 ? ` (${unread} unread)` : ''}`}
className="relative bg-surface border border-divider w-10 h-10 flex items-center justify-center text-ink cursor-pointer transition-colors hover:bg-ink/7 active:bg-ink/15"
>
<Bell size={18} strokeWidth={2} aria-hidden />
{unread > 0 && (
<span className="absolute -top-1 -right-1 bg-accent text-ground text-[10px] font-extrabold min-w-[18px] h-[18px] px-1 flex items-center justify-center">
{unread > 99 ? '99+' : unread}
</span>
)}
</button>
```
3. On the dropdown panel `<div className="absolute right-0 mt-2 w-80 …">`, make sure the classes read `absolute right-0 mt-2 w-80 max-h-96 overflow-y-auto bg-surface shadow-lg border border-divider` (the codemod already removed `rounded-xl` and renamed `bg-white`; change `shadow-lg` only if it is missing).
4. In the panel header, change the `border-b border-gray-100` to `border-b-2 border-divider`, and the "Mark all read" button's `text-blue-600 hover:underline` to `text-accent-700 hover:underline`.
Leave the list-item markup for the Task 7 sweep, which finds any remaining off-system classes.
- [ ] **Step 5: Update the protected layout**
In `app/(protected)/layout.tsx` change the wrapper to use the ground token:
```tsx
<div className="min-h-screen bg-ground">
```
- [ ] **Step 6: Run the tests and build**
```bash
npx vitest run tests/components/layout/sidebar.test.tsx
npx vitest run 2>&1 | tail -6
npx tsc --noEmit 2>&1 | head -5
```
Expected: sidebar tests pass (4), full suite passes, `tsc` prints nothing.
- [ ] **Step 7: Commit**
```bash
git add components/layout/sidebar.tsx components/notifications/bell.tsx "app/(protected)/layout.tsx" tests/components/layout/sidebar.test.tsx
git commit -m "feat(design): restyle shell with flat Modernist sidebar, mobile nav and bell
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
```
### Task 6: Replace scattered status, priority and severity color maps
**Files (11), each holds a color map to delete or replace:**
- `app/(protected)/reporter/page.tsx` (`STATUS_COLORS`, used ~line 113)
- `app/(protected)/reporter/incidents/[id]/page.tsx` (`STATUS_COLORS`, ~line 77)
- `app/(protected)/supervisor/page.tsx` (`STATUS_COLORS`, ~line 152)
- `app/(protected)/capa-owner/page.tsx` (`STATUS_COLORS`, `PRIORITY_COLORS`, ~lines 104, 111, 134)
- `app/(protected)/management/page.tsx` (`SEVERITY_COLORS`, ~line 146)
- `components/incidents/incident-list.tsx` (`STATUS_COLORS`, used ~lines 89 and 110)
- `components/incidents/incident-detail.tsx` (`STATUS_COLORS`, ~line 83)
- `components/incidents/incident-header.tsx` (`STATUS_COLORS`, ~line 48)
- `components/capa/capa-board.tsx` (`STATUS_COLORS`, `PRIORITY_BADGE`)
- `components/dashboard/risk-flags-panel.tsx` (`LEVEL_COLORS`)
- `app/(protected)/hse/capa/[id]/page.tsx` (`PRIORITY_BADGE`, found during execution; the CAPA board table view also used `PRIORITY_BADGE`)
- Test: `tests/components/incidents/incident-list.test.tsx` (existing, must keep passing)
**Interfaces:**
- Consumes: `StatusTag`, `PriorityTag` from `@/components/ui/status-tag` (Task 3).
- Produces: no new exports; after this task `grep -rn "STATUS_COLORS\|PRIORITY_BADGE" app components` prints only the `incident-list.tsx` filter-list usage described in step 3.
Pattern for the eight span-based files. Read each file first, then apply.
- [ ] **Step 1: Incident status pills (reporter, reporter detail, supervisor, incident-detail, incident-header)**
In each file: delete the `STATUS_COLORS` constant, add `import { StatusTag } from '@/components/ui/status-tag'`, and replace the pill element that used it.
Example for `app/(protected)/reporter/page.tsx`. Before (class list as left by the Task 2 codemod, your file may differ slightly):
```tsx
<span className={`text-xs rounded-full px-2 py-0.5 shrink-0 ${STATUS_COLORS[inc.status] ?? 'bg-gray-100 text-gray-600'}`}>
{inc.status.replace('_', ' ')}
</span>
```
After:
```tsx
<StatusTag status={inc.status} />
```
If the span's child is a label expression other than the raw status (for example a `STATUS_LABELS[...]` lookup), pass it through as children: `<StatusTag status={inc.status}>{STATUS_LABELS[inc.status]}</StatusTag>`. If the tag sits in a flex row that relied on `shrink-0`, wrap it: `<span className="shrink-0"><StatusTag status={inc.status} /></span>`. Same replacement in the other four files, using the expression each file passes to its map (`inc.status`, `incident.status`, `status`).
- [ ] **Step 2: CAPA status pills and priority text (capa-owner page)**
Delete `STATUS_COLORS`. Replace both status spans (lines ~104 and ~134) with:
```tsx
<StatusTag status={capa.status}>{STATUS_LABELS[capa.status] ?? capa.status}</StatusTag>
```
(the file already defines `STATUS_LABELS`; keep it). Replace the `PRIORITY_COLORS` constant, which maps to text classes, with token-based classes:
```tsx
const PRIORITY_COLORS: Record<string, string> = {
high: 'text-accent-700 font-extrabold',
med: 'text-accent-700 font-medium',
low: 'text-ink/50',
}
```
- [ ] **Step 3: Incident list (filter chips + rows)**
In `components/incidents/incident-list.tsx`, line ~89 iterates `Object.keys(STATUS_COLORS)` to build the status filter. Keep a plain ordered list for that and delete only the colors:
```tsx
const STATUS_ORDER = ['reported', 'triaged', 'investigating', 'capa_pending', 'verification', 'closed'] as const
```
Replace `Object.keys(STATUS_COLORS)` with `STATUS_ORDER`, delete `STATUS_COLORS`, and replace the row pill (~line 110) with `<StatusTag status={inc.status} />`. Restyle the filter chips the same file renders: the active chip uses `bg-accent text-ground`, idle chips use `border border-divider text-ink hover:bg-ink/7`, no rounded classes. Then run the existing test:
Run: `npx vitest run tests/components/incidents/incident-list.test.tsx`
Expected: PASS. If an assertion breaks because the pill text changed (for example "capa pending" now renders "CAPA Pending"), update the expected text in that test to the StatusTag label.
- [ ] **Step 4: CAPA board (`components/capa/capa-board.tsx`)**
Replace the two maps and the markup that used them. Delete `STATUS_COLORS` and `PRIORITY_BADGE`, add `import { PriorityTag } from '@/components/ui/status-tag'`, and add a column rule map (overdue and reopened get the accent border, every other column a divider border):
```tsx
const COLUMN_BORDER: Record<CapaStatus, string> = {
open: 'border-divider',
in_progress: 'border-divider',
overdue: 'border-accent',
pending_verification: 'border-divider',
verified: 'border-divider',
reopened: 'border-accent',
closed: 'border-divider',
}
```
Change the column wrapper (~line 110) to:
```tsx
<div key={status} className={`border-2 p-4 bg-ground ${COLUMN_BORDER[status]}`}>
```
Change the column heading to `className="text-xs font-extrabold uppercase tracking-wide text-ink/70 mb-3 pb-2 border-b-2 border-divider"`. Change the card `Link` className to `block bg-surface p-3 shadow-sm hover:shadow-md transition-shadow border border-divider`. Replace the priority span (~line 117) with `<PriorityTag priority={c.priority} />`. Change the "Table view" button to `className="text-sm text-accent-700 hover:underline"`.
- [ ] **Step 5: Severity bars (`app/(protected)/management/page.tsx`)**
Replace the rainbow with the approved mono mapping: severity 1 to 2 neutral, 3 tinted accent, 4 to 5 accent.
```tsx
const SEVERITY_COLORS: Record<number, string> = {
1: 'bg-neutral-300', 2: 'bg-neutral-500', 3: 'bg-accent-300', 4: 'bg-accent', 5: 'bg-accent-700',
}
```
On the bar element (`className={`h-3 rounded-full ${SEVERITY_COLORS[sev]}`}`, ~line 146) drop `rounded-full` so it reads `className={`h-3 ${SEVERITY_COLORS[sev]}`}`. The labels beside the bars already carry the severity text (`SEVERITY_LABELS`), so color is never the only signal.
- [ ] **Step 6: Risk levels (`components/dashboard/risk-flags-panel.tsx`)**
```tsx
const LEVEL_COLORS: Record<RiskFlag['risk_level'], string> = {
low: 'bg-neutral-100 text-neutral-800 border-divider',
medium: 'bg-ground text-accent-700 border-accent',
high: 'bg-accent-100 text-accent-800 border-accent',
}
```
- [ ] **Step 7: Verify and commit**
```bash
npx tsc --noEmit 2>&1 | head -10
npx vitest run 2>&1 | tail -6
grep -rn "STATUS_COLORS\|PRIORITY_BADGE" app components | head
```
Expected: `tsc` clean, all tests pass, the grep prints nothing.
```bash
git add app components tests
git commit -m "refactor(design): replace status, priority and severity color maps with StatusTag and mono tokens
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
```
---
### Task 7: Sweep leftovers and add the design gate
**Files:**
- Create: `scripts/check-design-gates.mjs`, `tests/scripts/check-design-gates.test.ts`
- Modify: `app/globals.css` (red remap), `tests/design/tokens.test.ts`, `package.json` (`check:design`), plus every TSX file the gate flags (login form, forms, admin pages, dashboards, evidence, notifications list)
**Interfaces:**
- Consumes: primitives from Task 3.
- Produces: `export function findViolations(src: string, file: string): Array<{ file: string; line: number; rule: string; text: string }>`, `export const ROUND_ALLOWED: string[]`, and the command `npm run check:design` (exit 1 on any violation). Future work must keep it green.
- [ ] **Step 1: Remap the red ramp so existing error styling lands on the accent**
Red is used for errors and destructive actions (`text-red-600`, `bg-red-50`). Point it at the accent ramp, using step 600/700 for body-size text. In `app/globals.css`, add inside the `@theme static` block after the blue ramp:
```css
/* Existing red-* utilities (errors, destructive) render on the accent ramp;
600/700 map to accent-700 so body-size text clears contrast. */
--color-red-50: var(--color-accent-100);
--color-red-100: var(--color-accent-100);
--color-red-200: var(--color-accent-200);
--color-red-300: var(--color-accent-300);
--color-red-400: var(--color-accent-400);
--color-red-500: var(--color-accent-600);
--color-red-600: var(--color-accent-700);
--color-red-700: var(--color-accent-700);
--color-red-800: var(--color-accent-800);
--color-red-900: var(--color-accent-900);
```
Add to `tests/design/tokens.test.ts` inside the `describe`:
```ts
it('remaps the red ramp onto the accent ramp, with body-size steps on accent-700', () => {
expect(css).toMatch(/--color-red-600:\s*var\(--color-accent-700\)/)
expect(css).toMatch(/--color-red-50:\s*var\(--color-accent-100\)/)
})
```
Run: `npx vitest run tests/design/tokens.test.ts`. Expected: PASS.
- [ ] **Step 2: Write the failing gate tests**
Create `tests/scripts/check-design-gates.test.ts`:
```ts
import { describe, it, expect } from 'vitest'
import { findViolations, ROUND_ALLOWED } from '../../scripts/check-design-gates.mjs'
const rules = (src: string, file = 'components/x.tsx'): string[] =>
(findViolations(src, file) as Array<{ rule: string }>).map(v => v.rule)
describe('design gates', () => {
it('flags rounded corner classes', () => {
expect(rules('<div className="rounded-lg p-2" />')).toContain('no-rounded')
expect(rules('<div className="p-2 hover:rounded-md" />')).toContain('no-rounded')
})
it('flags rounded-full outside the allowlist and accepts it inside', () => {
expect(rules('<div className="rounded-full" />')).toContain('no-rounded-full')
expect(rules('<div className="rounded-full" />', ROUND_ALLOWED[0])).not.toContain('no-rounded-full')
})
it('flags off-palette colors but accepts remapped gray, blue and red', () => {
expect(rules('<p className="text-green-700" />')).toContain('off-palette')
expect(rules('<p className="bg-purple-100" />')).toContain('off-palette')
expect(rules('<p className="text-gray-500 text-blue-700 bg-red-50" />')).toEqual([])
})
it('flags hard-coded hex colors', () => {
expect(rules('<div style={{ color: "#ec3013" }} />')).toContain('no-hex')
expect(rules('<p>&#39;quoted&#39;</p>')).not.toContain('no-hex')
})
it('flags centered button labels', () => {
expect(rules('<button className="text-center px-2">x</button>')).toContain('no-centered-button')
})
it('flags leftovers the codemod should have replaced', () => {
expect(rules('<div className="bg-white shadow-2xl" />')).toEqual(expect.arrayContaining(['no-bg-white', 'no-heavy-shadow']))
})
it('reports file and 1-based line numbers', () => {
const v = findViolations('a\n<div className="rounded-md" />', 'components/y.tsx')
expect(v[0]).toMatchObject({ file: 'components/y.tsx', line: 2, rule: 'no-rounded' })
})
it('accepts clean on-system markup', () => {
expect(rules('<div className="bg-surface border border-divider p-4 text-ink shadow-sm" />')).toEqual([])
})
})
```
- [ ] **Step 3: Run the tests to verify they fail**
Run: `npx vitest run tests/scripts/check-design-gates.test.ts`
Expected: FAIL (module not found).
- [ ] **Step 4: Write the gate script**
Create `scripts/check-design-gates.mjs`:
```js
import { readdirSync, readFileSync, statSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
// Files where a circular element is legitimate (avatar). Add others only with a reason.
export const ROUND_ALLOWED = ['components/layout/sidebar.tsx']
const RULES = [
{
rule: 'no-rounded',
re: /(?<=[\s"'`:{])(?:[\w-]+:)*rounded(?:-(?!full(?![\w-]))[\w]+)*(?=[\s"'`}])/,
},
{ rule: 'no-bg-white', re: /(?<![\w-])bg-white(?![\w-])/ },
{ rule: 'no-heavy-shadow', re: /(?<![\w-])shadow-(?:xl|2xl)(?![\w-])/ },
{
rule: 'off-palette',
re: /(?<![\w-])(?:bg|text|border|ring|from|to|via|divide|fill|stroke|outline)-(?:green|yellow|amber|orange|purple|indigo|teal|emerald|sky|cyan|pink|rose|violet|lime|fuchsia)-\d{2,3}/,
},
{ rule: 'no-hex', re: /(?<![&\w])#[0-9a-fA-F]{3,8}\b/ },
{ rule: 'no-centered-button', re: /<button[^>]*className=[^>]*(?<![\w-])text-center(?![\w-])/ },
]
export function findViolations(src, file) {
const out = []
const roundAllowed = ROUND_ALLOWED.includes(file)
src.split('\n').forEach((text, i) => {
const line = i + 1
for (const { rule, re } of RULES) {
if (re.test(text)) out.push({ file, line, rule, text: text.trim() })
}
if (!roundAllowed && /(?<=[\s"'`:{])(?:[\w-]+:)*rounded-full(?=[\s"'`}])/.test(text)) {
out.push({ file, line, rule: 'no-rounded-full', text: text.trim() })
}
})
return out
}
function walk(dir, files = []) {
for (const name of readdirSync(dir)) {
const full = path.join(dir, name)
if (statSync(full).isDirectory()) walk(full, files)
else if (full.endsWith('.tsx')) files.push(full)
}
return files
}
function main() {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const all = []
for (const dir of ['app', 'components']) {
for (const abs of walk(path.join(root, dir))) {
const rel = path.relative(root, abs).split(path.sep).join('/')
all.push(...findViolations(readFileSync(abs, 'utf8'), rel))
}
}
for (const v of all) console.log(`${v.file}:${v.line} [${v.rule}] ${v.text}`)
console.log(all.length === 0 ? 'design gates: clean' : `design gates: ${all.length} violation(s)`)
process.exit(all.length === 0 ? 0 : 1)
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main()
```
Add the script to `package.json` under `scripts`: `"check:design": "node scripts/check-design-gates.mjs"`.
- [ ] **Step 5: Run the gate tests to verify they pass**
Run: `npx vitest run tests/scripts/check-design-gates.test.ts`
Expected: PASS (8 tests).
- [ ] **Step 6: Run the gate on the app and read the list**
Run: `npm run check:design 2>&1 | tail -60`
Expected: a list of violations (this is the sweep worklist). Note the total.
- [ ] **Step 7: Fix every violation, file by file**
Work through the list. Rules for each rule type:
| Rule | Fix |
| --- | --- |
| `no-rounded-full` | Status pills: use `StatusTag`. Progress bars, chips, badges and dots: remove `rounded-full`. Genuine circular avatars or radio dots: keep, and add the file to `ROUND_ALLOWED` in `scripts/check-design-gates.mjs` with a one-line comment naming the element. |
| `no-rounded` | Delete the class (should be rare after Task 2; usually a constant outside `className`). |
| `off-palette` | Green (done, success) becomes `text-ink` on `bg-neutral-100`; yellow, orange, purple, indigo (in progress, warnings) become `bg-ground text-accent-700 border border-accent` (or `StatusTag` / `PriorityTag` where it is a status). Success banners: `bg-neutral-100 border border-divider text-ink`. |
| `no-hex` | Replace with the token utility (`bg-accent`, `text-ink`, `border-divider`) or `var(--color-*)` in a style prop. |
| `no-centered-button` | Remove `text-center` from the button; use `Button` (flush left) where the button is a standard action. |
| `no-bg-white` / `no-heavy-shadow` | Re-run `node scripts/modernist-codemod.mjs`, then hand-fix what remains. |
Restyle raw form controls as you pass them: inputs, selects and textareas use `INPUT_CLASS` from `@/components/ui/field` (or the `Input`, `Select`, `Textarea` components); submit buttons use `Button`; replace every `bg-blue-600 … text-white` button with `<Button>` or `bg-accent text-ground hover:bg-accent-600`.
Review every remaining `blue-*` use and decide by intent (this is the spec's flagged risk):
```bash
grep -rnE "(bg|text|border|ring)-blue-[0-9]+" app components --include='*.tsx'
```
- Links and primary actions (`text-blue-600`, `bg-blue-600`): keep (they render as accent).
- Informational banners and selected chips (`bg-blue-50`, `bg-blue-100`, `border-blue-200`): change to `bg-neutral-100` and `border-divider`, so info never reads as an error.
- Body-size text in the accent: use `text-accent-700`.
Login form (`components/auth/login-form.tsx`): title `text-2xl font-bold` becomes `text-2xl font-extrabold text-left`; wrapper card `bg-surface border-2 border-divider`; inputs use `INPUT_CLASS`; submit uses `<Button variant="primary" block type="submit">` (the error paragraph keeps `bg-accent-100 border border-accent text-accent-800`).
Page headings: use one `<h1 className="text-3xl font-extrabold">`, separate major page sections with `<hr className="h-0.5 border-0 bg-divider my-4" />`, and keep headings and copy flush left (remove `text-center` on hero copy).
- [ ] **Step 8: Re-run until clean, then full verification**
```bash
npm run check:design 2>&1 | tail -5
npx tsc --noEmit 2>&1 | head -10
npx vitest run 2>&1 | tail -6
npm run build 2>&1 | tail -6
```
Expected: `design gates: clean`, `tsc` clean, all tests pass, build passes.
- [ ] **Step 9: Commit**
```bash
git add -A app components scripts tests package.json app/globals.css
git commit -m "feat(design): sweep off-system styles and add the check:design gate
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
```
Note: `git add -A` is scoped to the listed paths only, so the untracked `design-system/*` files stay out of this commit.
### Task 8: Document the design system for future development
**Files:**
- Modify: `CLAUDE.md` (add a "Design system" section)
- Create: memory file `/Users/yapweeihan/.claude/projects/-Users-yapweeihan-Projects-Setia/memory/ims-design-system.md`
- Modify: memory index `/Users/yapweeihan/.claude/projects/-Users-yapweeihan-Projects-Setia/memory/MEMORY.md` (append one line)
- Track: `design-system/_ds/` (the source of truth the docs point at)
**Interfaces:**
- Consumes: the finished primitives and gate script from Tasks 3 and 7.
- Produces: durable guidance so later sessions follow Modernist without re-deriving it.
- [ ] **Step 1: Add the section to `CLAUDE.md`**
Read `CLAUDE.md`, then insert this section immediately before the existing `## graphify` section:
```markdown
## Design system (Modernist)
Source of truth: `design-system/_ds/modernist-*/readme.md` and `styles.css`. Tokens live in `app/globals.css` (`@theme static`). Do not use `design-system/IMS Admin.dc.html` as a style reference.
- Flat and architectural: Archivo, ink on a `#f3f2f2` ground, one accent `#ec3013`. Zero corner radius, visible grid, strong 2px rules between major sections (`border-divider`, `border-b-2`).
- Use tokens, never hard-coded hex, font names or px values the tokens carry: `bg-ground`, `bg-surface`, `text-ink`, `bg-accent`, `border-divider`, `accent-100…900`, `neutral-100…900`. `gray-*`, `blue-*` and `red-*` are remapped onto the neutral and accent ramps.
- No `rounded-*` (except circular avatars, allowlisted in `scripts/check-design-gates.mjs`). Labels and headings are flush left, including button labels. No centered hero copy.
- Body-size accent text uses `accent-700`; the accent itself is for buttons, icons and large text.
- Icons: Lucide (`lucide-react`). Interaction: hover tint, pressed step from the accent ramp, `:focus-visible` 2px accent ring (global), disabled at 45% opacity.
- Build UI with `components/ui/*`: `Button`, `Tag`, `StatusTag`, `PriorityTag`, `Field`/`Input`/`Select`/`Textarea`, `Card`, `Modal`, and the `TABLE/TH/TR/TD` class constants.
- Status is never color alone. Needs attention, open, overdue, reported or severity 4-5 = accent tag; in progress = outline tag; done, closed, verified, low = neutral tag. Always keep the text label and an icon. Add new statuses in `components/ui/status-tag.tsx`, not per page.
- Incident evidence photos stay full color. `.grayscale` is for decorative photography only.
- Run `npm run check:design` before committing UI changes; it must print `design gates: clean`.
```
- [ ] **Step 2: Write the memory file**
Create `/Users/yapweeihan/.claude/projects/-Users-yapweeihan-Projects-Setia/memory/ims-design-system.md`:
```markdown
---
name: ims-design-system
description: IMS UI follows the Modernist design system (tokens in app/globals.css, primitives in components/ui, gate via npm run check:design)
metadata:
type: reference
---
IMS UI is restyled to the Modernist design system (restyle decided and planned 2026-09-30).
- Source of truth: `design-system/_ds/modernist-*/readme.md` + `styles.css` in the IMS repo. `design-system/IMS Admin.dc.html` (Geist, teal, 12px radius) is a superseded mockup; do not build from it.
- Rules: Archivo, ink on #f3f2f2 ground, single accent #ec3013, 0px radius, 2px rules, flush-left labels and buttons, Lucide icons, tokens only (never hard-coded hex or px the tokens carry).
- Tailwind v4 tokens live in `app/globals.css` (`@theme static`); `gray-*`, `blue-*`, `red-*` are remapped to neutral/accent ramps. Body-size accent text uses `accent-700`.
- Shared primitives: `components/ui/` (`Button`, `Tag`, `StatusTag`, `PriorityTag`, `Field`, `Card`, `Modal`, table class constants). Statuses go in `components/ui/status-tag.tsx`.
- Status mapping: attention/open/overdue/reported/severity 4-5 = accent tag; in progress = outline tag; done/closed/verified/low = neutral tag. Always text label + icon, never color alone. No green.
- Evidence photos stay full color (color can be evidence); `.grayscale` only for decorative imagery.
- Guardrail: `npm run check:design` (`scripts/check-design-gates.mjs`) must be clean before committing UI work.
**Why:** the user asked to study /design-system and implement it across the whole app, and to remember it for future development. Status colors collapsed to mono because Modernist has one accent; the user approved that mapping.
**How to apply:** any new or changed UI in IMS. Reach for `components/ui/*` first; if a pattern is missing, add it there with Modernist tokens rather than inline styling.
```
Then append one line to `MEMORY.md` (keep it under ~150 characters):
```bash
cat >> /Users/yapweeihan/.claude/projects/-Users-yapweeihan-Projects-Setia/memory/MEMORY.md << 'EOF'
- [IMS design system](ims-design-system.md) — Modernist tokens, components/ui primitives, status mapping, npm run check:design gate
EOF
```
- [ ] **Step 3: Track the design source and commit**
Stage only the documentation and the Modernist source. Leave the `IMS Admin.dc.html` mockup, `support.js`, the zip and the deleted `design-system/ims-admin/MASTER.md` for the owner to decide:
```bash
git add CLAUDE.md design-system/_ds
git status --short | head
git commit -m "docs(design): document Modernist design system and track its source
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
```
Expected: `git status` still lists `design-system/IMS Admin.dc.html`, `design-system/support.js`, the zip and ` D design-system/ims-admin/MASTER.md` as unstaged or untracked. `.DS_Store` is already gitignored.
---
### Task 9: Verify in a browser, then deploy (needs the owner's go-ahead)
**Files:** none modified (fixes found here go back into the relevant task's files).
**Interfaces:**
- Consumes: everything above.
- Produces: a verified, optionally deployed build.
- [ ] **Step 1: Full automated verification**
```bash
npm run check:design 2>&1 | tail -3
npx tsc --noEmit 2>&1 | head -5
npx vitest run 2>&1 | tail -6
npm run build 2>&1 | tail -6
```
Expected: `design gates: clean`, `tsc` clean, all tests pass, build passes.
- [ ] **Step 2: Visual check of the login page (no database needed)**
```bash
npm run dev
```
Open `http://localhost:3000/login` and confirm: Archivo headings, `#f3f2f2` ground, square inputs with a divider border, flush-left red primary button, no rounded corners, and a visible 2px accent focus ring when tabbing. Check at 360px width (Archivo 800 is wider than Geist; nothing may overflow). Stop the server afterwards.
- [ ] **Step 3: Authenticated pages (needs a seeded database)**
The local Postgres at `127.0.0.1:5433` may be empty on a dev machine (see memory `ims-database-setup`). If it is, say so and ask the owner whether to (a) seed a local admin, or (b) verify on production after deploying. Do not guess credentials. When a database is available, check each role's pages at desktop and 360px: reporter list and report form, HSE inbox, incident detail and header, CAPA board (table and board views), supervisor, management dashboard, admin users and settings, the notification bell, and a modal. Confirm: no rounded corners, status tags show label plus icon, severity bars read in mono, every interactive element shows the accent focus ring.
- [ ] **Step 4: Deploy only after the owner says go**
Follow the IMS deployment procedure. Build locally (already done), never build on the server, never touch `.env*` on the server, and exclude env files and macOS metadata from the archive:
```bash
cd /Users/yapweeihan/Projects/IMS.nosync
rm -rf /tmp/ims-stage && mkdir -p /tmp/ims-stage/.next
cp -R .next/standalone/. /tmp/ims-stage/
cp -R .next/static /tmp/ims-stage/.next/static
cp -R public /tmp/ims-stage/public
test -f /tmp/ims-stage/.next/BUILD_ID && echo "BUILD_ID present"
COPYFILE_DISABLE=1 tar --exclude='.env*' --exclude='._*' -czf /tmp/ims-deploy.tar.gz -C /tmp/ims-stage .
scp -P 9321 /tmp/ims-deploy.tar.gz setia@175.136.239.121:/tmp/
ssh -p 9321 setia@175.136.239.121 "cd /srv/apps/ims/app && tar -xzf /tmp/ims-deploy.tar.gz && test -f .next/BUILD_ID && ls .next/static | head -3 && sudo systemctl restart ims && sleep 4 && systemctl is-active ims"
curl -s -o /dev/null -w "%{http_code}\n" https://ims.setia.com.my/
```
Expected: `BUILD_ID present`, `.next/static` lists chunk folders, `active`, and HTTP `200` or `307`. Do not restart if `.next/BUILD_ID` is missing. If anything fails, stop and report; do not improvise.
- [ ] **Step 5: Merge**
After the owner confirms the deploy looks right, merge `feat/modernist-restyle` into `main` and push to `origin` and `setia`. Do not force-push.
---
## Self-Review Notes
Spec coverage: tokens and theme remap (Task 1), class removal and color-surface swaps (Task 2), components `Button`, `Tag`, `Field`, `Card`, table styles, `StatusTag`, `PriorityTag` (Task 3), Modal (Task 4), sidebar, mobile nav, bell, 2px rules (Task 5), central status, priority and severity mapping (Task 6), sweep, `blue-*` review, hard-coded hex, rounded gates (Task 7), `CLAUDE.md` and memory (Task 8), build, browser, and deploy verification (Task 9). Lucide is installed in Task 1 and used in Tasks 3 to 5. Grayscale rule (evidence stays color) is captured in constraints and docs. The `.grayscale` class is defined in Task 1.