123 KiB
IMS Admin Refresh, Slice 1 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: Replace the Modernist look with the IMS Admin refresh for the foundation (tokens, gate, primitives, TableCard, shells) and migrate the Incidents list (screens 01 and 10) as the first full screen.
Architecture: New tokens go in app/globals.css (@theme static). The old Modernist class names (gray-*, blue-*, red-*, accent-100..900, neutral-*, border-divider) stay defined but re-valued, so the ~60 unmigrated files keep rendering until later slices. New primitives live in components/ui/. The Incidents list becomes a TableCard fed by a shared server loader.
Tech Stack: Next.js 16.3.7 (App Router, Turbopack), React 19, Tailwind CSS v4 (@theme static), lucide-react, Geist and Geist Mono via next/font/google, vitest 4 + jsdom + @testing-library/react.
Spec: design-system/design.md (§2 tokens, §3 shells, §4 components, §8 build order). References: design-system/IMS Admin Spec.dc.html, design-system/IMS Admin.dc.html.
Global Constraints
- Source of truth is
design-system/design.md. The Modernist system underdesign-system/_ds/is retired. - Colours, type, radius, shadows exactly as design.md §2: ink
#1f1f1f, ground#f1f1f1, surface#ffffff, surface-2#f7f7f7, one teal accent#0f766e, danger#b3261e, top bar#1a1a1a. - Rules are 1px. Never
border-2orborder-{t,b,l,r}-2. - Radius scale:
rounded-md= 8 (buttons, chips, inputs, pills),rounded-xl= 12 (cards),rounded-[5px]checkbox,rounded-[6px]avatar, 999 only for badges. - Status and priority colours only through
StatusTagandPriorityTag(design.md §4.2): dark text on a light tint, text label always present. - Every list is a
TableCard(design.md §4.9). Do not hand-build tables. - Never write
*/inside a CSS comment inapp/globals.css; it ends the comment and silently swallows the@themeblock (this broke production builds once). - Do not run
next devwhile verifying a production build in the same.next. Verify CSS withrm -rf .next && npm run buildand inspect.next/static/chunks/*.css. - Baseline: 7 tests already fail before this work (missing
DEEPSEEK_API_KEY,BREVO_API_KEY, and acookies()scope error):lib/incidents/bulk-import.test.ts(2),tests/api/incidents/quality-check.test.ts(2),rca-draft.test.ts(1),triage-suggest.test.ts(1),tests/lib/notifications/email.test.ts(1). "No new failures" means exactly these 7 and no others. - No database, API, auth or routing changes. Do not deploy; deploying needs the owner's go-ahead.
- Work on branch
feat/admin-refresh-slice-1. Stage only named paths; nevergit add -A. Leave the untrackedModern table UI mockups.zipfiles and the deleteddesign-system/ims-admin/MASTER.mdalone.
File Structure
Create
components/ui/checkbox.tsx,filter-chip.tsx,segmented.tsx,avatar.tsx,drawer.tsx,table-card.tsxcomponents/layout/app-shell.tsx,components/layout/mobile-shell.tsx,components/layout/nav-items.tscomponents/incidents/incident-table.tsxlib/incidents/list-params.ts(pure URL-param parsing),lib/incidents/list-query.ts(DB loader)tests/**for each of the above
Modify
app/globals.css,app/layout.tsx,scripts/check-design-gates.mjs,tests/design/tokens.test.ts,tests/scripts/check-design-gates.test.tscomponents/ui/button.tsx,status-tag.tsx,field.tsx,card.tsx,modal.tsxcomponents/notifications/bell.tsx,components/incidents/incident-filters.tsxapp/(protected)/layout.tsx,app/(protected)/hse/incidents/page.tsx,app/(protected)/supervisor/incidents/page.tsxCLAUDE.md, memoryims-design-system.md
Delete
components/ui/tag.tsx,components/ui/table-styles.ts,components/layout/sidebar.tsx,components/incidents/incident-list.tsx(replaced; callers are updated in the same tasks)
Task 1: Gate, tokens and Geist
Files:
- Modify:
scripts/check-design-gates.mjs(full rewrite),tests/scripts/check-design-gates.test.ts(full rewrite),app/globals.css(full rewrite),tests/design/tokens.test.ts(full rewrite),app/layout.tsx,tests/components/layout/sidebar.test.tsx,tests/components/ui/modal.test.tsx - Modify (mechanical sweep): every
.tsxunderapp/andcomponents/containingborder-2orborder-{t,b,l,r}-2
Interfaces:
-
Consumes: nothing.
-
Produces: Tailwind utilities
bg-ground,bg-surface,bg-surface-2,text-ink,text-ink-2,text-ink-3,text-muted,text-faint,border-rule,border-rule-2,border-ring,bg-accent,text-accent,bg-accent-tint,bg-accent-tint-2,text-danger,bg-topbar,shadow-card,shadow-float,shadow-drawer,shadow-primary,shadow-secondary,shadow-input,shadow-chip,shadow-chip-set,font-sans,font-mono, and the status pairsbg-st-<hue>-bg/text-st-<hue>-fgfor hue inamber blue violet orange indigo green grey red; gate commandnpm run check:designwithfindViolations(src, file). -
Step 1: Branch and baseline
cd /Users/yapweeihan/Projects/IMS.nosync
git checkout main && git pull --ff-only 2>/dev/null; git checkout -b feat/admin-refresh-slice-1
npx vitest run 2>&1 | grep -E "Test Files|Tests "
Expected: Tests 7 failed | 239 passed (the 7 baseline failures). If the counts differ, stop and report.
- Step 2: Write the failing gate tests
Replace tests/scripts/check-design-gates.test.ts:
import { describe, it, expect } from 'vitest'
import { findViolations } 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 (IMS Admin refresh)', () => {
it('allows the radius scale, including rounded-full', () => {
expect(rules('<div className="rounded-md rounded-xl rounded-[5px] rounded-full" />')).toEqual([])
})
it.each(['border-2', 'border-b-2', 'border-t-2', 'border-l-2', 'border-r-2'])('flags %s', cls => {
expect(rules(`<div className="${cls}" />`)).toContain('no-2px-border')
})
it('accepts 1px rules', () => {
expect(rules('<div className="border border-b border-rule" />')).toEqual([])
})
it('flags the retired Archivo font', () => {
expect(rules("import { Archivo } from 'next/font/google'")).toContain('no-archivo')
})
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('accepts the status token classes', () => {
expect(rules('<span className="bg-st-green-bg text-st-green-fg" />')).toEqual([])
})
it('flags hard-coded hex colors, including the retired Modernist red', () => {
expect(rules('<div style={{ color: "#ec3013" }} />')).toContain('no-hex')
expect(rules('<p>'quoted'</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="border-2" />', 'components/y.tsx')
expect(v[0]).toMatchObject({ file: 'components/y.tsx', line: 2, rule: 'no-2px-border' })
})
it('accepts clean on-system markup', () => {
expect(rules('<div className="bg-surface border border-rule p-4 text-ink shadow-card rounded-xl" />')).toEqual([])
})
})
- Step 3: Write the failing token test
Replace tests/design/tokens.test.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('IMS Admin tokens in globals.css', () => {
it.each([
['--color-ink', '#1f1f1f'],
['--color-ink-2', '#303030'],
['--color-ink-3', '#4a4a4a'],
['--color-muted', '#616161'],
['--color-faint', '#8a8a8a'],
['--color-rule', '#ebebeb'],
['--color-rule-2', '#e3e3e3'],
['--color-ring', '#d4d4d4'],
['--color-surface', '#ffffff'],
['--color-surface-2', '#f7f7f7'],
['--color-ground', '#f1f1f1'],
['--color-accent', '#0f766e'],
['--color-accent-tint', '#f2f7f6'],
['--color-accent-tint-2', '#e6f4f1'],
['--color-danger', '#b3261e'],
['--color-topbar', '#1a1a1a'],
])('declares %s as %s', (name, value) => {
expect(css).toMatch(new RegExp(`${name}:\\s*${value}\\b`, 'i'))
})
it.each([
['amber', '#fff1c2', '#6b4a00'],
['blue', '#e0efff', '#00527c'],
['violet', '#ede7ff', '#4b2e99'],
['orange', '#ffe6cf', '#7a3a00'],
['indigo', '#e3e8ff', '#2c3e8f'],
['green', '#d7f4e3', '#0c5132'],
['grey', '#ebebeb', '#4a4a4a'],
['red', '#fee3e0', '#8e1f0b'],
])('declares the %s status pair', (hue, bg, fg) => {
expect(css).toMatch(new RegExp(`--color-st-${hue}-bg:\\s*${bg}`, 'i'))
expect(css).toMatch(new RegExp(`--color-st-${hue}-fg:\\s*${fg}`, 'i'))
})
it('sets the radius scale: md 8, xl 12', () => {
expect(css).toMatch(/--radius-md:\s*8px/)
expect(css).toMatch(/--radius-xl:\s*12px/)
})
it('declares the card and floating shadows', () => {
expect(css).toMatch(/--shadow-card:\s*0 0 0 1px rgba\(0, ?0, ?0, ?\.08\), 0 1px 2px rgba\(0, ?0, ?0, ?\.06\)/)
expect(css).toMatch(/--shadow-float:\s*0 0 0 1px rgba\(0, ?0, ?0, ?\.1\), 0 12px 32px rgba\(0, ?0, ?0, ?\.18\)/)
})
it('declares the component shadows', () => {
for (const name of ['drawer', 'primary', 'secondary', 'input', 'chip', 'chip-set']) {
expect(css).toMatch(new RegExp(`--shadow-${name}:`))
}
})
it('uses Geist through the next/font variables', () => {
expect(css).toMatch(/--font-sans:\s*var\(--font-geist\)/)
expect(css).toMatch(/--font-mono:\s*var\(--font-geist-mono\)/)
})
it('keeps the legacy remaps so unmigrated pages still render', () => {
expect(css).toMatch(/--color-gray-100:\s*var\(--color-neutral-200\)/)
expect(css).toMatch(/--color-blue-600:\s*var\(--color-accent\)/)
expect(css).toMatch(/--color-red-600:\s*var\(--color-danger\)/)
expect(css).toMatch(/--color-divider:/)
})
it('styles keyboard focus with the 2px accent ring', () => {
expect(css).toMatch(/:focus-visible\s*\{[^}]*outline:\s*2px solid var\(--color-accent\)/)
})
it('has no dark mode block and no Modernist leftovers', () => {
expect(css).not.toContain('prefers-color-scheme')
expect(css).not.toMatch(/ec3013/i)
expect(css).not.toMatch(/archivo/i)
})
it('has no stray comment terminator before @theme', () => {
const head = css.slice(0, css.indexOf('@theme'))
expect(head.match(/\*\//g)?.length).toBe(head.match(/\/\*/g)?.length)
})
})
- Step 4: Run both to verify they fail
Run: npx vitest run tests/scripts/check-design-gates.test.ts tests/design/tokens.test.ts 2>&1 | grep -E "Test Files|Tests "
Expected: FAIL (both files have failing tests).
- Step 5: Rewrite the gate
Replace scripts/check-design-gates.mjs:
import { readdirSync, readFileSync, statSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const RULES = [
{ rule: 'no-2px-border', re: /(?<![\w-])border(?:-[tblrxy])?-2(?![\w-])/ },
{ rule: 'no-archivo', re: /Archivo/ },
{ 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 = []
src.split('\n').forEach((text, i) => {
for (const { rule, re } of RULES) {
if (re.test(text)) out.push({ file, line: i + 1, rule, 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()
- Step 6: Rewrite
app/globals.css
Read the file first (the harness requires it), then replace it entirely:
@import "tailwindcss";
/* IMS Admin refresh tokens. Source of truth: design-system/design.md section 2.
Static emits every variable so plain CSS can use var(--color-*) too. */
@theme static {
--color-ink: #1f1f1f;
--color-ink-2: #303030;
--color-ink-3: #4a4a4a;
--color-muted: #616161;
--color-faint: #8a8a8a;
--color-rule: #ebebeb;
--color-rule-2: #e3e3e3;
--color-ring: #d4d4d4;
--color-surface: #ffffff;
--color-surface-2: #f7f7f7;
--color-ground: #f1f1f1;
--color-accent: #0f766e;
--color-accent-tint: #f2f7f6;
--color-accent-tint-2: #e6f4f1;
--color-danger: #b3261e;
--color-topbar: #1a1a1a;
/* Status pills: a dark step on a light tint, one pair per hue. */
--color-st-amber-bg: #fff1c2;
--color-st-amber-fg: #6b4a00;
--color-st-blue-bg: #e0efff;
--color-st-blue-fg: #00527c;
--color-st-violet-bg: #ede7ff;
--color-st-violet-fg: #4b2e99;
--color-st-orange-bg: #ffe6cf;
--color-st-orange-fg: #7a3a00;
--color-st-indigo-bg: #e3e8ff;
--color-st-indigo-fg: #2c3e8f;
--color-st-green-bg: #d7f4e3;
--color-st-green-fg: #0c5132;
--color-st-grey-bg: #ebebeb;
--color-st-grey-fg: #4a4a4a;
--color-st-red-bg: #fee3e0;
--color-st-red-fg: #8e1f0b;
/* Legacy names kept, re-valued, until every page is migrated. */
--color-divider: #e3e3e3;
--color-neutral-100: #f7f7f7;
--color-neutral-200: #ebebeb;
--color-neutral-300: #d4d4d4;
--color-neutral-400: #c4c4c4;
--color-neutral-500: #8a8a8a;
--color-neutral-600: #616161;
--color-neutral-700: #4a4a4a;
--color-neutral-800: #303030;
--color-neutral-900: #1f1f1f;
--color-accent-100: #e6f4f1;
--color-accent-200: #c5e8e0;
--color-accent-300: #9fd3c7;
--color-accent-400: #5fb3a5;
--color-accent-500: #2b9488;
--color-accent-600: #0c615a;
--color-accent-700: #0b4f47;
--color-accent-800: #083b36;
--color-accent-900: #052a26;
--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-ink);
--color-gray-950: var(--color-ink);
--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);
--color-red-50: #fee3e0;
--color-red-100: #fee3e0;
--color-red-200: #f9c4bd;
--color-red-300: #f2a198;
--color-red-400: #e06a5a;
--color-red-500: #c9382a;
--color-red-600: var(--color-danger);
--color-red-700: #8e1f0b;
--color-red-800: #6b1708;
--color-red-900: #4a1005;
/* Radius scale: 8 buttons, chips, inputs, pills; 12 cards; 14 drawer. */
--radius: 8px;
--radius-xs: 4px;
--radius-sm: 6px;
--radius-md: 8px;
--radius-lg: 8px;
--radius-xl: 12px;
--radius-2xl: 14px;
--radius-3xl: 14px;
--radius-4xl: 14px;
--shadow-card: 0 0 0 1px rgba(0,0,0,.08), 0 1px 2px rgba(0,0,0,.06);
--shadow-float: 0 0 0 1px rgba(0,0,0,.1), 0 12px 32px rgba(0,0,0,.18);
--shadow-drawer: 0 0 0 1px rgba(0,0,0,.1), 0 24px 60px rgba(0,0,0,.24);
--shadow-primary: inset 0 -1px 0 #000, inset 0 1px 0 rgba(255,255,255,.18), 0 1px 2px rgba(0,0,0,.2);
--shadow-secondary: inset 0 0 0 1px var(--color-ring), 0 1px 0 rgba(0,0,0,.05);
--shadow-input: inset 0 0 0 1px var(--color-faint);
--shadow-chip: inset 0 0 0 1px var(--color-ring);
--shadow-chip-set: inset 0 0 0 1px var(--color-accent-300);
--shadow-sm: 0 1px 2px rgba(0,0,0,.06);
--shadow-md: 0 3px 10px rgba(0,0,0,.12);
--shadow-lg: var(--shadow-float);
--shadow-xl: var(--shadow-float);
--shadow-2xl: var(--shadow-float);
--font-sans: var(--font-geist), system-ui, sans-serif;
--font-mono: var(--font-geist-mono), ui-monospace, SFMono-Regular, Menlo, monospace;
}
@layer base {
html {
background: var(--color-ground);
}
body {
background: var(--color-ground);
color: var(--color-ink);
font-family: var(--font-sans);
font-size: 13px;
line-height: 1.5;
}
h1, h2, h3, h4, h5, h6 {
font-weight: 650;
line-height: 1.25;
letter-spacing: -0.01em;
}
:focus {
outline: none;
}
:focus-visible {
outline: 2px solid var(--color-accent);
outline-offset: 2px;
}
::selection {
background: color-mix(in srgb, var(--color-accent) 25%, transparent);
}
input,
textarea,
select {
color: var(--color-ink);
}
input::placeholder,
textarea::placeholder {
color: var(--color-faint);
}
button:disabled,
input:disabled,
select:disabled,
textarea:disabled {
opacity: 0.45;
cursor: not-allowed;
}
}
- Step 7: Switch the font in
app/layout.tsx
Read the file, then replace the import, the font constants and the <html> className:
import { Geist, Geist_Mono } from 'next/font/google'
const geist = Geist({
variable: '--font-geist',
subsets: ['latin'],
})
const geistMono = Geist_Mono({
variable: '--font-geist-mono',
subsets: ['latin'],
})
className={`${geist.variable} ${geistMono.variable} h-full antialiased`}
Remove the Archivo import, constant and usage. Confirm: grep -n Archivo app/layout.tsx prints nothing.
- Step 8: Sweep 2px borders to 1px and fix the two tests that asserted them
python3 - <<'EOF'
import re, glob
tok1 = re.compile(r'(?<![\w-])border-([tblrxy])-2(?![\w-])')
tok2 = re.compile(r'(?<![\w-])border-2(?![\w-])')
n = 0
for f in glob.glob('app/**/*.tsx', recursive=True) + glob.glob('components/**/*.tsx', recursive=True):
s = open(f).read()
s2 = tok2.sub('border', tok1.sub(r'border-\1', s))
if s2 != s:
open(f, 'w').write(s2); n += 1
print('files changed:', n)
EOF
sed -i '' "s/'border-r-2'/'border-r'/; s/'border-b-2'/'border-b'/" tests/components/layout/sidebar.test.tsx tests/components/ui/modal.test.tsx
grep -rn "border-[a-z]-2\|border-2" tests | head
Expected: files changed: 11 (give or take; report the number), and the last grep prints nothing.
- Step 9: Run the tests, the gate, tsc and a clean build
npx vitest run tests/scripts/check-design-gates.test.ts tests/design/tokens.test.ts 2>&1 | grep -E "Test Files|Tests "
npm run check:design 2>&1 | tail -3
npx tsc --noEmit 2>&1 | head -5; echo "tsc done"
npx vitest run 2>&1 | grep -E "Test Files|Tests "
rm -rf .next && npm run build > /tmp/ims-build.log 2>&1; echo "build exit=$?"
f=$(ls .next/static/chunks/*.css | head -1)
echo "accent: $(grep -ho '\-\-color-accent:[^;}]*' $f | head -1) | md radius: $(grep -ho '\-\-radius-md:[^;}]*' $f | head -1) | st-green-bg: $(grep -ho '\-\-color-st-green-bg:[^;}]*' $f | head -1) | font: $(grep -ho '\-\-font-sans:[^;}]*' $f | head -1)"
Expected: token and gate tests all pass; design gates: clean; tsc prints nothing; the full suite shows exactly the 7 baseline failures; build exit 0; the CSS line shows #0f766e, 8px, #d7f4e3 and var(--font-geist). If the CSS line is empty or shows Tailwind defaults, the @theme block is not being compiled: check for a stray */ in comments before anything else.
- Step 10: Commit
git add scripts/check-design-gates.mjs tests/scripts/check-design-gates.test.ts app/globals.css app/layout.tsx tests/design/tokens.test.ts tests/components/layout/sidebar.test.tsx tests/components/ui/modal.test.tsx app components
git commit -m "feat(design): switch to IMS Admin tokens, Geist and the 1px-rule gate
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
Task 2: UI primitives
Files:
- Modify:
components/ui/button.tsx,components/ui/status-tag.tsx,components/ui/field.tsx,components/ui/card.tsx,components/ui/modal.tsx - Create:
components/ui/checkbox.tsx,components/ui/filter-chip.tsx,components/ui/segmented.tsx,components/ui/avatar.tsx,components/ui/drawer.tsx - Delete:
components/ui/tag.tsx,components/ui/table-styles.ts - Test:
tests/components/ui/primitives.test.tsx(full rewrite),tests/components/ui/modal.test.tsx(rewrite)
Interfaces:
-
Consumes: Task 1 utilities.
-
Produces (later tasks import exactly these):
cx(...parts)from./cx(unchanged)Button({ variant?: 'primary'|'secondary'|'icon', block?: boolean, mobile?: boolean } & ButtonHTMLAttributes); defaulttype="button"StatusTag({ status: string, children?: ReactNode }),PriorityTag({ priority: string, children?: ReactNode }),statusHue(key: string): StatusHuewhereStatusHue = 'amber'|'blue'|'violet'|'orange'|'indigo'|'green'|'grey'|'red'Checkbox({ checked: boolean, indeterminate?: boolean, onChange: (next: boolean) => void, label: string })FilterChip({ label: string, value: string, options: Array<{ value: string, label: string }>, onChange: (value: string) => void })Segmented({ value: string, onChange: (v: string) => void, options: Array<{ value: string, label: ReactNode }> })Avatar({ name: string })Drawer({ open: boolean, onClose: () => void, title: string, actions?: ReactNode, children: ReactNode })Field,Input,Textarea,Select,INPUT_CLASSfrom./field;Card({ kicker?, title?, meta?, children? });Modal(same props as today)
-
Step 1: Write the failing primitives test
Replace tests/components/ui/primitives.test.tsx:
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { Button } from '@/components/ui/button'
import { StatusTag, PriorityTag, statusHue } from '@/components/ui/status-tag'
import { Checkbox } from '@/components/ui/checkbox'
import { FilterChip } from '@/components/ui/filter-chip'
import { Segmented } from '@/components/ui/segmented'
import { Avatar } from '@/components/ui/avatar'
import { Drawer } from '@/components/ui/drawer'
import { Field, Input } from '@/components/ui/field'
import { Card } from '@/components/ui/card'
describe('Button', () => {
it('primary is the dark 32px button, type=button by default', () => {
render(<Button>Report incident</Button>)
const b = screen.getByRole('button', { name: 'Report incident' })
expect(b.getAttribute('type')).toBe('button')
expect(b.className).toContain('bg-ink-2')
expect(b.className).toContain('h-8')
expect(b.className).toContain('rounded-md')
expect(b.className).toContain('shadow-primary')
})
it('secondary is white with a ring', () => {
render(<Button variant="secondary">Export</Button>)
const b = screen.getByRole('button', { name: 'Export' })
expect(b.className).toContain('bg-surface')
expect(b.className).toContain('shadow-secondary')
})
it('icon is a 28px ghost button', () => {
render(<Button variant="icon" aria-label="More" />)
const b = screen.getByRole('button', { name: 'More' })
expect(b.className).toContain('w-7')
expect(b.className).toContain('h-7')
})
it('mobile and block make a full-width 48px button', () => {
render(<Button block mobile>Submit</Button>)
const b = screen.getByRole('button', { name: 'Submit' })
expect(b.className).toContain('w-full')
expect(b.className).toContain('h-12')
expect(b.className).toContain('rounded-xl')
})
})
describe('StatusTag and PriorityTag', () => {
it.each([
['reported', 'amber'], ['triaged', 'blue'], ['investigating', 'violet'], ['capa_pending', 'orange'],
['verification', 'indigo'], ['closed', 'green'], ['open', 'grey'], ['in_progress', 'blue'],
['overdue', 'red'], ['pending_verification', 'indigo'], ['verified', 'green'], ['reopened', 'red'],
['high', 'orange'], ['med', 'amber'], ['low', 'grey'], ['nonsense', 'grey'],
])('%s uses the %s pair', (key, hue) => {
expect(statusHue(key)).toBe(hue)
})
it('renders a dark-on-tint pill with a text label', () => {
render(<StatusTag status="capa_pending" />)
const el = screen.getByText('CAPA pending')
expect(el.className).toContain('bg-st-orange-bg')
expect(el.className).toContain('text-st-orange-fg')
expect(el.className).toContain('rounded-md')
})
it('accepts a label override', () => {
render(<StatusTag status="overdue">Late</StatusTag>)
expect(screen.getByText('Late').className).toContain('bg-st-red-bg')
})
it('priority med reads Medium on the amber pair', () => {
render(<PriorityTag priority="med" />)
expect(screen.getByText('Medium').className).toContain('bg-st-amber-bg')
})
it('never uses white text on a saturated fill', () => {
const { container } = render(<StatusTag status="closed" />)
expect(container.innerHTML).not.toContain('text-white')
})
})
describe('Checkbox', () => {
it('toggles and reports the next value', () => {
const onChange = vi.fn()
render(<Checkbox checked={false} onChange={onChange} label="Select row" />)
const cb = screen.getByRole('checkbox', { name: 'Select row' })
expect(cb.getAttribute('aria-checked')).toBe('false')
fireEvent.click(cb)
expect(onChange).toHaveBeenCalledWith(true)
})
it('shows checked and indeterminate states', () => {
const { rerender } = render(<Checkbox checked onChange={() => {}} label="a" />)
expect(screen.getByRole('checkbox').getAttribute('aria-checked')).toBe('true')
expect(screen.getByRole('checkbox').className).toContain('bg-accent')
rerender(<Checkbox checked={false} indeterminate onChange={() => {}} label="a" />)
expect(screen.getByRole('checkbox').getAttribute('aria-checked')).toBe('mixed')
})
})
describe('FilterChip', () => {
const options = [{ value: 'open', label: 'Open' }, { value: 'closed', label: 'Closed' }]
it('unset shows the label and a select with an empty option', () => {
const { container } = render(<FilterChip label="Status" value="" options={options} onChange={() => {}} />)
expect(container.querySelector('label > span')?.textContent).toBe('Status')
expect((screen.getByLabelText('Status') as HTMLSelectElement).value).toBe('')
})
it('changes through the select', () => {
const onChange = vi.fn()
render(<FilterChip label="Status" value="" options={options} onChange={onChange} />)
fireEvent.change(screen.getByLabelText('Status'), { target: { value: 'closed' } })
expect(onChange).toHaveBeenCalledWith('closed')
})
it('set shows Label: value in the teal tint with a clear button', () => {
const onChange = vi.fn()
render(<FilterChip label="Status" value="closed" options={options} onChange={onChange} />)
expect(screen.getByText('Status: Closed').closest('label')?.className).toContain('bg-accent-tint-2')
fireEvent.click(screen.getByRole('button', { name: 'Clear Status' }))
expect(onChange).toHaveBeenCalledWith('')
})
})
describe('Segmented', () => {
it('marks the active option and reports changes', () => {
const onChange = vi.fn()
render(<Segmented value="list" onChange={onChange} options={[{ value: 'list', label: 'List' }, { value: 'board', label: 'Board' }]} />)
expect(screen.getByRole('button', { name: 'List' }).getAttribute('aria-pressed')).toBe('true')
fireEvent.click(screen.getByRole('button', { name: 'Board' }))
expect(onChange).toHaveBeenCalledWith('board')
})
})
describe('Avatar', () => {
it('shows up to two initials on the teal tile', () => {
render(<Avatar name="Ada Lovelace King" />)
const el = screen.getByText('AL')
expect(el.className).toContain('bg-accent-200')
expect(el.className).toContain('rounded-[6px]')
})
})
describe('Drawer', () => {
it('renders nothing when closed', () => {
const { container } = render(<Drawer open={false} onClose={() => {}} title="Notifications">x</Drawer>)
expect(container.firstChild).toBeNull()
})
it('renders a labelled dialog, closes on the X button and on Escape', () => {
const onClose = vi.fn()
render(<Drawer open onClose={onClose} title="Notifications" actions={<span>Mark all read</span>}>body</Drawer>)
expect(screen.getByRole('dialog', { name: 'Notifications' })).toBeTruthy()
expect(screen.getByText('Mark all read')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
fireEvent.keyDown(document, { key: 'Escape' })
expect(onClose).toHaveBeenCalledTimes(2)
})
})
describe('Field, Input, Card', () => {
it('Input is 36px with the faint ring and is labelled', () => {
render(<Field label="Email" htmlFor="email"><Input id="email" /></Field>)
const input = screen.getByLabelText('Email')
expect(input.className).toContain('h-9')
expect(input.className).toContain('shadow-input')
expect(input.className).toContain('rounded-md')
})
it('Card is a white 12px card with the card shadow', () => {
const { container } = render(<Card title="Forklift" kicker="Open" meta="Due Friday">Body</Card>)
expect(container.firstElementChild?.className).toContain('rounded-xl')
expect(container.firstElementChild?.className).toContain('shadow-card')
expect(screen.getByText('Forklift')).toBeTruthy()
})
})
- Step 2: Rewrite the modal test
Replace tests/components/ui/modal.test.tsx:
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { Modal } from '@/components/ui/modal'
describe('Modal', () => {
it('renders nothing when closed', () => {
const { container } = render(<Modal open={false} onClose={() => {}} title="T">body</Modal>)
expect(container.firstChild).toBeNull()
})
it('renders a 12px card dialog with the floating shadow and a 1px header rule', () => {
render(<Modal open onClose={() => {}} title="Confirm" footer={<span>actions</span>}>body text</Modal>)
const dialog = screen.getByRole('dialog')
expect(screen.getByText('Confirm')).toBeTruthy()
expect(screen.getByText('body text')).toBeTruthy()
expect(screen.getByText('actions')).toBeTruthy()
expect(dialog.innerHTML).toContain('rounded-xl')
expect(dialog.innerHTML).toContain('shadow-float')
expect(dialog.innerHTML).toContain('border-b border-rule')
expect(dialog.innerHTML).not.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 3: Run to verify they fail
Run: npx vitest run tests/components/ui 2>&1 | grep -E "Test Files|Tests |Failed to resolve" | head -5
Expected: FAIL (modules such as @/components/ui/checkbox not found, old assertions failing).
- Step 4: Write the primitives
components/ui/button.tsx:
import type { ButtonHTMLAttributes } from 'react'
import { cx } from './cx'
type Variant = 'primary' | 'secondary' | 'icon'
const BASE =
'inline-flex items-center justify-center gap-1.5 whitespace-nowrap transition-colors cursor-pointer ' +
'disabled:opacity-45 disabled:cursor-not-allowed'
const VARIANTS: Record<Variant, string> = {
primary: 'h-8 px-3 rounded-md bg-ink-2 text-white text-[13px] font-semibold shadow-primary hover:bg-ink active:bg-black',
secondary: 'h-8 px-3 rounded-md bg-surface text-ink text-[13px] font-medium shadow-secondary hover:bg-surface-2 active:bg-rule',
icon: 'w-7 h-7 rounded-md text-ink-3 hover:bg-rule',
}
type Props = ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: Variant
block?: boolean
mobile?: boolean
}
export function Button({ variant = 'primary', block = false, mobile = false, className, type = 'button', ...rest }: Props) {
return (
<button
type={type}
className={cx(
BASE,
VARIANTS[variant],
mobile && variant !== 'icon' && 'h-12 rounded-xl text-sm',
block && 'w-full',
className,
)}
{...rest}
/>
)
}
components/ui/status-tag.tsx (replaces the file; Tag is gone):
import type { ReactNode } from 'react'
import { cx } from './cx'
export type StatusHue = 'amber' | 'blue' | 'violet' | 'orange' | 'indigo' | 'green' | 'grey' | 'red'
const HUES: Record<string, StatusHue> = {
reported: 'amber', triaged: 'blue', investigating: 'violet', capa_pending: 'orange',
verification: 'indigo', closed: 'green',
open: 'grey', in_progress: 'blue', overdue: 'red', pending_verification: 'indigo',
verified: 'green', reopened: 'red',
critical: 'red', high: 'orange', med: 'amber', medium: 'amber', low: 'grey', active: 'green',
}
const LABELS: Record<string, string> = {
capa_pending: 'CAPA pending', pending_verification: 'Verification', in_progress: 'In progress', med: 'Medium',
}
// Full literal class strings so Tailwind can see them.
const HUE_CLASS: Record<StatusHue, string> = {
amber: 'bg-st-amber-bg text-st-amber-fg',
blue: 'bg-st-blue-bg text-st-blue-fg',
violet: 'bg-st-violet-bg text-st-violet-fg',
orange: 'bg-st-orange-bg text-st-orange-fg',
indigo: 'bg-st-indigo-bg text-st-indigo-fg',
green: 'bg-st-green-bg text-st-green-fg',
grey: 'bg-st-grey-bg text-st-grey-fg',
red: 'bg-st-red-bg text-st-red-fg',
}
export function statusHue(key: string): StatusHue {
return HUES[key] ?? 'grey'
}
function label(key: string): string {
if (LABELS[key]) return LABELS[key]
const words = key.split('_').join(' ')
return words.charAt(0).toUpperCase() + words.slice(1)
}
function Pill({ hue, className, children }: { hue: StatusHue; className?: string; children: ReactNode }) {
return (
<span
className={cx(
'inline-flex items-center px-2 py-0.5 rounded-md text-xs font-[550] whitespace-nowrap',
HUE_CLASS[hue],
className,
)}
>
{children}
</span>
)
}
export function StatusTag({ status, children }: { status: string; children?: ReactNode }) {
return <Pill hue={statusHue(status)}>{children ?? label(status)}</Pill>
}
export function PriorityTag({ priority, children }: { priority: string; children?: ReactNode }) {
return <Pill hue={statusHue(priority)}>{children ?? label(priority)}</Pill>
}
components/ui/checkbox.tsx:
import { Check, Minus } from 'lucide-react'
import { cx } from './cx'
export function Checkbox({
checked,
indeterminate = false,
onChange,
label,
}: {
checked: boolean
indeterminate?: boolean
onChange: (next: boolean) => void
label: string
}) {
const on = checked || indeterminate
return (
<button
type="button"
role="checkbox"
aria-checked={indeterminate ? 'mixed' : checked}
aria-label={label}
onClick={e => {
e.stopPropagation()
onChange(!checked)
}}
className={cx(
'inline-grid place-items-center w-4 h-4 rounded-[5px] cursor-pointer',
on ? 'bg-accent text-white' : 'bg-surface shadow-[inset_0_0_0_1.5px_var(--color-faint)]',
)}
>
{indeterminate ? <Minus size={12} strokeWidth={3} aria-hidden /> : checked ? <Check size={12} strokeWidth={3} aria-hidden /> : null}
</button>
)
}
components/ui/filter-chip.tsx:
import { ChevronDown, X } from 'lucide-react'
import { cx } from './cx'
export function FilterChip({
label,
value,
options,
onChange,
}: {
label: string
value: string
options: Array<{ value: string; label: string }>
onChange: (value: string) => void
}) {
const selected = options.find(o => o.value === value)
const set = Boolean(value && selected)
return (
<label
className={cx(
'relative inline-flex items-center gap-1 h-7 px-2.5 rounded-md text-[12.5px] whitespace-nowrap cursor-pointer',
set ? 'bg-accent-tint-2 text-accent-700 shadow-chip-set' : 'bg-surface text-ink-2 shadow-chip',
)}
>
<span>{set ? `${label}: ${selected!.label}` : label}</span>
{!set && <ChevronDown size={12} strokeWidth={2.5} aria-hidden />}
<select
aria-label={label}
value={value}
onChange={e => onChange(e.target.value)}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
>
<option value="">{label}</option>
{options.map(o => (
<option key={o.value} value={o.value}>{o.label}</option>
))}
</select>
{set && (
<button
type="button"
aria-label={`Clear ${label}`}
onClick={() => onChange('')}
className="relative z-10 inline-grid place-items-center w-4 h-4 cursor-pointer"
>
<X size={12} strokeWidth={2.5} aria-hidden />
</button>
)}
</label>
)
}
components/ui/segmented.tsx:
import type { ReactNode } from 'react'
import { cx } from './cx'
export function Segmented({
value,
onChange,
options,
}: {
value: string
onChange: (v: string) => void
options: Array<{ value: string; label: ReactNode }>
}) {
return (
<div className="inline-flex p-0.5 rounded-[10px] bg-rule-2">
{options.map(o => (
<button
key={o.value}
type="button"
aria-pressed={o.value === value}
onClick={() => onChange(o.value)}
className={cx(
'inline-flex items-center gap-1.5 px-2.5 py-[5px] rounded-md text-[13px] cursor-pointer whitespace-nowrap',
o.value === value ? 'bg-surface font-semibold shadow-sm' : 'text-ink-3',
)}
>
{o.label}
</button>
))}
</div>
)
}
components/ui/avatar.tsx:
export function initials(name: string): string {
return name
.split(' ')
.map(w => w[0] ?? '')
.join('')
.toUpperCase()
.slice(0, 2)
}
export function Avatar({ name }: { name: string }) {
return (
<span className="inline-grid place-items-center w-6 h-6 rounded-[6px] bg-accent-200 text-accent-700 text-[11px] font-[650]">
{initials(name)}
</span>
)
}
components/ui/drawer.tsx:
'use client'
import { useEffect } from 'react'
import { X } from 'lucide-react'
import { Button } from './button'
export function Drawer({
open,
onClose,
title,
actions,
children,
}: {
open: boolean
onClose: () => void
title: string
actions?: React.ReactNode
children: React.ReactNode
}) {
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
return (
<div className="fixed inset-0 z-50">
<div className="absolute inset-0 bg-black/30" onClick={onClose} aria-hidden />
<aside
role="dialog"
aria-modal="true"
aria-label={title}
className="absolute top-2 right-2 bottom-2 w-[420px] max-w-[calc(100vw-16px)] flex flex-col overflow-hidden rounded-2xl bg-surface shadow-drawer"
>
<div className="flex items-center justify-between px-4 pt-3.5 pb-2.5">
<h2 className="text-base font-[650]">{title}</h2>
<div className="flex items-center gap-1">
{actions}
<Button variant="icon" aria-label="Close" onClick={onClose}>
<X size={16} strokeWidth={2} aria-hidden />
</Button>
</div>
</div>
<div className="flex-1 overflow-y-auto">{children}</div>
</aside>
</div>
)
}
components/ui/field.tsx (keep exports; restyle):
import type { InputHTMLAttributes, ReactNode, SelectHTMLAttributes, TextareaHTMLAttributes } from 'react'
import { cx } from './cx'
export const INPUT_CLASS =
'w-full h-9 px-3 rounded-md bg-surface text-[13px] text-ink caret-accent shadow-input ' +
'placeholder:text-faint 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 text-muted mb-[5px]">
{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, 'h-auto min-h-[90px] py-2 resize-y', className)} {...rest} />
}
export function Select({ className, ...rest }: SelectHTMLAttributes<HTMLSelectElement>) {
return <select className={cx(INPUT_CLASS, className)} {...rest} />
}
components/ui/card.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-4 bg-surface rounded-xl shadow-card">
{kicker && <span className="text-[11px] font-semibold tracking-wide uppercase text-muted">{kicker}</span>}
{title && <h3 className="text-base font-[650]">{title}</h3>}
{children && <div className="flex-1 text-[13px] text-ink-3">{children}</div>}
{meta && <div className="flex items-center gap-1.5 text-xs text-faint">{meta}</div>}
</div>
)
}
components/ui/modal.tsx (full replacement; same props):
'use client'
import { useEffect } from 'react'
import { X } from 'lucide-react'
import { Button } from './button'
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-black/30" onClick={onClose} />
<div className={`relative w-full ${maxW} bg-surface rounded-xl shadow-float`}>
<div className="flex items-center justify-between px-5 py-3.5 border-b border-rule">
<h2 className="text-base font-[650]">{title}</h2>
<Button variant="icon" aria-label="Close" onClick={onClose}>
<X size={16} strokeWidth={2} aria-hidden />
</Button>
</div>
<div className="px-5 py-4">{children}</div>
{footer && (
<div className="px-5 py-3.5 border-t border-rule flex justify-end gap-2">
{footer}
</div>
)}
</div>
</div>
)
}
- Step 5: Delete the retired primitives
git rm -q components/ui/tag.tsx components/ui/table-styles.ts
grep -rn "ui/tag'\|ui/table-styles'\|statusTone" app components tests | head
Expected: the grep prints nothing.
- Step 6: Run the tests, the gate, tsc and the full suite
npx vitest run tests/components/ui 2>&1 | grep -E "Test Files|Tests |×"
npm run check:design 2>&1 | tail -3
npx tsc --noEmit 2>&1 | head -8; echo "tsc done"
npx vitest run 2>&1 | grep -E "Test Files|Tests "
Expected: ui tests pass; design gates: clean; tsc prints nothing; the full suite shows exactly the 7 baseline failures. If tsc reports a caller using Button variant="ghost" or Tag, migrate that caller to Button variant="secondary" or StatusTag; the only known Button caller is components/auth/login-form.tsx, which uses variant="primary" block. The login form's Input still compiles.
- Step 7: Commit
git add components/ui tests/components/ui
git commit -m "feat(design): add IMS Admin primitives (Button, StatusTag, Checkbox, FilterChip, Segmented, Avatar, Drawer) and restyle Field, Card, Modal
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
Task 3: TableCard
Files:
- Create:
components/ui/table-card.tsx - Test:
tests/components/ui/table-card.test.tsx
Interfaces:
- Consumes:
Checkbox(Task 2),cx. - Produces (Task 5 imports exactly these):
export type Column<T> = { key: string; header: string; sortKey?: string; cell: (row: T) => ReactNode }
export type Sort = { key: string; dir: 'asc' | 'desc' }
export type TableView = { key: string; label: string; count?: number }
export interface TableCardProps<T> {
columns: Column<T>[]
rows: T[]
rowKey: (row: T) => string
onRowOpen?: (row: T) => void
rowActions?: (row: T) => ReactNode
views?: { items: TableView[]; active: string; onChange: (key: string) => void }
toolbar?: ReactNode
sort?: Sort
onSortChange?: (sortKey: string) => void
selection?: { selected: Set<string>; onChange: (next: Set<string>) => void }
bulkActions?: ReactNode
footer?: { from: number; to: number; total: number; page: number; pageCount: number; onPage: (page: number) => void }
empty?: { title: string; action?: ReactNode }
mobileRow?: (row: T) => ReactNode
}
export function TableCard<T>(props: TableCardProps<T>): JSX.Element
- Step 1: Write the failing test
Create tests/components/ui/table-card.test.tsx:
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent, within } from '@testing-library/react'
import { TableCard, type Column } from '@/components/ui/table-card'
type Row = { id: string; ref: string; status: string }
const rows: Row[] = [
{ id: '1', ref: 'IMS-0001', status: 'Open' },
{ id: '2', ref: 'IMS-0002', status: 'Closed' },
{ id: '3', ref: 'IMS-0003', status: 'Open' },
]
const columns: Column<Row>[] = [
{ key: 'ref', header: 'Reference', sortKey: 'ref', cell: r => r.ref },
{ key: 'status', header: 'Status', cell: r => r.status },
]
const base = { columns, rows, rowKey: (r: Row) => r.id }
describe('TableCard', () => {
it('renders a 12px card with a grey header and the rows', () => {
const { container } = render(<TableCard {...base} />)
expect(container.firstElementChild?.className).toContain('rounded-xl')
expect(container.firstElementChild?.className).toContain('shadow-card')
expect(screen.getByText('Reference').closest('th')?.className).toContain('bg-surface-2')
expect(screen.getByText('IMS-0002')).toBeTruthy()
expect(screen.getAllByRole('row')).toHaveLength(4)
})
it('opens a row on click and on Enter, but not from the actions cell', () => {
const onRowOpen = vi.fn()
render(<TableCard {...base} onRowOpen={onRowOpen} rowActions={() => <button>quick</button>} />)
fireEvent.click(screen.getByText('IMS-0001'))
expect(onRowOpen).toHaveBeenCalledWith(rows[0])
fireEvent.keyDown(screen.getByText('IMS-0002').closest('tr')!, { key: 'Enter' })
expect(onRowOpen).toHaveBeenCalledWith(rows[1])
onRowOpen.mockClear()
fireEvent.click(screen.getAllByText('quick')[0])
expect(onRowOpen).not.toHaveBeenCalled()
})
it('sorts a single column: sortable header is a button, aria-sort reflects state', () => {
const onSortChange = vi.fn()
render(<TableCard {...base} sort={{ key: 'ref', dir: 'asc' }} onSortChange={onSortChange} />)
expect(screen.getByText('Reference').closest('th')?.getAttribute('aria-sort')).toBe('ascending')
expect(screen.getByText('Status').closest('th')?.getAttribute('aria-sort')).toBeNull()
expect(screen.queryByRole('button', { name: /Status/ })).toBeNull()
fireEvent.click(screen.getByRole('button', { name: /Reference/ }))
expect(onSortChange).toHaveBeenCalledWith('ref')
})
it('selects rows and all rows, and shows the bulk bar with the count', () => {
const onChange = vi.fn()
const { rerender } = render(
<TableCard {...base} selection={{ selected: new Set(), onChange }} bulkActions={<button>Export</button>} />,
)
expect(screen.queryByText(/selected/)).toBeNull()
fireEvent.click(screen.getByRole('checkbox', { name: 'Select all rows' }))
expect(onChange).toHaveBeenLastCalledWith(new Set(['1', '2', '3']))
fireEvent.click(screen.getAllByRole('checkbox', { name: 'Select row' })[1])
expect(onChange).toHaveBeenLastCalledWith(new Set(['2']))
rerender(<TableCard {...base} selection={{ selected: new Set(['1']), onChange }} bulkActions={<button>Export</button>} />)
expect(screen.getByText('1 selected')).toBeTruthy()
expect(screen.getByRole('button', { name: 'Export' })).toBeTruthy()
expect(screen.getByRole('checkbox', { name: 'Select all rows' }).getAttribute('aria-checked')).toBe('mixed')
expect(screen.getByText('IMS-0001').closest('tr')?.className).toContain('bg-accent-tint')
})
it('renders saved views with counts and reports changes', () => {
const onChange = vi.fn()
render(
<TableCard
{...base}
views={{ items: [{ key: 'all', label: 'All', count: 248 }, { key: 'open', label: 'Open', count: 37 }], active: 'all', onChange }}
/>,
)
expect(screen.getByRole('button', { name: /All/ }).className).toContain('bg-rule-2')
expect(screen.getByText('248')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /Open/ }))
expect(onChange).toHaveBeenCalledWith('open')
})
it('renders the footer count and pager', () => {
const onPage = vi.fn()
render(<TableCard {...base} footer={{ from: 1, to: 3, total: 248, page: 1, pageCount: 83, onPage }} />)
expect(screen.getByText('Showing 1–3 of 248')).toBeTruthy()
expect((screen.getByRole('button', { name: 'Previous page' }) as HTMLButtonElement).disabled).toBe(true)
fireEvent.click(screen.getByRole('button', { name: 'Next page' }))
expect(onPage).toHaveBeenCalledWith(2)
})
it('shows the empty state instead of the table', () => {
render(<TableCard {...base} rows={[]} empty={{ title: 'No incidents found', action: <button>Report incident</button> }} />)
expect(screen.queryByRole('table')).toBeNull()
expect(screen.getByText('No incidents found')).toBeTruthy()
expect(screen.getByRole('button', { name: 'Report incident' })).toBeTruthy()
})
it('renders a stacked mobile list beside the desktop table', () => {
const onRowOpen = vi.fn()
const { container } = render(<TableCard {...base} onRowOpen={onRowOpen} mobileRow={r => <span>mobile {r.ref}</span>} />)
const list = container.querySelector('ul')!
expect(list.className).toContain('md:hidden')
expect(within(list).getByText('mobile IMS-0003')).toBeTruthy()
expect(container.querySelector('table')!.parentElement!.className).toContain('hidden md:block')
fireEvent.click(within(list).getByText('mobile IMS-0003'))
expect(onRowOpen).toHaveBeenCalledWith(rows[2])
})
})
- Step 2: Run to verify it fails
Run: npx vitest run tests/components/ui/table-card.test.tsx 2>&1 | grep -E "Test Files|Failed to resolve"
Expected: FAIL (Failed to resolve import "@/components/ui/table-card").
- Step 3: Write
components/ui/table-card.tsx
'use client'
import type { ReactNode } from 'react'
import { ArrowDown, ArrowUp, ChevronLeft, ChevronRight, ChevronsUpDown, Inbox } from 'lucide-react'
import { Checkbox } from './checkbox'
import { cx } from './cx'
export type Column<T> = { key: string; header: string; sortKey?: string; cell: (row: T) => ReactNode }
export type Sort = { key: string; dir: 'asc' | 'desc' }
export type TableView = { key: string; label: string; count?: number }
export interface TableCardProps<T> {
columns: Column<T>[]
rows: T[]
rowKey: (row: T) => string
onRowOpen?: (row: T) => void
rowActions?: (row: T) => ReactNode
views?: { items: TableView[]; active: string; onChange: (key: string) => void }
toolbar?: ReactNode
sort?: Sort
onSortChange?: (sortKey: string) => void
selection?: { selected: Set<string>; onChange: (next: Set<string>) => void }
bulkActions?: ReactNode
footer?: { from: number; to: number; total: number; page: number; pageCount: number; onPage: (page: number) => void }
empty?: { title: string; action?: ReactNode }
mobileRow?: (row: T) => ReactNode
}
const TH = 'px-3 py-[9px] text-xs font-[550] text-muted text-left bg-surface-2 border-b border-rule-2 whitespace-nowrap'
const TD = 'px-3 py-3 text-[13px] border-b border-rule'
export function TableCard<T>({
columns, rows, rowKey, onRowOpen, rowActions, views, toolbar, sort, onSortChange,
selection, bulkActions, footer, empty, mobileRow,
}: TableCardProps<T>) {
const selectedOnPage = selection ? rows.filter(r => selection.selected.has(rowKey(r))).length : 0
const allSelected = rows.length > 0 && selectedOnPage === rows.length
const setAll = (next: boolean) => {
if (!selection) return
const s = new Set(selection.selected)
rows.forEach(r => (next ? s.add(rowKey(r)) : s.delete(rowKey(r))))
selection.onChange(s)
}
const setOne = (id: string, next: boolean) => {
if (!selection) return
const s = new Set(selection.selected)
if (next) s.add(id)
else s.delete(id)
selection.onChange(s)
}
const open = (row: T) => onRowOpen?.(row)
const isEmpty = rows.length === 0 && empty
return (
<div className="relative bg-surface rounded-xl shadow-card overflow-hidden">
{views && (
<div className="flex items-center gap-0.5 p-2 border-b border-rule">
{views.items.map(v => (
<button
key={v.key}
type="button"
onClick={() => views.onChange(v.key)}
className={cx(
'inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md text-[13px] cursor-pointer',
v.key === views.active ? 'bg-rule-2 font-semibold text-ink' : 'font-medium text-ink-3 hover:bg-surface-2',
)}
>
{v.label}
{v.count !== undefined && <span className="text-xs font-medium text-faint">{v.count}</span>}
</button>
))}
</div>
)}
{toolbar && <div className="flex flex-wrap items-center gap-2 px-3 py-2.5 border-b border-rule">{toolbar}</div>}
{isEmpty ? (
<div className="flex flex-col items-center gap-3 px-4 py-14 text-center">
<span className="inline-grid place-items-center w-16 h-16 rounded-xl bg-surface-2 text-faint">
<Inbox size={28} strokeWidth={1.8} aria-hidden />
</span>
<p className="text-sm text-ink-3">{empty.title}</p>
{empty.action}
</div>
) : (
<>
<div className="hidden md:block overflow-x-auto">
<table className="w-full border-collapse">
<thead>
<tr>
{selection && (
<th className={cx(TH, 'w-7 pl-4')}>
<Checkbox
checked={allSelected}
indeterminate={selectedOnPage > 0 && !allSelected}
onChange={setAll}
label="Select all rows"
/>
</th>
)}
{columns.map(c => {
const sorted = sort && c.sortKey && sort.key === c.sortKey ? sort.dir : null
return (
<th
key={c.key}
className={TH}
aria-sort={sorted ? (sorted === 'asc' ? 'ascending' : 'descending') : undefined}
>
{c.sortKey && onSortChange ? (
<button
type="button"
onClick={() => onSortChange(c.sortKey!)}
className="inline-flex items-center gap-1 cursor-pointer"
>
{c.header}
{sorted === 'asc' ? (
<ArrowUp size={12} strokeWidth={2.5} className="text-ink" aria-hidden />
) : sorted === 'desc' ? (
<ArrowDown size={12} strokeWidth={2.5} className="text-ink" aria-hidden />
) : (
<ChevronsUpDown size={12} strokeWidth={2} className="text-neutral-400" aria-hidden />
)}
</button>
) : (
c.header
)}
</th>
)
})}
{rowActions && <th className={cx(TH, 'w-24')} />}
</tr>
</thead>
<tbody>
{rows.map(row => {
const id = rowKey(row)
const selected = Boolean(selection?.selected.has(id))
return (
<tr
key={id}
tabIndex={onRowOpen ? 0 : undefined}
onClick={() => open(row)}
onKeyDown={e => { if (e.key === 'Enter') open(row) }}
className={cx(
'group',
onRowOpen && 'cursor-pointer',
selected ? 'bg-accent-tint' : 'bg-surface hover:bg-surface-2',
)}
>
{selection && (
<td className={cx(TD, 'pl-4')} onClick={e => e.stopPropagation()}>
<Checkbox checked={selected} onChange={next => setOne(id, next)} label="Select row" />
</td>
)}
{columns.map(c => (
<td key={c.key} className={TD}>{c.cell(row)}</td>
))}
{rowActions && (
<td className={TD} onClick={e => e.stopPropagation()}>
<div className="flex justify-end gap-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100">
{rowActions(row)}
</div>
</td>
)}
</tr>
)
})}
</tbody>
</table>
</div>
{mobileRow && (
<ul className="md:hidden">
{rows.map(row => (
<li
key={rowKey(row)}
onClick={() => open(row)}
className={cx('px-4 py-3 border-b border-rule', onRowOpen && 'cursor-pointer')}
>
{mobileRow(row)}
</li>
))}
</ul>
)}
</>
)}
{footer && (
<div className="flex items-center justify-between px-4 py-2.5 bg-surface-2 text-[13px] text-muted">
<span>{`Showing ${footer.from}–${footer.to} of ${footer.total}`}</span>
<div className="flex">
<button
type="button"
aria-label="Previous page"
disabled={footer.page <= 1}
onClick={() => footer.onPage(footer.page - 1)}
className="inline-flex items-center h-8 px-[7px] rounded-l-md bg-surface text-ink shadow-chip disabled:text-neutral-400 cursor-pointer"
>
<ChevronLeft size={16} strokeWidth={2} aria-hidden />
</button>
<button
type="button"
aria-label="Next page"
disabled={footer.page >= footer.pageCount}
onClick={() => footer.onPage(footer.page + 1)}
className="inline-flex items-center h-8 px-[7px] rounded-r-md bg-surface text-ink shadow-chip -ml-px disabled:text-neutral-400 cursor-pointer"
>
<ChevronRight size={16} strokeWidth={2} aria-hidden />
</button>
</div>
</div>
)}
{selection && bulkActions && selection.selected.size > 0 && (
<div className="sticky bottom-3 flex justify-center px-4 pb-3 pt-5 bg-gradient-to-t from-surface">
<div className="flex items-center gap-1.5 py-1.5 pr-1.5 pl-3 rounded-xl bg-surface shadow-float">
<span className="text-[13px] font-semibold px-2">{`${selection.selected.size} selected`}</span>
<span className="w-px h-5 bg-rule-2" />
{bulkActions}
</div>
</div>
)}
</div>
)
}
- Step 4: Run the tests, the gate and tsc
npx vitest run tests/components/ui/table-card.test.tsx 2>&1 | grep -E "Test Files|Tests |×"
npm run check:design 2>&1 | tail -2
npx tsc --noEmit 2>&1 | head -5; echo "tsc done"
Expected: 8 tests pass; design gates: clean; tsc prints nothing. If the getAllByRole('row') count is off, the header row counts as one row (4 in total for 3 data rows).
- Step 5: Commit
git add components/ui/table-card.tsx tests/components/ui/table-card.test.tsx
git commit -m "feat(design): add TableCard (views, toolbar, sortable header, selection, bulk bar, footer pager, empty, mobile list)
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
Task 4: Shells (AppShell, MobileShell) and the notifications drawer
Files:
- Create:
components/layout/nav-items.ts,components/layout/mobile-shell.tsx,components/layout/app-shell.tsx - Modify:
components/notifications/bell.tsx(full rewrite),app/(protected)/layout.tsx - Delete:
components/layout/sidebar.tsx,tests/components/layout/sidebar.test.tsx - Test:
tests/components/layout/nav-items.test.ts,tests/components/layout/app-shell.test.tsx,tests/components/notifications/bell.test.tsx
Interfaces:
-
Consumes:
Avatar,initials,Button,Drawer,cx(Task 2);lucide-react. -
Produces:
NavItem = { label: string; href: string; icon: LucideIcon },navItemsFor(role: string): NavItem[],isActivePath(href: string, pathname: string): boolean,searchHrefFor(role: string): string | nullMobileShell({ items: NavItem[], pathname: string, onLogout: () => void }): JSX.Element(tab bar,md:hidden)AppShell({ role: string, userName: string, children: ReactNode })NotificationBell()(bell button plus drawer; same name as before, no props)
-
Step 1: Write the failing tests
tests/components/layout/nav-items.test.ts:
import { describe, it, expect } from 'vitest'
import { navItemsFor, isActivePath, searchHrefFor } from '@/components/layout/nav-items'
describe('nav items', () => {
it('returns the role menu and falls back to reporter', () => {
expect(navItemsFor('hse').map(i => i.label)).toEqual(['Dashboard', 'Incidents', 'CAPA', 'Settings'])
expect(navItemsFor('admin')[0].label).toBe('Admin')
expect(navItemsFor('nobody')).toEqual(navItemsFor('reporter'))
})
it('matches root pages exactly and nested pages by prefix', () => {
expect(isActivePath('/reporter', '/reporter')).toBe(true)
expect(isActivePath('/reporter', '/reporter/incidents/1')).toBe(false)
expect(isActivePath('/hse/incidents', '/hse/incidents/abc')).toBe(true)
})
it('offers the search box only to roles that have an incident list', () => {
expect(searchHrefFor('hse')).toBe('/hse/incidents')
expect(searchHrefFor('admin')).toBe('/hse/incidents')
expect(searchHrefFor('supervisor')).toBe('/supervisor/incidents')
expect(searchHrefFor('reporter')).toBeNull()
expect(searchHrefFor('capa_owner')).toBeNull()
})
})
tests/components/layout/app-shell.test.tsx:
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
const push = vi.fn()
const refresh = vi.fn()
vi.mock('next/navigation', () => ({
usePathname: () => '/hse/capa',
useRouter: () => ({ push, refresh }),
}))
vi.mock('@/components/notifications/bell', () => ({ NotificationBell: () => <button aria-label="Notifications" /> }))
import { AppShell } from '@/components/layout/app-shell'
beforeEach(() => {
push.mockClear()
refresh.mockClear()
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }))
})
describe('AppShell', () => {
it('has a 56px dark top bar, a grey sidebar and the page content', () => {
const { container } = render(<AppShell role="hse" userName="Ada Lovelace"><p>page body</p></AppShell>)
expect(container.querySelector('header')?.className).toContain('h-14')
expect(container.querySelector('header')?.className).toContain('bg-topbar')
expect(container.querySelector('aside')?.className).toContain('bg-rule')
expect(container.querySelector('aside')?.className).toContain('w-60')
expect(screen.getByText('page body')).toBeTruthy()
expect(screen.getByText('Setia HSE')).toBeTruthy()
})
it('marks the active sidebar item with aria-current on a white ringed item', () => {
render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
const active = screen.getAllByRole('link', { name: /CAPA/ }).find(a => a.getAttribute('aria-current') === 'page')!
expect(active.className).toContain('bg-surface')
expect(active.className).toContain('shadow-chip')
})
it('shows a GET search form that targets the incident list for HSE roles', () => {
const { container } = render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
const form = container.querySelector('header form')!
expect(form.getAttribute('action')).toBe('/hse/incidents')
expect(form.getAttribute('method')).toBe('get')
expect((form.querySelector('input') as HTMLInputElement).name).toBe('q')
})
it('focuses the search box on Cmd-K', () => {
render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
fireEvent.keyDown(document, { key: 'k', metaKey: true })
expect(document.activeElement?.getAttribute('name')).toBe('q')
})
it('hides the search box for roles without an incident list', () => {
const { container } = render(<AppShell role="reporter" userName="Ada"><span /></AppShell>)
expect(container.querySelector('header form')).toBeNull()
})
it('shows the user chip, version label, and logs out', async () => {
render(<AppShell role="hse" userName="Ada Lovelace"><span /></AppShell>)
expect(screen.getAllByText('AL').length).toBeGreaterThan(0)
expect(screen.getByText('v1.2.2')).toBeTruthy()
fireEvent.click(screen.getAllByRole('button', { name: /Log ?out/i })[0])
await Promise.resolve()
expect(fetch).toHaveBeenCalledWith('/api/auth/logout', { method: 'POST' })
})
it('renders a mobile tab bar that is hidden from md up', () => {
const { container } = render(<AppShell role="hse" userName="Ada"><span /></AppShell>)
const nav = container.querySelector('nav[aria-label="Mobile"]')!
expect(nav.className).toContain('md:hidden')
expect(nav.className).toContain('border-t')
})
it('has no 2px rules and no Modernist rounding', () => {
const { container } = render(<AppShell role="admin" userName="Ada"><span /></AppShell>)
expect(container.innerHTML).not.toMatch(/border-[a-z]?-?2\b/)
})
})
tests/components/notifications/bell.test.tsx:
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { NotificationBell } from '@/components/notifications/bell'
const payload = {
unread: 2,
notifications: [
{ id: 'n1', title: 'CAPA overdue', link: '/hse/capa/1', sent_at: new Date().toISOString(), read_at: null },
{ id: 'n2', title: 'New incident', link: null, sent_at: '2020-01-01T08:00:00Z', read_at: '2020-01-01T09:00:00Z' },
],
}
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => payload }))
})
describe('NotificationBell', () => {
it('shows the unread count on the bell', async () => {
render(<NotificationBell />)
await waitFor(() => expect(screen.getByRole('button', { name: 'Notifications (2 unread)' })).toBeTruthy())
expect(screen.getByText('2')).toBeTruthy()
})
it('opens a drawer with grouped notifications and an Unread tab', async () => {
render(<NotificationBell />)
fireEvent.click(await screen.findByRole('button', { name: /Notifications/ }))
expect(screen.getByRole('dialog', { name: 'Notifications' })).toBeTruthy()
expect(screen.getByText('CAPA overdue')).toBeTruthy()
expect(screen.getByText('Today')).toBeTruthy()
expect(screen.getByText('Earlier')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /Unread/ }))
expect(screen.queryByText('New incident')).toBeNull()
expect(screen.getByText('CAPA overdue')).toBeTruthy()
})
it('marks everything read', async () => {
render(<NotificationBell />)
fireEvent.click(await screen.findByRole('button', { name: /Notifications/ }))
fireEvent.click(screen.getByRole('button', { name: 'Mark all read' }))
await waitFor(() =>
expect(fetch).toHaveBeenCalledWith('/api/notifications', expect.objectContaining({ method: 'POST', body: JSON.stringify({ all: true }) })),
)
})
})
- Step 2: Run to verify they fail
Run: npx vitest run tests/components/layout tests/components/notifications 2>&1 | grep -E "Test Files|Tests |Failed to resolve" | head -6
Expected: FAIL (modules missing, old sidebar test still present).
- Step 3: Write
components/layout/nav-items.ts
import {
AlignLeft,
CircleCheck,
ClipboardList,
LayoutDashboard,
Plus,
Settings,
Users,
type LucideIcon,
} from 'lucide-react'
export interface NavItem {
label: string
href: string
icon: LucideIcon
}
const NAV_ITEMS: Record<string, NavItem[]> = {
reporter: [
{ label: 'My Reports', href: '/reporter', icon: ClipboardList },
{ label: 'New Incident', href: '/report', icon: Plus },
],
supervisor: [
{ label: 'Overview', href: '/supervisor', icon: AlignLeft },
{ label: 'Incidents', href: '/supervisor/incidents', icon: ClipboardList },
],
hse: [
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
{ label: 'Incidents', href: '/hse/incidents', icon: ClipboardList },
{ label: 'CAPA', href: '/hse/capa', icon: CircleCheck },
{ label: 'Settings', href: '/hse/settings', icon: Settings },
],
management: [{ label: 'Dashboard', href: '/management', icon: LayoutDashboard }],
capa_owner: [{ label: 'My CAPAs', href: '/capa-owner', icon: CircleCheck }],
admin: [
{ label: 'Admin', href: '/admin', icon: Users },
{ label: 'Dashboard', href: '/hse/dashboard', icon: LayoutDashboard },
{ label: 'Incidents', href: '/hse/incidents', icon: ClipboardList },
{ label: 'CAPA', href: '/hse/capa', icon: CircleCheck },
{ label: 'Management', href: '/management', icon: AlignLeft },
{ label: 'Settings', href: '/hse/settings', icon: Settings },
],
}
const EXACT_ROOTS = ['/reporter', '/supervisor', '/management', '/capa-owner', '/admin', '/report', '/account']
export function navItemsFor(role: string): NavItem[] {
return NAV_ITEMS[role] ?? NAV_ITEMS.reporter
}
export function isActivePath(href: string, pathname: string): boolean {
return EXACT_ROOTS.includes(href) ? pathname === href : pathname.startsWith(href)
}
export function searchHrefFor(role: string): string | null {
if (role === 'hse' || role === 'admin') return '/hse/incidents'
if (role === 'supervisor') return '/supervisor/incidents'
return null
}
- Step 4: Write
components/layout/mobile-shell.tsx
'use client'
import Link from 'next/link'
import { LogOut } from 'lucide-react'
import { isActivePath, type NavItem } from './nav-items'
import { cx } from '@/components/ui/cx'
export function MobileShell({
items,
pathname,
onLogout,
}: {
items: NavItem[]
pathname: string
onLogout: () => void
}) {
const tabs = items.slice(0, 4)
return (
<nav
aria-label="Mobile"
className="md:hidden fixed bottom-0 left-0 right-0 z-40 flex bg-surface border-t border-rule pb-[env(safe-area-inset-bottom)]"
>
{tabs.map(item => {
const active = isActivePath(item.href, pathname)
const Icon = item.icon
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? 'page' : undefined}
className={cx(
'flex-1 flex flex-col items-center gap-1 pt-2 pb-1.5 text-[10.5px] font-medium',
active ? 'text-accent' : 'text-faint',
)}
>
<Icon size={22} strokeWidth={1.8} aria-hidden />
<span className="leading-none">{item.label}</span>
</Link>
)
})}
{items.length <= 4 && (
<button
type="button"
onClick={onLogout}
className="flex-1 flex flex-col items-center gap-1 pt-2 pb-1.5 text-[10.5px] font-medium text-faint cursor-pointer"
>
<LogOut size={22} strokeWidth={1.8} aria-hidden />
<span className="leading-none">Log out</span>
</button>
)}
</nav>
)
}
- Step 5: Write
components/layout/app-shell.tsx
'use client'
import { useEffect, useRef } from 'react'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { LogOut, Search, ShieldCheck, User } from 'lucide-react'
import { NotificationBell } from '@/components/notifications/bell'
import { Avatar } from '@/components/ui/avatar'
import { cx } from '@/components/ui/cx'
import { MobileShell } from './mobile-shell'
import { isActivePath, navItemsFor, searchHrefFor } from './nav-items'
const ITEM = 'flex items-center gap-2.5 h-8 px-2.5 rounded-md text-[13px] w-full text-left'
const ITEM_ACTIVE = 'bg-surface text-ink font-semibold shadow-chip'
const ITEM_IDLE = 'text-ink-3 hover:bg-rule-2'
export function AppShell({
role,
userName,
children,
}: {
role: string
userName: string
children: React.ReactNode
}) {
const pathname = usePathname()
const router = useRouter()
const items = navItemsFor(role)
const searchHref = searchHrefFor(role)
const searchRef = useRef<HTMLInputElement>(null)
const displayName = userName || 'User'
const roleLabel = role.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault()
searchRef.current?.focus()
}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [])
const logout = async () => {
await fetch('/api/auth/logout', { method: 'POST' })
router.push('/login')
router.refresh()
}
const accountActive = pathname === '/account'
return (
<div className="min-h-screen bg-ground">
<header className="hidden md:flex fixed top-0 left-0 right-0 z-40 h-14 items-center justify-between gap-4 pl-5 pr-4 bg-topbar">
<div className="flex items-center gap-2.5 w-56">
<span className="inline-grid place-items-center w-7 h-7 rounded-md bg-accent text-white">
<ShieldCheck size={16} strokeWidth={2} aria-hidden />
</span>
<span className="text-[15px] font-[650] text-white tracking-tight">IMS</span>
<span className="text-[13px] text-neutral-400">Setia HSE</span>
</div>
{searchHref ? (
<form action={searchHref} method="get" className="flex-1 max-w-[520px]">
<label className="flex items-center gap-2 h-[34px] px-2.5 rounded-[10px] bg-ink-2 shadow-[inset_0_0_0_1px_var(--color-ink-3)] text-neutral-400 text-[13px]">
<Search size={16} strokeWidth={2} aria-hidden />
<input
ref={searchRef}
name="q"
type="search"
placeholder="Search incidents"
aria-label="Search incidents"
className="flex-1 bg-transparent text-white placeholder:text-neutral-400 outline-none"
/>
<kbd className="font-mono text-[11px] text-neutral-400">⌘K</kbd>
</label>
</form>
) : (
<div className="flex-1" />
)}
<div className="flex items-center gap-2 w-56 justify-end">
<NotificationBell />
<div className="flex items-center gap-2 py-1 pl-1 pr-2.5 rounded-md bg-ink-2">
<Avatar name={displayName} />
<span className="text-[13px] text-rule-2 max-w-32 truncate">{displayName}</span>
</div>
</div>
</header>
<aside className="hidden md:flex fixed top-14 left-0 bottom-0 z-30 w-60 flex-col gap-0.5 p-3 bg-rule border-r border-rule-2">
{items.map(item => {
const active = isActivePath(item.href, pathname)
const Icon = item.icon
return (
<Link
key={item.href}
href={item.href}
aria-current={active ? 'page' : undefined}
className={cx(ITEM, active ? ITEM_ACTIVE : ITEM_IDLE)}
>
<Icon size={16} strokeWidth={2} className={active ? 'text-accent' : 'text-ink-3'} aria-hidden />
<span className="flex-1">{item.label}</span>
</Link>
)
})}
<div className="flex-1" />
<div className="flex flex-col gap-0.5 pt-2.5 border-t border-rule-2">
<div className="px-2.5 pb-1">
<p className="text-[13px] font-semibold truncate">{displayName}</p>
<p className="text-xs text-muted truncate">{roleLabel}</p>
</div>
<Link
href="/account"
aria-current={accountActive ? 'page' : undefined}
className={cx(ITEM, accountActive ? ITEM_ACTIVE : ITEM_IDLE)}
>
<User size={16} strokeWidth={2} className={accountActive ? 'text-accent' : 'text-ink-3'} aria-hidden />
Account
</Link>
<button type="button" onClick={logout} className={cx(ITEM, ITEM_IDLE, 'cursor-pointer')}>
<LogOut size={16} strokeWidth={2} className="text-ink-3" aria-hidden />
Log out
</button>
<p className="px-2.5 pt-2 text-xs text-faint">v1.2.2</p>
</div>
</aside>
<main className="md:pl-60 md:pt-14 pb-16 md:pb-0">{children}</main>
<MobileShell items={items} pathname={pathname} onLogout={logout} />
</div>
)
}
- Step 6: Rewrite
components/notifications/bell.tsx
Read the file first (the harness requires it), then replace it entirely. The fetch, polling and mark-all-read behaviour are unchanged; only the UI moves into a Drawer:
'use client'
import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import { Bell } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Drawer } from '@/components/ui/drawer'
import { cx } from '@/components/ui/cx'
type Notification = {
id: string
title: string | null
link: string | null
sent_at: string
read_at: string | null
}
const POLL_MS = 60_000
function isToday(iso: string): boolean {
return new Date(iso).toDateString() === new Date().toDateString()
}
export function NotificationBell() {
const [notifications, setNotifications] = useState<Notification[]>([])
const [unread, setUnread] = useState(0)
const [open, setOpen] = useState(false)
const [tab, setTab] = useState<'all' | 'unread'>('all')
const load = useCallback(() => {
fetch('/api/notifications')
.then(r => (r.ok ? r.json() : Promise.reject()))
.then((data: { notifications: Notification[]; unread: number }) => {
setNotifications(data.notifications)
setUnread(data.unread)
})
.catch(() => {})
}, [])
useEffect(() => {
load()
const id = setInterval(load, POLL_MS)
return () => clearInterval(id)
}, [load])
const markAllRead = () => {
fetch('/api/notifications', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ all: true }),
})
.then(() => {
setUnread(0)
setNotifications(prev => prev.map(n => ({ ...n, read_at: n.read_at ?? new Date().toISOString() })))
})
.catch(() => {})
}
const shown = tab === 'unread' ? notifications.filter(n => !n.read_at) : notifications
const groups: Array<{ label: string; items: Notification[] }> = [
{ label: 'Today', items: shown.filter(n => isToday(n.sent_at)) },
{ label: 'Earlier', items: shown.filter(n => !isToday(n.sent_at)) },
].filter(g => g.items.length > 0)
return (
<>
<button
type="button"
onClick={() => setOpen(true)}
aria-label={`Notifications${unread > 0 ? ` (${unread} unread)` : ''}`}
className="relative inline-grid place-items-center w-8 h-8 rounded-md text-neutral-300 hover:bg-ink-2 cursor-pointer"
>
<Bell size={16} strokeWidth={2} aria-hidden />
{unread > 0 && (
<span className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-accent text-white text-[10px] font-semibold grid place-items-center">
{unread > 99 ? '99+' : unread}
</span>
)}
</button>
<Drawer
open={open}
onClose={() => setOpen(false)}
title="Notifications"
actions={
unread > 0 ? (
<button
type="button"
onClick={markAllRead}
className="px-2 text-[12.5px] font-[550] text-accent hover:underline cursor-pointer"
>
Mark all read
</button>
) : undefined
}
>
<div className="flex gap-0.5 px-3 pb-2 border-b border-rule">
{(['all', 'unread'] as const).map(t => (
<button
key={t}
type="button"
onClick={() => setTab(t)}
className={cx(
'inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md text-[13px] cursor-pointer',
tab === t ? 'bg-rule-2 font-semibold' : 'font-medium text-ink-3 hover:bg-surface-2',
)}
>
{t === 'all' ? 'All' : 'Unread'}
<span className="text-xs font-medium text-faint">{t === 'all' ? notifications.length : unread}</span>
</button>
))}
</div>
{groups.length === 0 ? (
<p className="px-4 py-10 text-sm text-faint text-center">No notifications</p>
) : (
groups.map(g => (
<section key={g.label}>
<h3 className="px-4 pt-3 pb-1 text-[11.5px] font-semibold tracking-wide uppercase text-faint">{g.label}</h3>
<ul>
{g.items.map(n => {
const body = (
<>
<p className={cx('text-[13px]', n.read_at ? 'text-muted' : 'text-ink font-medium')}>
{n.title ?? 'Notification'}
</p>
<p className="text-xs text-faint mt-0.5">{new Date(n.sent_at).toLocaleString()}</p>
</>
)
return (
<li key={n.id} className={cx('border-b border-rule', !n.read_at && 'bg-accent-tint')}>
{n.link ? (
<Link href={n.link} className="block px-4 py-3" onClick={() => setOpen(false)}>
{body}
</Link>
) : (
<div className="px-4 py-3">{body}</div>
)}
</li>
)
})}
</ul>
</section>
))
)}
</Drawer>
</>
)
}
(Button is imported by Drawer only; remove the unused Button import from this file if tsc or lint flags it.)
- Step 7: Wire the layout and delete the old sidebar
Replace app/(protected)/layout.tsx body (read it first):
export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation'
import { getSession } from '@/lib/auth/get-session'
import { AppShell } from '@/components/layout/app-shell'
export default async function ProtectedLayout({
children,
}: {
children: React.ReactNode
}) {
const session = await getSession()
if (!session) redirect('/login')
return (
<AppShell role={session.role} userName={session.name}>
{children}
</AppShell>
)
}
git rm -q components/layout/sidebar.tsx tests/components/layout/sidebar.test.tsx
grep -rn "layout/sidebar" app components tests | head
Expected: the grep prints nothing.
- Step 8: Run the tests, the gate, tsc and the full suite
npx vitest run tests/components/layout tests/components/notifications 2>&1 | grep -E "Test Files|Tests |×"
npm run check:design 2>&1 | tail -3
npx tsc --noEmit 2>&1 | head -8; echo "tsc done"
npx vitest run 2>&1 | grep -E "Test Files|Tests "
Expected: all pass; design gates: clean; tsc prints nothing; the full suite shows exactly the 7 baseline failures. The gate's no-hex rule ignores shadow-[inset_0_0_0_1px_var(--color-ink-3)], which uses a variable, not a hex. If the gate flags text-neutral-300 or text-neutral-400, those are legacy ramp classes and are allowed.
- Step 9: Commit
git add components/layout components/notifications "app/(protected)/layout.tsx" tests/components/layout tests/components/notifications
git commit -m "feat(design): add AppShell, MobileShell and the notifications drawer
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
Task 5: Migrate the Incidents list (screens 01 and 10)
Files:
- Create:
lib/incidents/types.ts,lib/incidents/list-params.ts,lib/incidents/list-query.ts,components/incidents/incident-table.tsx - Modify:
components/ui/button.tsx(exportbuttonClass),app/(protected)/hse/incidents/page.tsx(full rewrite),app/(protected)/supervisor/incidents/page.tsx(full rewrite) - Delete:
components/incidents/incident-list.tsx,components/incidents/incident-filters.tsx,tests/components/incidents/incident-list.test.tsx;components/incidents/pagination.tsxonly if nothing else imports it (checked in Step 9) - Test:
tests/lib/incidents/list-params.test.ts,tests/components/incidents/incident-table.test.tsx, add a case totests/components/ui/primitives.test.tsx
Interfaces:
-
Consumes:
TableCard,Column,Sort,TableView(Task 3);StatusTag,FilterChip,Button(Task 2);AppShellsupplies the page frame. -
Produces:
Incident,SiteOption,TruckOptionfromlib/incidents/types.tsPAGE_SIZE = 25,OPEN_STATUSES,parseListParams(raw),nextSort(current, key),withParams(search, updates),ListParams,SortKey,ListViewfromlib/incidents/list-params.tsloadIncidentList(params: ListParams)returning{ incidents: Incident[]; total: number; counts: { all: number; open: number; closed: number }; sites: SiteOption[]; trucks: TruckOption[] }buttonClass(variant?: 'primary' | 'secondary' | 'icon', opts?: { block?: boolean; mobile?: boolean }): stringIncidentTable({ incidents, basePath, total, counts, params, sites, trucks })
-
Step 1: Write the failing tests for the pure helpers
tests/lib/incidents/list-params.test.ts:
import { describe, it, expect } from 'vitest'
import { parseListParams, nextSort, withParams, PAGE_SIZE, OPEN_STATUSES } from '@/lib/incidents/list-params'
describe('parseListParams', () => {
it('applies defaults', () => {
expect(parseListParams({})).toEqual({
page: 1, q: '', status: '', type: '', siteId: '', truckId: '', view: 'all', sort: 'reported_at', dir: 'desc',
})
})
it('reads every param and rejects bad values', () => {
const p = parseListParams({ page: '3', q: 'fork', status: 'closed', type: 'injury', site_id: 's1', truck_id: 't1', view: 'open', sort: 'status', dir: 'asc' })
expect(p).toMatchObject({ page: 3, q: 'fork', status: 'closed', siteId: 's1', truckId: 't1', view: 'open', sort: 'status', dir: 'asc' })
expect(parseListParams({ page: '-4' }).page).toBe(1)
expect(parseListParams({ page: 'x' }).page).toBe(1)
expect(parseListParams({ view: 'bogus' }).view).toBe('all')
expect(parseListParams({ sort: 'drop table' }).sort).toBe('reported_at')
expect(parseListParams({ dir: 'sideways' }).dir).toBe('desc')
})
it('exposes the page size and the open statuses', () => {
expect(PAGE_SIZE).toBe(25)
expect(OPEN_STATUSES).toEqual(['reported', 'triaged', 'investigating', 'capa_pending', 'verification'])
})
})
describe('nextSort', () => {
it('flips the direction on the same column', () => {
expect(nextSort({ key: 'reference_no', dir: 'asc' }, 'reference_no')).toEqual({ key: 'reference_no', dir: 'desc' })
expect(nextSort({ key: 'reference_no', dir: 'desc' }, 'reference_no')).toEqual({ key: 'reference_no', dir: 'asc' })
})
it('starts a new column ascending, but the date column newest first', () => {
expect(nextSort({ key: 'reported_at', dir: 'desc' }, 'status')).toEqual({ key: 'status', dir: 'asc' })
expect(nextSort({ key: 'status', dir: 'asc' }, 'reported_at')).toEqual({ key: 'reported_at', dir: 'desc' })
})
})
describe('withParams', () => {
it('sets and removes params and resets the page', () => {
expect(withParams('?status=closed&page=3', { q: 'fork' })).toBe('?status=closed&q=fork')
expect(withParams('?status=closed', { status: null })).toBe('')
expect(withParams('?page=2', { page: '4' })).toBe('?page=4')
})
})
- Step 2: Write the failing component tests
tests/components/incidents/incident-table.test.tsx:
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, within, act } from '@testing-library/react'
const push = vi.fn()
const replace = vi.fn()
let search = ''
vi.mock('next/navigation', () => ({
useRouter: () => ({ push, replace }),
usePathname: () => '/hse/incidents',
useSearchParams: () => new URLSearchParams(search),
}))
import { IncidentTable } from '@/components/incidents/incident-table'
import type { Incident } from '@/lib/incidents/types'
const incidents: Incident[] = [
{ id: 'a', reference_no: 'SCW1-202607-0001', incident_type: 'near_miss', status: 'reported', severity: null,
reported_at: '2026-07-10T09:00:00Z', sites: { name: 'SCW1' }, zones: { name: 'Dock A' }, trucks: null, reporter: { name: 'John' } },
{ id: 'b', reference_no: 'SCW1-202607-0002', incident_type: 'injury', status: 'capa_pending', severity: 3,
reported_at: '2026-07-11T10:00:00Z', sites: { name: 'SCW1' }, zones: { name: 'Loading Bay' }, trucks: { truck_no: 'WXY1234' }, reporter: { name: 'Jane' } },
]
const props = {
incidents,
basePath: '/hse',
total: 248,
counts: { all: 248, open: 37, closed: 211 },
params: { page: 1, q: '', status: '', type: '', siteId: '', truckId: '', view: 'all' as const, sort: 'reported_at' as const, dir: 'desc' as const },
sites: [{ id: 's1', name: 'SCW1' }],
trucks: [{ id: 't1', truck_no: 'WXY1234' }],
}
beforeEach(() => {
push.mockClear()
replace.mockClear()
search = ''
})
afterEach(() => vi.useRealTimers())
describe('IncidentTable', () => {
it('renders rows with reference, label pills and type', () => {
render(<IncidentTable {...props} />)
expect(screen.getAllByText('SCW1-202607-0001').length).toBeGreaterThan(0)
expect(screen.getAllByText('Reported')[0].className).toContain('bg-st-amber-bg')
expect(screen.getAllByText('CAPA pending')[0].className).toContain('bg-st-orange-bg')
expect(screen.getAllByText('Near Miss').length).toBeGreaterThan(0)
expect(screen.getAllByText('Injury / Medical').length).toBeGreaterThan(0)
})
it('shows saved views with counts and switches view through the URL', () => {
search = '?status=closed&page=2'
render(<IncidentTable {...props} />)
expect(screen.getByText('248')).toBeTruthy()
expect(screen.getByText('37')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /Open/ }))
expect(replace).toHaveBeenCalledWith('/hse/incidents?status=closed&view=open')
})
it('opens an incident from the row and from the eye action', () => {
render(<IncidentTable {...props} />)
const row = screen.getAllByText('SCW1-202607-0002')[0].closest('tr')!
fireEvent.click(row)
expect(push).toHaveBeenCalledWith('/hse/incidents/b')
expect(within(row).getByRole('link', { name: 'Open incident' }).getAttribute('href')).toBe('/hse/incidents/b')
})
it('sorts server-side by writing sort and dir to the URL', () => {
render(<IncidentTable {...props} />)
fireEvent.click(screen.getByRole('button', { name: /Reference/ }))
expect(replace).toHaveBeenCalledWith('/hse/incidents?sort=reference_no&dir=asc')
expect(screen.getByText('Reported').closest('th')?.getAttribute('aria-sort')).toBe('descending')
})
it('changes a filter chip through the URL and clears it', () => {
render(<IncidentTable {...props} />)
fireEvent.change(screen.getByLabelText('Status'), { target: { value: 'closed' } })
expect(replace).toHaveBeenCalledWith('/hse/incidents?status=closed')
})
it('debounces search into the q param', () => {
vi.useFakeTimers()
render(<IncidentTable {...props} />)
fireEvent.change(screen.getByRole('searchbox', { name: 'Search incidents' }), { target: { value: 'forklift' } })
expect(replace).not.toHaveBeenCalled()
act(() => { vi.advanceTimersByTime(300) })
expect(replace).toHaveBeenCalledWith('/hse/incidents?q=forklift')
})
it('shows the footer count and pages through the URL', () => {
render(<IncidentTable {...props} />)
expect(screen.getByText('Showing 1–2 of 248')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Next page' }))
expect(replace).toHaveBeenCalledWith('/hse/incidents?page=2')
})
it('renders the stacked mobile list', () => {
const { container } = render(<IncidentTable {...props} />)
expect(container.querySelector('ul.md\\:hidden')).not.toBeNull()
})
it('shows the empty state with a report action', () => {
render(<IncidentTable {...props} incidents={[]} total={0} counts={{ all: 0, open: 0, closed: 0 }} />)
expect(screen.getByText('No incidents found')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Report incident' }))
expect(push).toHaveBeenCalledWith('/report')
})
})
Add this case inside describe('Button', ...) in tests/components/ui/primitives.test.tsx and add buttonClass to its imports (import { Button, buttonClass } from '@/components/ui/button'):
it('buttonClass gives links the same look as buttons', () => {
expect(buttonClass()).toContain('bg-ink-2')
expect(buttonClass('secondary')).toContain('shadow-secondary')
expect(buttonClass('primary', { block: true })).toContain('w-full')
})
- Step 3: Run to verify they fail
Run: npx vitest run tests/lib/incidents tests/components/incidents/incident-table.test.tsx tests/components/ui/primitives.test.tsx 2>&1 | grep -E "Test Files|Tests |Failed to resolve" | head -6
Expected: FAIL (modules missing, buttonClass not exported).
- Step 4: Export
buttonClassfromcomponents/ui/button.tsx
Replace the component body (keep BASE and VARIANTS as they are) so Button is built on a shared function:
export function buttonClass(
variant: Variant = 'primary',
opts: { block?: boolean; mobile?: boolean } = {},
): string {
return cx(
BASE,
VARIANTS[variant],
opts.mobile && variant !== 'icon' && 'h-12 rounded-xl text-sm',
opts.block && 'w-full',
)
}
export function Button({ variant = 'primary', block = false, mobile = false, className, type = 'button', ...rest }: Props) {
return <button type={type} className={cx(buttonClass(variant, { block, mobile }), className)} {...rest} />
}
- Step 5: Write the types and the pure helpers
lib/incidents/types.ts:
export type Incident = {
id: string
reference_no: string | null
incident_type: string
status: string
severity: number | null
reported_at: string
sites: { name: string } | null
zones: { name: string } | null
trucks: { truck_no: string } | null
reporter: { name: string } | null
}
export interface SiteOption { id: string; name: string }
export interface TruckOption { id: string; truck_no: string }
lib/incidents/list-params.ts:
export const PAGE_SIZE = 25
export const OPEN_STATUSES = ['reported', 'triaged', 'investigating', 'capa_pending', 'verification'] as const
export type SortKey = 'reported_at' | 'reference_no' | 'status'
export type ListView = 'all' | 'open' | 'closed'
export interface ListParams {
page: number
q: string
status: string
type: string
siteId: string
truckId: string
view: ListView
sort: SortKey
dir: 'asc' | 'desc'
}
type Raw = {
page?: string; q?: string; status?: string; type?: string; site_id?: string; truck_id?: string
view?: string; sort?: string; dir?: string
}
const SORT_KEYS: SortKey[] = ['reported_at', 'reference_no', 'status']
const VIEWS: ListView[] = ['all', 'open', 'closed']
export function parseListParams(raw: Raw): ListParams {
const page = Number.parseInt(raw.page ?? '1', 10)
return {
page: Number.isFinite(page) && page > 0 ? page : 1,
q: raw.q ?? '',
status: raw.status ?? '',
type: raw.type ?? '',
siteId: raw.site_id ?? '',
truckId: raw.truck_id ?? '',
view: VIEWS.includes(raw.view as ListView) ? (raw.view as ListView) : 'all',
sort: SORT_KEYS.includes(raw.sort as SortKey) ? (raw.sort as SortKey) : 'reported_at',
dir: raw.dir === 'asc' ? 'asc' : 'desc',
}
}
export function nextSort(
current: { key: SortKey; dir: 'asc' | 'desc' },
key: SortKey,
): { key: SortKey; dir: 'asc' | 'desc' } {
if (current.key === key) return { key, dir: current.dir === 'asc' ? 'desc' : 'asc' }
return { key, dir: key === 'reported_at' ? 'desc' : 'asc' }
}
export function withParams(search: string, updates: Record<string, string | null>): string {
const p = new URLSearchParams(search)
for (const [k, v] of Object.entries(updates)) {
if (v) p.set(k, v)
else p.delete(k)
}
if (!('page' in updates)) p.delete('page')
const s = p.toString()
return s ? `?${s}` : ''
}
- Step 6: Write the loader
lib/incidents/list-query.ts
import { and, asc, desc, eq, ilike, inArray, or, sql, aliasedTable } from 'drizzle-orm'
import { asAdmin } from '@/lib/db/with-user'
import { incidents, sites, trucks, users, zones } from '@/lib/db/schema'
import { OPEN_STATUSES, PAGE_SIZE, type ListParams } from './list-params'
import type { Incident, SiteOption, TruckOption } from './types'
export interface IncidentListData {
incidents: Incident[]
total: number
counts: { all: number; open: number; closed: number }
sites: SiteOption[]
trucks: TruckOption[]
}
export async function loadIncidentList(p: ListParams): Promise<IncidentListData> {
const reporter = aliasedTable(users, 'reporter')
const base = []
if (p.q) base.push(or(ilike(incidents.referenceNo, `%${p.q}%`), ilike(incidents.description, `%${p.q}%`)))
if (p.type) base.push(eq(incidents.incidentType, p.type as never))
if (p.siteId) base.push(eq(incidents.siteId, p.siteId))
if (p.truckId) base.push(eq(incidents.truckId, p.truckId))
const scoped = [...base]
if (p.status) scoped.push(eq(incidents.status, p.status as never))
if (p.view === 'open') scoped.push(inArray(incidents.status, [...OPEN_STATUSES] as never))
if (p.view === 'closed') scoped.push(eq(incidents.status, 'closed' as never))
const where = scoped.length ? and(...scoped) : undefined
const baseWhere = base.length ? and(...base) : undefined
const sortColumn = { reported_at: incidents.reportedAt, reference_no: incidents.referenceNo, status: incidents.status }[p.sort]
const orderBy = p.dir === 'asc' ? asc(sortColumn) : desc(sortColumn)
const [[countRow], rows, statusCounts, siteRows, truckRows] = await Promise.all([
asAdmin(db => db.select({ count: sql<number>`count(*)` }).from(incidents).where(where)),
asAdmin(db =>
db.select({
id: incidents.id,
referenceNo: incidents.referenceNo,
incidentType: incidents.incidentType,
status: incidents.status,
severity: incidents.severity,
reportedAt: incidents.reportedAt,
siteName: sites.name,
zoneName: zones.name,
reporterName: reporter.name,
truckNo: trucks.truckNo,
})
.from(incidents)
.leftJoin(sites, eq(incidents.siteId, sites.id))
.leftJoin(zones, eq(incidents.zoneId, zones.id))
.leftJoin(reporter, eq(incidents.reportedBy, reporter.id))
.leftJoin(trucks, eq(incidents.truckId, trucks.id))
.where(where)
.orderBy(orderBy)
.limit(PAGE_SIZE)
.offset((p.page - 1) * PAGE_SIZE)
),
asAdmin(db =>
db.select({ status: incidents.status, count: sql<number>`count(*)` })
.from(incidents)
.where(baseWhere)
.groupBy(incidents.status)
),
asAdmin(db => db.select({ id: sites.id, name: sites.name }).from(sites).orderBy(asc(sites.name))),
asAdmin(db =>
db.select({ id: trucks.id, truckNo: trucks.truckNo })
.from(trucks)
.where(eq(trucks.active, true))
.orderBy(asc(trucks.truckNo))
),
])
const byStatus = new Map(statusCounts.map(r => [r.status as string, Number(r.count)]))
const all = [...byStatus.values()].reduce((a, b) => a + b, 0)
const open = OPEN_STATUSES.reduce((sum, s) => sum + (byStatus.get(s) ?? 0), 0)
return {
incidents: rows.map(r => ({
id: r.id,
reference_no: r.referenceNo,
incident_type: r.incidentType,
status: r.status,
severity: r.severity,
reported_at: r.reportedAt.toISOString(),
sites: r.siteName ? { name: r.siteName } : null,
zones: r.zoneName ? { name: r.zoneName } : null,
trucks: r.truckNo ? { truck_no: r.truckNo } : null,
reporter: r.reporterName ? { name: r.reporterName } : null,
})),
total: Number(countRow?.count ?? 0),
counts: { all, open, closed: byStatus.get('closed') ?? 0 },
sites: siteRows.map(s => ({ id: s.id, name: s.name })),
trucks: truckRows.map(t => ({ id: t.id, truck_no: t.truckNo })),
}
}
- Step 7: Write
components/incidents/incident-table.tsx
'use client'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { ChevronRight, Eye, Search } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { FilterChip } from '@/components/ui/filter-chip'
import { StatusTag } from '@/components/ui/status-tag'
import { TableCard, type Column } from '@/components/ui/table-card'
import { PAGE_SIZE, nextSort, withParams, type ListParams, type SortKey } from '@/lib/incidents/list-params'
import type { Incident, SiteOption, TruckOption } from '@/lib/incidents/types'
const TYPE_LABELS: Record<string, string> = {
injury: 'Injury / Medical',
near_miss: 'Near Miss',
hazard: 'Hazard',
asset_damage: 'Asset Damage',
environmental: 'Environmental',
security: 'Security',
fire: 'Fire / Emergency',
transport: 'Transport / Vehicle',
}
const STATUS_OPTIONS = [
{ value: 'reported', label: 'Reported' },
{ value: 'triaged', label: 'Triaged' },
{ value: 'investigating', label: 'Investigating' },
{ value: 'capa_pending', label: 'CAPA pending' },
{ value: 'verification', label: 'Verification' },
{ value: 'closed', label: 'Closed' },
]
const TYPE_OPTIONS = Object.entries(TYPE_LABELS).map(([value, label]) => ({ value, label }))
interface Props {
incidents: Incident[]
basePath: string
total: number
counts: { all: number; open: number; closed: number }
params: ListParams
sites: SiteOption[]
trucks: TruckOption[]
}
const fmtDate = (iso: string) => new Date(iso).toLocaleDateString('en-MY')
export function IncidentTable({ incidents, basePath, total, counts, params, sites, trucks }: Props) {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const search = searchParams.toString() ? `?${searchParams.toString()}` : ''
const [q, setQ] = useState(params.q)
const update = (updates: Record<string, string | null>) =>
router.replace(`${pathname}${withParams(search, updates)}`)
useEffect(() => {
if (q === params.q) return
const timer = setTimeout(() => update({ q: q || null }), 300)
return () => clearTimeout(timer)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [q])
const columns: Column<Incident>[] = [
{
key: 'reference',
header: 'Reference',
sortKey: 'reference_no',
cell: r => <span className="font-mono text-[12.5px] text-accent">{r.reference_no ?? '—'}</span>,
},
{ key: 'status', header: 'Status', sortKey: 'status', cell: r => <StatusTag status={r.status} /> },
{ key: 'type', header: 'Type', cell: r => TYPE_LABELS[r.incident_type] ?? r.incident_type },
{
key: 'location',
header: 'Location',
cell: r => [r.zones?.name, r.sites?.name, r.trucks?.truck_no].filter(Boolean).join(' · ') || '—',
},
{ key: 'severity', header: 'Severity', cell: r => (r.severity ? `Sev ${r.severity}` : '—') },
{ key: 'reported', header: 'Reported', sortKey: 'reported_at', cell: r => fmtDate(r.reported_at) },
]
const clearable = Boolean(params.q || params.status || params.type || params.siteId || params.truckId)
const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE))
const from = total === 0 ? 0 : (params.page - 1) * PAGE_SIZE + 1
const to = Math.min(total, from + incidents.length - 1)
const toolbar = (
<>
<label className="flex items-center gap-2 h-8 px-2.5 rounded-md bg-surface shadow-input text-[13px] min-w-[260px]">
<Search size={16} strokeWidth={2} className="text-muted" aria-hidden />
<input
type="search"
aria-label="Search incidents"
placeholder="Search reference or description"
value={q}
onChange={e => setQ(e.target.value)}
className="flex-1 bg-transparent outline-none placeholder:text-faint"
/>
</label>
<FilterChip label="Status" value={params.status} options={STATUS_OPTIONS} onChange={v => update({ status: v || null })} />
<FilterChip label="Type" value={params.type} options={TYPE_OPTIONS} onChange={v => update({ type: v || null })} />
{sites.length > 0 && (
<FilterChip
label="Site"
value={params.siteId}
options={sites.map(s => ({ value: s.id, label: s.name }))}
onChange={v => update({ site_id: v || null })}
/>
)}
{trucks.length > 0 && (
<FilterChip
label="Truck"
value={params.truckId}
options={trucks.map(t => ({ value: t.id, label: t.truck_no }))}
onChange={v => update({ truck_id: v || null })}
/>
)}
{clearable && (
<button
type="button"
onClick={() => {
setQ('')
router.replace(pathname)
}}
className="text-[12.5px] text-muted hover:text-ink cursor-pointer"
>
Clear filters
</button>
)}
</>
)
return (
<TableCard
columns={columns}
rows={incidents}
rowKey={r => r.id}
onRowOpen={r => router.push(`${basePath}/incidents/${r.id}`)}
rowActions={r => (
<Link
href={`${basePath}/incidents/${r.id}`}
aria-label="Open incident"
className="inline-grid place-items-center w-7 h-7 rounded-md text-ink-3 hover:bg-rule"
>
<Eye size={16} strokeWidth={2} aria-hidden />
</Link>
)}
views={{
items: [
{ key: 'all', label: 'All', count: counts.all },
{ key: 'open', label: 'Open', count: counts.open },
{ key: 'closed', label: 'Closed', count: counts.closed },
],
active: params.view,
onChange: key => update({ view: key === 'all' ? null : key }),
}}
toolbar={toolbar}
sort={{ key: params.sort, dir: params.dir }}
onSortChange={key => {
const next = nextSort({ key: params.sort, dir: params.dir }, key as SortKey)
update({ sort: next.key, dir: next.dir })
}}
footer={{ from, to, total, page: params.page, pageCount, onPage: p => update({ page: String(p) }) }}
empty={{
title: 'No incidents found',
action: <Button onClick={() => router.push('/report')}>Report incident</Button>,
}}
mobileRow={r => (
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1 space-y-1">
<div className="flex items-center gap-2">
<span className="font-mono text-[12.5px] text-accent">{r.reference_no ?? '—'}</span>
<StatusTag status={r.status} />
</div>
<p className="text-[13px] text-ink-3">
{[TYPE_LABELS[r.incident_type] ?? r.incident_type, r.zones?.name].filter(Boolean).join(' · ')}
</p>
<p className="text-xs text-faint">{fmtDate(r.reported_at)}</p>
</div>
<ChevronRight size={16} strokeWidth={2} className="mt-1 text-faint" aria-hidden />
</div>
)}
/>
)
}
Note on reported header: the date column's aria-sort must read descending by default (params.sort === 'reported_at', dir === 'desc'), which the sort test asserts.
- Step 8: Rewrite the two pages
app/(protected)/hse/incidents/page.tsx:
export const dynamic = 'force-dynamic'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { getSession } from '@/lib/auth/get-session'
import { buttonClass } from '@/components/ui/button'
import { IncidentTable } from '@/components/incidents/incident-table'
import { loadIncidentList } from '@/lib/incidents/list-query'
import { parseListParams } from '@/lib/incidents/list-params'
export default async function HseInboxPage({
searchParams,
}: {
searchParams: Promise<Record<string, string | undefined>>
}) {
const session = await getSession()
if (!session) redirect('/login')
const params = parseListParams(await searchParams)
const data = await loadIncidentList(params)
return (
<div className="px-4 py-5 md:px-8 md:py-6 space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-[22px] md:text-xl font-[650]">Incidents</h1>
<Link href="/report" className={buttonClass('primary')}>Report incident</Link>
</div>
<IncidentTable
incidents={data.incidents}
basePath="/hse"
total={data.total}
counts={data.counts}
params={params}
sites={data.sites}
trucks={data.trucks}
/>
</div>
)
}
app/(protected)/supervisor/incidents/page.tsx: identical, with SupervisorInboxPage as the function name and basePath="/supervisor".
- Step 9: Delete the replaced files
git rm -q components/incidents/incident-list.tsx components/incidents/incident-filters.tsx tests/components/incidents/incident-list.test.tsx
grep -rn "incident-list'\|incident-filters'\|components/incidents/pagination" app components tests | head
If the grep shows no import of components/incidents/pagination, also run git rm -q components/incidents/pagination.tsx. If other pages still import it, leave it. The grep must show nothing for incident-list or incident-filters.
- Step 10: Run the tests, the gate, tsc, the full suite and a clean build
npx vitest run tests/lib/incidents tests/components/incidents tests/components/ui 2>&1 | grep -E "Test Files|Tests |×"
npm run check:design 2>&1 | tail -3
npx tsc --noEmit 2>&1 | head -8; echo "tsc done"
npx vitest run 2>&1 | grep -E "Test Files|Tests "
rm -rf .next && npm run build > /tmp/ims-build.log 2>&1; echo "build exit=$?"
Expected: all new tests pass; design gates: clean; tsc prints nothing; the full suite shows exactly the 7 baseline failures; build exit 0. The data loader (loadIncidentList) has no unit test because the local database is empty; its pure inputs are covered by list-params.test.ts, and the query must be exercised on a seeded database before release (see Task 6).
- Step 11: Commit
git add lib/incidents components/incidents components/ui/button.tsx "app/(protected)/hse/incidents/page.tsx" "app/(protected)/supervisor/incidents/page.tsx" tests/lib/incidents tests/components/incidents tests/components/ui/primitives.test.tsx
git commit -m "feat(design): migrate the Incidents list to TableCard with server-side views, sort, filters and paging
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
Task 6: Fix accent-as-danger leftovers, update docs and memory, verify
Files:
- Modify:
components/auth/login-form.tsx, the accent-as-danger sites listed in Step 2,design-system/design.md,CLAUDE.md - Modify (outside the repo): memory
/Users/yapweeihan/.claude/projects/-Users-yapweeihan-Projects-Setia/memory/ims-design-system.md
Interfaces:
-
Consumes: everything above.
-
Produces: a verified branch, ready for the owner's go-ahead to deploy.
-
Step 1: Fix the login error banner
The Modernist build used the red accent for error banners. With a teal accent they would read as success. In components/auth/login-form.tsx change the error paragraph class from bg-accent-100 border border-accent text-accent-800 text-sm px-3 py-2 to:
<p className="bg-st-red-bg text-st-red-fg text-[13px] px-3 py-2 rounded-md">
Also change the title block's pb-3 border-b-2 border-divider (already border-b after Task 1) to pb-3 border-b border-rule and the title text-3xl font-extrabold to text-[22px] font-[650]. In app/(auth)/login/page.tsx change the card to bg-surface rounded-xl shadow-card p-8 w-full max-w-sm (drop the border classes).
- Step 2: Review the other accent-as-danger sites
Run:
grep -rnE "bg-accent-100[^\"'\`]*border-accent|border-accent[^\"'\`]*bg-accent-100|bg-accent-100[^\"'\`]*text-accent-[78]00" app components --include='*.tsx' | cut -c1-140
Known sites: app/(protected)/hse/dashboard/page.tsx (~190), components/dashboard/risk-flags-panel.tsx (16, 54), components/incidents/offline-sync.tsx (~59), components/incidents/triage-form.tsx (~160, ~174), components/incidents/investigation-form.tsx (~139), components/incidents/report-form.tsx (~217, ~311). Read each site and apply this table:
| What the element says | Replace the tint classes with |
|---|---|
| Error, overdue, failure | bg-st-red-bg text-st-red-fg |
| Warning, needs attention, offline | bg-st-amber-bg text-st-amber-fg |
| Information, AI suggestion, neutral hint | bg-accent-tint text-ink (no accent border) |
Drop any border-accent* class on those elements when you apply the pair. In risk-flags-panel.tsx map high to the red pair, medium to the amber pair and low to bg-st-grey-bg text-st-grey-fg. Keep every element's layout classes unchanged.
- Step 3: Update
design-system/design.md
In section 4.2, replace the sentence "Tailwind: st-<name>-bg / st-<name>-fg pairs." with: "Tailwind: one pair per hue, bg-st-<hue>-bg / text-st-<hue>-fg, hue in amber blue violet orange indigo green grey red; StatusTag maps each status to a hue (reported amber, triaged blue, investigating violet, capa_pending orange, verification and pending_verification indigo, closed and verified green, open and low grey, in_progress blue, overdue and reopened red, high orange, med amber)." Under section 8 add: "Slice 1 (gate, tokens, primitives, TableCard, shells, Incidents list) is implemented; the remaining screens follow in later plans."
- Step 4: Update
CLAUDE.md
Read it first. In the "Design system" section replace the last bullet (the one starting "Run npm run check:design") with:
- Run `npm run check:design` before committing UI changes; it must print `design gates: clean`. The gate flags 2px borders, `Archivo`, hard-coded hex, `bg-white`, `shadow-xl/2xl`, centered button labels and off-palette hues; rounded corners are allowed. Extend `scripts/check-design-gates.mjs` when design.md adds a rule.
Do not touch any other section.
- Step 5: Update the memory file
Replace /Users/yapweeihan/.claude/projects/-Users-yapweeihan-Projects-Setia/memory/ims-design-system.md with:
---
name: ims-design-system
description: IMS UI follows the IMS Admin refresh (design-system/design.md): Geist, teal accent, 12px cards, TableCard; gate via npm run check:design
metadata:
type: reference
---
IMS UI is moving from the retired Modernist system to the IMS Admin refresh (owner decision 2026-10-01).
- Source of truth: `design-system/design.md` in the IMS repo, derived from `IMS Admin Spec.dc.html` (patterns) and `IMS Admin.dc.html` (25 artboards). The Modernist files under `design-system/_ds/` are retired.
- Look: Geist, ink `#1f1f1f` on `#f1f1f1`, white cards radius 12 with `shadow-card`, one teal accent `#0f766e`, 1px rules, dark `#303030` primary button.
- Components: `components/ui/` (`Button`, `StatusTag`, `PriorityTag`, `Checkbox`, `FilterChip`, `Segmented`, `Avatar`, `Drawer`, `Field`, `Card`, `Modal`, `TableCard`); frames `AppShell` and `MobileShell`. Every list is a `TableCard`.
- Status colours only via `StatusTag` / `PriorityTag` (hues amber, blue, violet, orange, indigo, green, grey, red; dark text on light tint).
- Legacy class names (`gray-*`, `blue-*`, `red-*`, `accent-100..900`, `border-divider`) stay re-valued until each page is migrated; migrate screens in design.md section 5 order.
- Guardrail: `npm run check:design` must be clean. Never write `*/` in a CSS comment in `globals.css`.
- Slice 1 done: gate, tokens, primitives, TableCard, shells, Incidents list. Remaining screens (incident detail and forms, dashboard, CAPA, admin, settings, reporter, mobile) are later slices.
**Why:** the owner asked to restructure the UI to follow the two IMS Admin HTML files and recorded that in CLAUDE.md; the earlier Modernist restyle (live on production until this ships) is superseded.
**How to apply:** any new or changed UI. Reach for `components/ui/*` first; if a pattern is missing, check design.md, then add it there with tokens rather than inline styling.
- Step 6: Full verification
npm run check:design 2>&1 | tail -2
npx tsc --noEmit 2>&1 | head -5; echo "tsc done"
npx vitest run 2>&1 | grep -E "Test Files|Tests "
rm -rf .next && npm run build > /tmp/ims-build.log 2>&1; echo "build exit=$?"
f=$(ls .next/static/chunks/*.css | head -1)
echo "accent: $(grep -ho '\-\-color-accent:[^;}]*' $f | head -1) | st-red-bg: $(grep -ho '\-\-color-st-red-bg:[^;}]*' $f | head -1) | md: $(grep -ho '\-\-radius-md:[^;}]*' $f | head -1)"
grep -rn "Archivo\|ec3013" app components lib scripts --include='*.ts' --include='*.tsx' --include='*.mjs' --include='*.css' | head -3; echo "(nothing above = no Modernist leftovers)"
Expected: gate clean, tsc clean, the full suite shows exactly the 7 baseline failures, build exit 0, the CSS line shows #0f766e, #fee3e0, 8px, and the final grep prints nothing.
- Step 7: Browser check of the login page
The local database is empty, so only unauthenticated pages can be checked here; the Incidents list needs a seeded database.
npm run dev > /tmp/ims-dev.log 2>&1 &
sleep 8; curl -s -o /dev/null -w "login http %{http_code}\n" http://localhost:3000/login
Open http://localhost:3000/login and confirm with a script that the page shows Geist, a #f1f1f1 ground, a white 12px card, a dark #303030 48px-or-32px primary button, no horizontal overflow at 360px (use a same-origin iframe of width 360), and a visible 2px teal focus ring when tabbing to the email field. Then stop the server and undo the file next dev rewrites:
kill $(lsof -ti :3000 -sTCP:LISTEN) 2>/dev/null; git checkout -- AGENTS.md 2>/dev/null; git status --short | grep -v '^??'
Expected: the working tree shows only this task's changes plus the pre-existing D design-system/ims-admin/MASTER.md.
- Step 8: Commit
git add components/auth/login-form.tsx "app/(auth)/login/page.tsx" app components design-system/design.md CLAUDE.md
git commit -m "feat(design): fix accent-as-danger banners, document slice 1 and update design notes
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>"
- Step 9: Report, do not deploy
Report to the owner: what shipped, the test and gate results, that the Incidents list query (loadIncidentList) and the authenticated pages are unverified without a seeded database, and ask for the go-ahead to build, deploy per CLAUDE.md and check production. Do not deploy and do not push main without that go-ahead.
Self-Review Notes
Spec coverage (design.md): §2 tokens and §2.2 type (Task 1), §2.3 radius, shadows, focus and icons (Tasks 1 and 2), §3 desktop shell (Task 4), §3 mobile shell and tab bar (Task 4), §4.1 Button, §4.2 status and priority, §4.3 FilterChip, §4.4 Segmented, §4.5 Checkbox, §4.6 Field, §4.7 Avatar, §4.8 Card, §4.10 Drawer (Task 2), §4.9 TableCard including sort, selection, bulk bar, footer, empty and mobile list (Task 3), screens 01, 01b and 10 (Tasks 4 and 5), §8 gate-first order (Task 1), §9 changes from Modernist (Tasks 1 to 6).
Deliberate gaps, to carry into later slices:
- The saved-view "+" button and "Save current filters as view" are not built; views are the fixed All, Open and Closed.
- Selection and the bulk bar exist in
TableCard(tested) but the Incidents list does not enable them, because no bulk action (Assign, Export of a selection) exists in the backend. - The top-bar search targets the incident list only, and is hidden for roles without one.
- Screens 02 to 07, 09 and 11 to 16 are untouched and keep rendering through the re-valued legacy class names; mobile page padding and 48px controls apply when each screen is migrated.
loadIncidentListhas no automated test because the local database is empty; it must be exercised on a seeded database before release.
Type consistency: Column, Sort, TableView, TableCardProps (Task 3) match their use in IncidentTable (Task 5); Incident, SiteOption, TruckOption move to lib/incidents/types.ts and both pages and the loader import them from there; statusHue, StatusTag, PriorityTag keep the prop names used by the existing callers (status, priority, children); NotificationBell keeps its no-prop signature.