From 1047c738b5665c568ceb3777c651ad0e8205d4d0 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 21:06:25 +0100 Subject: [PATCH 01/48] AI-DLC: inception en ontwerp voor redesign B/E met contactformulier Requirements, application design (incl. concept-API-contract voor het contactformulier), units en functional design voor U1. Co-Authored-By: Claude Sonnet 5.5 --- .../reverse-engineering/api-documentation.md | 26 + .../reverse-engineering/architecture.md | 75 +++ .../reverse-engineering/business-overview.md | 34 ++ .../code-quality-assessment.md | 21 + .../reverse-engineering/code-structure.md | 38 ++ .../component-inventory.md | 21 + .../reverse-engineering/dependencies.md | 18 + .../reverse-engineering-timestamp.md | 16 + .../reverse-engineering/technology-stack.md | 19 + aidlc-docs/active-features.md | 7 +- .../redesign-modern-timetravel/aidlc-state.md | 64 +++ .../redesign-modern-timetravel/audit.md | 504 ++++++++++++++++++ .../theme-foundation-code-generation-plan.md | 48 ++ .../plans/theme-foundation-fd-questions.md | 25 + ...theme-foundation-functional-design-plan.md | 9 + .../functional-design/business-logic-model.md | 45 ++ .../functional-design/business-rules.md | 60 +++ .../functional-design/domain-entities.md | 41 ++ .../functional-design/frontend-components.md | 67 +++ .../application-design/application-design.md | 41 ++ .../component-dependency.md | 73 +++ .../application-design/component-methods.md | 61 +++ .../application-design/components.md | 73 +++ .../contact-api-contract.md | 226 ++++++++ .../inception/application-design/services.md | 26 + .../unit-of-work-dependency.md | 47 ++ .../unit-of-work-story-map.md | 36 ++ .../application-design/unit-of-work.md | 51 ++ .../plans/application-design-plan.md | 42 ++ .../inception/plans/execution-plan.md | 162 ++++++ .../inception/plans/unit-of-work-plan.md | 25 + .../requirement-verification-questions.md | 173 ++++++ .../inception/requirements/requirements.md | 65 +++ aidlc-docs/language-preference.md | 12 + 34 files changed, 2248 insertions(+), 3 deletions(-) create mode 100644 aidlc-docs/_shared/reverse-engineering/api-documentation.md create mode 100644 aidlc-docs/_shared/reverse-engineering/architecture.md create mode 100644 aidlc-docs/_shared/reverse-engineering/business-overview.md create mode 100644 aidlc-docs/_shared/reverse-engineering/code-quality-assessment.md create mode 100644 aidlc-docs/_shared/reverse-engineering/code-structure.md create mode 100644 aidlc-docs/_shared/reverse-engineering/component-inventory.md create mode 100644 aidlc-docs/_shared/reverse-engineering/dependencies.md create mode 100644 aidlc-docs/_shared/reverse-engineering/reverse-engineering-timestamp.md create mode 100644 aidlc-docs/_shared/reverse-engineering/technology-stack.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/aidlc-state.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/audit.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-code-generation-plan.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-fd-questions.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-functional-design-plan.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/business-logic-model.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/business-rules.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/domain-entities.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/frontend-components.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/application-design/application-design.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/application-design/component-dependency.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/application-design/component-methods.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/application-design/components.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/application-design/contact-api-contract.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/application-design/services.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/application-design/unit-of-work-dependency.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/application-design/unit-of-work-story-map.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/application-design/unit-of-work.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/plans/application-design-plan.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/plans/execution-plan.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/plans/unit-of-work-plan.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/requirements/requirement-verification-questions.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/inception/requirements/requirements.md create mode 100644 aidlc-docs/language-preference.md diff --git a/aidlc-docs/_shared/reverse-engineering/api-documentation.md b/aidlc-docs/_shared/reverse-engineering/api-documentation.md new file mode 100644 index 0000000..7e4d7f9 --- /dev/null +++ b/aidlc-docs/_shared/reverse-engineering/api-documentation.md @@ -0,0 +1,26 @@ +# API Documentation + +## REST APIs (consumed) +### Offerings +- **Method**: GET +- **Path**: `{VITE_API_BASE_URL ?? ''}/api/v1/offerings` +- **Purpose**: package cards for PackagesSection +- **Request**: none +- **Response**: JSON array of `PackageCardData`; contract documented in `aidlc-docs/features/react-frontend/construction/react-frontend-app/functional-design/packages-api-handoff.md` + +### Sentry tunnel +- **Method**: POST `/sentry-tunnel` (proxied by nginx; vite dev proxy locally) + +## REST APIs (provided by this repo) +None. No contact/form endpoint exists yet; `ContactSection` uses `mailto:`. + +## Internal APIs +### useTheme() +- **Methods**: `{ theme: 'red' | 'purple', toggleTheme() }`; throws outside ThemeProvider. +### usePackagesQuery() +- **Return**: TanStack Query result with `data: PackageCardData[]`. + +## Data Models +### PackageCardData +- **Fields**: `id, slug, title, description, price, priceNote, features[], ctaLabel, featured?` +- **Validation**: none client-side (trusts API). diff --git a/aidlc-docs/_shared/reverse-engineering/architecture.md b/aidlc-docs/_shared/reverse-engineering/architecture.md new file mode 100644 index 0000000..012d679 --- /dev/null +++ b/aidlc-docs/_shared/reverse-engineering/architecture.md @@ -0,0 +1,75 @@ +# System Architecture + +## System Overview +Static single-page React application (Vite build) served as static files behind nginx on Raspberry Pis (test and production). One route (`/`), hash-based history. Dynamic data: packages via same-origin `GET /api/v1/offerings`. Monitoring: Sentry (via `/sentry-tunnel`) and self-hosted Umami. + +## Architecture Diagram + +```mermaid +graph TD + Browser[Browser] --> RP[Reverse-proxy Pi nginx] + RP --> WS[Web server Pi - static dist/] + RP --> API[CMS and API backend] + RP --> Sentry[Sentry tunnel] + Browser --> Umami[Umami analytics] + subgraph SPA[React SPA] + Root[__root route + RootLayout] --> Nav + Root --> Landing[LandingPage] + Root --> Footer + Landing --> Hero + Landing --> About + Landing --> Packages[PackagesSection + usePackagesQuery] + Landing --> Process + Landing --> Contact[ContactSection] + Nav --> Toggle[ThemeToggle] + Toggle --> TP[ThemeProvider] + end + Packages -->|fetch| API + classDef infra fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + classDef ui fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef ext fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + class RP,WS,API infra; + class Root,Nav,Landing,Footer,Hero,About,Packages,Process,Contact,Toggle,TP ui; + class Sentry,Umami,Browser ext; +``` + +Text alternative: browser reaches nginx reverse proxy, which serves the static React bundle and proxies the API and Sentry tunnel; inside the SPA a root layout wraps nav, landing sections and footer. + +## Component Descriptions +### ThemeProvider / tokens.ts / index.css +- **Purpose**: Theme state. `ThemeName = 'red' | 'purple'`, stored in localStorage key `slp-software-theme`, applied as class `theme-red`/`theme-purple` on ``; colors are CSS variables mapped to Tailwind colors (`bg`, `surface`, `line`, `text`, `muted`, `accent`...). +- **Dependencies**: React context only. +- **Type**: Application + +### Nav / Footer / RootLayout +- **Purpose**: Sticky nav (anchor links, CTA, ThemeToggle, mobile menu), footer, layout shell incl. UmamiAnalytics and SentryTestButton. +- **Type**: Application + +### Landing feature (`src/features/landing`) +- **Purpose**: Sections and static content (`data/content.ts`), packages query hook. +- **Type**: Application + +## Data Flow +```mermaid +sequenceDiagram + box rgba(99,179,237,0.4) Client + participant U as Visitor + participant P as PackagesSection + end + box rgba(154,230,180,0.4) Server + participant A as API offerings + end + U->>P: open page + P->>A: GET /api/v1/offerings + A-->>P: PackageCardData array + P-->>U: render cards or error text +``` + +## Integration Points +- **External APIs**: `GET {VITE_API_BASE_URL}/api/v1/offerings` (packages); Sentry envelope via `/sentry-tunnel`. +- **Databases**: none in this repo. +- **Third-party Services**: Sentry, Umami (self-hosted). + +## Infrastructure Components +- **Deployment Model**: Gitea Actions (`continuous_integration.yaml`, `deploy.yaml`), static bundle on Raspberry Pi nginx; test and production environments. +- **Networking**: reverse-proxy Pi in front of web-server Pi (see feature react-frontend operations docs). diff --git a/aidlc-docs/_shared/reverse-engineering/business-overview.md b/aidlc-docs/_shared/reverse-engineering/business-overview.md new file mode 100644 index 0000000..819343a --- /dev/null +++ b/aidlc-docs/_shared/reverse-engineering/business-overview.md @@ -0,0 +1,34 @@ +# Business Overview + +## Business Context Diagram + +```mermaid +graph LR + V[Visitor / prospect] --> S[slpsoftware.nl marketing site] + S --> O[Offerings API /api/v1/offerings] + S --> M[mailto link info@slpsoftware.nl] + B[Bryan Slop - SLP Software] --> M + O --> C[CMS and API - sibling repo] + classDef actor fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + classDef app fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef ext fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + class V,B actor; + class S app; + class O,M,C ext; +``` + +Text alternative: visitors use the marketing site, which loads packages from the offerings API (hosted by the CMS and API repo) and currently hands contact requests off through a mailto link. + +## Business Description +- **Business Description**: Marketing site of SLP Software, a one-person web and .NET development business (Bryan Slop). Goal: explain the offering, show packages with fixed prices, and get prospects to start a project. +- **Business Transactions**: (1) Visitor reads about the business; (2) Visitor browses packages (data from API); (3) Visitor reads the 3-step process; (4) Visitor requests a project (today: opens a mail client via mailto); (5) Visitor switches colour theme. +- **Business Dictionary**: *Pakket* = fixed-scope, fixed-price offering; *Maatwerk* = custom work quoted after intake; *Werkwijze* = process (intake, build, live). + +## Component Level Business Descriptions +### Landing page (Hero, About, Packages, Process, Contact) +- **Purpose**: Single-page storefront. +- **Responsibilities**: Messaging, package presentation, call to action. + +### Theme system +- **Purpose**: Let visitors choose red or purple dark theme. +- **Responsibilities**: Persist choice, apply CSS variable set. diff --git a/aidlc-docs/_shared/reverse-engineering/code-quality-assessment.md b/aidlc-docs/_shared/reverse-engineering/code-quality-assessment.md new file mode 100644 index 0000000..c6f520e --- /dev/null +++ b/aidlc-docs/_shared/reverse-engineering/code-quality-assessment.md @@ -0,0 +1,21 @@ +# Code Quality Assessment + +## Test Coverage +- **Overall**: Fair (23 tests at last recorded run; coverage % not measured) +- **Unit Tests**: Present for theme, nav, shared components, packages section +- **Integration Tests**: None + +## Code Quality Indicators +- **Linting**: Configured (ESLint + typescript-eslint) +- **Code Style**: Consistent (Prettier) +- **Documentation**: Good (README, aidlc-docs) + +## Technical Debt +- `ThemeName` is a closed union of two colour themes; adding light/dark and a variant (B vs E) needs a model change (theme = mode x variant). +- Design is heavily tied to the current dark red/purple look; B and E need new tokens, fonts (Archivo, Open Sans, Trebuchet/Verdana, VT323) and section components. +- `ContactSection` is mailto only; no form, validation or submit endpoint. +- `SKELETON_COUNT = 3` and `sm:grid-cols-3` hard-code three packages. + +## Patterns and Anti-patterns +- **Good Patterns**: semantic Tailwind colors via CSS variables, feature folders, guarded localStorage access. +- **Anti-patterns**: none significant. diff --git a/aidlc-docs/_shared/reverse-engineering/code-structure.md b/aidlc-docs/_shared/reverse-engineering/code-structure.md new file mode 100644 index 0000000..d723afb --- /dev/null +++ b/aidlc-docs/_shared/reverse-engineering/code-structure.md @@ -0,0 +1,38 @@ +# Code Structure + +## Build System +- **Type**: pnpm + Vite 5 + `tsc -b` +- **Configuration**: `vite.config.ts` (react plugin, `__APP_VERSION__` define, dev proxy `/sentry-tunnel`, vitest jsdom), `tailwind.config.ts`, `postcss.config.js`, `tsconfig*.json`, `eslint.config.js`, `.prettierrc` + +## Key Modules +Entry: `index.html` → `src/main.tsx` (Sentry init, RouterProvider) → `src/router.tsx` (hash history) → `src/routes/__root.tsx` (ThemeProvider + RootLayout) → `src/routes/index.tsx` (LandingPage). + +### Existing Files Inventory +- `src/main.tsx` - bootstrap, Sentry +- `src/router.tsx`, `src/routes/__root.tsx`, `src/routes/index.tsx` - routing +- `src/fonts.ts` - @fontsource imports (Instrument Sans, Sora, JetBrains Mono) +- `src/index.css` - Tailwind layers, `.theme-red`/`.theme-purple` variable sets, caret animation +- `src/theme/ThemeProvider.tsx`, `src/theme/tokens.ts` - theme context, ids, storage key +- `src/components/layout/Nav.tsx`, `Footer.tsx`, `RootLayout.tsx` - shell +- `src/components/ui/ThemeToggle.tsx` - round swatch button +- `src/components/shared/UmamiAnalytics.tsx`, `ErrorBoundary.tsx`, `SentryTestButton.tsx` - cross-cutting +- `src/features/landing/pages/LandingPage.tsx` - section composition (Hero, About, Packages, Process, Contact) +- `src/features/landing/components/*` - Hero, AboutSection (photo, WebP variants in `public/`), PackagesSection, PackageCard, PackageCardSkeleton, ProcessSection, ProcessStep, ContactSection (mailto only) +- `src/features/landing/data/content.ts` - nav links, hero, packages seed, process steps, about, contact info +- `src/features/landing/hooks/usePackagesQuery.ts` - TanStack Query fetch of offerings +- `src/lib/queryClient.ts`, `src/utils/scrollToHash.ts`, `src/test/setup.ts` +- Tests: `Nav.test.tsx`, `ErrorBoundary.test.tsx`, `SentryTestButton.test.tsx`, `UmamiAnalytics.test.tsx`, `ThemeProvider.test.tsx`, `PackagesSection.test.tsx` +- `References/` - original static HTML designs (purple and red) + +## Design Patterns +### CSS-variable theming +- **Location**: `index.css`, `tailwind.config.ts` +- **Purpose**: switch theme by swapping a class on ``; components use semantic Tailwind colors. +- **Implementation**: `ThemeName` union + `themeClassName()`. + +### Feature folder +- **Location**: `src/features/landing` +- **Purpose**: group components/data/hooks by feature. + +## Critical Dependencies +- react 18.3, @tanstack/react-router 1.79 (hash history), @tanstack/react-query 5, tailwindcss 3.4, @sentry/react 10, @fontsource fonts. diff --git a/aidlc-docs/_shared/reverse-engineering/component-inventory.md b/aidlc-docs/_shared/reverse-engineering/component-inventory.md new file mode 100644 index 0000000..42fdc7c --- /dev/null +++ b/aidlc-docs/_shared/reverse-engineering/component-inventory.md @@ -0,0 +1,21 @@ +# Component Inventory + +## Application Packages +- slp-software-frontend (this repo) - React SPA marketing site + +## Infrastructure Packages +- `.gitea/workflows/continuous_integration.yaml`, `deploy.yaml` - Gitea Actions CI/CD +- nginx example configs in `aidlc-docs/features/react-frontend/operations/deployment/nginx/` + +## Shared Packages +- none (sibling repo `AndreaSlopFotografie-cms-api-foundation` hosts CMS/API, external to this workspace) + +## Test Packages +- Vitest + Testing Library co-located `__tests__` folders (6 test files) + +## Total Count +- **Total Packages**: 1 +- **Application**: 1 +- **Infrastructure**: 0 (config only) +- **Shared**: 0 +- **Test**: 0 (in-package) diff --git a/aidlc-docs/_shared/reverse-engineering/dependencies.md b/aidlc-docs/_shared/reverse-engineering/dependencies.md new file mode 100644 index 0000000..3dc8db3 --- /dev/null +++ b/aidlc-docs/_shared/reverse-engineering/dependencies.md @@ -0,0 +1,18 @@ +# Dependencies + +## Internal Dependencies +```mermaid +graph TD + main --> router --> root[__root] --> TP[ThemeProvider] + root --> RL[RootLayout] --> Nav --> TT[ThemeToggle] --> TP + root --> idx[routes/index] --> LP[LandingPage] --> Sections + Sections --> content[data/content.ts] + Sections --> hook[usePackagesQuery] + classDef a fill:#63b3ed,stroke:#2b6cb0,color:#000; + class main,router,root,TP,RL,Nav,TT,idx,LP,Sections,content,hook a; +``` +Text alternative: entry point leads through router and root route to ThemeProvider, layout and landing sections which use static content and the packages hook. + +## External Dependencies +See `package.json` (react, @tanstack/*, @sentry/react, @fontsource/*, tailwindcss, vite, vitest). Licenses: MIT/Apache-2.0 typical; not audited here. +External service dependency: CMS/API backend for `/api/v1/offerings` (sibling repo). diff --git a/aidlc-docs/_shared/reverse-engineering/reverse-engineering-timestamp.md b/aidlc-docs/_shared/reverse-engineering/reverse-engineering-timestamp.md new file mode 100644 index 0000000..d6a9d2f --- /dev/null +++ b/aidlc-docs/_shared/reverse-engineering/reverse-engineering-timestamp.md @@ -0,0 +1,16 @@ +# Reverse Engineering Metadata + +**Analysis Date**: 2026-11-09T13:20:00Z +**Analyzer**: AI-DLC +**Workspace**: K:\Development\SlpSoftware\Projects\SlpSoftware +**Total Files Analyzed**: ~25 (key source, config and structure files) + +## Artifacts Generated +- [x] business-overview.md +- [x] architecture.md +- [x] code-structure.md +- [x] api-documentation.md +- [x] component-inventory.md +- [x] technology-stack.md +- [x] dependencies.md +- [x] code-quality-assessment.md diff --git a/aidlc-docs/_shared/reverse-engineering/technology-stack.md b/aidlc-docs/_shared/reverse-engineering/technology-stack.md new file mode 100644 index 0000000..ce911f3 --- /dev/null +++ b/aidlc-docs/_shared/reverse-engineering/technology-stack.md @@ -0,0 +1,19 @@ +# Technology Stack + +## Programming Languages +- TypeScript 5.6 - all source + +## Frameworks +- React 18.3 - UI +- TanStack Router 1.79 (hash history) - routing +- TanStack Query 5.59 - data fetching +- Tailwind CSS 3.4 - styling via CSS variables + +## Infrastructure +- Gitea Actions, nginx on Raspberry Pi (reverse proxy + static web server), Sentry, Umami + +## Build Tools +- Vite 5.4, pnpm, tsc -b, PostCSS/Autoprefixer + +## Testing Tools +- Vitest 2.1 (jsdom), Testing Library (react, user-event, jest-dom); ESLint 9 + typescript-eslint, Prettier 3 diff --git a/aidlc-docs/active-features.md b/aidlc-docs/active-features.md index 16f8b5b..e598001 100644 --- a/aidlc-docs/active-features.md +++ b/aidlc-docs/active-features.md @@ -1,5 +1,6 @@ # Active Features -| Feature | Status | Branch | Affected Components | Session Start | -|---------|--------|--------|---------------------|---------------| -| react-frontend | ✅ Complete | master | React frontend (SLP Software marketing site) | 2026-07-18 | +| Type | Name | Status | Branch | Affected Components | Session Start | +|------|------|--------|--------|---------------------|---------------| +| Feature | react-frontend | ✅ Complete | master | React frontend (SLP Software marketing site) | 2026-07-18 | +| Feature | redesign-modern-timetravel | 🔵 Inception | feature/redesign-modern-timetravel | Theme system, Nav, all landing sections, Contact form (+ CMS/API for form endpoint) | 2026-11-09 | diff --git a/aidlc-docs/features/redesign-modern-timetravel/aidlc-state.md b/aidlc-docs/features/redesign-modern-timetravel/aidlc-state.md new file mode 100644 index 0000000..fa18d98 --- /dev/null +++ b/aidlc-docs/features/redesign-modern-timetravel/aidlc-state.md @@ -0,0 +1,64 @@ +# AI-DLC State Tracking + +## Project Information +- **Feature Name**: Redesign — Modern (B) as default with Time-travel (E) variant switch, plus contact form +- **Feature Slug**: redesign-modern-timetravel +- **Project Type**: Brownfield +- **Start Date**: 2026-11-09T13:00:00Z +- **Current Stage**: CONSTRUCTION - U1 theme-foundation Code Generation (in progress) +- **Branch**: feature/redesign-modern-timetravel + +## Workspace State +- **Existing Code**: Yes +- **Reverse Engineering Needed**: Yes (done 2026-11-09, awaiting approval) +- **Workspace Root**: K:\Development\SlpSoftware\Projects\SlpSoftware + +## Code Location Rules +- **Application Code**: Workspace root (NEVER in aidlc-docs/) +- **Feature Documentation**: aidlc-docs/features/redesign-modern-timetravel/ only +- **Shared Artifacts**: aidlc-docs/_shared/ +- **Structure patterns**: See code-generation.md Critical Rules + +## Language Configuration +- **Documentation Language**: English (confirmed by user 2026-11-09) +- **Conversation Language**: User Language (Dutch) + +## Extension Configuration +| Extension | Enabled | Decided At | +|---|---|---| +| Security Baseline | Yes | Requirements Analysis | +| Property-Based Testing | Partial (pure functions and serialization round-trips only) | Requirements Analysis | + +## Operations Configuration +- **Include Operations Phase**: Undecided +- **Decided At**: Pending — asked at Requirements Analysis + +## Coordination Notes +- **Contact form**: the user wants to be notified BEFORE the form build starts, so other sessions that also need a form and the CMS & API session can be attached to build it together. +- **Design source**: Claude Design canvas https://claude.ai/artifact/UkpzA5YPLheZm3fpmWdPtn (B = Modern.dc.html, E = Tijdreis2.dc.html, packages blocks PakkettenModern/PakkettenTijd, dark variants). +- **Open input**: mobile packages as swipeable scroll-snap row instead of stacked (candidate requirement). + +- **Sessions to attach (confirmed by user 2026-11-09)**: `CMS & API` [df4818] = website session of AndreaSlopFotografie (ASF); `AndreaSlopFotografie` [7d5867] = CMS session of ASF; `SLS Software - CMS` [9d882f] = CMS session of SLP Software (owner of the endpoint/headless module for this site). All three idle at 2026-11-09. +- **Coordination update 2026-11-09**: user asked to involve sessions immediately (they may need something else). Briefings sent: `CMS & API` (form needs of the ASF website: fields, validation, ?onderwerp preselect, spam/privacy, slots) and `SLS Software - CMS` (endpoint, `category`, headless module; owner of the build). `AndreaSlopFotografie` (ASF CMS session) is NOT asked now; use later as a cross-check reviewer. Replies are folded into the form contract in Application Design. + +## Stage Progress + +### 🔵 INCEPTION PHASE +- [x] Workspace Detection +- [x] Reverse Engineering (approved 2026-11-09) → aidlc-docs/_shared/reverse-engineering/ +- [x] Requirements Analysis (approved 2026-11-09) +- [x] User Stories (SKIP) +- [x] Workflow Planning (approved 2026-11-09) +- [x] Application Design (approved 2026-11-09) +- [x] Units Generation (approved 2026-11-10) + +### 🟢 CONSTRUCTION PHASE (units U1 theme-foundation, U2 b-modern-sections, U3 packages-block, U4 contact-form, U5 e-timetravel) +- [ ] Functional Design (EXECUTE U1, U3, U4; SKIP U2, U5) +- [ ] NFR Requirements (EXECUTE U4, U5; SKIP U1-U3) +- [ ] NFR Design (EXECUTE U4, U5) +- [ ] Infrastructure Design (EXECUTE U4 only) +- [ ] Code Generation (EXECUTE, per unit) +- [ ] Build and Test (EXECUTE) + +### 🟡 OPERATIONS PHASE +- [ ] Deployment Setup, Monitoring Setup, Production Readiness Validation — UNDECIDED (asked at Build and Test) diff --git a/aidlc-docs/features/redesign-modern-timetravel/audit.md b/aidlc-docs/features/redesign-modern-timetravel/audit.md new file mode 100644 index 0000000..049c954 --- /dev/null +++ b/aidlc-docs/features/redesign-modern-timetravel/audit.md @@ -0,0 +1,504 @@ +# Audit Log — redesign-modern-timetravel + +## Workspace Detection — Initial Request + +**Timestamp**: 2026-11-09T13:00:00Z + +**User Input**: "ik wil als uitgangspunt nu optie B bouwen. ik wil dan naast de light/dark theme switch een knop hebben waarmee ik naar optie E kan wisselen. ik wil dit met aidlc oppakken. ik wil meteen het formulier meebouwen. Zodra je het formulier gaat bouwen wil ik het wetenm dan haak ik andere sessies aan die ook nog een formulier wilen hebben en de sessie van het cms zodat het samen gebouwd kan worden" + +**AI Response**: "Invoked aidlc-workflow. Classified as Feature (new capability: redesign + variant switch + contact form). Brownfield (existing React/Vite site, no shared reverse-engineering artifacts yet). Created branch feature/redesign-modern-timetravel from master. Created feature directory. Starting Reverse Engineering." + +**Context**: Workspace Detection. Design source: Claude Design canvas artifact https://claude.ai/artifact/UkpzA5YPLheZm3fpmWdPtn (Modern.dc.html = B, Tijdreis2.dc.html = E, PakkettenModern.dc.html, PakkettenTijd.dc.html, plus dark wrappers). Standing coordination requirement: notify the user BEFORE the contact-form build starts, so they can attach other sessions that also want a form and the CMS & API session. + +--- + +## Mid-turn user message — mobile packages layout + +**Timestamp**: 2026-11-09T13:10:00Z + +**User Input**: "voor de paketten heb ik nog wel een vraag voor de mobiele versie. ipv onder elkaar. is naast elkaar en swipeable niet makkelijker en mooier?" + +**AI Response**: "Answered: yes, a horizontally swipeable scroll-snap row (peek of next card, dots, featured card first, keyboard/screen-reader accessible, desktop grid unchanged) is likely better, especially with 6+ packages. Recorded as a requirement candidate for Requirements Analysis. Canvas design not changed (not requested)." + +**Context**: Requirement input for Requirements Analysis (packages block, mobile). + +--- + +## Workspace Detection — Findings + +**Timestamp**: 2026-11-09T13:12:00Z + +**User Input**: "(none — internal finding)" + +**AI Response**: "Brownfield: Vite + React 18 + TS + Tailwind 3 + TanStack Router (hash history) + TanStack Query + Vitest. Two themes (red/purple) via CSS custom properties and a ThemeToggle in Nav. Packages fetched from /api/v1/offerings. ContactSection currently only a mailto link. Sibling repo AndreaSlopFotografie-cms-api-foundation (branch feature/cms-api-foundation) hosts the CMS/API and has a 'contact-page' feature in its aidlc-docs — to be inspected in Requirements Analysis as potential reuse/coordination point. Active feature react-frontend is Complete; no conflict." + +**Context**: Workspace Detection complete; next stage Reverse Engineering. + +--- + +## Reverse Engineering — Approval + +**Timestamp**: 2026-11-09T13:40:00Z + +**User Input**: "taalgebruik is goed. ga verder" + +**AI Response**: "Language preference confirmed as default (English docs, Dutch conversation; answer A). Reverse Engineering treated as approved; proceeding to Requirements Analysis. Created requirement-verification-questions.md (15 questions + Security Baseline + PBT opt-ins, in Dutch). Finding: CMS lives in separate repo SlpModularCms; sibling repo AndreaSlopFotografie-cms-api-foundation holds its feature briefs and a completed contact-page feature with its own ContactForm." + +**Context**: Requirements Analysis, Step 6 (questions). Awaiting user answers. + +--- + +## Requirements Analysis — Interactive Answers + +**Timestamp**: 2026-11-09T14:10:00Z + +**User Input**: "stuur mij de vragen hier interactief" + +**AI Response**: "Asked all questions interactively in chat (AskUserQuestion) at the user's request instead of the file. Answers: Q1 A (B+E fully), Q2 B (icon only), Q3 A (variant not remembered), Q4 A (red/purple removed), Q5 B (follow system), Q6 A (generic, category from API, chips from 4), Q7 A (always swipe row on mobile), Q8 A (extra packages content out of scope), Q9 A (basic fields), Q10 A (API stores + mails), Q11 B (reusable module), Q12 C (honeypot/time/rate-limit + captcha fallback), Q13 A (privacy sentence), Q14 A (WCAG AA + reduced motion), Q15 C (operations undecided), Security A (enabled), PBT B (partial), Q16 follow-up on Q11: A (headless + theme slots). Answers copied into requirement-verification-questions.md. Wrote requirements.md; updated aidlc-state.md Extension and Operations configuration." + +**Context**: Requirements Analysis, Steps 6-7. Completion message presented; awaiting approval. Note: Q11-B implies CMS repo SlpModularCms delivers the form module; form coordination notice to user still due before form build starts. + +--- + +## Requirements Analysis — Approval + +**Timestamp**: 2026-11-09T14:30:00Z + +**User Input**: "goed idee, ga verder" + +**AI Response**: "Requirements approved (User Stories remain skipped). 'Goed idee' read as agreement with attaching the CMS session at Workflow Planning/Application Design; no cross-session message sent yet because the user said they themselves attach the sessions — AI will offer a ready briefing and ask which sessions to message. Created execution-plan.md: Application Design EXECUTE, Units Generation EXECUTE (5 units U1-U5), Functional Design U1/U3/U4, NFR Requirements+Design U4/U5, Infrastructure Design U4, Operations undecided." + +**Context**: Workflow Planning. Completion message presented; awaiting approval. + +--- + +## Workflow Planning — Sessions to Attach + +**Timestamp**: 2026-11-09T14:45:00Z + +**User Input**: "`CMS & API`, `AndreaSlopFotografie` en `SLS Software - CMS` zijn de andere sessies. de 1e is de website sessie van andreaslopfotografie. De 2e is de cms sessie van ASF. de laatste is de cms sessie van SLP Software" + +**AI Response**: "Verified via ListAgents: all three exist and are idle (SLS Software - CMS = [9d882f], formerly listed as slpmodularcms-f7). Recorded in aidlc-state.md Coordination Notes. No messages sent yet; plan approval for Workflow Planning still pending." + +**Context**: Workflow Planning; coordination input. + +--- + +## Workflow Planning — Sessions Briefed Early + +**Timestamp**: 2026-11-09T15:00:00Z + +**User Input**: "Is het niet slim de andere sessies meteen mee te nemen? Misschien hebben zij nog wat anders nodig. Dat is waarom ik zei dat je dat moest doen. De sessie `AndreaSlopFotografie` van de cms die hoef je niet per se te vragen. Ik denk dat CMS & API meer context heeft van het foprmulier op de website. UIteindleijk moet het in SLS Software - CMS worden gebouwd. Je kan de cms sessie van AndreaSlopFotografie wel gfebruiken om misschien het een en ander tegen te controleren." + +**AI Response**: "Agreed. Sent briefings with questions (no build, no changes requested) to CMS & API [df4818] and SLS Software - CMS [9d882f], both with idle notification. AndreaSlopFotografie [7d5867] kept as later cross-check reviewer. Replies will be folded into the form contract in Application Design." + +**Context**: Workflow Planning; cross-session coordination. Plan approval still not explicit. + +--- + +## Cross-session Reply — SLS Software - CMS + +**Timestamp**: 2026-11-09T15:20:00Z + +**User Input**: "(cross-session message from SLS Software - CMS, not typed by the user)" + +**AI Response**: "Recorded reply. Fit: mostly yes (modular setup, per-site hosts Api.SlpSoftware/Api.AndreaSlopFotografie, IEmailSender in Core/Email returning MailSendResult, AddCmsRateLimiting extensible with own policy, Sentry/SecurityEvents). Missing: Contact/Forms module (+tests), message storage (table + migration), honeypot/time check, retention-cleanup job. Rule: store first, mail best-effort, keep status. `category` on offerings: small change (model, migration, DTO, admin form), optional string/enum per site, empty = no chip. Module: small package (e.g. @slp/cms-forms) in SlpModularCms, consumed first via pnpm workspace/file dependency or tagged copy; private registry (Gitea packages) only with a third consumer — a decision for Bryan. Contract: OpenAPI as source of truth plus short markdown with behaviour agreements (spam rules, error codes, retention); versioned via /api/v1 and semver on package; AI drafts, CMS side delivers final OpenAPI and checks deviations. Parallel work possible once contract fixes fields, validation limits, error shape, honeypot/time field names. Suggestions: (a) server-signed timestamp token from GET for the time check, (b) idempotency key against double submit, (c) same 202/identical response on spam detection, (d) no email/message in logs or Sentry breadcrumbs (scrub), (e) site-id from host/config, not request body. Open for Bryan: retention period, required fields, captcha fallback yes/no." + +**Context**: Pending reply from CMS & API [df4818]. Open decisions to ask the user: retention period, package consumption route. + +--- + +## Cross-session Reply — CMS & API (ASF website) + +**Timestamp**: 2026-11-09T15:35:00Z + +**User Input**: "(cross-session message from CMS & API, not typed by the user)" + +**AI Response**: "Recorded. ASF form today: fields naam (max 100), email (max 254, regex /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/), shoot (select, required, value = package id or 'overig'), bericht (max 2000); trimmed payload {naam,email,shoot,bericht}; first failing rule per field wins (required, length, format); NL messages baked in; errors on blur of touched field or on submit, focus first error, noValidate; statuses editing/sending/sent/failed via pure reducer (input kept on failed; edits and second submit ignored while sending); preselect via ?pakket= with key counter so same choice can be re-applied; unknown value ignored; query string read stays in the site router. No backend yet: submit throws, form behind ContactFormGate (inert, mailto shown, address assembled after hydration). Planned: POST /api/contact JSON + Friendly Captcha token; generic failure message; honeypot 'website' hidden field + time check (<3000 ms = spam); spam gets the thanks message but nothing is sent; API repeats checks. Privacy: one sentence with link to /privacyverklaring, no checkbox (PrivacyNote); success replaces form, focus + role=status, site-configurable reply time. Module needs: headless hook/state (values, errors, status, onChange/onBlur/onSubmit, preselect with change counter), pure reducer/validation testable, idPrefix for field ids, render slots (honeypot, robot check, status message), injectable texts/i18n, per-site options and reply time, injectable submit function, mailto fallback path without address in HTML, recipient server-side per site. Pitfalls: a11y (labels, errors linked, role=alert on server error, role=status + focus on success, honeypot invisible to AT), CSP extension for API + captcha, no inline scripts/styles, prerender/hydration safety (no Date.now differences; useState(() => Date.now())), captcha widget not in SSR HTML, rate limit needs ForwardedHeaders:KnownProxies for real client IP, mail via IEmailSender (sender allow-list, per-site sender), retention in privacy statement." + +**Context**: Input for the form contract in Application Design. Note difference with SLS CMS suggestion (server-signed timestamp token vs client time check) to reconcile in the contract; ASF plans Friendly Captcha (captcha fallback provider to settle). + +--- + +## Requirements Analysis — Follow-up Decisions (interactive) + +**Timestamp**: 2026-11-09T15:40:00Z + +**User Input**: "12 maanden, maar ik wil ze later gebruiken om voor de amdinistratie een opdracht in het systeem te kunnen zetten waaruit ik offertes en facturen kan opmaken. Dat wil ik nu nog niet doen, maar dat idee zit er wel achter. Dan weet je dat vast." / "Ik dacht dat het om de module ging in de API. Net zoals die van offerings. Maar dit is een front-end package heb ik het idee? Ik wil even weten wat de meerwaarde is dus die mag je even toelichten. Verder wil ik consistentie dus zou zoiets bij de offerings ook kunnen dan?" / "Alle vier verplicht (Recommended)" + +**AI Response**: "Retention 12 months recorded; future idea (turn a message into an assignment for quotes and invoices) noted as out of scope but the stored message entity must stay extensible (status, id, no destructive design). All four fields required. Package question: user thought the module was an API module like Offerings; clarified there are two parts (API module + optional frontend package) and asked to decide after explanation." + +**Context**: Requirements follow-up; requirements.md to be amended (retention 12 months, all fields required, future quotes/invoices idea, package decision pending). + +--- + +## Requirements Analysis — Frontend Package Decision + +**Timestamp**: 2026-11-09T15:55:00Z + +**User Input**: "Één cms-client-pakket. Elk onderdeel wel los te importeren zodat een site niet alles importeert als die het niet gebruikt, maar wel dat het 1 package is." + +**AI Response**: "Decision recorded: one frontend package (working name cms-client) with separately importable subparts (subpath imports), plus an API module in SlpModularCms. requirements.md amended (FR-13 all fields required, FR-14 retention 12 months and store-first/mail-best-effort, FR-14a future quotes/invoices idea, FR-16 hardening suggestions, FR-18 two-part module, NFR-5). Briefing both sessions of the decisions." + +**Context**: Requirements amended after approval question; Workflow Planning approval still pending. + +--- + +## Cross-session Message — SLS Software - CMS (contract requirements) + +**Timestamp**: 2026-11-09T16:05:00Z + +**User Input**: "(cross-session message from SLS Software - CMS, not typed by the user)" + +**AI Response**: "Decisions acknowledged, no objections, nothing being built. Requests for the contract: (1) fix the error shape (e.g. ProblemDetails with field errors) and the rate-limit response (429 + Retry-After); (2) state that stored messages get their own id and a status so they can later become an assignment. They note the final API-side check should come from the 'CMS & API' session; per the user, that session is the ASF website session and the ASF CMS session is 'AndreaSlopFotografie', so the API-side cross-check goes to AndreaSlopFotografie. No reply needed." + +**Context**: Input for the form contract in Application Design; awaiting user go-ahead for Application Design. + +--- + +## Cross-session Message — CMS & API (no deviating wishes) + +**Timestamp**: 2026-11-09T16:15:00Z + +**User Input**: "(cross-session message from CMS & API, not typed by the user)" + +**AI Response**: "Recorded: no deviating ASF wishes for captcha or privacy sentence; Friendly Captcha fits (existing [data-robot-check] slot); privacy sentence stays one sentence with link to /privacyverklaring, no checkbox. Addition for the contract: recipient, retention period and privacy link/text configurable per site. FR-17 in requirements.md updated. They are happy to review the draft contract." + +**Context**: Input for Application Design; still awaiting the user's go-ahead on the Workflow Planning approval. + +--- + +## Workflow Planning — Approval + +**Timestamp**: 2026-11-09T16:30:00Z + +**User Input**: "okee top, ga verder" + +**AI Response**: "Workflow Planning approved. Starting Application Design: asking the design questions interactively in chat (user's earlier preference), recording answers in application-design-plan.md, then producing the design artifacts and the draft form contract for the CMS sessions." + +**Context**: Workflow Planning approved; Application Design started. + +--- + +## Application Design — Completed, Contract Sent for Review + +**Timestamp**: 2026-11-09T17:10:00Z + +**User Input**: "(interactive answers) Q1 Gedeelde laag + eigen weergave; Q2 Alleen in de app; Q3 Hier voorbouwen, dan overdragen" + +**AI Response**: "Created application-design-plan.md, components.md, component-methods.md, services.md, component-dependency.md, contact-api-contract.md (v0.1.0-draft) and consolidated application-design.md. Sent the draft contract for review to SLS Software - CMS [9d882f], CMS & API [df4818] and AndreaSlopFotografie [7d5867] (ASF CMS, cross-check only), each with idle notification. This is the form-coordination moment the user asked for. Approval prompt for Application Design presented to the user: Request Changes / Continue to Units Generation." + +**Context**: Application Design, awaiting approval. + +--- + +## Contract Reviews Received and Product Decisions + +**Timestamp**: 2026-11-09T18:20:00Z + +**User Input**: (interactive answers) "Ja, volledig (Recommended)" for admin view Berichten in the CMS; "Opslaan als 'spam' (Recommended)" for honeypot/too-fast submissions; "Doorlaten (Recommended)" for captcha provider failure. + +**AI Response**: "Folded three cross-session reviews (SLS Software - CMS, CMS & API, AndreaSlopFotografie) into contact-api-contract.md v0.3.0-draft: Retry-After and own ProblemDetails (new work in OnRejected), ICaptchaVerifier, idempotency table, DataProtection tokens, mail after commit with retry job and mailAttempts, admin endpoints (list/detail/status/delete/resend, capabilities entry), spam stored as status spam for 30 days, honeypot renamed hpCheck (autofill), 503 availability gate with mailto fallback, subject opaque value with per-site label for other, messages[field][code] with ASF-equal Dutch defaults, lazy token after hydration, captcha slot data and CSP notes per provider, no nginx hard-coding (ASF production IIS), env-only recipient/sender for ASF, backups vs retention note, KnownProxies per host. Open: category list location (appsettings vs free text), ASF migration to cms-client (separate ASF-web feature)." + +**Context**: Application Design; awaiting final approval after contract confirmation by the builders. + +--- + +## Contract v0.3.1 — Final Review Comments and Category Decision + +**Timestamp**: 2026-11-09T19:00:00Z + +**User Input**: "Vaste lijst per site (Recommended)" (interactive answer: category list is a fixed list per site in appsettings, no free text) + +**AI Response**: "Folded comments of AndreaSlopFotografie (text fix on spam; spam row cap) and SLS Software - CMS (mail via BackgroundService + sweep + backoff; spam cap per day, excluded from unread counter and default list, retentionUntil +30d per row; DataProtection key ring persistent per host with per-site purpose; availability bypass = policy decision, default no bypass; OnRejected/Retry-After as separate first CMS unit; resend rate-limited; hard delete; idempotency record without PII; category migration; suggested CMS build order a-f) into contact-api-contract.md v0.3.1-draft. Category decision recorded." + +**Context**: Application Design awaiting approval; no open product decisions left for the contract except confirmation by the builders and the policy question on the availability bypass. + +--- + +## Availability Gate Decision + +**Timestamp**: 2026-11-09T19:30:00Z + +**User Input**: "De statussen blokkeren alleen het CMS. De master blokkeert alleen het wijzigen van data en instellingen, maar de content zal altijd beschikbaar blijven." + +**AI Response**: "Recorded in contact-api-contract.md § 1: the availability statuses block only the CMS/admin; public content stays available. Interpreted the public contact routes (token + submit) and GET offerings as public content that must stay reachable; the CMS must align AvailabilityMiddleware (currently 503 for all /api/). Mailto fallback remains as a safety net for network errors/503. Interpretation of the contact submit as public (not a CMS data change) flagged for the user." + +**Context**: Application Design; contract v0.3.1 amended. + +--- + +## Builder of the CMS/API Side + +**Timestamp**: 2026-11-09T19:50:00Z + +**User Input**: "`SLS Software - CMS` heeft nog niks gebouwd, dat klopt, maar die sessie heb ik wel bedoeld als bouwer van de CMD/API kant." + +**AI Response**: "Recorded: SLS Software - CMS [9d882f] is the intended builder of the CMS/API side. The session itself had stated it is not the build session; relayed the user's statement and asked it to report any reason against. Not a build order: the user has not yet instructed it to start." + +**Context**: Application Design / coordination. + +--- + +## Cross-session Message — SLS Software - CMS Accepts Builder Role + +**Timestamp**: 2026-11-09T20:00:00Z + +**User Input**: "(cross-session message from SLS Software - CMS, not typed by the user)" + +**AI Response**: "Recorded: SLS Software - CMS accepts the builder role for SlpModularCms (branch feature/identity-email-notifications is clean; no role/repo agreement against it). Will not build until Bryan gives the order. Before starting: read contract v0.3.1 fully, walk through build order a-f, create a new feature branch from master (current branch belongs to other work); build and test per unit." + +**Context**: Coordination; awaiting the user's start order for the builder and go-ahead for Units Generation. + +--- + +## Leading the Builder Session + +**Timestamp**: 2026-11-09T20:20:00Z + +**User Input**: "de bouwer moet ook aidlc gebruiken. De bouwer moet ook nog even rekening houden met de huidige sessie `AndreaSlopFotografie`. Die zit in de laatste fase, maar is nog niet helemaal afgerond. Ik wil dat jij die bouwer leidt en vragen zelf beantwoord aan de hand van de kennis die je hebt. Vragen die je niet kan beantwoorden mag je doorsturen zodat ik dat kan doen. Ik zal tegen die sessie zeggen dat jij namens mij toestemming mag geven." + +**AI Response**: "Sent the builder (SLS Software - CMS [9d882f]) an assignment: use aidlc (Feature lane) in its own repo with contract v0.3.1 as input, build order a-f with per-unit build+test, new branch from master after coordinating with AndreaSlopFotografie, send stage completions to Redesign - SLS (approved by AI where within Bryan's decisions, otherwise forwarded to Bryan), no Code Generation before plan approval, no push/merge/PR without explicit order. Asked AndreaSlopFotografie [7d5867] which branches/areas of SlpModularCms it still touches, when it merges and what the builder must know." + +**Context**: Coordination. Authority limits: AI answers builder questions from known decisions; forwards unknowns to the user; major/irreversible actions (push/merge/PR) still need explicit user order." + +--- + +## Cross-session Reply — AndreaSlopFotografie (SlpModularCms coordination) + +**Timestamp**: 2026-11-09T20:40:00Z + +**User Input**: "(cross-session message from AndreaSlopFotografie, not typed by the user)" + +**AI Response**: "Recorded and relayed to builder SLS Software - CMS: ASF work lives on SlpModularCms branch feature/identity-email-notifications (HEAD e17d967, pushed, ~56 commits/~300 files ahead of master, awaiting deploy + manual test by Bryan, merge only on Bryan's decision). The builder's current checkout is on that same branch: told it NOT to switch branches there and to use a separate git worktree from master. Conflict areas on later rebase: appsettings (Email, RateLimiting), Program.cs/host-config, AvailabilityMiddleware, EF migrations (regenerate own migration after rebase). Contact mail: add a new MailKind, keep dark-mode contrast, secrets via env. Availability gate: marker attribute [PublicSiteEndpoint] via endpoint metadata (deny-by-default, tests for admin 503, ~6-10 tests affected), as own unit with (b). Spam rows per-site cap and separate admin view. Builder to send plan after Inception for approval." + +**Context**: Coordination with builder; Code Generation still gated on plan approval. + +--- + +## Builder Requirements Questions Answered + +**Timestamp**: 2026-11-09T21:00:00Z + +**User Input**: "(cross-session message from SLS Software - CMS asking to answer 8 requirement questions; earlier user instruction: AI leads the builder and answers within known decisions)" + +**AI Response**: "Answered: Q1 A (Security on), Q2 B (PBT partial), Q3 C (Operations undecided - to put to Bryan), Q4 A (Modules.Contact + Tests), Q5 A (own DbContext, MySQL, Migrate at startup, regenerate migration after rebase), Q6 A ([PublicSiteEndpoint] marker, deny-by-default), Q7 A (targeted review), Q8 A (admin UI last after ASF merge). Builder worktree: K:\Development\Projects\SlpModularCms-contact-forms, branch feature/contact-forms-module from master d9cc539; main checkout untouched." + +**Context**: Leading the builder; open for Bryan: Operations phase for the CMS side (Q3). +--- + +## Builder Requirements Approved + +**Timestamp**: 2026-11-09T21:30:00Z + +**User Input**: "(cross-session messages from SLS Software - CMS: requirements ready, correction that the file now exists)" + +**AI Response**: "Read K:\Development\Projects\SlpModularCms-contact-forms\aidlc-docs\features\contact-forms-module\inception\requirements\requirements.md (D1-D12, review findings, R1-R3). Approved. Decided R1: build units a, b, c, e on master base with the mail sender behind an own small interface; units d (mail+retry on Core/Email) and f (admin UI) after the merge of feature/identity-email-notifications and a rebase; that merge is Bryan's decision. Builder continues with Workflow Planning and sends the execution plan for approval; no Code Generation yet." + +**Context**: Leading the builder. Dependency for the user: the merge of the ASF branch gates units d and f. + +--- + +## Application Design — Approval and Units Generation + +**Timestamp**: 2026-11-09T21:50:00Z + +**User Input**: "ja ga ondertussen verder met units generation" / (interactive answer) "Formulier eerst (Recommended)" + +**AI Response**: "Application Design treated as approved (user told to continue with Units Generation). Question: order of last two frontend units answered A (U4 form before U5 E). Generated unit-of-work-plan.md, unit-of-work.md (U1-U5 plus external X-a..X-f), unit-of-work-dependency.md and unit-of-work-story-map.md (requirements-to-unit map). Completion message presented; awaiting approval." + +**Context**: Units Generation complete. + +--- + +## Builder Execution Plan Approved + +**Timestamp**: 2026-11-09T22:00:00Z + +**User Input**: "(cross-session message from SLS Software - CMS: Workflow Planning ready for approval)" + +**AI Response**: "Read-through of the builder's summary and approved the execution plan: phase 1 on master base (CMS-U1 category, CMS-U2 OnRejected + [PublicSiteEndpoint], CMS-U3 Modules.Contact, CMS-U4 admin API), phase 2 after Bryan's merge of feature/identity-email-notifications (CMS-U5 mail + retry, CMS-U6 admin UI). Agreed that Application Design (minimal) and Units Generation may be sent together and approved together if within the contract and decisions. Per-unit Code Generation plans go to this session for approval; CMS-U1 starts only after that." + +**Context**: Leading the builder. Note: the execution-plan.md of the builder was approved on the basis of the builder's summary (file path given). + +--- + +## Builder Application Design and Units Approved + +**Timestamp**: 2026-11-09T22:15:00Z + +**User Input**: "(cross-session message from SLS Software - CMS: Application Design (minimal) + Units Generation ready)" + +**AI Response**: "Approved. Decision 1: follow repo convention for admin routes (GET /api/v1/contact-messages/admin, .../admin/{id} GET/PATCH/DELETE, POST .../admin/{id}/resend with policy RateLimiting:ContactResend); the gate test iterates all endpoints without [PublicSiteEndpoint]. Contract § 6, § 10a updated. Decision 2: accepted correction, DataProtection is host-level (AddCmsDataProtection, keys in DB), Contact only uses IDataProtector purpose SlpModularCms.Contact.Token.{siteId}; contract § 2.1 note added. Other items (config keys, rate limits, openapi/cms-api.v1.json snapshot test, Contact only in Api.SlpSoftware in phase 1) accepted. Next: builder sends Code Generation plan for CMS-U1." + +**Context**: Leading the builder. Files were approved on the basis of the builder's summary. + +--- + +## Builder CMS-U1 Code Generation Plan Approved + +**Timestamp**: 2026-11-09T22:40:00Z + +**User Input**: "(cross-session message from SLS Software - CMS: CMS-U1 plan for approval; file read in full)" + +**AI Response**: "Read K:\Development\Projects\SlpModularCms-contact-forms\aidlc-docs\features\contact-forms-module\construction\plans\cms-u1-offerings-category-code-generation-plan.md and approved. Q1: initial categories [Websites, Software, Beheer] (config only; content confirmation still to be put to Bryan). Q2: add a small separate unit CMS-U1b (admin form dropdown) right after CMS-U1, before CMS-U2, only touching frontend/src/features/offerings. One commit per unit, no push/merge/PR; builder to report real test output." + +**Context**: Leading the builder. Open for Bryan: confirm that categories Websites/Software/Beheer fit the offering (unanswered since the start). + +--- + +## Route Design Decision — No /admin Segment + +**Timestamp**: 2026-11-09T23:10:00Z + +**User Input**: "waarom zit er in de routes van de api uberhaubt een /admin-deel? Dat is onnodig. ik wil het zo RESTful mogelijk houden. Dat de admin het mag gebruiken betekent niet dat er per se een admin route moet zijn. Admin kan gewoon POST, PUT DELETE en GET doen" + +**AI Response**: "Decision recorded in contract § 6: RESTful routes without /admin; authorization policy AdminOnly for admin use, [PublicSiteEndpoint] marker for public endpoints; contact-messages: POST + GET token public, GET list/GET,PATCH,DELETE {id:guid}, POST {id}/resend AdminOnly; offerings categories at GET /api/v1/offerings/categories (AdminOnly). Builder told to adjust CMS-U1 (in build) before committing. Existing offerings/admin... routes and Availability admin/status left untouched; possible RESTful refactor of them put to the user as a later follow-up." + +**Context**: Leading the builder; affects contract and CMS-U1. + +--- + +## Category Decision Revised — CMS-managed Data + +**Timestamp**: 2026-11-09T23:40:00Z + +**User Input**: "Over de catagorie-vraag. Op dit moment had ik nog helemaal geen plan om categorieën te gebruiken, dus ik heb er nog niet over nagedacht. De categorieën kunnen in het cms toegevoegd worden neem ik aan? Niet via de settings. Dat wordt te onhandig. De categorieën mogen in een soort sub-scherm het hoeft geen volledig nieuwe pagina te worden, maar gewoon onderdeel van offerings. Voor als het handig is om te weten. Ik denk dat ik begin met de categorieën Websites en Onderhoud. Als biedt ik voor nu totaalpakketten aan en nieuwbouw. Over overname had ik nog niet nagedacht namelijk." + +**AI Response**: "Revised: categories are CMS data (OfferingCategory entity with CRUD under /api/v1/offerings/categories, AdminOnly), managed in a sub-section of the Offerings admin; starting categories Websites and Onderhoud created by Bryan in the CMS; Offering.categoryId FK; public offerings keep category as name string; delete of used category rejected with 409. Contract § 7 and requirements FR-8 updated (placeholders Websites/Software/Beheer replaced by Websites/Onderhoud). Builder told to send a revised CMS-U1 plan before committing and that CMS-U1b grows into a categories sub-section plus a dropdown in OfferingForm." + +**Context**: Leading the builder; supersedes D4 and the approved CMS-U1 plan. + +--- + +## Existing /admin Routes Refactored Now + +**Timestamp**: 2026-11-10T00:00:00Z + +**User Input**: "Over de bestaande routes. Dat klopt, dat is niet goed gegaan. Die routes wil ik nu ook aanpassen. Meteen meenemen want nu ben ik beide websites aan het onderhouden voor dit soort dingen. Dus ik doe het liever nu dan later" + +**AI Response**: "Decision recorded in contract § 10 and unit-of-work.md (X-0 Offerings routes now in phase 1 before the category units; X-g Availability status route in phase 2 after the ASF merge). Builder told: new unit CMS-U0 offerings-restful-routes first (incl. admin frontend call sites, tests, OpenAPI snapshot), open design question public vs admin DTO on the same URL (AI preference: one URL, public DTO for anonymous, extended DTO for authorized admins, builder to weigh alternatives), reorder as collection action instead of move-up/down, then CMS-U1 category on the new routes and CMS-U1b. Availability admin/status becomes PUT only in phase 2 because the ASF branch touches Availability and master/slave callers. Other controllers only reported if relevant." + +**Context**: Leading the builder; scope extension decided by the user. + +--- + +## Builder CMS-U0 and CMS-U1 v2 Plans Approved + +**Timestamp**: 2026-11-10T00:30:00Z + +**User Input**: "(cross-session message from SLS Software - CMS: merged plan CMS-U0 + CMS-U1 v2; both plan files read in full)" + +**AI Response**: "Approved CMS-U0 (RESTful offerings routes, DTO choice A: one URL and one OfferingDto for everyone, displayOrder added, OfferingAdminDto removed, order route PUT /offerings/order, move-up/down removed, no old routes kept) and CMS-U1 v2 (OfferingCategory entity, nullable Offering.CategoryId FK Restrict, CRUD under /offerings/categories AdminOnly, 409 for duplicate/in-use, 400 errors.categoryId invalid, offeringCount in list, nothing seeded). Extras: run the 4 failing Api.Tests on the clean worktree to document the baseline; test 201+Location and order-route validation; verify rename is immediately visible on the public GET; keep git stash until U1 v2 is done. Contract § 7 updated with additive fields and write routes. Order: U0 -> U1 -> U1b -> U2 -> U3 -> U4 | merge | U5 -> U6 -> U7 (Availability PUT)." + +**Context**: Leading the builder. v1 of CMS-U1 was built (74 tests green) but stashed, not committed. + +--- + +## Units Generation Approved; CMS-U0 Accepted + +**Timestamp**: 2026-11-10T01:10:00Z + +**User Input**: "moeten we voor lokaal een mariadb opzetten voor ASF? Dan moet ik dat even gaan doen. Voor jouw frontendheb je akkoord en kan je verder" + +**AI Response**: "Answered the MariaDB question (CI uses mariadb:11 on port 3307; same container locally lets Api.Tests run; not ASF-specific). Units Generation approved by the user: proceeding to Construction, U1 theme-foundation Functional Design. Builder reported it had already started a temporary podman MariaDB (slp-contact-test-db, port 3306) following the earlier allowance; baseline proven (Api.Tests 4/4 fail without database, 4/4 pass with database on clean master). CMS-U0 commit d62b33d reviewed (controller, stat) and accepted; Offerings.Tests 52, Core 196, Availability 82, Identity 37, Master 57, Api 4 passed; frontend vitest 260 passed, eslint and tsc clean. Prettier warnings on 15 untouched files recorded as tech-debt note only." + +**Context**: Construction phase start for the frontend; builder continues with CMS-U1 v2. + +--- + +## U1 Functional Design Questions (interactive) + +**Timestamp**: 2026-11-10T01:15:00Z + +**User Input**: (interactive) "Naar boven (Recommended)"; "Tweestanden (Recommended)"; "Tijdreis-effect" + +**AI Response**: "U1 FD answers: variant switch scrolls to top; mode button is two-state (follows system until the user clicks, then persisted); variant switch uses a short time-travel effect (dither/flash toward E and back), disabled under reduced motion." + +**Context**: Functional Design U1. + +--- + +## U1 Functional Design Complete + +**Timestamp**: 2026-11-10T01:40:00Z + +**User Input**: "(none)" + +**AI Response**: "Generated theme-foundation-functional-design-plan.md, theme-foundation-fd-questions.md (answers A, A, C), and construction/theme-foundation/functional-design/{domain-entities, business-rules, business-logic-model, frontend-components}.md with Mermaid diagrams. Key decisions: /theme-init.js as blocking same-origin script to avoid theme flash (no inline script); two-state mode button following system until first click; variant never persisted and not in URL; time-travel dither transition (cover, swap, reveal) disabled under reduced motion; E lazy chunk with error boundary falling back to B. Completion message presented; awaiting approval." + +**Context**: Construction, Functional Design U1; next stage for U1 is Code Generation (NFR Requirements/Design/Infrastructure skipped for U1 per execution plan). + +--- + +## Builder CMS-U1 v2 Accepted + +**Timestamp**: 2026-11-10T02:00:00Z + +**User Input**: "(cross-session message from SLS Software - CMS: CMS-U1 v2 done, commit f2ac377)" + +**AI Response**: "Accepted CMS-U1 v2: OfferingCategory table + Offering.CategoryId FK Restrict, migration AddOfferingCategories, CRUD under /offerings/categories (AdminOnly, 409 duplicate and in-use, soft-deleted offerings detached in same transaction), OfferingDto category name + additive categoryId and displayOrder, nothing seeded; Offerings.Tests 84, Core 196, Availability 82, Identity 37, Master 57, Api 4 passed; migration verified on a real MariaDB. Rename is immediately visible (no response caching in code; nginx/IIS must not cache /api/v1/offerings long: to Operations list). Stash cms-u1-v1 may be dropped. Next: CMS-U1b plan." + +**Context**: Leading the builder. + +--- + +## Builder CMS-U1b Plan Approved + +**Timestamp**: 2026-11-10T02:20:00Z + +**User Input**: "(cross-session message from SLS Software - CMS: stash dropped, CMS-U1b plan; plan file read in full)" + +**AI Response**: "Approved CMS-U1b (categories dialog inside the Offerings list, select with 'Geen categorie' in OfferingForm, badge on OfferingRow, Dutch error messages, query invalidation, mocks without seed, tests). Remarks: verify query key after CMS-U0 and add a rename-visible-without-reload test. Stash e5e3652 dropped by the builder (superseded). Next: CMS-U2 plan." + +**Context**: Leading the builder. + +--- + +## U1 Functional Design Approved; Code Generation Plan Ready + +**Timestamp**: 2026-11-10T03:00:00Z + +**User Input**: "akkoord, ga verder" + +**AI Response**: "Functional Design U1 approved. Created construction/plans/theme-foundation-code-generation-plan.md (13 steps: preparation, font dependency, tokens, media-query hooks, CSS tokens, theme-init.js, ThemeProvider, toggles/renderer/overlay/boundary, layout integration, tests, build+test, docs, commit). Approval prompt for the plan presented: Request Changes / Approve Plan." + +**Context**: Code Generation Part 1 (planning) for U1. + +--- + +## Builder CMS-U1b Accepted; CMS-U2 Plan Approved + +**Timestamp**: 2026-11-10T03:20:00Z + +**User Input**: "(cross-session message from SLS Software - CMS: CMS-U1b done, commit 20f4c3c; CMS-U2 plan; plan file read in full)" + +**AI Response**: "Accepted CMS-U1b (categories dialog, select, badge, query key renamed to ['offerings','list'], fixes for star button clearing category and Radix empty value; lint, tsc -b clean, vitest 42 files / 278 tests). Approved CMS-U2 (PublicSiteEndpoint marker, OnRejected 429 with Retry-After + problem+json, route-table test, only GetOfferings marked now). Flagged release prerequisite: on CMS master rate-limit policies are global buckets; per-client partitioning (ClientPartitionKey, ForwardedHeaders) exists only on the ASF branch, so the contact routes must not go live on a public host before it is on the base branch. Added to contract § 4.5; builder to include in CMS-U2 summary and CMS-U3 plan." + +**Context**: Leading the builder. Add to Operations list/open for Bryan: ASF merge is a prerequisite for enabling the contact routes publicly. + +--- + +## Builder CMS-U2 Accepted; CMS-U3 Plan Approved + +**Timestamp**: 2026-11-10T03:50:00Z + +**User Input**: "(cross-session message from SLS Software - CMS: CMS-U2 done, commit 9e8e8ef; CMS-U3 plan; plan file read in full)" + +**AI Response**: "Accepted CMS-U2 (marker, OnRejected 429 + Retry-After, route-table tests; Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api 4 passed; real-pipeline smoke test with CMS disabled). Approved CMS-U3 (Modules.Contact + Tests, own DbContext, token via DataProtection, spam path stored with 30 days and daily cap, idempotency table, retention job, Contact:Enabled=false default giving 404 as in-code release condition, rate-limit partition key function constant 'global' on master). Answers: Contact:Enabled default false with 404 OK; ProblemDetails type configurable default about:blank OK; OpenAPI export split into CMS-U3b OK. Contract updated (§ 3 type, § 5 Contact:Enabled). Additions requested: rebase checklist with exact line, retention job inert when disabled, no token/idempotency key in logs, list of Contact:* keys in the summary." + +**Context**: Leading the builder. Frontend: 404 on the token route means form unavailable, fall back to mailto (to design in U4). + +--- + +## Form Builder and On/Off Switch Decisions; U1 Plan Approved + +**Timestamp**: 2026-11-10T04:20:00Z + +**User Input**: "Krijgen we voor het formulier een soort builder waarin je kan aangeven welke velden er zijn of is het een vast aantal velden? Als de velden uiteen gaan lopen zou zoiets wel handig zijn. Maar als dat nu nog niet wordt meegenomen komt dat later wel. Al moet contactformulier ook nog aangezet kunnen worden." / (interactive) "Nu vaste velden (Recommended)"; "Beide lagen (Recommended)" / "Akkoord op jouw bouwplan" + +**AI Response**: "Recorded: fixed fields now (builder later as own feature); two-layer on/off switch (host Contact:Enabled plus a CMS switch via singleton GET/PUT /api/v1/contact-settings, default off, form active only when both on, 404 when either is off, switch visible in the Berichten screen; CMS-U4/U6). Contract § 5a added. Builder to be told to build the CMS-U3 gate behind an interface. U1 Code Generation plan approved by the user; starting Part 2." + +**Context**: Code Generation U1 Part 2 starts. + +--- diff --git a/aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-code-generation-plan.md b/aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-code-generation-plan.md new file mode 100644 index 0000000..c743ab2 --- /dev/null +++ b/aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-code-generation-plan.md @@ -0,0 +1,48 @@ +# Code Generation Plan — theme-foundation (U1) + +Single source of truth for U1 Code Generation. Inputs: `unit-of-work.md` (U1), Functional Design in `construction/theme-foundation/functional-design/`, requirements FR-3..FR-6, NFR-1, NFR-3, NFR-7. + +## Unit context +- **Workspace root**: `K:\Development\SlpSoftware\Projects\SlpSoftware` (brownfield; modify in place, no `_new` copies). Branch `feature/redesign-modern-timetravel`. +- **Dependencies**: none. **Blocks**: U2..U5. **External**: none. +- **Owned entities**: `ThemeState`, `StoredMode`, `TransitionState`, token sets (see domain-entities.md). +- **Interim visual note**: U1 swaps the token values (B light/dark replace red/purple). Existing sections keep using the semantic Tailwind colors and are restyled to design B in U2. The branch is not deployed between units. +- **Story/requirement mapping**: FR-3, FR-4, FR-5, FR-6 (shell), NFR-1 (toggle a11y, reduced motion), NFR-3 (self-hosted font), NFR-7. + +## Files (modify = M, create = C, delete = D) +- M `package.json`, `pnpm-lock.yaml` (add `@fontsource-variable/archivo`), M `src/fonts.ts`, M `tailwind.config.ts` (font family key) +- M `src/theme/tokens.ts`, M `src/theme/ThemeProvider.tsx`, M `src/index.css` +- C `public/theme-init.js`, M `index.html` +- C `src/shared/hooks/usePrefersReducedMotion.ts`, C `src/shared/hooks/usePrefersDark.ts` +- C `src/components/ui/ModeToggle.tsx`, C `src/components/ui/VariantToggle.tsx`, D `src/components/ui/ThemeToggle.tsx` +- C `src/components/layout/VariantRenderer.tsx`, C `src/components/layout/TransitionOverlay.tsx`, C `src/components/layout/LiveRegion.tsx`, C `src/components/layout/EBoundary.tsx` +- C `src/variants/e/LandingE.tsx` (placeholder shell for the lazy chunk; real content in U5) +- M `src/components/layout/Nav.tsx`, M `src/components/layout/RootLayout.tsx` +- Tests: M `src/theme/__tests__/ThemeProvider.test.tsx`, M `src/components/layout/__tests__/Nav.test.tsx`, C `src/theme/__tests__/tokens.test.ts`, C `src/shared/hooks/__tests__/*.test.ts(x)`, C `src/components/layout/__tests__/VariantRenderer.test.tsx`, C `src/components/layout/__tests__/TransitionOverlay.test.tsx`, C `src/components/ui/__tests__/ModeToggle.test.tsx`, C `src/components/ui/__tests__/VariantToggle.test.tsx` +- Docs: C `aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/code/summary.md` + +## Steps +- [ ] **Step 0 — Preparation**: commit the AI-DLC inception/design documents separately (`aidlc-docs/`) on the branch so code commits stay clean. Verify the baseline: `pnpm test`, `pnpm lint`, `pnpm build` are green before changes (record the numbers). +- [ ] **Step 1 — Dependency and fonts**: add `@fontsource-variable/archivo` (variable weight + width axis) respecting the repo's pnpm settings; if the package is blocked by the release-age policy or missing, stop and report instead of working around it. Import it in `src/fonts.ts` next to the existing fonts (old fonts are removed in U2); add Tailwind `fontFamily.archivo`. +- [ ] **Step 2 — Tokens (pure logic)**: rewrite `src/theme/tokens.ts`: types `Variant`, `Mode`, `ModeSource`; constants `MODE_STORAGE_KEY = 'slp-software-mode'`, `LEGACY_THEME_STORAGE_KEY = 'slp-software-theme'`; pure functions `isValidMode`, `resolveInitialMode(stored, systemPrefersDark)` returning `{ mode, source }`. (BR-U1-1, 2, 11) +- [ ] **Step 3 — Media-query hooks**: `usePrefersReducedMotion`, `usePrefersDark` (SSR-safe, subscribe/unsubscribe, jsdom-safe when `matchMedia` is missing → defaults false). (BR-U1-3, 9) +- [ ] **Step 4 — CSS tokens**: in `src/index.css` replace `.theme-red/.theme-purple` with `html[data-variant='b'][data-mode='light'|'dark']` and E placeholders (`'e'`, light/dark, accent `#AC0000`) with the semantic variables; B accent `#7A1414`; transitions guarded by `prefers-reduced-motion`; add the dither overlay classes (checker mask + `steps()` keyframes, accent colored), all disabled under reduced motion. (FR-3, BR-U1-9) +- [ ] **Step 5 — No-flash script**: create `public/theme-init.js` (plain ES5, guarded storage access, sets `data-variant="b"` and `data-mode` on ``, mirrors `resolveInitialMode`); add `` (blocking, in ``) in `index.html`. No inline script. (BR-U1-5) +- [ ] **Step 6 — ThemeProvider**: rewrite with `variant`, `mode`, `modeSource`, `toggleMode`, `toggleVariant`, `transition`, `announce`; follow system changes while source is `system`; persist mode on user toggle (guarded); remove the legacy key once; apply data attributes in an effect; `toggleVariant` runs the phases cover → swap → reveal (timers, ~300 ms each), scrolls to top and moves focus to `#main` after the swap, immediate under reduced motion. (BR-U1-1..10, FR-5) +- [ ] **Step 7 — UI components**: `ModeToggle` (aria-pressed = dark, label "Donkere weergave", ≥44px target on mobile, `data-testid="mode-toggle-button"`), icon-only `VariantToggle` (label "Tijdreis: bekijk de site zoals vroeger" / "Terug naar nu", tooltip = label, `data-testid="variant-toggle-button"`), `TransitionOverlay`, `LiveRegion`, `EBoundary`, `VariantRenderer` (B eager, E via `React.lazy(() => import('../../variants/e/LandingE'))`, `Suspense` fallback = cover, error → B + alert + retry). Delete `ThemeToggle.tsx`. (FR-4, FR-6, BR-U1-6..8, 12) +- [ ] **Step 8 — Layout integration**: `Nav.tsx` shows `ModeToggle` then `VariantToggle` (desktop and mobile bar); `RootLayout.tsx` wraps content in `
`, renders `VariantRenderer` (B shell = Nav + page + Footer), `TransitionOverlay`, `LiveRegion`; `LandingE` is a minimal placeholder ("Tijdreis — in aanbouw") with its own nav containing the two toggles so the round trip is testable. `src/routes/__root.tsx` composition order unchanged. +- [ ] **Step 9 — Tests**: per the acceptance list in `frontend-components.md` (8 items): table-driven `resolveInitialMode`; ThemeProvider (first render, legacy key removal, system change following, user click stops following, persistence, storage failure, variant never persisted); variant switch (scroll to top, focus on `#main`, announcement, reduced-motion path with no overlay, failure path with alert + retry); accessibility attributes of both buttons; Nav test updates. Replace obsolete red/purple assertions. +- [ ] **Step 10 — Build and test (automatic, Step 13.5)**: `pnpm lint`, `pnpm test`, `pnpm build` (runs `tsc -b`). Fix and retry until green; report real counts. Manual smoke check of both modes via `pnpm build` output is not required. +- [ ] **Step 11 — Docs**: write `construction/theme-foundation/code/summary.md` (files, behaviour, how to use the hooks, notes for U2..U5, the `/theme-init.js` CSP/nginx note for Operations: must be served same-origin and not cached long). +- [ ] **Step 12 — Commit**: one commit for U1 code (Dutch message in the repo's style, `Co-Authored-By` line as required). No push. + +## Explicitly NOT touched in U1 +Section content and layout (Hero, About, Packages, Process, Contact), `content.ts`, `usePackagesQuery`, Sentry/Umami wiring, nginx configs, router. Old fonts stay until U2. The E variant's real content is U5. + +## Risks +- jsdom has no `matchMedia`/`scrollTo`: mocks live in `src/test/setup.ts` additions (Step 9). +- Dependency policy (release age) could block the font package: handled in Step 1 by reporting, not bypassing. +- The interim look changes (light default for many visitors) until U2; accepted because units are not deployed separately. + +## Traceability +FR-3, FR-4, FR-5, FR-6 (shell), NFR-1, NFR-3, NFR-7; Functional Design BR-U1-1..12; Security Baseline: no inline script (CSP), guarded storage access, no external font requests. diff --git a/aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-fd-questions.md b/aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-fd-questions.md new file mode 100644 index 0000000..5385b55 --- /dev/null +++ b/aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-fd-questions.md @@ -0,0 +1,25 @@ +# Functional Design Questions — theme-foundation (U1) + +Asked interactively in chat at the user's request (2026-11-10); answers copied here. + +## Question 1 — Scroll position when switching between B and E +- A) Go to the top of the page +- B) Stay in the same section +- X) Other + +[Answer]: A + +## Question 2 — How does the light/dark button work? +- A) Two states: toggles light and dark; starts from the system preference; after a click the choice is persisted +- B) Three states: system, light, dark +- X) Other + +[Answer]: A + +## Question 3 — Transition when switching to E and back +- A) Short fade (about 300 ms) +- B) Instant +- C) Time-travel effect (short retro dither/flash); off under reduced motion +- X) Other + +[Answer]: C diff --git a/aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-functional-design-plan.md b/aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-functional-design-plan.md new file mode 100644 index 0000000..8614fae --- /dev/null +++ b/aidlc-docs/features/redesign-modern-timetravel/construction/plans/theme-foundation-functional-design-plan.md @@ -0,0 +1,9 @@ +# Functional Design Plan — theme-foundation (U1) + +- [x] Analyze unit context (unit-of-work.md U1, requirements FR-3..FR-6, NFR-1, NFR-3, NFR-7) +- [x] Resolve design questions (asked interactively, see `theme-foundation-fd-questions.md`) +- [x] Generate `business-logic-model.md` (mode and variant flows, transition sequence) +- [x] Generate `business-rules.md` (BR-U1-1 .. BR-U1-12, decision flow) +- [x] Generate `domain-entities.md` (ThemeState, stored mode, TransitionState, token sets) +- [x] Generate `frontend-components.md` (component hierarchy, props/state, flows, acceptance tests) +- [x] Validate against requirements and Application Design diff --git a/aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/business-logic-model.md b/aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/business-logic-model.md new file mode 100644 index 0000000..cc3f848 --- /dev/null +++ b/aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/business-logic-model.md @@ -0,0 +1,45 @@ +# Business Logic Model — theme-foundation (U1) + +## Startup +1. `/theme-init.js` (blocking, same origin) reads the stored mode (guarded), falls back to `prefers-color-scheme`, and sets `data-variant="b"` and `data-mode` on ``. +2. `ThemeProvider` initializes its state with the same function (`resolveInitialMode`) so React and the script always agree; it removes the legacy key `slp-software-theme`. +3. `ThemeProvider` subscribes to the `prefers-color-scheme` media query; while `modeSource = 'system'` the mode follows it. + +## Mode toggle +`toggleMode()`: `mode = (mode === 'light') ? 'dark' : 'light'`, `modeSource = 'user'`, persist (guarded), update ``. + +## Variant switch (sequence) +```mermaid +sequenceDiagram + box rgba(99,179,237,0.4) Browser UI + participant U as Visitor + participant VT as VariantToggle + participant TP as ThemeProvider + participant TO as TransitionOverlay + end + box rgba(154,230,180,0.4) App + participant VR as VariantRenderer + end + U->>VT: click + VT->>TP: toggleVariant + TP->>TO: start cover + TO-->>TP: cover done + TP->>VR: set variant, load E chunk if needed + VR-->>TP: ready or failed + TP->>TP: scroll to top and move focus + TP->>TO: reveal + TP-->>U: announce result in live region +``` + +Text alternative: the click asks the theme provider to switch; the overlay covers the page; the renderer loads and swaps the variant; the provider scrolls, moves focus, reveals and announces. + +## Time-travel transition (effect) +- **cover**: a full-viewport overlay with a pixel-dither pattern (CSS `steps()` animation over a checker mask, accent-coloured) fades in over ~300 ms; pointer events are blocked and `aria-hidden` is set. +- **swap**: variant changes, `data-variant` updated, scroll to top, focus to `main`. +- **reveal**: the dither clears over ~300 ms. Total about 600 ms plus E chunk load time on first visit. +- Reduced motion: none of this renders. + +## Error handling +- Storage unavailable: mode works for the session only. +- E chunk fails to load: stay in B, show the alert, offer retry; the overlay is removed. +- Media query unsupported: treat as light. diff --git a/aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/business-rules.md b/aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/business-rules.md new file mode 100644 index 0000000..31dd887 --- /dev/null +++ b/aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/business-rules.md @@ -0,0 +1,60 @@ +# Business Rules — theme-foundation (U1) + +| Id | Rule | +|---|---| +| BR-U1-1 | The variant is `'b'` on every page load. It is never read from or written to storage or the URL. | +| BR-U1-2 | Initial mode: a valid stored mode wins; otherwise `dark` if `prefers-color-scheme: dark`, else `light`. | +| BR-U1-3 | While `modeSource = 'system'`, the mode follows live changes of the system preference. After the user clicks the mode button, `modeSource = 'user'` and system changes are ignored. | +| BR-U1-4 | The mode button toggles light and dark (two states), sets `modeSource = 'user'` and persists the new mode. Storage errors never break the toggle (state still changes for the session). | +| BR-U1-5 | The initial `data-variant` and `data-mode` are set before first paint by a small same-origin script (`/theme-init.js`, no inline script, CSP-friendly) so there is no flash of the wrong theme; React then takes over the same values. | +| BR-U1-6 | The variant button switches between B and E using the time-travel transition (cover → swap → reveal). After the swap the page scrolls to the top and focus moves to the start of the new page (skip target / `main`). | +| BR-U1-7 | A live region announces the change in Dutch ("Tijdreis-weergave geladen." / "Terug naar de moderne weergave."). | +| BR-U1-8 | E is loaded lazily. While it loads, the transition stays in `cover`. If loading fails, the variant stays `'b'`, the cover is removed and an alert says "De tijdreis kon niet worden geladen." with a retry; B stays usable. | +| BR-U1-9 | Under `prefers-reduced-motion: reduce` there is no transition, no dither, no fade: the swap is immediate (all other rules still apply). | +| BR-U1-10 | The mode is shared by both variants; switching variant keeps the mode. | +| BR-U1-11 | The old red/purple themes and their classes (`theme-red`, `theme-purple`) are removed; the old storage key is ignored and removed. | +| BR-U1-12 | Both buttons are real ` + + + ); +} diff --git a/src/components/layout/VariantRenderer.tsx b/src/components/layout/VariantRenderer.tsx new file mode 100644 index 0000000..7fd2232 --- /dev/null +++ b/src/components/layout/VariantRenderer.tsx @@ -0,0 +1,28 @@ +import { lazy, Suspense } from 'react'; +import type { ReactNode } from 'react'; +import { useTheme } from '../../theme/ThemeProvider'; +import { EBoundary } from './EBoundary'; + +// Variant E is its own chunk (FR-6): visitors who never use the easter egg never download it. +const LandingE = lazy(() => import('../../variants/e/LandingE')); + +/** + * Renders the eager B shell or the lazy E landing depending on the current variant. The + * transition (see ThemeProvider) preloads the E chunk before the swap, so the Suspense fallback is + * only a safety net. + */ +export function VariantRenderer({ b }: { b: ReactNode }) { + const { variant, reportVariantError } = useTheme(); + + if (variant === 'b') { + return <>{b}; + } + + return ( + + + + + + ); +} diff --git a/src/components/layout/__tests__/Nav.test.tsx b/src/components/layout/__tests__/Nav.test.tsx index d0ebb44..d6062aa 100644 --- a/src/components/layout/__tests__/Nav.test.tsx +++ b/src/components/layout/__tests__/Nav.test.tsx @@ -14,7 +14,6 @@ function renderNav() { describe('Nav', () => { beforeEach(() => { window.localStorage.clear(); - document.documentElement.className = ''; }); it('renders all nav links including the CTA', () => { @@ -25,14 +24,24 @@ describe('Nav', () => { expect(screen.getByTestId('nav-cta-link')).toHaveTextContent('Start project'); }); - it('renders the theme toggle with a Dutch accessible label', () => { + it('renders the mode toggle and the icon-only variant toggle with Dutch labels', () => { renderNav(); - expect(screen.getByRole('button', { name: 'Wissel kleurthema' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Donkere weergave' })).toBeInTheDocument(); + expect( + screen.getByRole('button', { name: 'Tijdreis: bekijk de site zoals vroeger' }), + ).toBeInTheDocument(); }); - it('toggles the theme when the toggle button is clicked', () => { + it('puts the variant toggle right after the mode toggle', () => { renderNav(); - const toggle = screen.getByTestId('theme-toggle-button'); + const mode = screen.getByTestId('mode-toggle-button'); + const variant = screen.getByTestId('variant-toggle-button'); + expect(mode.compareDocumentPosition(variant) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + }); + + it('toggles the mode when the mode toggle is clicked', () => { + renderNav(); + const toggle = screen.getByTestId('mode-toggle-button'); expect(toggle).toHaveAttribute('aria-pressed', 'false'); fireEvent.click(toggle); expect(toggle).toHaveAttribute('aria-pressed', 'true'); @@ -58,11 +67,10 @@ describe('Nav', () => { renderNav(); fireEvent.click(screen.getByTestId('nav-mobile-toggle')); const mobileMenu = screen.getByTestId('nav-mobile-menu'); - - const link = mobileMenu.querySelector('a[href="#pakketten"]'); + expect(mobileMenu).toBeInTheDocument(); + const link = mobileMenu.querySelector('a'); expect(link).not.toBeNull(); fireEvent.click(link as HTMLAnchorElement); - expect(screen.queryByTestId('nav-mobile-menu')).not.toBeInTheDocument(); }); }); diff --git a/src/components/layout/__tests__/VariantRenderer.test.tsx b/src/components/layout/__tests__/VariantRenderer.test.tsx new file mode 100644 index 0000000..aa78be1 --- /dev/null +++ b/src/components/layout/__tests__/VariantRenderer.test.tsx @@ -0,0 +1,131 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { VariantRenderer } from '../VariantRenderer'; +import { TransitionOverlay } from '../TransitionOverlay'; +import { LiveRegion } from '../LiveRegion'; +import { VariantAlert } from '../VariantAlert'; +import { EBoundary } from '../EBoundary'; +import { ThemeProvider } from '../../../theme/ThemeProvider'; +import { VariantToggle } from '../../ui/VariantToggle'; +import { clearMatchMedia, mockMatchMedia } from '../../../test/matchMedia'; +import { REDUCED_MOTION_QUERY } from '../../../shared/hooks/usePrefersReducedMotion'; + +function renderApp(loadVariant: (v: 'b' | 'e') => Promise = () => Promise.resolve()) { + return render( + + + +
+ Moderne weergave +
+ + } + /> + + + +
, + ); +} + +describe('VariantRenderer and transition UI', () => { + beforeEach(() => window.localStorage.clear()); + afterEach(() => { + clearMatchMedia(); + vi.restoreAllMocks(); + }); + + it('renders B first', () => { + renderApp(); + expect(screen.getByText('Moderne weergave')).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: 'Tijdreis' })).not.toBeInTheDocument(); + }); + + it('shows the lazy E landing after the switch and announces it (FR-6, BR-U1-7)', async () => { + mockMatchMedia({ [REDUCED_MOTION_QUERY]: true }); + renderApp(); + fireEvent.click(screen.getByTestId('variant-toggle-button')); + expect(await screen.findByRole('heading', { name: 'Tijdreis' })).toBeInTheDocument(); + expect(screen.queryByText('Moderne weergave')).not.toBeInTheDocument(); + await waitFor(() => + expect(screen.getByTestId('live-region')).toHaveTextContent('Tijdreis-weergave geladen.'), + ); + + // The way back to B exists inside E. + fireEvent.click(screen.getAllByTestId('variant-toggle-button')[0]); + expect(await screen.findByText('Moderne weergave')).toBeInTheDocument(); + }); + + it('shows the dither overlay during the transition (BR-U1-6)', async () => { + mockMatchMedia(); + renderApp(); + expect(screen.queryByTestId('transition-overlay')).not.toBeInTheDocument(); + fireEvent.click(screen.getByTestId('variant-toggle-button')); + expect(screen.getByTestId('transition-overlay')).toHaveAttribute('data-phase', 'cover'); + expect(screen.getByTestId('transition-overlay')).toHaveAttribute('aria-hidden', 'true'); + await waitFor( + () => expect(screen.queryByTestId('transition-overlay')).not.toBeInTheDocument(), + { + timeout: 2000, + }, + ); + }); + + it('renders no overlay at all under reduced motion (BR-U1-9)', async () => { + mockMatchMedia({ [REDUCED_MOTION_QUERY]: true }); + renderApp(); + fireEvent.click(screen.getByTestId('variant-toggle-button')); + expect(screen.queryByTestId('transition-overlay')).not.toBeInTheDocument(); + await screen.findByRole('heading', { name: 'Tijdreis' }); + expect(screen.queryByTestId('transition-overlay')).not.toBeInTheDocument(); + }); + + it('stays in B with an alert when E cannot be loaded, and retry recovers (BR-U1-8)', async () => { + mockMatchMedia({ [REDUCED_MOTION_QUERY]: true }); + const load = vi + .fn<(v: 'b' | 'e') => Promise>() + .mockRejectedValueOnce(new Error('offline')) + .mockResolvedValue(undefined); + renderApp(load); + fireEvent.click(screen.getByTestId('variant-toggle-button')); + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'De tijdreis kon niet worden geladen.', + ); + expect(screen.getByText('Moderne weergave')).toBeInTheDocument(); + + fireEvent.click(screen.getByTestId('variant-alert-retry')); + expect(await screen.findByRole('heading', { name: 'Tijdreis' })).toBeInTheDocument(); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); + + it('lets the visitor dismiss the alert', async () => { + mockMatchMedia({ [REDUCED_MOTION_QUERY]: true }); + renderApp(() => Promise.reject(new Error('offline'))); + fireEvent.click(screen.getByTestId('variant-toggle-button')); + await screen.findByRole('alert'); + fireEvent.click(screen.getByTestId('variant-alert-dismiss')); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); +}); + +describe('EBoundary', () => { + afterEach(() => vi.restoreAllMocks()); + + it('calls onError and renders nothing when the child throws (BR-U1-8)', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const onError = vi.fn(); + function Bomb(): never { + throw new Error('boom'); + } + const { container } = render( + + + , + ); + expect(onError).toHaveBeenCalledTimes(1); + expect(container).toBeEmptyDOMElement(); + }); +}); diff --git a/src/components/ui/ModeToggle.tsx b/src/components/ui/ModeToggle.tsx new file mode 100644 index 0000000..d95ac6d --- /dev/null +++ b/src/components/ui/ModeToggle.tsx @@ -0,0 +1,44 @@ +import { useTheme } from '../../theme/ThemeProvider'; + +/** + * Light/dark switch (requirements FR-4, BR-U1-4, BR-U1-12). Two states; starts from the system + * preference and remembers the visitor's choice after the first click. + */ +export function ModeToggle() { + const { mode, toggleMode } = useTheme(); + const isDark = mode === 'dark'; + + return ( + + ); +} diff --git a/src/components/ui/ThemeToggle.tsx b/src/components/ui/ThemeToggle.tsx deleted file mode 100644 index 76627f2..0000000 --- a/src/components/ui/ThemeToggle.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { useTheme } from '../../theme/ThemeProvider'; - -/** - * Visible theme switcher (requirements FR-3, Functional Design Q1/Q7). - * Rendered as a small icon/swatch button in the nav. - */ -export function ThemeToggle() { - const { theme, toggleTheme } = useTheme(); - const isPurple = theme === 'purple'; - - return ( - - ); -} diff --git a/src/components/ui/VariantToggle.tsx b/src/components/ui/VariantToggle.tsx new file mode 100644 index 0000000..a6a8e22 --- /dev/null +++ b/src/components/ui/VariantToggle.tsx @@ -0,0 +1,40 @@ +import { useTheme } from '../../theme/ThemeProvider'; + +/** + * Icon-only button next to the mode toggle that switches between B and E (FR-4, BR-U1-6, + * BR-U1-12). The label changes with the current variant; the tooltip equals the label. + */ +export function VariantToggle() { + const { variant, toggleVariant, transition } = useTheme(); + const inE = variant === 'e'; + const label = inE ? 'Terug naar nu' : 'Tijdreis: bekijk de site zoals vroeger'; + + return ( + + ); +} diff --git a/src/components/ui/__tests__/Toggles.test.tsx b/src/components/ui/__tests__/Toggles.test.tsx new file mode 100644 index 0000000..b6b5eab --- /dev/null +++ b/src/components/ui/__tests__/Toggles.test.tsx @@ -0,0 +1,63 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ModeToggle } from '../ModeToggle'; +import { VariantToggle } from '../VariantToggle'; +import { ThemeProvider } from '../../../theme/ThemeProvider'; +import { clearMatchMedia, mockMatchMedia } from '../../../test/matchMedia'; +import { REDUCED_MOTION_QUERY } from '../../../shared/hooks/usePrefersReducedMotion'; + +function renderToggles() { + return render( + Promise.resolve()}> + + +
+ , + ); +} + +describe('ModeToggle', () => { + beforeEach(() => window.localStorage.clear()); + afterEach(() => clearMatchMedia()); + + it('has a Dutch accessible name and reflects the mode in aria-pressed (BR-U1-12)', () => { + renderToggles(); + const button = screen.getByRole('button', { name: 'Donkere weergave' }); + expect(button).toHaveAttribute('aria-pressed', 'false'); + fireEvent.click(button); + expect(button).toHaveAttribute('aria-pressed', 'true'); + }); + + it('is a real button with a touch target of at least 44px on mobile (BR-U1-12)', () => { + renderToggles(); + const button = screen.getByTestId('mode-toggle-button'); + expect(button.tagName).toBe('BUTTON'); + expect(button).toHaveClass('h-11', 'w-11'); + }); +}); + +describe('VariantToggle', () => { + beforeEach(() => window.localStorage.clear()); + afterEach(() => clearMatchMedia()); + + it('is icon-only with a label that changes with the variant (BR-U1-12)', async () => { + mockMatchMedia({ [REDUCED_MOTION_QUERY]: true }); + renderToggles(); + const button = screen.getByTestId('variant-toggle-button'); + expect(button).toHaveAccessibleName('Tijdreis: bekijk de site zoals vroeger'); + expect(button).toHaveAttribute('title', 'Tijdreis: bekijk de site zoals vroeger'); + expect(button.textContent).toBe(''); + expect(button).toHaveClass('h-11', 'w-11'); + + fireEvent.click(button); + await waitFor(() => expect(button).toHaveAccessibleName('Terug naar nu')); + }); + + it('is disabled while a switch is running', async () => { + renderToggles(); + const button = screen.getByTestId('variant-toggle-button'); + fireEvent.click(button); + expect(button).toBeDisabled(); + await waitFor(() => expect(button).toBeEnabled(), { timeout: 2000 }); + }); +}); diff --git a/src/fonts.ts b/src/fonts.ts index c191b5a..19e2139 100644 --- a/src/fonts.ts +++ b/src/fonts.ts @@ -6,6 +6,9 @@ * Weights match the reference designs' Google Fonts request: * Sora: 400;600;700;800 — Instrument Sans: 400;500;600 — JetBrains Mono: 400;500;700 */ +// Archivo (variable: weight 100-900, width 62-125%) is the display/body face of design B. +// The three families below are removed when the B sections are restyled (unit U2). +import '@fontsource-variable/archivo/wdth.css'; import '@fontsource/sora/400.css'; import '@fontsource/sora/600.css'; import '@fontsource/sora/700.css'; diff --git a/src/index.css b/src/index.css index 060269d..18c4959 100644 --- a/src/index.css +++ b/src/index.css @@ -2,36 +2,73 @@ @tailwind components; @tailwind utilities; -/* Theme tokens — values ported 1-to-1 from References/slp-software-rood.html (red, default) - and References/slp-software.html (purple, alternate). See - aidlc-docs/features/react-frontend/construction/react-frontend-app/functional-design/domain-entities.md - (ThemeTokens) for the data model these mirror. */ -.theme-red { - --color-bg: #140c0e; - --color-surface: #1f1315; - --color-surface-2: #291719; - --color-line: #402226; - --color-text: #f5eaeb; - --color-muted: #b69c9f; - --color-accent: #e04848; - --color-accent-soft: rgba(224, 72, 72, 0.16); - --color-accent-line: rgba(224, 72, 72, 0.4); - --color-accent-hover: #ea6161; - --color-accent-contrast: #140c0e; +/* Theme tokens: variant (b | e) x mode (light | dark), selected by + (set before first paint by public/theme-init.js and kept in sync by ThemeProvider). + Semantic names stay the same so the Tailwind colors in tailwind.config.ts keep working. + B values follow the canvas design B (accent #7A1414); E values are base tokens, refined per era + in unit U5 (accent #AC0000). See + aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/functional-design/domain-entities.md */ + +/* Default (also used when the attributes are missing): B light. */ +:root, +html[data-variant='b'][data-mode='light'] { + color-scheme: light; + --color-bg: #ffffff; + --color-surface: #f1efec; + --color-surface-2: #faf8f5; + --color-line: #e4e0dc; + --color-text: #0e0d0d; + --color-muted: #5c5753; + --color-accent: #7a1414; + --color-accent-soft: rgba(122, 20, 20, 0.1); + --color-accent-line: rgba(122, 20, 20, 0.35); + --color-accent-hover: #911a1a; + --color-accent-contrast: #ffffff; } -.theme-purple { - --color-bg: #0e1220; - --color-surface: #151a2c; - --color-surface-2: #1b2138; - --color-line: #262e4a; - --color-text: #e9ebf5; - --color-muted: #98a0ba; - --color-accent: #8b7cff; - --color-accent-soft: rgba(139, 124, 255, 0.14); - --color-accent-line: rgba(139, 124, 255, 0.35); - --color-accent-hover: #9d90ff; - --color-accent-contrast: #0e1220; +html[data-variant='b'][data-mode='dark'] { + color-scheme: dark; + --color-bg: #0f0e0e; + --color-surface: #181615; + --color-surface-2: #232020; + --color-line: #3a3532; + --color-text: #f3f0ec; + --color-muted: #b3ada7; + --color-accent: #e5524a; + --color-accent-soft: rgba(229, 82, 74, 0.16); + --color-accent-line: rgba(229, 82, 74, 0.4); + --color-accent-hover: #ec6a62; + --color-accent-contrast: #0f0e0e; +} + +html[data-variant='e'][data-mode='light'] { + color-scheme: light; + --color-bg: #ffffff; + --color-surface: #f3f3f3; + --color-surface-2: #e9e9e9; + --color-line: #d0d0d0; + --color-text: #1a1a1a; + --color-muted: #555555; + --color-accent: #ac0000; + --color-accent-soft: rgba(172, 0, 0, 0.1); + --color-accent-line: rgba(172, 0, 0, 0.35); + --color-accent-hover: #c40000; + --color-accent-contrast: #ffffff; +} + +html[data-variant='e'][data-mode='dark'] { + color-scheme: dark; + --color-bg: #1b1b1d; + --color-surface: #232326; + --color-surface-2: #2c2c30; + --color-line: #3d3d42; + --color-text: #ededed; + --color-muted: #a8a8ad; + --color-accent: #ff6b5e; + --color-accent-soft: rgba(255, 107, 94, 0.16); + --color-accent-line: rgba(255, 107, 94, 0.4); + --color-accent-hover: #ff8277; + --color-accent-contrast: #1b1b1d; } html { @@ -49,15 +86,15 @@ body { color: var(--color-text); } -/* Instant, non-animated theme switch when the visitor prefers reduced motion (BR-5). */ -.theme-red, -.theme-purple { - transition: background-color 0.2s ease, color 0.2s ease; +/* Smooth colour change on mode switch; instant for visitors who prefer reduced motion (BR-U1-9). */ +html { + transition: + background-color 0.2s ease, + color 0.2s ease; } @media (prefers-reduced-motion: reduce) { - .theme-red, - .theme-purple { + html { transition: none; } } @@ -82,3 +119,58 @@ body { animation: none; } } + +/* Time-travel transition between variants (BR-U1-6): a pixel-dither overlay that covers the page + (phase "cover"), stays while the variant swaps, then clears (phase "reveal"). Not rendered at all + under prefers-reduced-motion (see TransitionOverlay) and hidden here as a safety net. */ +@keyframes tt-dither-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes tt-dither-out { + from { + opacity: 1; + } + to { + opacity: 0; + } +} + +.tt-overlay { + position: fixed; + inset: 0; + z-index: 100; + pointer-events: all; + background-color: var(--color-accent); + background-image: conic-gradient( + var(--color-bg) 25%, + transparent 0 50%, + var(--color-bg) 0 75%, + transparent 0 + ); + background-size: 8px 8px; + image-rendering: pixelated; +} + +.tt-overlay[data-phase='cover'] { + animation: tt-dither-in 300ms steps(6) forwards; +} + +.tt-overlay[data-phase='swap'] { + opacity: 1; +} + +.tt-overlay[data-phase='reveal'] { + animation: tt-dither-out 300ms steps(6) forwards; +} + +@media (prefers-reduced-motion: reduce) { + .tt-overlay { + display: none; + } +} diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index 43da2cf..2d1a957 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -2,6 +2,7 @@ import { createRootRoute, Outlet } from '@tanstack/react-router'; import { QueryClientProvider } from '@tanstack/react-query'; import { ErrorBoundary } from '../components/shared/ErrorBoundary'; import { ThemeProvider } from '../theme/ThemeProvider'; +import { loadVariant } from '../theme/loadVariant'; import { RootLayout } from '../components/layout/RootLayout'; import { queryClient } from '../lib/queryClient'; @@ -12,7 +13,7 @@ import { queryClient } from '../lib/queryClient'; export const rootRoute = createRootRoute({ component: () => ( - + diff --git a/src/shared/hooks/__tests__/mediaQueryHooks.test.tsx b/src/shared/hooks/__tests__/mediaQueryHooks.test.tsx new file mode 100644 index 0000000..8c0819f --- /dev/null +++ b/src/shared/hooks/__tests__/mediaQueryHooks.test.tsx @@ -0,0 +1,36 @@ +import { act, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it } from 'vitest'; +import { clearMatchMedia, mockMatchMedia } from '../../../test/matchMedia'; +import { PREFERS_DARK_QUERY, usePrefersDark } from '../usePrefersDark'; +import { REDUCED_MOTION_QUERY, usePrefersReducedMotion } from '../usePrefersReducedMotion'; + +function Probe() { + return ( +
+ {String(usePrefersDark())} + {String(usePrefersReducedMotion())} +
+ ); +} + +describe('media query hooks', () => { + afterEach(() => clearMatchMedia()); + + it('default to false when matchMedia is unavailable', () => { + render(); + expect(screen.getByTestId('dark')).toHaveTextContent('false'); + expect(screen.getByTestId('reduced')).toHaveTextContent('false'); + }); + + it('read the initial value and follow live changes', () => { + const media = mockMatchMedia({ [PREFERS_DARK_QUERY]: true }); + render(); + expect(screen.getByTestId('dark')).toHaveTextContent('true'); + expect(screen.getByTestId('reduced')).toHaveTextContent('false'); + + act(() => media.set(PREFERS_DARK_QUERY, false)); + act(() => media.set(REDUCED_MOTION_QUERY, true)); + expect(screen.getByTestId('dark')).toHaveTextContent('false'); + expect(screen.getByTestId('reduced')).toHaveTextContent('true'); + }); +}); diff --git a/src/shared/hooks/mediaQuery.ts b/src/shared/hooks/mediaQuery.ts new file mode 100644 index 0000000..535dd96 --- /dev/null +++ b/src/shared/hooks/mediaQuery.ts @@ -0,0 +1,25 @@ +import { useSyncExternalStore } from 'react'; + +/** Safe `matchMedia` access: environments without it (jsdom, very old browsers) count as "no match". */ +export function matchesMedia(query: string): boolean { + if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') { + return false; + } + return window.matchMedia(query).matches; +} + +/** Subscribes to a media query and re-renders when its result changes. */ +export function useMediaQuery(query: string): boolean { + return useSyncExternalStore( + (onChange) => { + if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') { + return () => {}; + } + const list = window.matchMedia(query); + list.addEventListener('change', onChange); + return () => list.removeEventListener('change', onChange); + }, + () => matchesMedia(query), + () => false, + ); +} diff --git a/src/shared/hooks/usePrefersDark.ts b/src/shared/hooks/usePrefersDark.ts new file mode 100644 index 0000000..8635d6c --- /dev/null +++ b/src/shared/hooks/usePrefersDark.ts @@ -0,0 +1,8 @@ +import { useMediaQuery } from './mediaQuery'; + +export const PREFERS_DARK_QUERY = '(prefers-color-scheme: dark)'; + +/** BR-U1-2/3: the system colour-scheme preference, live. */ +export function usePrefersDark(): boolean { + return useMediaQuery(PREFERS_DARK_QUERY); +} diff --git a/src/shared/hooks/usePrefersReducedMotion.ts b/src/shared/hooks/usePrefersReducedMotion.ts new file mode 100644 index 0000000..47e0ad5 --- /dev/null +++ b/src/shared/hooks/usePrefersReducedMotion.ts @@ -0,0 +1,8 @@ +import { useMediaQuery } from './mediaQuery'; + +export const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)'; + +/** BR-U1-9: true when the visitor asks for less motion; all effects must then be skipped. */ +export function usePrefersReducedMotion(): boolean { + return useMediaQuery(REDUCED_MOTION_QUERY); +} diff --git a/src/test/matchMedia.ts b/src/test/matchMedia.ts new file mode 100644 index 0000000..7a3b34e --- /dev/null +++ b/src/test/matchMedia.ts @@ -0,0 +1,42 @@ +import { vi } from 'vitest'; + +type Listener = (event: { matches: boolean }) => void; + +/** + * Installs a controllable `window.matchMedia` (jsdom has none). `initial` maps a media query to + * its current result; `set()` flips a query and notifies subscribers like a real change event. + */ +export function mockMatchMedia(initial: Record = {}) { + const state: Record = { ...initial }; + const listeners = new Map>(); + + window.matchMedia = vi.fn((query: string) => ({ + get matches() { + return Boolean(state[query]); + }, + media: query, + onchange: null, + addEventListener: (_type: string, cb: Listener) => { + if (!listeners.has(query)) listeners.set(query, new Set()); + listeners.get(query)!.add(cb); + }, + removeEventListener: (_type: string, cb: Listener) => { + listeners.get(query)?.delete(cb); + }, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + })) as unknown as typeof window.matchMedia; + + return { + set(query: string, value: boolean) { + state[query] = value; + listeners.get(query)?.forEach((cb) => cb({ matches: value })); + }, + }; +} + +/** Restores the jsdom default: no `matchMedia` at all. */ +export function clearMatchMedia() { + delete (window as unknown as { matchMedia?: unknown }).matchMedia; +} diff --git a/src/test/setup.ts b/src/test/setup.ts index bb02c60..53cba17 100644 --- a/src/test/setup.ts +++ b/src/test/setup.ts @@ -1 +1,5 @@ import '@testing-library/jest-dom/vitest'; +import { vi } from 'vitest'; + +// jsdom does not implement window.scrollTo; the variant switch scrolls to the top (BR-U1-6). +window.scrollTo = vi.fn() as unknown as typeof window.scrollTo; diff --git a/src/theme/ThemeProvider.tsx b/src/theme/ThemeProvider.tsx index 8414aa1..523a356 100644 --- a/src/theme/ThemeProvider.tsx +++ b/src/theme/ThemeProvider.tsx @@ -1,55 +1,235 @@ -import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'; -import type { ReactNode } from 'react'; import { - DEFAULT_THEME, - THEME_STORAGE_KEY, - resolveInitialTheme, - themeClassName, - type ThemeName, + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; +import type { ReactNode } from 'react'; +import { matchesMedia } from '../shared/hooks/mediaQuery'; +import { PREFERS_DARK_QUERY, usePrefersDark } from '../shared/hooks/usePrefersDark'; +import { usePrefersReducedMotion } from '../shared/hooks/usePrefersReducedMotion'; +import { + DEFAULT_VARIANT, + LEGACY_THEME_STORAGE_KEY, + MODE_STORAGE_KEY, + otherMode, + otherVariant, + resolveInitialMode, + type Mode, + type ModeSource, + type Variant, } from './tokens'; +/** Phases of the time-travel transition (BR-U1-6). `idle` = nothing running. */ +export type TransitionPhase = 'idle' | 'cover' | 'swap' | 'reveal'; + +export interface TransitionState { + phase: TransitionPhase; + target: Variant | null; +} + +/** Duration of the cover and the reveal phase in ms (skipped under reduced motion, BR-U1-9). */ +export const TRANSITION_PHASE_MS = 300; + interface ThemeContextValue { - theme: ThemeName; - toggleTheme: () => void; + variant: Variant; + mode: Mode; + modeSource: ModeSource; + toggleMode: () => void; + toggleVariant: () => void; + transition: TransitionState; + /** Text for the polite live region (BR-U1-7). */ + announcement: string; + /** True when switching to E failed (chunk could not be loaded or E crashed), BR-U1-8. */ + variantError: boolean; + retryVariant: () => void; + dismissVariantError: () => void; + /** Called by the E error boundary: falls back to B and shows the alert. */ + reportVariantError: () => void; } const ThemeContext = createContext(undefined); -function readStoredTheme(): string | null { +function readStoredMode(): string | null { try { - return window.localStorage.getItem(THEME_STORAGE_KEY); + return window.localStorage.getItem(MODE_STORAGE_KEY); } catch { - // BR-3: treat unavailable/unreadable storage the same as "nothing stored" — fall back to default. + // Treat unavailable/unreadable storage the same as "nothing stored". return null; } } -function persistTheme(theme: ThemeName): void { +function persistMode(mode: Mode): void { try { - window.localStorage.setItem(THEME_STORAGE_KEY, theme); + window.localStorage.setItem(MODE_STORAGE_KEY, mode); } catch { - // Ignore write failures (e.g. storage disabled) — theme still works for this session via state. + // Ignore write failures (storage disabled): the mode still works for this session. } } -export function ThemeProvider({ children }: { children: ReactNode }) { - const [theme, setTheme] = useState(() => resolveInitialTheme(readStoredTheme())); +function removeLegacyThemeKey(): void { + try { + window.localStorage.removeItem(LEGACY_THEME_STORAGE_KEY); + } catch { + // Nothing to clean up when storage is unavailable. + } +} + +const ANNOUNCE_TO_E = 'Tijdreis-weergave geladen.'; +const ANNOUNCE_TO_B = 'Terug naar de moderne weergave.'; + +function wait(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +interface ThemeProviderProps { + children: ReactNode; + /** + * Preloads what a variant needs before the swap (E is a lazy chunk). Rejecting keeps the + * current variant and raises `variantError` (BR-U1-8). Default: nothing to load. + */ + loadVariant?: (variant: Variant) => Promise; +} + +export function ThemeProvider({ children, loadVariant }: ThemeProviderProps) { + const systemDark = usePrefersDark(); + const reducedMotion = usePrefersReducedMotion(); + + const [initial] = useState(() => + resolveInitialMode(readStoredMode(), matchesMedia(PREFERS_DARK_QUERY)), + ); + const [variant, setVariant] = useState(DEFAULT_VARIANT); + const [mode, setMode] = useState(initial.mode); + const [modeSource, setModeSource] = useState(initial.source); + const [transition, setTransition] = useState({ phase: 'idle', target: null }); + const [announcement, setAnnouncement] = useState(''); + const [variantError, setVariantError] = useState(false); + + const busyRef = useRef(false); + const mountedRef = useRef(true); useEffect(() => { - const root = document.documentElement; - root.classList.remove('theme-red', 'theme-purple'); - root.classList.add(themeClassName(theme)); - }, [theme]); - - const toggleTheme = useCallback(() => { - setTheme((current) => { - const next: ThemeName = current === 'red' ? 'purple' : 'red'; - persistTheme(next); - return next; - }); + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; }, []); - const value = useMemo(() => ({ theme, toggleTheme }), [theme, toggleTheme]); + // BR-U1-11: the red/purple key is obsolete. + useEffect(() => { + removeLegacyThemeKey(); + }, []); + + // BR-U1-3: follow the system preference until the visitor has chosen. + useEffect(() => { + if (modeSource === 'system') { + setMode(systemDark ? 'dark' : 'light'); + } + }, [systemDark, modeSource]); + + // Keep in sync (theme-init.js already set the same values before first paint). + useEffect(() => { + const root = document.documentElement; + root.setAttribute('data-variant', variant); + root.setAttribute('data-mode', mode); + root.classList.remove('theme-red', 'theme-purple'); + }, [variant, mode]); + + const toggleMode = useCallback(() => { + const next = otherMode(mode); + setMode(next); + setModeSource('user'); + persistMode(next); + }, [mode]); + + const runSwitch = useCallback( + async (target: Variant) => { + if (busyRef.current) { + return; + } + busyRef.current = true; + setVariantError(false); + const phaseMs = reducedMotion ? 0 : TRANSITION_PHASE_MS; + try { + setTransition({ phase: 'cover', target }); + // The cover runs while the target variant loads; both must finish before the swap. + await Promise.all([wait(phaseMs), loadVariant ? loadVariant(target) : Promise.resolve()]); + if (!mountedRef.current) { + return; + } + setVariant(target); + setTransition({ phase: 'swap', target }); + // Let React render the new variant, then scroll/focus (BR-U1-6) and announce (BR-U1-7). + await wait(0); + window.scrollTo({ top: 0, left: 0, behavior: 'instant' }); + document.getElementById('main')?.focus({ preventScroll: true }); + setAnnouncement(target === 'e' ? ANNOUNCE_TO_E : ANNOUNCE_TO_B); + setTransition({ phase: 'reveal', target }); + await wait(phaseMs); + } catch { + // BR-U1-8: stay in the current variant and tell the visitor. + if (mountedRef.current) { + setVariantError(true); + setAnnouncement('De tijdreis kon niet worden geladen.'); + } + } finally { + busyRef.current = false; + if (mountedRef.current) { + setTransition({ phase: 'idle', target: null }); + } + } + }, + [loadVariant, reducedMotion], + ); + + const toggleVariant = useCallback(() => { + void runSwitch(otherVariant(variant)); + }, [runSwitch, variant]); + + const retryVariant = useCallback(() => { + void runSwitch('e'); + }, [runSwitch]); + + const dismissVariantError = useCallback(() => setVariantError(false), []); + + const reportVariantError = useCallback(() => { + setVariant(DEFAULT_VARIANT); + setVariantError(true); + setAnnouncement('De tijdreis kon niet worden geladen.'); + setTransition({ phase: 'idle', target: null }); + }, []); + + const value = useMemo( + () => ({ + variant, + mode, + modeSource, + toggleMode, + toggleVariant, + transition, + announcement, + variantError, + retryVariant, + dismissVariantError, + reportVariantError, + }), + [ + variant, + mode, + modeSource, + toggleMode, + toggleVariant, + transition, + announcement, + variantError, + retryVariant, + dismissVariantError, + reportVariantError, + ], + ); return {children}; } @@ -61,5 +241,3 @@ export function useTheme(): ThemeContextValue { } return context; } - -export { DEFAULT_THEME }; diff --git a/src/theme/__tests__/ThemeProvider.test.tsx b/src/theme/__tests__/ThemeProvider.test.tsx index 91c34d7..e76bc9c 100644 --- a/src/theme/__tests__/ThemeProvider.test.tsx +++ b/src/theme/__tests__/ThemeProvider.test.tsx @@ -1,63 +1,210 @@ -import { render, screen, fireEvent } from '@testing-library/react'; -import { describe, it, expect, beforeEach } from 'vitest'; -import { ThemeProvider, useTheme } from '../ThemeProvider'; -import { THEME_STORAGE_KEY } from '../tokens'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { ThemeProvider, TRANSITION_PHASE_MS, useTheme } from '../ThemeProvider'; +import { LEGACY_THEME_STORAGE_KEY, MODE_STORAGE_KEY } from '../tokens'; +import { clearMatchMedia, mockMatchMedia } from '../../test/matchMedia'; +import { PREFERS_DARK_QUERY } from '../../shared/hooks/usePrefersDark'; +import { REDUCED_MOTION_QUERY } from '../../shared/hooks/usePrefersReducedMotion'; function ThemeProbe() { - const { theme, toggleTheme } = useTheme(); + const t = useTheme(); return (
- {theme} - + {t.variant} + {t.mode} + {t.modeSource} + {t.transition.phase} + {t.announcement} + {String(t.variantError)} + + + +
); } +function renderProvider(loadVariant?: (v: 'b' | 'e') => Promise) { + return render( + + + , + ); +} + describe('ThemeProvider', () => { beforeEach(() => { window.localStorage.clear(); - document.documentElement.className = ''; + document.documentElement.removeAttribute('data-variant'); + document.documentElement.removeAttribute('data-mode'); + vi.mocked(window.scrollTo).mockClear(); + }); + afterEach(() => { + clearMatchMedia(); + vi.restoreAllMocks(); + vi.useRealTimers(); }); - it('defaults to red when nothing is stored (BR-1)', () => { - render( - - - , - ); - expect(screen.getByTestId('current-theme')).toHaveTextContent('red'); - expect(document.documentElement.classList.contains('theme-red')).toBe(true); + describe('mode', () => { + it('starts in B and follows the system preference when nothing is stored (BR-U1-1, 2)', () => { + mockMatchMedia({ [PREFERS_DARK_QUERY]: true }); + renderProvider(); + expect(screen.getByTestId('variant')).toHaveTextContent('b'); + expect(screen.getByTestId('mode')).toHaveTextContent('dark'); + expect(screen.getByTestId('source')).toHaveTextContent('system'); + expect(document.documentElement).toHaveAttribute('data-variant', 'b'); + expect(document.documentElement).toHaveAttribute('data-mode', 'dark'); + }); + + it('uses light when the system preference is unavailable', () => { + renderProvider(); + expect(screen.getByTestId('mode')).toHaveTextContent('light'); + }); + + it('prefers a valid stored mode over the system preference', () => { + mockMatchMedia({ [PREFERS_DARK_QUERY]: true }); + window.localStorage.setItem(MODE_STORAGE_KEY, 'light'); + renderProvider(); + expect(screen.getByTestId('mode')).toHaveTextContent('light'); + expect(screen.getByTestId('source')).toHaveTextContent('user'); + }); + + it('ignores an invalid stored mode', () => { + window.localStorage.setItem(MODE_STORAGE_KEY, 'purple'); + renderProvider(); + expect(screen.getByTestId('mode')).toHaveTextContent('light'); + expect(screen.getByTestId('source')).toHaveTextContent('system'); + }); + + it('removes the legacy red/purple key once (BR-U1-11)', () => { + window.localStorage.setItem(LEGACY_THEME_STORAGE_KEY, 'purple'); + renderProvider(); + expect(window.localStorage.getItem(LEGACY_THEME_STORAGE_KEY)).toBeNull(); + }); + + it('follows system changes until the visitor clicks (BR-U1-3)', () => { + const media = mockMatchMedia({ [PREFERS_DARK_QUERY]: false }); + renderProvider(); + act(() => media.set(PREFERS_DARK_QUERY, true)); + expect(screen.getByTestId('mode')).toHaveTextContent('dark'); + + fireEvent.click(screen.getByText('mode')); + expect(screen.getByTestId('mode')).toHaveTextContent('light'); + expect(screen.getByTestId('source')).toHaveTextContent('user'); + + act(() => media.set(PREFERS_DARK_QUERY, false)); + act(() => media.set(PREFERS_DARK_QUERY, true)); + expect(screen.getByTestId('mode')).toHaveTextContent('light'); + }); + + it('persists the chosen mode and updates (BR-U1-4)', () => { + renderProvider(); + fireEvent.click(screen.getByText('mode')); + expect(screen.getByTestId('mode')).toHaveTextContent('dark'); + expect(window.localStorage.getItem(MODE_STORAGE_KEY)).toBe('dark'); + expect(document.documentElement).toHaveAttribute('data-mode', 'dark'); + }); + + it('still toggles when storage is unavailable (BR-U1-4)', () => { + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('blocked'); + }); + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new Error('blocked'); + }); + renderProvider(); + fireEvent.click(screen.getByText('mode')); + expect(screen.getByTestId('mode')).toHaveTextContent('dark'); + }); }); - it('persists the chosen theme to localStorage on toggle (BR-2)', () => { - render( - - - , - ); - fireEvent.click(screen.getByText('toggle')); - expect(screen.getByTestId('current-theme')).toHaveTextContent('purple'); - expect(window.localStorage.getItem(THEME_STORAGE_KEY)).toBe('purple'); - expect(document.documentElement.classList.contains('theme-purple')).toBe(true); - }); + describe('variant', () => { + it('never stores the variant (BR-U1-1)', async () => { + mockMatchMedia({ [REDUCED_MOTION_QUERY]: true }); + renderProvider(() => Promise.resolve()); + fireEvent.click(screen.getByText('variant')); + await waitFor(() => expect(screen.getByTestId('variant')).toHaveTextContent('e')); + await waitFor(() => expect(screen.getByTestId('phase')).toHaveTextContent('idle')); + expect(window.localStorage.length).toBe(0); + }); - it('falls back to the default theme when the stored value is invalid (BR-3)', () => { - window.localStorage.setItem(THEME_STORAGE_KEY, 'blue'); - render( - - - , - ); - expect(screen.getByTestId('current-theme')).toHaveTextContent('red'); - }); + it('switches to E, scrolls to the top, focuses main and announces (BR-U1-6, 7)', async () => { + mockMatchMedia({ [REDUCED_MOTION_QUERY]: true }); + renderProvider(() => Promise.resolve()); + fireEvent.click(screen.getByText('variant')); + await waitFor(() => + expect(screen.getByTestId('announcement')).toHaveTextContent('Tijdreis-weergave geladen.'), + ); + expect(screen.getByTestId('variant')).toHaveTextContent('e'); + expect(window.scrollTo).toHaveBeenCalledWith({ top: 0, left: 0, behavior: 'instant' }); + expect(document.activeElement).toBe(screen.getByTestId('main')); + expect(document.documentElement).toHaveAttribute('data-variant', 'e'); - it('uses a valid stored theme on load', () => { - window.localStorage.setItem(THEME_STORAGE_KEY, 'purple'); - render( - - - , - ); - expect(screen.getByTestId('current-theme')).toHaveTextContent('purple'); + await waitFor(() => expect(screen.getByTestId('phase')).toHaveTextContent('idle')); + fireEvent.click(screen.getByText('variant')); + await waitFor(() => + expect(screen.getByTestId('announcement')).toHaveTextContent( + 'Terug naar de moderne weergave.', + ), + ); + expect(screen.getByTestId('variant')).toHaveTextContent('b'); + }); + + it('keeps the mode when switching variant (BR-U1-10)', async () => { + mockMatchMedia({ [REDUCED_MOTION_QUERY]: true }); + renderProvider(() => Promise.resolve()); + fireEvent.click(screen.getByText('mode')); + fireEvent.click(screen.getByText('variant')); + await waitFor(() => expect(screen.getByTestId('variant')).toHaveTextContent('e')); + expect(screen.getByTestId('mode')).toHaveTextContent('dark'); + }); + + it('runs cover -> swap -> reveal -> idle with the dither timings (BR-U1-6)', async () => { + vi.useFakeTimers(); + mockMatchMedia(); + let release: () => void = () => {}; + const load = vi.fn(() => new Promise((resolve) => (release = resolve))); + renderProvider(load); + + fireEvent.click(screen.getByText('variant')); + expect(screen.getByTestId('phase')).toHaveTextContent('cover'); + expect(load).toHaveBeenCalledWith('e'); + + // The cover time alone is not enough: the chunk must be loaded as well. + await act(async () => { + await vi.advanceTimersByTimeAsync(TRANSITION_PHASE_MS); + }); + expect(screen.getByTestId('variant')).toHaveTextContent('b'); + + await act(async () => { + release(); + await vi.advanceTimersByTimeAsync(0); + }); + expect(screen.getByTestId('variant')).toHaveTextContent('e'); + expect(screen.getByTestId('phase')).toHaveTextContent('reveal'); + + await act(async () => { + await vi.advanceTimersByTimeAsync(TRANSITION_PHASE_MS); + }); + expect(screen.getByTestId('phase')).toHaveTextContent('idle'); + }); + + it('stays in B and reports an error when loading E fails, retry works (BR-U1-8)', async () => { + mockMatchMedia({ [REDUCED_MOTION_QUERY]: true }); + const load = vi + .fn<(v: 'b' | 'e') => Promise>() + .mockRejectedValueOnce(new Error('chunk failed')) + .mockResolvedValue(undefined); + renderProvider(load); + + fireEvent.click(screen.getByText('variant')); + await waitFor(() => expect(screen.getByTestId('error')).toHaveTextContent('true')); + expect(screen.getByTestId('variant')).toHaveTextContent('b'); + expect(screen.getByTestId('phase')).toHaveTextContent('idle'); + + fireEvent.click(screen.getByText('retry')); + await waitFor(() => expect(screen.getByTestId('variant')).toHaveTextContent('e')); + expect(screen.getByTestId('error')).toHaveTextContent('false'); + }); }); }); diff --git a/src/theme/__tests__/tokens.test.ts b/src/theme/__tests__/tokens.test.ts new file mode 100644 index 0000000..00ade65 --- /dev/null +++ b/src/theme/__tests__/tokens.test.ts @@ -0,0 +1,32 @@ +import { describe, it, expect } from 'vitest'; +import { isValidMode, otherMode, otherVariant, resolveInitialMode } from '../tokens'; + +describe('resolveInitialMode (BR-U1-2)', () => { + it.each([ + ['light', true, 'light', 'user'], + ['dark', false, 'dark', 'user'], + [null, true, 'dark', 'system'], + [null, false, 'light', 'system'], + ['blue', true, 'dark', 'system'], + ['', false, 'light', 'system'], + ['purple', false, 'light', 'system'], + ] as const)('stored=%s systemDark=%s -> %s (%s)', (stored, systemDark, mode, source) => { + expect(resolveInitialMode(stored, systemDark)).toEqual({ mode, source }); + }); +}); + +describe('helpers', () => { + it('validates only light and dark', () => { + expect(isValidMode('light')).toBe(true); + expect(isValidMode('dark')).toBe(true); + expect(isValidMode('red')).toBe(false); + expect(isValidMode(undefined)).toBe(false); + }); + + it('flips mode and variant', () => { + expect(otherMode('light')).toBe('dark'); + expect(otherMode('dark')).toBe('light'); + expect(otherVariant('b')).toBe('e'); + expect(otherVariant('e')).toBe('b'); + }); +}); diff --git a/src/theme/loadVariant.ts b/src/theme/loadVariant.ts new file mode 100644 index 0000000..ef151b6 --- /dev/null +++ b/src/theme/loadVariant.ts @@ -0,0 +1,10 @@ +import type { Variant } from './tokens'; + +/** + * Preloads the code of a variant before the transition swaps to it (BR-U1-8). B is part of the + * main bundle; E is a separate chunk. The same dynamic import is used by VariantRenderer, so the + * module is cached and the lazy component resolves immediately after the swap. + */ +export function loadVariant(variant: Variant): Promise { + return variant === 'e' ? import('../variants/e/LandingE') : Promise.resolve(); +} diff --git a/src/theme/tokens.ts b/src/theme/tokens.ts index 2ad629e..6967d72 100644 --- a/src/theme/tokens.ts +++ b/src/theme/tokens.ts @@ -1,30 +1,46 @@ /** - * Theme values (BR-3: only 'red' and 'purple' are valid). - * Actual token colors live in src/index.css (.theme-red / .theme-purple); - * this module only owns the *selectable* theme identifiers and the - * localStorage key used for persistence (BR-2). + * Theme model: variant (B = modern default, E = time-travel easter egg) x mode (light | dark). + * Actual token colors live in src/index.css (html[data-variant][data-mode]); this module only + * owns the identifiers, the storage keys and the pure rules for the initial mode. + * + * Rules: see aidlc-docs/features/redesign-modern-timetravel/construction/theme-foundation/ + * functional-design/business-rules.md (BR-U1-1 .. BR-U1-12). */ -export type ThemeName = 'red' | 'purple'; +export type Variant = 'b' | 'e'; +export type Mode = 'light' | 'dark'; +/** `system` until the visitor clicks the mode button, `user` afterwards (BR-U1-3/4). */ +export type ModeSource = 'system' | 'user'; -export const THEMES: ThemeName[] = ['red', 'purple']; +/** BR-U1-1: every page load starts in B; the variant is never stored and not in the URL. */ +export const DEFAULT_VARIANT: Variant = 'b'; -export const DEFAULT_THEME: ThemeName = 'red'; +export const MODE_STORAGE_KEY = 'slp-software-mode'; +/** Key of the former red/purple theme; ignored and removed once (BR-U1-11). */ +export const LEGACY_THEME_STORAGE_KEY = 'slp-software-theme'; -export const THEME_STORAGE_KEY = 'slp-software-theme'; - -/** BR-3: fall back to the default theme for anything that isn't a valid ThemeName. */ -export function isValidTheme(value: unknown): value is ThemeName { - return value === 'red' || value === 'purple'; +export function isValidMode(value: unknown): value is Mode { + return value === 'light' || value === 'dark'; } -export function resolveInitialTheme(storedValue: string | null): ThemeName { - if (isValidTheme(storedValue)) { - return storedValue; +/** + * BR-U1-2: a valid stored mode wins; otherwise the system preference decides. + * Must stay in sync with public/theme-init.js, which runs this same rule before first paint. + */ +export function resolveInitialMode( + stored: string | null, + systemPrefersDark: boolean, +): { mode: Mode; source: ModeSource } { + if (isValidMode(stored)) { + return { mode: stored, source: 'user' }; } - return DEFAULT_THEME; + return { mode: systemPrefersDark ? 'dark' : 'light', source: 'system' }; } -export function themeClassName(theme: ThemeName): string { - return `theme-${theme}`; +export function otherVariant(variant: Variant): Variant { + return variant === 'b' ? 'e' : 'b'; +} + +export function otherMode(mode: Mode): Mode { + return mode === 'light' ? 'dark' : 'light'; } diff --git a/src/variants/e/LandingE.tsx b/src/variants/e/LandingE.tsx new file mode 100644 index 0000000..a6adbad --- /dev/null +++ b/src/variants/e/LandingE.tsx @@ -0,0 +1,32 @@ +import { ModeToggle } from '../../components/ui/ModeToggle'; +import { VariantToggle } from '../../components/ui/VariantToggle'; + +/** + * Placeholder shell for variant E (time-travel). The real content (eras 2026 / 2013 / 2006 / + * 1998 / 1989) is built in unit U5; U1 only provides the lazy chunk and the way back to B. + */ +export default function LandingE() { + return ( + <> + +
+

Tijdreis

+

Deze weergave is in aanbouw.

+
+ + ); +} diff --git a/tailwind.config.ts b/tailwind.config.ts index eee494a..d72af96 100644 --- a/tailwind.config.ts +++ b/tailwind.config.ts @@ -19,6 +19,7 @@ export default { sans: ['Instrument Sans', 'system-ui', 'sans-serif'], display: ['Sora', 'sans-serif'], mono: ['JetBrains Mono', 'monospace'], + archivo: ['Archivo Variable', 'system-ui', 'sans-serif'], }, borderRadius: { DEFAULT: '14px', -- 2.39.5 From e1d950cd33672a2ef237f20015c7208bb4005969 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 10 Nov 2026 00:10:27 +0100 Subject: [PATCH 03/48] B-secties: nav, hero, Over, Werkwijze, contactblok en footer volgens ontwerp B Nieuwe tokens (brand, inv, panel, field, prog, body), Archivo als lettertype (Sora en Instrument Sans verwijderd), witte toggles op het rode kopblok, en tests voor structuur, landmarks en contrast in alle vier de thema's. Co-Authored-By: Claude Sonnet 5.5 --- .../redesign-modern-timetravel/aidlc-state.md | 2 +- .../redesign-modern-timetravel/audit.md | 72 ++++++++ .../b-modern-sections/code/summary.md | 28 ++++ .../b-modern-sections-code-generation-plan.md | 44 +++++ .../contact-api-contract.md | 2 +- package.json | 2 - pnpm-lock.yaml | 16 -- src/components/layout/Footer.tsx | 4 +- src/components/layout/Nav.tsx | 31 ++-- src/components/layout/RootLayout.tsx | 6 +- .../layout/__tests__/RootLayout.test.tsx | 47 ++++++ src/components/ui/ModeToggle.tsx | 5 +- src/components/ui/VariantToggle.tsx | 5 +- src/components/ui/toggleTone.ts | 10 ++ .../landing/__tests__/Sections.test.tsx | 156 ++++++++++++++++++ .../landing/components/AboutSection.tsx | 87 +++++----- .../landing/components/ContactSection.tsx | 68 +++++--- src/features/landing/components/Hero.tsx | 80 +++++---- .../landing/components/ProcessSection.tsx | 30 ++-- .../landing/components/ProcessStep.tsx | 33 +++- src/features/landing/data/content.ts | 22 +++ src/fonts.ts | 13 +- src/index.css | 28 ++++ src/theme/__tests__/contrast.test.ts | 80 +++++++++ tailwind.config.ts | 14 +- 25 files changed, 715 insertions(+), 170 deletions(-) create mode 100644 aidlc-docs/features/redesign-modern-timetravel/construction/b-modern-sections/code/summary.md create mode 100644 aidlc-docs/features/redesign-modern-timetravel/construction/plans/b-modern-sections-code-generation-plan.md create mode 100644 src/components/layout/__tests__/RootLayout.test.tsx create mode 100644 src/components/ui/toggleTone.ts create mode 100644 src/features/landing/__tests__/Sections.test.tsx create mode 100644 src/theme/__tests__/contrast.test.ts diff --git a/aidlc-docs/features/redesign-modern-timetravel/aidlc-state.md b/aidlc-docs/features/redesign-modern-timetravel/aidlc-state.md index fa18d98..c7b17a4 100644 --- a/aidlc-docs/features/redesign-modern-timetravel/aidlc-state.md +++ b/aidlc-docs/features/redesign-modern-timetravel/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: redesign-modern-timetravel - **Project Type**: Brownfield - **Start Date**: 2026-11-09T13:00:00Z -- **Current Stage**: CONSTRUCTION - U1 theme-foundation Code Generation (in progress) +- **Current Stage**: CONSTRUCTION - U2 b-modern-sections Code Generation (in progress) - **Branch**: feature/redesign-modern-timetravel ## Workspace State diff --git a/aidlc-docs/features/redesign-modern-timetravel/audit.md b/aidlc-docs/features/redesign-modern-timetravel/audit.md index 7412252..725e0f9 100644 --- a/aidlc-docs/features/redesign-modern-timetravel/audit.md +++ b/aidlc-docs/features/redesign-modern-timetravel/audit.md @@ -514,3 +514,75 @@ **Context**: Leading the builder. Summary file to be read when preparing the frontend handoff (U4). --- + +## U1 Code Generation Complete + +**Timestamp**: 2026-11-10T06:30:00Z + +**User Input**: "Akkoord op jouw bouwplan" + +**AI Response**: "Executed all 13 steps of theme-foundation-code-generation-plan.md. Baseline 6 files / 24 tests; after: 10 files / 56 tests passed, lint 0 errors (2 pre-existing warnings), pnpm build OK, E as separate lazy chunk. Docs commit 1047c73 and code commit made on feature/redesign-modern-timetravel; no push. Prettier run on touched folders reformatted two unrelated files (Footer.tsx, routes/index.tsx), reverted. Summary at construction/theme-foundation/code/summary.md. Completion message presented; awaiting approval." + +**Context**: Code Generation U1 complete (Step 13.5 verified). + +--- + +## Builder CMS-U3b Accepted + +**Timestamp**: 2026-11-10T06:50:00Z + +**User Input**: "(cross-session message from SLS Software - CMS: CMS-U3b openapi-export done, commit 0813656)" + +**AI Response**: "Accepted on the builder's report: committed openapi/slpsoftware.v1.json (no hosts/addresses/secrets), snapshot test with UPDATE_OPENAPI=1 regeneration and drift detection verified by changing one value, contact contract details in the document (reusable Validation/TooLarge/RateLimited, Idempotency-Key header, required fields and maxLength, 404 form closed). Findings: controller without [ApiController] needs ApiExplorerSettings(IgnoreApi=false); class-wide Produces overwrote problem+json (caught by own test, removed). Contact.Tests 117, Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api 4 passed. Contract status line updated. Builder continues with CMS-U4." + +**Context**: Leading the builder. + +--- + +## Resume After Credits Top-up + +**Timestamp**: 2026-11-10T07:30:00Z + +**User Input**: "Credits zijn aangevuld kan je kijken of de andere sessie of jij iets moeten hervatten" + +**AI Response**: "Checked sessions and worktree. SLS Software - CMS [9d882f] is idle with unfinished CMS-U4 work in its worktree (uncommitted admin API, settings, gates, migration AddContactSettings, tests, plus a stray Scratch.cs); sent a resume instruction (verify state, remove Scratch.cs, finish per plan, report). CMS & API [df4818] is busy with its own work. This session: U1 code committed (0854e3a), waiting for the user's approval before U2; no unfinished work on this side." + +**Context**: Coordination. + +--- + +## Builder CMS-U4 Accepted; Phase 1 Complete + +**Timestamp**: 2026-11-10T08:10:00Z + +**User Input**: "(cross-session message from SLS Software - CMS: CMS-U4 contact-admin-api done, commit 44f161a)" + +**AI Response**: "Accepted on the builder's report: seven AdminOnly routes (list, detail, patch, delete, resend, GET/PUT contact-settings), two-layer gate (host flag first, CMS switch cached 5 s, default off), migration AddContactSettings, OpenAPI snapshot regenerated. Real bug caught by the pipeline test (statuses.Contains query -> 500) fixed. Tests: Contact 223, Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api 4 passed. Deviation from plan accepted: with the CMS disabled (availability) a verified Owner/Administrator still passes the gate (existing gate design); others get 503. No data lost by the interruption; container removed. CMS phase 1 (U0, U1, U1b, U2, U3, U3b, U4) done; phase 2 (U5 mail+retry, U6 admin UI, U7 availability PUT) waits for Bryan's decision on merging feature/identity-email-notifications. Builder on stand-by; asked for a consolidated phase-1 handoff file." + +**Context**: Leading the builder. Open for Bryan: merge decision of the ASF branch; whether the CMS branch feature/contact-forms-module is pushed for a test deploy. + +--- + +## U1 Approved; U2 Code Generation Plan Ready + +**Timestamp**: 2026-11-10T09:00:00Z + +**User Input**: "Jij kan verder naar u2. De cms moet nog even wachten" + +**AI Response**: "U1 treated as approved (user said to continue to U2); CMS phase 2 stays on hold. U2 (b-modern-sections) skips Functional Design/NFR/Infrastructure per the execution plan because the design exists in the canvas. Read the canvas file Modern.dc.html and created construction/plans/b-modern-sections-code-generation-plan.md (9 steps). Key points: new brand/inv/panel/field/prog/body tokens, Archivo for all text (Sora and Instrument Sans removed), text stays from content.ts with only structural content additions, display headline from the design flagged, mobile menu kept, contact panel shows mailto until U4, packages untouched until U3. Plan approval prompt presented." + +**Context**: Code Generation Part 1 (planning) for U2. + +--- + +## U2 Plan Approved; ASF Branch Merge Authorized + +**Timestamp**: 2026-11-10T09:30:00Z + +**User Input**: "Approve plan. K denk dat de cms sessie ook wel kan mergen. De grootste changes zijn al gedaan en de rest kan wel later worden gemerged vanaf master" + +**AI Response**: "U2 Code Generation plan approved; starting Part 2. Interpreted 'de cms sessie kan mergen' as: the ASF CMS session (AndreaSlopFotografie, owner of feature/identity-email-notifications) may merge that branch into SlpModularCms master; relayed as Bryan's decision, asked it to merge by its normal process, report the merge commit and expected conflicts to this session and to the builder, and to flag any concrete risk first. Builder (SLS Software - CMS) told to wait for the merge message, then rebase feature/contact-forms-module on master (no push), switch ContactRateLimitPartition to ClientPartitionKey if present, run all tests, and send the rebase result plus plans for CMS-U5, U6, U7 for approval. Contact:Enabled stays off; nothing deployed or pushed." + +**Context**: CMS phase 2 unblocked pending the merge; U2 Code Generation starts. + +--- diff --git a/aidlc-docs/features/redesign-modern-timetravel/construction/b-modern-sections/code/summary.md b/aidlc-docs/features/redesign-modern-timetravel/construction/b-modern-sections/code/summary.md new file mode 100644 index 0000000..d0e887f --- /dev/null +++ b/aidlc-docs/features/redesign-modern-timetravel/construction/b-modern-sections/code/summary.md @@ -0,0 +1,28 @@ +# Code Summary — b-modern-sections (U2) + +## What was built (design B, light and dark) +- **Tokens**: seven new semantic tokens in all four variant×mode sets (`brand`, `on-brand`, `body`, `inv`, `panel`, `field`, `prog`) plus Tailwind names; the constant brand red `#7A1414` (E: `#AC0000`) is used for hero, contact and featured elements in both modes, as in the canvas. Archivo Variable is now the face for `sans` and `display`; Sora and Instrument Sans (fonts and npm packages) are removed; JetBrains Mono stays for the code strip. +- **Header/nav** (`Nav.tsx`): brand block, not sticky, white text, white CTA block "Start project", both round toggles in the white `onBrand` tone (`toggleTone.ts`), mobile hamburger menu kept; `