feat(web): set up Storybook (preview + MSW + stories for real components)

This commit is contained in:
2026-06-05 16:55:40 +02:00
parent 4e1138f8ce
commit b2d026f217
17 changed files with 2400 additions and 30 deletions
+3
View File
@@ -22,3 +22,6 @@ dist-ssr
*.njsproj
*.sln
*.sw?
*storybook.log
storybook-static
+18
View File
@@ -0,0 +1,18 @@
import type { StorybookConfig } from '@storybook/react-vite';
const config: StorybookConfig = {
"stories": [
"../src/**/*.mdx",
"../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"
],
"addons": [
"@chromatic-com/storybook",
"@storybook/addon-vitest",
"@storybook/addon-a11y",
"@storybook/addon-docs",
"@storybook/addon-mcp"
],
"framework": "@storybook/react-vite",
"staticDirs": ["../public"]
};
export default config;
+57
View File
@@ -0,0 +1,57 @@
import type { Preview } from '@storybook/react-vite'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { initialize, mswLoader } from 'msw-storybook-addon'
import { MemoryRouter } from 'react-router-dom'
import '../src/index.css'
import '../src/i18n'
import { LOCALE_KEY } from '../src/i18n'
import { ConfigProvider } from '../src/config/config-provider'
import { handlers } from '../src/test/handlers'
initialize({ onUnhandledRequest: 'bypass' })
const preview: Preview = {
parameters: {
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
a11y: {
// 'todo' - show a11y violations in the test UI only
// 'error' - fail CI on a11y violations
// 'off' - skip a11y checks entirely
test: 'todo'
},
msw: { handlers },
},
loaders: [mswLoader],
beforeEach() {
// Pin the UI language so text-based assertions are deterministic; also
// stops ConfigProvider from switching to the instance default at runtime.
localStorage.setItem(LOCALE_KEY, 'en')
},
decorators: [
(Story) => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
return (
<QueryClientProvider client={queryClient}>
<ConfigProvider>
<MemoryRouter>
<Story />
</MemoryRouter>
</ConfigProvider>
</QueryClientProvider>
)
},
],
};
export default preview;
+12 -12
View File
@@ -1,19 +1,19 @@
// For more info, see https://github.com/storybookjs/eslint-plugin-storybook#configuration-flat-config-format
import storybook from "eslint-plugin-storybook";
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
export default tseslint.config(
{ ignores: ["dist", "src/components/ui", "src/api/schema.d.ts"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
languageOptions: { ecmaVersion: 2022, globals: globals.browser },
plugins: { "react-hooks": reactHooks, "react-refresh": reactRefresh },
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
},
export default tseslint.config({ ignores: ["dist", "src/components/ui", "src/api/schema.d.ts", "public/mockServiceWorker.js"] }, {
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
languageOptions: { ecmaVersion: 2022, globals: globals.browser },
plugins: { "react-hooks": reactHooks, "react-refresh": reactRefresh },
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
},
);
}, storybook.configs["flat/recommended"]);
+21 -2
View File
@@ -13,7 +13,9 @@
"typecheck": "tsc -b --noEmit",
"lint": "eslint .",
"gen:api": "openapi-typescript http://localhost:8080/api-docs/openapi.json -o src/api/schema.d.ts",
"check:size": "node scripts/check-bundle-size.mjs"
"check:size": "node scripts/check-bundle-size.mjs",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
},
"dependencies": {
"@base-ui/react": "^1.5.0",
@@ -33,7 +35,13 @@
"tw-animate-css": "^1.4.0"
},
"devDependencies": {
"@chromatic-com/storybook": "^5.2.1",
"@eslint/js": "^10.0.1",
"@storybook/addon-a11y": "^10.4.2",
"@storybook/addon-docs": "^10.4.2",
"@storybook/addon-mcp": "^0.6.0",
"@storybook/addon-vitest": "^10.4.2",
"@storybook/react-vite": "^10.4.2",
"@tailwindcss/vite": "^4.3.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
@@ -42,18 +50,29 @@
"@types/react": "^19.1.5",
"@types/react-dom": "^19.1.3",
"@vitejs/plugin-react": "^4.5.2",
"@vitest/browser": "3.2.6",
"@vitest/coverage-v8": "3.2.6",
"eslint": "^10.4.1",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"eslint-plugin-storybook": "^10.4.2",
"globals": "^17.6.0",
"jsdom": "^26.1.0",
"msw": "^2.14.6",
"msw-storybook-addon": "^2.0.7",
"openapi-typescript": "^7.13.0",
"playwright": "^1.60.0",
"shadcn": "^4.10.0",
"storybook": "^10.4.2",
"tailwindcss": "^4.3.0",
"typescript": "~5.8.3",
"typescript-eslint": "^8.60.1",
"vite": "^6.3.5",
"vitest": "^3.2.2"
},
"msw": {
"workerDirectory": [
"public"
]
}
}
}
+1594 -2
View File
File diff suppressed because it is too large Load Diff
+349
View File
@@ -0,0 +1,349 @@
/* eslint-disable */
/* tslint:disable */
/**
* Mock Service Worker.
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
*/
const PACKAGE_VERSION = '2.14.6'
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
addEventListener('install', function () {
self.skipWaiting()
})
addEventListener('activate', function (event) {
event.waitUntil(self.clients.claim())
})
addEventListener('message', async function (event) {
const clientId = Reflect.get(event.source || {}, 'id')
if (!clientId || !self.clients) {
return
}
const client = await self.clients.get(clientId)
if (!client) {
return
}
const allClients = await self.clients.matchAll({
type: 'window',
})
switch (event.data) {
case 'KEEPALIVE_REQUEST': {
sendToClient(client, {
type: 'KEEPALIVE_RESPONSE',
})
break
}
case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
type: 'INTEGRITY_CHECK_RESPONSE',
payload: {
packageVersion: PACKAGE_VERSION,
checksum: INTEGRITY_CHECKSUM,
},
})
break
}
case 'MOCK_ACTIVATE': {
activeClientIds.add(clientId)
sendToClient(client, {
type: 'MOCKING_ENABLED',
payload: {
client: {
id: client.id,
frameType: client.frameType,
},
},
})
break
}
case 'CLIENT_CLOSED': {
activeClientIds.delete(clientId)
const remainingClients = allClients.filter((client) => {
return client.id !== clientId
})
// Unregister itself when there are no more clients
if (remainingClients.length === 0) {
self.registration.unregister()
}
break
}
}
})
addEventListener('fetch', function (event) {
const requestInterceptedAt = Date.now()
// Bypass navigation requests.
if (event.request.mode === 'navigate') {
return
}
// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
if (
event.request.cache === 'only-if-cached' &&
event.request.mode !== 'same-origin'
) {
return
}
// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
// after it's been terminated (still remains active until the next reload).
if (activeClientIds.size === 0) {
return
}
const requestId = crypto.randomUUID()
event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
})
/**
* @param {FetchEvent} event
* @param {string} requestId
* @param {number} requestInterceptedAt
*/
async function handleRequest(event, requestId, requestInterceptedAt) {
const client = await resolveMainClient(event)
const requestCloneForEvents = event.request.clone()
const response = await getResponse(
event,
client,
requestId,
requestInterceptedAt,
)
// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
const serializedRequest = await serializeRequest(requestCloneForEvents)
// Clone the response so both the client and the library could consume it.
const responseClone = response.clone()
sendToClient(
client,
{
type: 'RESPONSE',
payload: {
isMockedResponse: IS_MOCKED_RESPONSE in response,
request: {
id: requestId,
...serializedRequest,
},
response: {
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
headers: Object.fromEntries(responseClone.headers.entries()),
body: responseClone.body,
},
},
},
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
)
}
return response
}
/**
* Resolve the main client for the given event.
* Client that issues a request doesn't necessarily equal the client
* that registered the worker. It's with the latter the worker should
* communicate with during the response resolving phase.
* @param {FetchEvent} event
* @returns {Promise<Client | undefined>}
*/
async function resolveMainClient(event) {
const client = await self.clients.get(event.clientId)
if (activeClientIds.has(event.clientId)) {
return client
}
if (client?.frameType === 'top-level') {
return client
}
const allClients = await self.clients.matchAll({
type: 'window',
})
return allClients
.filter((client) => {
// Get only those clients that are currently visible.
return client.visibilityState === 'visible'
})
.find((client) => {
// Find the client ID that's recorded in the
// set of clients that have registered the worker.
return activeClientIds.has(client.id)
})
}
/**
* @param {FetchEvent} event
* @param {Client | undefined} client
* @param {string} requestId
* @param {number} requestInterceptedAt
* @returns {Promise<Response>}
*/
async function getResponse(event, client, requestId, requestInterceptedAt) {
// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
const requestClone = event.request.clone()
function passthrough() {
// Cast the request headers to a new Headers instance
// so the headers can be manipulated with.
const headers = new Headers(requestClone.headers)
// Remove the "accept" header value that marked this request as passthrough.
// This prevents request alteration and also keeps it compliant with the
// user-defined CORS policies.
const acceptHeader = headers.get('accept')
if (acceptHeader) {
const values = acceptHeader.split(',').map((value) => value.trim())
const filteredValues = values.filter(
(value) => value !== 'msw/passthrough',
)
if (filteredValues.length > 0) {
headers.set('accept', filteredValues.join(', '))
} else {
headers.delete('accept')
}
}
return fetch(requestClone, { headers })
}
// Bypass mocking when the client is not active.
if (!client) {
return passthrough()
}
// Bypass initial page load requests (i.e. static assets).
// The absence of the immediate/parent client in the map of the active clients
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
// and is not ready to handle requests.
if (!activeClientIds.has(client.id)) {
return passthrough()
}
// Notify the client that a request has been intercepted.
const serializedRequest = await serializeRequest(event.request)
const clientMessage = await sendToClient(
client,
{
type: 'REQUEST',
payload: {
id: requestId,
interceptedAt: requestInterceptedAt,
...serializedRequest,
},
},
[serializedRequest.body],
)
switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
return respondWithMock(clientMessage.data)
}
case 'PASSTHROUGH': {
return passthrough()
}
}
return passthrough()
}
/**
* @param {Client} client
* @param {any} message
* @param {Array<Transferable>} transferrables
* @returns {Promise<any>}
*/
function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()
channel.port1.onmessage = (event) => {
if (event.data && event.data.error) {
return reject(event.data.error)
}
resolve(event.data)
}
client.postMessage(message, [
channel.port2,
...transferrables.filter(Boolean),
])
})
}
/**
* @param {Response} response
* @returns {Response}
*/
function respondWithMock(response) {
// Setting response status code to 0 is a no-op.
// However, when responding with a "Response.error()", the produced Response
// instance will have status code set to 0. Since it's not possible to create
// a Response instance with status code 0, handle that use-case separately.
if (response.status === 0) {
return Response.error()
}
const mockedResponse = new Response(response.body, response)
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
value: true,
enumerable: true,
})
return mockedResponse
}
/**
* @param {Request} request
*/
async function serializeRequest(request) {
return {
url: request.url,
mode: request.mode,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
cache: request.cache,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body: await request.arrayBuffer(),
keepalive: request.keepalive,
}
}
@@ -0,0 +1,46 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { useState } from 'react'
import { expect } from 'storybook/test'
import type { components } from '../api/schema'
import { LabelEditor } from './label-editor'
type LabelInput = components['schemas']['LabelInput']
// LabelEditor is controlled — drive it from local state so typing is reflected.
function ControlledLabelEditor({ value: initial }: { value: LabelInput[] }) {
const [value, setValue] = useState<LabelInput[]>(initial)
return <LabelEditor value={value} onChange={setValue} />
}
const meta = {
component: LabelEditor,
render: (args) => <ControlledLabelEditor value={args.value} />,
args: { value: [], onChange: () => {} },
tags: ['ai-generated'],
} satisfies Meta<typeof LabelEditor>
export default meta
type Story = StoryObj<typeof meta>
export const Empty: Story = {
play: async ({ canvas }) => {
await expect(canvas.getByLabelText('Label')).toHaveValue('')
},
}
export const Prefilled: Story = {
args: { value: [{ lang: 'en', label: 'Bronze' }] },
play: async ({ canvas }) => {
await expect(canvas.getByLabelText('Label')).toHaveValue('Bronze')
},
}
export const Editing: Story = {
play: async ({ canvas, userEvent }) => {
const input = canvas.getByLabelText('Label')
await userEvent.type(input, 'Ceramic')
await expect(input).toHaveValue('Ceramic')
},
}
+32
View File
@@ -0,0 +1,32 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect } from 'storybook/test'
import { Badge } from './badge'
const meta = {
component: Badge,
tags: ['ai-generated'],
} satisfies Meta<typeof Badge>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {
args: { children: 'Public' },
play: async ({ canvas }) => {
const badge = canvas.getByText('Public')
await expect(badge).toHaveAttribute('data-slot', 'badge')
},
}
export const Secondary: Story = {
args: { variant: 'secondary', children: 'Internal' },
}
export const Destructive: Story = {
args: { variant: 'destructive', children: 'Error' },
}
export const Outline: Story = {
args: { variant: 'outline', children: 'Draft' },
}
+35
View File
@@ -0,0 +1,35 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect } from 'storybook/test'
import { Button } from './button'
const meta = {
component: Button,
tags: ['ai-generated'],
} satisfies Meta<typeof Button>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {
args: { children: 'Save' },
play: async ({ canvas }) => {
const button = canvas.getByRole('button', { name: /save/i })
await expect(button).toHaveAttribute('data-slot', 'button')
},
}
export const Outline: Story = {
args: { variant: 'outline', children: 'Cancel' },
}
export const Destructive: Story = {
args: { variant: 'destructive', children: 'Delete' },
}
export const Disabled: Story = {
args: { children: 'Save', disabled: true },
play: async ({ canvas }) => {
await expect(canvas.getByRole('button', { name: /save/i })).toBeDisabled()
},
}
@@ -0,0 +1,35 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect } from 'storybook/test'
import { Checkbox } from './checkbox'
const meta = {
component: Checkbox,
args: { 'aria-label': 'required' },
tags: ['ai-generated'],
} satisfies Meta<typeof Checkbox>
export default meta
type Story = StoryObj<typeof meta>
export const Unchecked: Story = {
play: async ({ canvas }) => {
await expect(canvas.getByRole('checkbox')).toHaveAttribute('aria-checked', 'false')
},
}
export const Checked: Story = {
args: { defaultChecked: true },
play: async ({ canvas }) => {
await expect(canvas.getByRole('checkbox')).toHaveAttribute('aria-checked', 'true')
},
}
export const Toggle: Story = {
play: async ({ canvas, userEvent }) => {
const checkbox = canvas.getByRole('checkbox')
await expect(checkbox).toHaveAttribute('aria-checked', 'false')
await userEvent.click(checkbox)
await expect(checkbox).toHaveAttribute('aria-checked', 'true')
},
}
+32
View File
@@ -0,0 +1,32 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect } from 'storybook/test'
import { Input } from './input'
const meta = {
component: Input,
tags: ['ai-generated'],
} satisfies Meta<typeof Input>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {
args: { placeholder: 'Object name', 'aria-label': 'name' },
}
export const Disabled: Story = {
args: { 'aria-label': 'name', disabled: true, defaultValue: 'Amphora' },
play: async ({ canvas }) => {
await expect(canvas.getByLabelText('name')).toBeDisabled()
},
}
export const Typing: Story = {
args: { 'aria-label': 'name' },
play: async ({ canvas, userEvent }) => {
const input = canvas.getByLabelText('name')
await userEvent.type(input, 'Bronze fibula')
await expect(input).toHaveValue('Bronze fibula')
},
}
@@ -0,0 +1,41 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect } from 'storybook/test'
import { VisibilityBadge } from './visibility-badge'
const meta = {
component: VisibilityBadge,
tags: ['ai-generated'],
} satisfies Meta<typeof VisibilityBadge>
export default meta
type Story = StoryObj<typeof meta>
export const Public: Story = {
args: { visibility: 'public' },
play: async ({ canvas }) => {
await expect(canvas.getByText('Public')).toBeVisible()
},
}
export const Internal: Story = {
args: { visibility: 'internal' },
}
export const Draft: Story = {
args: { visibility: 'draft' },
}
// The single project-wide CssCheck. VisibilityBadge applies `bg-green-100` for
// the `public` visibility (see STYLES in visibility-badge.tsx). A concrete
// resolved background colour proves the shared preview actually loaded the app's
// Tailwind stylesheet — an unstyled badge would report a transparent background.
export const CssCheck: Story = {
args: { visibility: 'public' },
play: async ({ canvas }) => {
const badge = canvas.getByText('Public')
await expect(getComputedStyle(badge).backgroundColor).toBe(
'oklch(0.962 0.044 156.743)',
)
},
}
+35
View File
@@ -0,0 +1,35 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect } from 'storybook/test'
import { Highlight } from './highlight'
const PRE = '\x02'
const POST = '\x03'
const meta = {
component: Highlight,
tags: ['ai-generated'],
} satisfies Meta<typeof Highlight>
export default meta
type Story = StoryObj<typeof meta>
export const PlainText: Story = {
args: { text: 'cast bronze with green patina' },
}
export const Marked: Story = {
args: { text: `cast ${PRE}bronze${POST} with green patina` },
play: async ({ canvas }) => {
const mark = canvas.getByText('bronze')
await expect(mark.tagName).toBe('MARK')
},
}
export const MultipleMarks: Story = {
args: { text: `${PRE}cast${POST} bronze with ${PRE}green${POST} patina` },
play: async ({ canvas }) => {
await expect(canvas.getByText('cast').tagName).toBe('MARK')
await expect(canvas.getByText('green').tagName).toBe('MARK')
},
}
@@ -0,0 +1,47 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect } from 'storybook/test'
import type { components } from '../api/schema'
import { SearchResultRow } from './search-result-row'
type SearchHitView = components['schemas']['SearchHitView']
const hit: SearchHitView = {
id: '11111111-1111-1111-1111-111111111111',
object_number: '2019.4.12',
object_name: 'Bronze figurine',
brief_description: 'A small cast figure.',
visibility: 'public',
snippet: 'cast \x02bronze\x03 with green patina',
}
const meta = {
component: SearchResultRow,
render: (args) => (
<ul>
<SearchResultRow {...args} />
</ul>
),
tags: ['ai-generated'],
} satisfies Meta<typeof SearchResultRow>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {
args: { hit },
play: async ({ canvas }) => {
const link = canvas.getByRole('link', { name: /bronze figurine/i })
await expect(link).toHaveAttribute('href', `/search/${hit.id}`)
// The snippet's marked term renders through Highlight.
await expect(canvas.getByText('bronze').tagName).toBe('MARK')
},
}
export const NoSnippet: Story = {
args: { hit: { ...hit, snippet: null } },
}
export const Internal: Story = {
args: { hit: { ...hit, visibility: 'internal' } },
}
+42 -14
View File
@@ -3,29 +3,57 @@ import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import path from "node:path";
import { defineConfig } from "vite";
import { fileURLToPath } from 'node:url';
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin';
const dirname = typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url));
// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
"@": path.resolve(__dirname, "./src")
}
},
server: {
proxy: {
"/api": "http://localhost:8080",
"/api-docs": "http://localhost:8080",
"/health": "http://localhost:8080",
},
"/health": "http://localhost:8080"
}
},
test: {
environment: "jsdom",
globals: true,
setupFiles: ["./src/test/setup.ts"],
environmentOptions: {
jsdom: {
url: "http://localhost",
},
},
},
});
projects: [{
extends: true,
test: {
environment: "jsdom",
globals: true,
setupFiles: ["./src/test/setup.ts"],
environmentOptions: {
jsdom: {
url: "http://localhost"
}
}
}
}, {
extends: true,
plugins: [
// The plugin will run tests for the stories defined in your Storybook config
// See options at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon#storybooktest
storybookTest({
configDir: path.join(dirname, '.storybook')
})],
test: {
name: 'storybook',
browser: {
enabled: true,
headless: true,
provider: 'playwright',
instances: [{
browser: 'chromium'
}]
}
}
}]
}
});
+1
View File
@@ -0,0 +1 @@
/// <reference types="@vitest/browser/providers/playwright" />