diff --git a/.nuxtrc b/.nuxtrc new file mode 100644 index 0000000..7fe0c55 --- /dev/null +++ b/.nuxtrc @@ -0,0 +1 @@ +setups.@nuxt/test-utils="4.4.0" \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index 908b208..9bbfff8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,10 +19,15 @@ Course milestones: working prototype for Business Angel Meeting II (December), p - Supabase: Postgres, Auth (email/password, Google), private Storage - Deployment target: Vercel (app) + Supabase (backend services), free tiers - Backend prototype exists and is being hardened (see `docs/BACKLOG.md`). - The frontend is being built now; `app.vue` is still a stub. + The frontend has an app shell (layout, navigation, design tokens, DE/EN/NL); the feature pages are placeholders. - Frontend stack from `docs/Lastenheft_Ons.md`: Pinia, `@nuxtjs/i18n` (DE/EN/NL), Tailwind or UnoCSS, Leaflet or MapLibre, Chart.js or ECharts. The frontend dev decides between the "or" options and records the choice here. A new dependency goes in `package.json`, a shared file: say why in the PR description. +- Decided: styling uses **Tailwind CSS v4** (`tailwindcss` with `@tailwindcss/vite`). Design tokens are plain CSS + variables, so the look can be changed without knowing Tailwind (see Frontend rules). +- Decided: `@nuxtjs/i18n` is pinned to exactly **10.2.3**. Later releases require `vue-router` 5, while Nuxt 3.21 + ships version 4. Do not upgrade it without moving to a Nuxt version that matches. +- Not installed yet: Pinia, the map library and the chart library. ## Ownership (who works where) @@ -43,8 +48,8 @@ stop and describe what is needed (route, fields, error codes) instead of editing (e.g. `useApi`) that also handles 401 (redirect to login) and maps error codes; do not call `$fetch` ad hoc. - Any API change (route, field, error code) updates the API table in `README.md` and the types in `shared/` in the same PR, and the PR description names the frontend impact. -- Error responses carry a stable `code`; the frontend maps codes to i18n messages and never shows server text. - (Planned in backlog B5; until then, handle HTTP status only.) +- Error responses carry a stable `data.code` (listed in `shared/api-errors.ts`); the frontend maps codes to + i18n messages and never shows server text. - Schema changes (migrations) are backend-only, and only one migration PR is open at a time. ## Commands @@ -55,12 +60,17 @@ supabase start # local Postgres/Auth/Storage (needs Docker) supabase migration up --local # apply supabase/migrations/* cp .env.example .env # then set NUXT_PUBLIC_SUPABASE_KEY from `supabase status` npm run dev # Nuxt dev server on :3000 (frontend and API together) -npm test # node:test + PGlite, no Docker needed +npm test # Vitest, backend and frontend tests, no Docker needed npm run build # Nuxt/Nitro production build ``` `npm test` and `npm run build` must pass before every merge. +- On Windows, run npm from a path with an upper-case drive letter (`E:\...`, not `e:\...`). Otherwise Vitest + fails with "failed to find the runner". +- CI uses npm 10 (Node 22). After adding or updating a package with npm 11, run + `npx npm@10 install --package-lock-only`, otherwise `npm ci` can fail in CI. + ## Test-driven development (applies to everyone) We work test-first: red (a failing test that states the behavior), green (the smallest change that passes), @@ -91,8 +101,9 @@ What to test, per layer: Test behavior, not implementation: no snapshot tests of whole pages, no asserting on CSS classes or internal state, no mocking of the unit under test. Keep tests fast and independent of each other. -Tooling target: Vitest as the single runner for unit, component and database tests (`npm test`), Playwright for E2E. -Until the backend dev has migrated the existing test (backlog B9), `npm test` still runs `node:test`. +Vitest is the single runner for unit, component and database tests (`npm test`). Playwright for E2E is not set up yet. +Backend tests live in `tests/`. Frontend tests live in `__tests__/` folders next to the code: `*.nuxt.spec.ts` +runs inside a Nuxt runtime, other `*.spec.ts` files run in plain Node (see `vitest.config.ts`). "Done" always includes: new behavior has a test, and `npm test` and `npm run build` pass. ## Backend rules (do not break these) @@ -108,24 +119,32 @@ Rule 1 applies to everyone, including the frontend. 3. **Every `security definer` function**: `set search_path = ''`, fully qualified names, `revoke ... from public, anon`, `grant execute ... to authenticated`. 4. **Migrations are append-only.** Add a new numbered file in `supabase/migrations/`. - Do not edit `001_*` or `002_*` once they are applied anywhere other than your own machine. + Do not edit an existing migration once it is applied anywhere other than your own machine. 5. **Validate all input with zod** (`z.strictObject`, bounded lengths, UUID params with `z.uuid()`). 6. **Map DB errors through `result()`** and do not leak raw database messages to clients. 7. **Photos** live in the private bucket `gallery` under `/`. Access goes through signed URLs only. Resolve the space with `room(db)` before touching storage paths. 8. **Any change to SQL, RLS or grants requires an extension of `tests/isolation.test.mjs`.** - The test only loads `001_couple_planner.sql` today; if you add policies in a later migration, load it too. + The test loads every file in `supabase/migrations/` in order. ## Frontend rules - **All user-facing text goes through i18n** (DE, EN, NL; fallback DE). No hardcoded strings. A new key is added in - all three languages in the same PR. + all three languages in the same PR. Message files are in `i18n/locales/`. +- **Language URLs:** German has no prefix (`/dates`), the others do (`/en/dates`, `/nl/dates`). Link with + `NuxtLinkLocale`. The choice is saved in the `ons_locale` cookie. SEO link tags stay off until F10. - **Mobile first and responsive.** Everything must work by keyboard with visible focus, and with sufficient contrast. +- **New main page:** add the file in `pages/` and one entry in `components/AppNav.vue`. - **Design tokens in one place** (colors, type scale, spacing, radius), derived from the logo and illustrations provided by the designer; no magic values in components. Illustrations live in `assets/illustrations/`. + - Raw values live only in `assets/css/tokens.css`. `assets/css/main.css` maps them to Tailwind utilities and + removes Tailwind's default scales, so a class such as `p-5` produces no CSS: add the token first. + - Components use colour roles (`bg-canvas`, `text-muted`), never palette values. + - `assets/__tests__/template-guard.spec.ts` rejects hardcoded text, raw colours and bracket values such as + `p-[13px]` in `pages/`, `components/` and `layouts/` (short exception list in the test). + `assets/__tests__/contrast.spec.ts` checks the colour contrast of the tokens. - **Pinia** for session, space and shared UI state; data fetching lives in composables, not in components. -- **Categories** are free text today. After backlog B2 they become keys whose labels come from i18n; do not build - features that depend on the raw category text. +- **Date categories** are fixed keys from `shared/date-categories.ts`; their labels come from i18n by key. - Auth: the Supabase client is provided as `useNuxtApp().$supabase` (client only, see `plugins/auth.client.ts`). Protect pages with route middleware, not with `v-if` in components. @@ -135,7 +154,7 @@ Rule 1 applies to everyone, including the frontend. | --- | --- | | `spaces(id, invite)` | `invite` is a 32-char hex code, set to null when a partner joins (one-time) | | `members(user_id, space_id, slot)` | `user_id` is the PK, so one space per person; `slot` is 1 or 2, so max two members | -| `dates(id, space_id, title, category, status, meeting_at, created_at)` | `status` is `planned` or `done`; `category` is currently free text (see backlog) | +| `dates(id, space_id, title, category, status, meeting_at, created_at)` | `status` is `planned` or `done`; `category` is one of the keys in `shared/date-categories.ts` (check constraint) | | `locations(user_id, space_id, lat, lon)` | one row per member; only the owner can write | | RPCs | `my_space()`, `create_space()`, `join_space(code)`, `dashboard()` | | Storage | bucket `gallery`: private, 5 MiB, jpeg/png/webp | @@ -144,7 +163,7 @@ The API surface is documented in the table in `README.md`. Do not duplicate it h ## Conventions -- Code, comments, docs and commit messages in **English** (course language). The existing `README.md` is German; translate it when touching it. +- Code, comments, docs and commit messages in **English** (course language). - Write readable code: one statement per line, no clever one-liners, short comments for any non-obvious SQL. The team has to explain every line in the final pitch. - Do not add dependencies without saying why in the PR description. @@ -170,7 +189,7 @@ The API surface is documented in the table in `README.md`. Do not duplicate it h - `docs/Lastenheft_Ons.md`: requirements, evaluation criteria, timeline - `docs/BACKLOG.md`: known gaps and the agreed order of work - `README.md`: setup and the API table (the contract with the frontend) -- `shared/`: types shared between frontend and API (create when first needed) -- `server/utils/backend.ts`: shared Nitro helpers (`client`, `result`, `room`, `dateFields`) +- `shared/`: request and response schemas, error codes and category keys shared between frontend and API +- `server/utils/backend.ts`: shared Nitro helpers (`client`, `result`, `room`) - `supabase/migrations/`: schema, RLS, storage policies - `tests/isolation.test.mjs`: RLS and pairing tests diff --git a/app.vue b/app.vue index 6b5e28c..d14f9c4 100644 --- a/app.vue +++ b/app.vue @@ -1 +1,25 @@ - + + + diff --git a/assets/__tests__/contrast.spec.ts b/assets/__tests__/contrast.spec.ts new file mode 100644 index 0000000..4cc1fa5 --- /dev/null +++ b/assets/__tests__/contrast.spec.ts @@ -0,0 +1,81 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, test } from 'vitest' + +// Guards a palette swap: every text and focus colour must stay readable (WCAG 2.1 AA). +const css = readFileSync(new URL('../css/tokens.css', import.meta.url), 'utf8') + +// Matches "--palette-ink-900: #1f1a24;" +const paletteDeclaration = /--(palette-[\w-]+):\s*(#[0-9a-f]{6});/gi +// Matches "--ons-color-ink: light-dark(var(--palette-a), var(--palette-b));" +const roleDeclaration = /--ons-color-([\w-]+):\s*light-dark\(\s*var\(--(palette-[\w-]+)\),\s*var\(--(palette-[\w-]+)\)\s*\);/g + +const palette = new Map() +for (const [, name, hex] of css.matchAll(paletteDeclaration)) { + palette.set(name!, hex!) +} + +const roles = new Map() +for (const [, role, light, dark] of css.matchAll(roleDeclaration)) { + roles.set(role!, { light: light!, dark: dark! }) +} + +function colourOf(role: string, theme: 'light' | 'dark'): string { + const paletteName = roles.get(role)?.[theme] + const hex = paletteName ? palette.get(paletteName) : undefined + if (!hex) { + throw new Error(`--ons-color-${role} (${theme}) does not resolve to a #rrggbb palette value`) + } + return hex +} + +// Relative luminance as defined by WCAG. +function luminance(hex: string): number { + const [red, green, blue] = [1, 3, 5].map((start) => { + const channel = Number.parseInt(hex.slice(start, start + 2), 16) / 255 + return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4 + }) + return 0.2126 * red! + 0.7152 * green! + 0.0722 * blue! +} + +function contrast(first: string, second: string): number { + const [lighter, darker] = [luminance(first), luminance(second)].sort((a, b) => b - a) + return (lighter! + 0.05) / (darker! + 0.05) +} + +// [foreground role, background role, minimum ratio] +const pairs: [string, string, number][] = [ + ['ink', 'canvas', 4.5], + ['ink', 'surface', 4.5], + ['muted', 'canvas', 4.5], + ['muted', 'surface', 4.5], + ['accent', 'canvas', 4.5], + ['accent', 'surface', 4.5], + ['on-accent', 'accent', 4.5], + // Focus rings are not text, so 3:1 is enough. + ['focus', 'canvas', 3], + ['focus', 'surface', 3], +] + +describe('design tokens', () => { + test('the contrast formula matches the known black and white ratio', () => { + expect(contrast('#000000', '#ffffff')).toBeCloseTo(21, 5) + }) + + test('every colour role is written as light-dark() of two palette values', () => { + const declared = [...css.matchAll(/--ons-color-[\w-]+:/g)] + expect(declared.length).toBeGreaterThan(0) + expect(roles.size).toBe(declared.length) + }) + + test('raw colour values appear only in the palette', () => { + const withoutPalette = css.replaceAll(paletteDeclaration, '') + expect(withoutPalette).not.toMatch(/#[0-9a-f]{3,8}\b|\b(rgb|rgba|hsl|hsla|oklch)\(/i) + }) + + describe.each(['light', 'dark'] as const)('%s theme', (theme) => { + test.each(pairs)('%s on %s reaches %s:1', (foreground, background, minimum) => { + const ratio = contrast(colourOf(foreground, theme), colourOf(background, theme)) + expect(ratio).toBeGreaterThanOrEqual(minimum) + }) + }) +}) diff --git a/assets/__tests__/template-guard.spec.ts b/assets/__tests__/template-guard.spec.ts new file mode 100644 index 0000000..aae7a45 --- /dev/null +++ b/assets/__tests__/template-guard.spec.ts @@ -0,0 +1,155 @@ +import { readdirSync, readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +// Part of Vue, which Nuxt installs. +import { parse } from 'vue/compiler-sfc' +import { describe, expect, test } from 'vitest' + +// Checks .vue files in pages/, components/ and layouts/ for three things: +// text that is not translated, raw colours, and one-off class values such as p-[13px]. +const folders = ['pages', 'components', 'layouts'] + +// Exceptions. Keep these lists short and give every entry a reason. +// Symbols that read the same in every language. +const allowedText = ['–', '·', '|', '/', '×'] +// Bracket class values that do not introduce a new design value. +const allowedClassValues = [ + /-\[var\(--ons-[\w-]+\)\]$/, // refers to a token + /-\[env\(safe-area-inset-[a-z]+\)\]$/, // device safe area + /^grid-(cols|rows)-\[[\da-z_]*(fr|auto)[\da-z_]*\]$/, // grid proportions +] + +// Attributes whose text people see or hear. +const textAttributes = ['alt', 'aria-label', 'aria-description', 'placeholder', 'title', 'label'] + +const rawColour = /#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})\b|\b(?:rgba?|hsla?|oklch|oklab)\(/i +const quotedHexColour = /(['"`])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})\1/i +// "p-[13px]", but not variants such as "data-[state=open]:p-2": there a colon follows +// before the class name ends. +const bracketValue = /[^\s'"`{}:,]*-\[[^\]\s]+\](?![^\s'"`[\]]*:)/g +// "[margin:13px]" +const bracketProperty = /(?<=^|[\s'"`])\[[a-z-]+:[^\]\s]+\](?!:)/g + +// Node type numbers of the Vue template parser. +const ELEMENT = 1 +const TEXT = 2 +const ATTRIBUTE = 6 +const DIRECTIVE = 7 + +function findViolations(source: string): string[] { + const { descriptor } = parse(source) + const violations: string[] = [] + + function checkClasses(value: string) { + for (const match of [...value.matchAll(bracketValue), ...value.matchAll(bracketProperty)]) { + if (!allowedClassValues.some(allowed => allowed.test(match[0]))) { + violations.push(`one-off class value: ${match[0]}`) + } + } + if (rawColour.test(value)) { + violations.push(`raw colour: ${value}`) + } + } + + function walk(node: any) { + if (node.type === TEXT) { + const text = node.content.trim() + if (text && !allowedText.includes(text)) { + violations.push(`untranslated text: ${text}`) + } + } + if (node.type === ELEMENT) { + for (const property of node.props) { + if (property.type === ATTRIBUTE) { + const value = property.value?.content ?? '' + if (textAttributes.includes(property.name) && value.trim()) { + violations.push(`untranslated attribute: ${property.name}="${value}"`) + } + if (property.name === 'class' || property.name === 'style') { + checkClasses(value) + } + } + // Bound classes and styles, for example :class="{ 'p-[13px]': open }". + if (property.type === DIRECTIVE && ['class', 'style'].includes(property.arg?.content)) { + checkClasses(property.exp?.content ?? '') + } + } + } + for (const child of node.children ?? []) { + walk(child) + } + } + + if (descriptor.template?.ast) { + walk(descriptor.template.ast) + } + for (const style of descriptor.styles) { + if (rawColour.test(style.content)) { + violations.push('raw colour in a '], + ['colour in a script', ''], + ])('reports %s', (_name, source) => { + expect(findViolations(source)).not.toEqual([]) + }) + + test.each([ + ['translated text', ''], + ['anchors and slots', '