diff --git a/aidlc-docs/features/homepage-sections/aidlc-state.md b/aidlc-docs/features/homepage-sections/aidlc-state.md index b079b23..e8ca169 100644 --- a/aidlc-docs/features/homepage-sections/aidlc-state.md +++ b/aidlc-docs/features/homepage-sections/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: homepage-sections - **Project Type**: Brownfield - **Start Date**: 2026-10-19T19:19:38Z -- **Current Stage**: CONSTRUCTION - Unit 5 Contact - Functional Design +- **Current Stage**: CONSTRUCTION - Unit 5 Contact - Code Generation (awaiting approval) - **Branch**: feature/homepage-sections ## Workspace State @@ -62,7 +62,7 @@ - [x] Units Generation - EXECUTE (approved) ### 🟒 CONSTRUCTION PHASE -- [ ] Functional Design - EXECUTE (Prijzen βœ…, Lieve woorden βœ…, Contact) / SKIP (Lifestyle fotografie, Over mij, Instagram) +- [ ] Functional Design - EXECUTE (Prijzen βœ…, Lieve woorden βœ…, Contact βœ…) / SKIP (Lifestyle fotografie, Over mij, Instagram) - [ ] NFR Requirements - SKIP - [ ] NFR Design - SKIP - [ ] Infrastructure Design - SKIP @@ -74,7 +74,7 @@ ## Current Status - **Lifecycle Phase**: CONSTRUCTION -- **Current Stage**: Unit 5 Contact β€” Functional Design +- **Current Stage**: Unit 5 Contact β€” Code Generation complete, awaiting approval (pushed, test deploy running) - **Next Stage**: Unit 5 Contact β€” Code Generation ## Reverse Engineering Status diff --git a/aidlc-docs/features/homepage-sections/audit.md b/aidlc-docs/features/homepage-sections/audit.md index cc48bc8..4b7b6ca 100644 --- a/aidlc-docs/features/homepage-sections/audit.md +++ b/aidlc-docs/features/homepage-sections/audit.md @@ -604,3 +604,127 @@ De foto mag nog iets kleiner? 75% van huidige groote maken is denk ik goed. Het **Context**: CONSTRUCTION - Unit 4 complete; Unit 5 start --- + +## Unit 5 Contact β€” Functional Design Plan and Questions + +**Timestamp**: 2026-10-20T22:20:00Z + +**User Input**: (none β€” AI-initiated, following "Ga dan verder naar de volgende stage") + +**AI Response**: "Committed 0b8e8d5, pushed, dispatched CI run 554 (deploy to test). Created construction/plans/contact-functional-design-plan.md (6 steps, listing what is already fixed) and contact-fd-questions.md with 6 questions: when errors appear, error messages, success behaviour (+ reply time text), mail button subject, focus after a 'Boek' click, failure message." + +**Context**: CONSTRUCTION - Unit 5 Functional Design (awaiting answers) + +--- + +## Unit 5 Contact β€” Functional Design Answers (partial) + +**Timestamp**: 2026-10-20T22:30:00Z + +**User Input**: "1B +2X, emailadres: \"Dit e-mailadres is ongeldig.\" Te lang: \"Het bericht is te lang\" +3A, maar het bericht is: \"Bedankt voor je bericht! Ik reageer binnen 1-2 werkdagen. +4A +5A" + +**AI Response**: "Recorded answers 1–5 in contact-fd-questions.md. Question 6 unanswered; the 'too long' message is ambiguous for the name and e-mail fields. Created contact-fd-clarification-questions.md with 2 follow-up questions." + +**Context**: CONSTRUCTION - Unit 5 Functional Design (awaiting clarifications) + +--- + +## Unit 5 Contact β€” Clarification Answers + +**Timestamp**: 2026-10-20T22:40:00Z + +**User Input**: "1A, 2A" + +**AI Response**: "Recorded: failure message with mailto link, input kept (Q6 = A); per-field 'too long' messages (A). Added design detail for Q1 = B: an untouched empty field gets no error on blur, and a shown error clears as soon as the field becomes valid while typing. Generating functional design artifacts." + +**Context**: CONSTRUCTION - Unit 5 Functional Design (answers complete) + +--- + +## Unit 5 Contact β€” Clarification Answers + +**Timestamp**: 2026-10-20T22:40:00Z + +**User Input**: "1A, 2A" + +**AI Response**: "Recorded: failure message with mailto link, input kept (Q6 = A); per-field 'too long' messages (A). Added design detail for Q1 = B: an untouched empty field gets no error on blur, and a shown error clears as soon as the field becomes valid while typing. Generating functional design artifacts." + +**Context**: CONSTRUCTION - Unit 5 Functional Design (answers complete) + +--- + +## Unit 5 Contact β€” Functional Design Complete + +**Timestamp**: 2026-10-20T23:00:00Z + +**User Input**: (none β€” generation) + +**AI Response**: "Generated construction/contact/functional-design/: domain-entities.md (values, errors, payload, shoot options, limits, setting, anti-spam inputs), business-rules.md (BR-FORM-01..13 incl. the user's messages and blur timing, BR-SEND-01..04 with the 1-2 werkdagen thank-you, BR-SPAM-01..03, BR-GATE-01..03, BR-MAIL-01 subject, BR-PARAM-02/04 and BR-FOCUS-01; two decision flowcharts; misuse notes), business-logic-model.md (submit sequence, pure reducer state machine, 8 pure functions, 10 PBT properties incl. stateful PBT-06), frontend-components.md (ContactSection, ContactFormGate, ContactForm, content, accessibility). Prompt: Request Changes or Continue to Code Generation." + +**Context**: CONSTRUCTION - Unit 5 Functional Design (awaiting approval) + +--- + +## Test Deploy Result (units 1–4 incl. review fixes) + +**Timestamp**: 2026-10-20T23:05:00Z + +**User Input**: (none β€” CI run finished) + +**AI Response**: "CI run 554 (workflow_dispatch on feature/homepage-sections at 0b8e8d5, deploy_test=true) completed: check success, deploy-test success, lighthouse success, deploy-production skipped." + +**Context**: Test environment updated with units 1–4 and the review fixes + +--- + +## Unit 5 Contact β€” Functional Design Approval + +**Timestamp**: 2026-10-20T23:10:00Z + +**User Input**: "Ga verder naar de volgende stage" + +**AI Response**: "Functional design approved. Proceeding to Code Generation Part 1 (planning) for unit 5." + +**Context**: CONSTRUCTION - Unit 5 Functional Design approved + +--- + +## Unit 5 Contact β€” Code Generation Plan + +**Timestamp**: 2026-10-20T23:15:00Z + +**User Input**: (none β€” AI-initiated) + +**AI Response**: "Created construction/plans/contact-code-generation-plan.md (19 steps): types/content, six pure helpers incl. the form reducer with stateful PBT, adapter, formControl recipe and panel shadow, ContactForm, ContactFormGate, ContactSection (preselect, URL clean-up, focus), route + app tests, pnpm check with a performance comparison (defer the form like the carousel if it costs performance), visual checks, summary, commit. Prompt: approve plan or request changes." + +**Context**: CONSTRUCTION - Unit 5 Code Generation Part 1 (awaiting plan approval) + +--- + +## Unit 5 Contact β€” Plan Approval + +**Timestamp**: 2026-10-20T23:20:00Z + +**User Input**: "Approve plan. Je mag na het genereren de code alvast committed, pushen en een deploy naar test doen" + +**AI Response**: "Plan approved. Authorised for this unit: after generation, commit, push and dispatch a test deploy. Starting Code Generation Part 2." + +**Context**: CONSTRUCTION - Unit 5 Code Generation Part 2 (start) + +--- + +## Unit 5 Contact β€” Code Generation Complete, Push and Test Deploy + +**Timestamp**: 2026-10-21T00:30:00Z + +**User Input**: "Kan je mij een screenshot van de desktop versie sturen zodra je klaar bent?" (received mid-generation) + +**AI Response**: "Executed all 19 steps. Findings: labels were not linked (control id overridden; Ark uses Field.Root id) β€” fixed; React-compiler lint on field refs β€” focus by id instead; lazy form unmounted after ?pakket= cleanup β€” latched once loaded; two reducer branches only randomly covered β€” deterministic tests added. Performance: 5-run medians against a rebuilt unit-4 build (sparse worktree; a full worktree hit the Windows path limit): 0.83 β†’ 0.80 with the form in the route chunk, 0.81 with the form lazy, 0.83 after replacing Chakra List/Blockquote (slot recipes) in PriceCard and TestimonialSlide with plain elements so the route no longer fetches a new shared chunk. Placeholder heights measured. Final pnpm check green: 237 tests, 100% lib coverage, Lighthouse mobile 0.83, desktop 1.0, a11y/BP/SEO 1.0. Sent desktop screenshots (overlay; form switched on locally and reverted) and a phone screenshot. Committing, pushing and dispatching a test deploy as authorised for this unit." + +**Context**: CONSTRUCTION - Unit 5 Code Generation (complete, awaiting approval) + +--- diff --git a/aidlc-docs/features/homepage-sections/construction/contact/code/code-summary.md b/aidlc-docs/features/homepage-sections/construction/contact/code/code-summary.md new file mode 100644 index 0000000..5b8d94a --- /dev/null +++ b/aidlc-docs/features/homepage-sections/construction/contact/code/code-summary.md @@ -0,0 +1,61 @@ +# Code Summary β€” Unit 5: Contact + +Plan: [contact-code-generation-plan.md](../../plans/contact-code-generation-plan.md). Functional design: [../functional-design/](../functional-design/). Branch: `feature/homepage-sections`. + +## Files + +### Created +| File | Purpose | +|---|---| +| `web/src/contact/types.ts` | Values, errors, payload, shoot option, limits, empty values | +| `web/src/contact/submitContactForm.ts` + test | The single submission adapter; fails until the API exists (comment shows the future `POST /api/contact`) | +| `web/src/lib/shootOptions.ts` + test | Shown packages + Overig | +| `web/src/lib/validateContact.ts` + test | `validateField` / `validateContact` with the agreed messages | +| `web/src/lib/toContactPayload.ts` + test | Trimmed payload | +| `web/src/lib/isLikelySpam.ts` + test | Honeypot or under 3000 ms | +| `web/src/lib/mailLink.ts` + test | `mailSubject`, `mailtoLink` | +| `web/src/lib/contactFormReducer.ts` + test | The form as a pure state machine (editing β†’ sending β†’ sent / failed) | +| `web/src/recipes/formControl.ts` | The design's square fields for Input, Textarea and NativeSelect | +| `web/src/components/ContactForm/ContactForm.tsx` + test | The form (lazy chunk) | +| `web/src/components/ContactForm/ContactFormGate.tsx` + test | Dimmed, inert form under the coming-soon notice | +| `web/src/components/home/ContactSection/ContactSection.tsx` + test | The section: heading, gate, lazy form, `?pakket=` handling, focus | + +### Modified +| File | Change | +|---|---| +| `web/src/content/types.ts`, `homeContent.ts`, `siteContent.ts` | `HomeContent.contact`; `SiteContent.contactForm = { enabled: false }` | +| `web/src/theme.ts` | `error` colour (#a4443a: 5.7:1 on paper, 6.1:1 on white), `panel` shadow, `formControl` recipe | +| `web/src/components/SectionHeading/SectionHeading.tsx` | `focusable` (tabIndex βˆ’1 for the programmatic focus) | +| `web/src/components/home/Pricing/PriceCard.tsx` | Feature list as plain `ul`/`li` instead of Chakra `List` (see performance) | +| `web/src/components/home/Testimonials/TestimonialSlide.tsx` | Plain `figure`/`blockquote`/`figcaption` instead of Chakra `Blockquote` (see performance) | +| `web/src/routes/index.tsx` | Renders `ContactSection` with `pakket` from `Route.useSearch()` | +| `web/src/test/arbitraries.ts` | `contactValues`, `anyContactValues`, `contactEvent` | +| `web/src/test/setup.ts` | No-op `Element.scrollIntoView` (the router's hash scroll; jsdom lacks it) | +| `web/src/app.test.tsx` | "Contact" in the page order; full "Boek Newborn" path through the real route | + +## Findings and fixes during generation +- **Labels not linked** (found by a test): Chakra's `Field.Root` links the label to the control through its own id; overriding the control's `id` broke that. In Ark, `Field.Root`'s `id` is the control's id (and `ids.control` is, confusingly, the root group's id), so the id now goes on `Field.Root`. Ark links the error text with `aria-errormessage` (not `aria-describedby` as written in the functional design); `aria-invalid` is set. +- **Field refs vs the React compiler lint**: refs set from a helper called during render were rejected; focus now finds the first invalid field by its id. +- **Form disappearing after a "Boek" arrival**: with the form loaded because of `?pakket=`, removing the parameter made it unload until the observer fired, losing typed input. Once loaded the form now stays (asserted in the app test). +- **Coverage**: two reducer branches were only reached randomly by the stateful property test; fixed with deterministic example tests (100% on `src/lib/**`). +- **Performance** (5-run Lighthouse medians, unit 4 rebuilt alongside for the same conditions): + + | Build | Median | LCP | TBT | + |---|---|---|---| + | Unit 4 | 0.83 | 3.84 s | 177 ms | + | Unit 5, form in the route chunk | 0.80 | 3.99 s | 232 ms | + | Unit 5, form lazy | 0.81 | 3.99 s | 207 ms | + | Unit 5, form lazy, no slot recipes in the route chunk | **0.83** | 3.84 s | 175 ms | + + First the form was moved into its own chunk, loaded when the section comes within 200 px of the screen, or at once when arriving via "Boek …". The remaining gap came from a new shared chunk (Chakra's slot-recipe factory, now used by three chunks) that the route had to fetch on page load: the price cards' `List` and the review slide's `Blockquote` were the only slot-recipe components on the route, so they became plain elements with the same styling, and the route no longer needs that chunk. +- **Placeholder** while the form loads: measured 604 px on phones, 502 px from `sm`. + +## Verification (`pnpm check`) +- Lint βœ…, Prettier βœ…, build βœ… (`ContactForm` in its own chunk, Β±5.7 KB gzipped) +- Tests: 52 files, **237 passed**; 100% coverage on `src/lib/**` +- Lighthouse home: mobile **0.83**, desktop **1.0**; accessibility, best practices, SEO **1.0** +- Visual check: 1440 and 390 with the overlay; 1440 with the form switched on locally (reverted before the build that was checked) + +## Extension compliance +- **Security Baseline**: client-side limits and format (SECURITY-05, server side in the API feature); misuse: gate + honeypot + time check (SECURITY-11); generic failure text (SECURITY-15); the e-mail address is assembled in the browser; no new dependencies or external resources; CSP unchanged. +- **PBT**: PBT-02 (mailto round-trip), PBT-03 (validation invariants), PBT-04 (payload idempotency), PBT-05 (spam and e-mail oracles), PBT-06 (stateful reducer test over random event sequences), PBT-07 (generators), PBT-08/09 (existing seed setup), PBT-10 (example tests). diff --git a/aidlc-docs/features/homepage-sections/construction/contact/functional-design/business-logic-model.md b/aidlc-docs/features/homepage-sections/construction/contact/functional-design/business-logic-model.md new file mode 100644 index 0000000..d2c6772 --- /dev/null +++ b/aidlc-docs/features/homepage-sections/construction/contact/functional-design/business-logic-model.md @@ -0,0 +1,80 @@ +# Business Logic Model β€” Unit 5: Contact + +## Submit sequence + +```mermaid +sequenceDiagram + box rgba(246,224,94,0.4) Visitor + participant V as Visitor + end + box rgba(99,179,237,0.4) Homepage + participant F as ContactForm + participant L as PureHelpers + participant A as SubmitAdapter + end + V->>F: Clicks the send button + F->>L: validateContact with the values and options + L-->>F: Errors per field, or none + F->>L: isLikelySpam with honeypot and elapsed time + L-->>F: Spam or not + F->>A: submitContactForm with the trimmed payload + A-->>F: Resolved or rejected + F-->>V: Thank-you message, or failure message with mail link +``` + +Text alternative: on submit the form validates, checks for spam, sends the trimmed payload through the single adapter, and shows the thank-you or the failure message. + +## Form state (a pure reducer) + +The form's behaviour is a pure reducer `contactFormReducer(state, event)`, so it can be tested as a state machine (PBT-06) independently of React. + +```mermaid +graph LR + Editing["editing"] -->|"submit, invalid"| Editing + Editing -->|"submit, spam"| Sent["sent"] + Editing -->|"submit, valid"| Sending["sending"] + Sending -->|"resolved"| Sent + Sending -->|"rejected"| Failed["failed"] + Failed -->|"edit or blur"| Failed + Failed -->|"submit, valid"| Sending + + classDef state fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef final fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + class Editing,Sending,Failed state; + class Sent final; +``` + +Text alternative: the form is editing until a submit; an invalid submit stays in editing (with errors), spam goes straight to sent, a valid submit goes to sending, which ends in sent or failed; from failed, a valid submit sends again. + +**State**: `{ status: 'editing' | 'sending' | 'sent' | 'failed'; values; touched: Set of fields; errors }` +**Events**: `edit(field, value)`, `blur(field)`, `preselect(shoot)`, `submit({ now, shownAt, honeypot })`, `resolved`, `rejected`. + +## Pure functions (`web/src/lib/`) + +| Function | Purpose | Rules | +|---|---|---| +| `shootOptions(packages)` | shown packages + Overig | domain-entities.md | +| `validateField(field, values, options)` | first failing message for one field, or undefined | BR-FORM-01…07 | +| `validateContact(values, options)` | errors for all fields | BR-FORM-01…07 | +| `toContactPayload(values)` | trimmed payload | BR-SEND-01 | +| `isLikelySpam({ honeypot, shownAt, now })` | honeypot or under 3000 ms | BR-SPAM-01 | +| `mailSubject(packageName?)` | "Aanvraag fotoshoot: X" or "Vraag via andreaslop.nl" | BR-MAIL-01 | +| `mailtoLink(address, subject)` | `mailto:` with encoded subject | BR-MAIL-01 | +| `contactFormReducer(state, event)` | the state machine above | BR-FORM-10…12, BR-SEND-01…04, BR-SPAM-02 | + +## Testable properties (PBT-01) + +| Function | Category | Property | +|---|---|---| +| `shootOptions` | Invariant | Last option is Overig; the others are the packages' ids and names in order | +| `validateContact` | Oracle | For generated valid values there are no errors | +| `validateContact` | Invariant | Emptying any one required field gives exactly that field's "required" message | +| `validateContact` | Invariant | Exceeding a limit gives that field's "te lang" message | +| `validateContact` | Oracle | E-mail error ⇔ the trimmed value fails the format regex (for non-empty, short values) | +| `toContactPayload` | Idempotency | Making a payload of a payload changes nothing; no field has outer whitespace | +| `isLikelySpam` | Oracle | Equals `honeypot !== '' \|\| now - shownAt < 3000` | +| `mailtoLink` | Round-trip | Decoding the `subject` parameter gives back the subject; the link starts with `mailto:
?` | +| `mailSubject` | Invariant | Contains the package name when given, otherwise the general subject | +| `contactFormReducer` | Stateful (PBT-06) | For random event sequences: status only moves along the allowed transitions; `sending` only after a valid, non-spam submit; values never change while `sending`; errors never show for an untouched field unless a submit happened; after `sent` nothing changes | + +Generators (PBT-07): valid `contactValues` (realistic names, e-mails from the existing `validEmail`, a shoot from the options, messages up to the limit), `anyContactValues` (empty, whitespace, overlong, bad e-mails), and event sequences for the reducer (`fc.commands` or a list of events). diff --git a/aidlc-docs/features/homepage-sections/construction/contact/functional-design/business-rules.md b/aidlc-docs/features/homepage-sections/construction/contact/functional-design/business-rules.md new file mode 100644 index 0000000..a959640 --- /dev/null +++ b/aidlc-docs/features/homepage-sections/construction/contact/functional-design/business-rules.md @@ -0,0 +1,114 @@ +# Business Rules β€” Unit 5: Contact + +Sources: FR-HP-06…09, unit 3's BR-PARAM-02…04, [contact-fd-questions.md](../../plans/contact-fd-questions.md) and [contact-fd-clarification-questions.md](../../plans/contact-fd-clarification-questions.md). + +## Validation + +| ID | Rule | Message | +|---|---|---| +| BR-FORM-01 | `naam` is required (after trimming) | "Vul je naam in." | +| BR-FORM-02 | `email` is required | "Vul je e-mailadres in." | +| BR-FORM-03 | `email` must look like an address: `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$` after trimming | "Dit e-mailadres is ongeldig." | +| BR-FORM-04 | `shoot` must be one of the shoot options | "Kies een soort shoot." | +| BR-FORM-05 | `bericht` is required | "Schrijf hier je vraag." | +| BR-FORM-06 | Maximum lengths: `naam` 100, `email` 254, `bericht` 2000 (also `maxLength` on the fields) | "De naam is te lang." / "Het e-mailadres is te lang." / "Het bericht is te lang." | +| BR-FORM-07 | Per field the first failing rule wins, in the order required β†’ length β†’ format | β€” | + +## When errors show (Q1 = B) + +| ID | Rule | +|---|---| +| BR-FORM-10 | A field is checked when the visitor **leaves** it, but only once they have typed in it; tabbing through an untouched empty field shows nothing. | +| BR-FORM-11 | On **submit** every field is checked; if any is invalid, nothing is sent and focus moves to the first invalid field. | +| BR-FORM-12 | A shown error is re-checked while typing and **disappears** as soon as the field is valid (it is not re-shown while typing; a new error only appears on leaving or submitting). | +| BR-FORM-13 | Errors are linked to their field (`aria-describedby`, `aria-invalid`) and announced. | + +## Sending + +| ID | Rule | +|---|---| +| BR-SEND-01 | Valid and not spam β†’ state **sending**: button disabled, label "Versturen…"; the payload (trimmed values) goes to `submitContactForm`. | +| BR-SEND-02 | Success β†’ state **sent**: the form is replaced by "Bedankt voor je bericht! Ik reageer binnen 1-2 werkdagen." and focus moves to that message (Q3 = A). | +| BR-SEND-03 | Failure β†’ state **failed**: above the button "Versturen lukte niet. Probeer het later nog eens of mail naar info@andreaslop.nl" with the address as a mail link (BR-MAIL-01); what the visitor typed stays; the next submit tries again (Q6 = A). | +| BR-SEND-04 | A second submit while sending is ignored. | + +## Anti-spam (FR-HP-08) + +| ID | Rule | +|---|---| +| BR-SPAM-01 | Spam when the honeypot `website` is not empty, or less than 3000 ms passed since the form became usable. | +| BR-SPAM-02 | Spam gets the normal success (state **sent**), but nothing is sent. Validation still runs first, like for a person. | +| BR-SPAM-03 | No robot-check script is loaded in this feature; the form keeps a slot for Friendly Captcha (FR-HP-09). | + +## Gate (FR-HP-07) + +| ID | Rule | +|---|---| +| BR-GATE-01 | `contactForm.enabled = false` β†’ the form is visible but dimmed and `inert`; over it the notice "Binnenkort", "Het contactformulier komt binnenkort. Mail me voor nu op info@andreaslop.nl" and the button "Stuur een e-mail". | +| BR-GATE-02 | The address is assembled from `siteContent.email` in the browser (existing `emailAddress`); if it is invalid the notice shows only "Het contactformulier komt binnenkort." without address or button. | +| BR-GATE-03 | `enabled = true` β†’ the form works normally and the notice is not rendered. | + +## Mail link (Q4 = A) + +| ID | Rule | +|---|---| +| BR-MAIL-01 | Every mail link (notice button, address in the notice, address in the failure message) opens a mail with a subject: "Aanvraag fotoshoot: " when the visitor arrived via a "Boek …" link (a package is selected from `?pakket=`), otherwise "Vraag via andreaslop.nl". Subject is URL-encoded. | + +## Preselection from "Boek …" (unit 3, BR-PARAM-02…04) + +| ID | Rule | +|---|---| +| BR-PARAM-02 | When the page has a `pakket` value: if it names a shown package (`packageFromSearch`), the shoot field takes that package β€” replacing an earlier choice (last click wins, BR-PARAM-03). Then `pakket` is removed from the URL with a history *replace*, keeping `#contact`, without scrolling. Unknown values are removed the same way and change nothing. | +| BR-PARAM-04 | This happens the same way with the gate on or off (with the gate on, the package still feeds the mail subject). | +| BR-FOCUS-01 | After arriving via a "Boek …" link (any `pakket` value present), focus moves to the "Contact" heading (programmatic focus, no visible ring), so keyboard and screen reader users continue in the right place (Q5 = A). A normal page load does not move focus. | + +## Decision flow: submit + +```mermaid +graph TD + Submit["Visitor submits"] --> Busy{"Already sending?"} + Busy -->|"yes"| Ignore["Ignore"] + Busy -->|"no"| Valid{"All fields valid?"} + Valid -->|"no"| ShowErrors["Show errors, focus first invalid field"] + Valid -->|"yes"| Spam{"Honeypot filled or under 3 s?"} + Spam -->|"yes"| FakeSent["Show thank-you, send nothing"] + Spam -->|"no"| Sending["Sending: button disabled"] + Sending --> Result{"Adapter result"} + Result -->|"ok"| Sent["Replace form by thank-you, focus it"] + Result -->|"error"| Failed["Failure message with mail link, keep input"] + + classDef input fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + classDef decision fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef outcome fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + class Submit input; + class Busy,Valid,Spam,Result decision; + class Ignore,ShowErrors,FakeSent,Sending,Sent,Failed outcome; +``` + +Text alternative: a submit is ignored while sending; otherwise invalid input shows errors and focuses the first invalid field; valid spam gets the thank-you without sending; valid input is sent, and the result either replaces the form by the thank-you or shows the failure message with a mail link while keeping the input. + +## Decision flow: arriving with `?pakket=` + +```mermaid +graph TD + Arrive["Homepage with pakket in the URL"] --> Known{"Names a shown package?"} + Known -->|"yes"| Select["Shoot field takes the package, replacing an earlier choice"] + Known -->|"no"| Keep["Shoot field unchanged"] + Select --> Clean["Remove pakket with history replace, keep hash contact"] + Keep --> Clean + Clean --> Focus["Focus the Contact heading"] + + classDef input fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000; + classDef decision fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000; + classDef outcome fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + class Arrive input; + class Known decision; + class Select,Keep,Clean,Focus outcome; +``` + +Text alternative: a known package is selected (replacing an earlier choice), an unknown one changes nothing; either way the parameter is removed from the URL with a history replace and focus moves to the Contact heading. + +## Misuse considerations (SECURITY-11) +- Form spam: gate today; honeypot and time check in the browser; Friendly Captcha, server-side validation and rate limiting in the API feature (the browser checks are never the only defence). +- Input is only ever rendered as text by React and sent as JSON later; `pakket` is never reflected. +- Failure messages are generic (no technical details, SECURITY-15). diff --git a/aidlc-docs/features/homepage-sections/construction/contact/functional-design/domain-entities.md b/aidlc-docs/features/homepage-sections/construction/contact/functional-design/domain-entities.md new file mode 100644 index 0000000..6ebdc19 --- /dev/null +++ b/aidlc-docs/features/homepage-sections/construction/contact/functional-design/domain-entities.md @@ -0,0 +1,57 @@ +# Domain Entities β€” Unit 5: Contact + +## Relationships + +```mermaid +graph TD + Values["ContactValues"] + Errors["ContactErrors"] + Payload["ContactPayload"] + Option["ShootOption"] + Package["PricingPackage"] + Config["Contact form setting"] + Address["EmailAddress"] + + Package -->|"becomes, plus Overig"| Option + Option -->|"allowed values of shoot"| Values + Values -->|"checked into"| Errors + Values -->|"trimmed into"| Payload + Config -->|"switches form or notice"| Values + Address -->|"mail link in notice and failure message"| Config + + classDef entity fill:#2196F3,stroke:#0d47a1,stroke-width:1px,color:#000; + classDef value fill:#FF9800,stroke:#e65100,stroke-width:1px,color:#000; + classDef config fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000; + class Values,Payload entity; + class Errors,Option,Package,Address value; + class Config config; +``` + +Text alternative: packages (plus Overig) become the shoot options that limit the shoot value; what the visitor typed is checked into errors and trimmed into the payload; the contact form setting switches between the form and the coming-soon notice, which, like the failure message, uses the site's e-mail address. + +## ContactValues (what the visitor typed) + +| Field | Type | Limit | Required | +|---|---|---|---| +| `naam` | string | 100 characters | yes | +| `email` | string | 254 characters | yes, valid format | +| `shoot` | string | one of the shoot option values | yes | +| `bericht` | string | 2000 characters | yes | + +The limits are also set as `maxLength` on the fields, so in practice they are rarely exceeded; the check is a safety net (and the server repeats it). + +## ContactErrors +`Partial>` β€” one message per field at most. + +## ContactPayload (sent to the API later) +Same four fields, trimmed. `shoot` is a package id (e.g. `newborn`) or `overig`. The Friendly Captcha token is added in the API feature. + +## ShootOption +`{ value: string; label: string }` β€” the shown packages in their order (`value` = package id, `label` = name), then `{ value: 'overig', label: 'Overig' }`. The empty "Kies een optie..." is the placeholder, not an option. + +## Contact form setting +`siteContent.contactForm.enabled: boolean` β€” `false` today (coming-soon notice); later delivered by the CMS. + +## Anti-spam inputs +- Honeypot field `website` (hidden from people and assistive technology). +- `shownAt`: when the form became usable (shown and enabled); minimum fill time **3000 ms**. diff --git a/aidlc-docs/features/homepage-sections/construction/contact/functional-design/frontend-components.md b/aidlc-docs/features/homepage-sections/construction/contact/functional-design/frontend-components.md new file mode 100644 index 0000000..517a0b3 --- /dev/null +++ b/aidlc-docs/features/homepage-sections/construction/contact/functional-design/frontend-components.md @@ -0,0 +1,66 @@ +# Frontend Components β€” Unit 5: Contact + +## Hierarchy + +```mermaid +graph TD + Route["routes/index.tsx"] --> Section["home/ContactSection"] + Section --> Home["HomeSection id contact, narrow"] + Section --> Heading["SectionHeading, focus target"] + Section --> Gate["ContactForm/ContactFormGate"] + Gate --> Form["ContactForm/ContactForm"] + Gate --> Notice["Coming-soon notice with mail button"] + Form --> Fields["Chakra Field: Input, NativeSelect, Textarea"] + Form --> Honeypot["Honeypot field"] + Form --> Slot["Robot-check slot, empty"] + Form --> Status["Sending, failure and thank-you"] + Logic["lib: reducer, validation, spam, mail link"] -.-> Form + Logic -.-> Gate + Adapter["contact/submitContactForm"] -.-> Form + + classDef root fill:#4CAF50,stroke:#2e7d32,stroke-width:1px,color:#000; + classDef ui fill:#2196F3,stroke:#0d47a1,stroke-width:1px,color:#000; + classDef logic fill:#9C27B0,stroke:#4a148c,stroke-width:1px,color:#000; + classDef ext fill:#F44336,stroke:#b71c1c,stroke-width:1px,color:#000; + class Route root; + class Section,Home,Heading,Gate,Form,Notice,Fields,Honeypot,Slot,Status ui; + class Logic logic; + class Adapter ext; +``` + +Text alternative: the home route renders ContactSection (HomeSection with id contact, the heading as focus target, and the gate); the gate wraps the form and the coming-soon notice; the form has Chakra fields, a honeypot, an empty robot-check slot and status messages; pure helpers and the submit adapter support it. + +## ContactSection (`components/home/ContactSection`) +- **Props**: `{ content: HomeContent['contact']; packages: PricingPackage[]; enabled: boolean; email: EmailAddress; pakket?: string }` +- **Behaviour**: resolves `pakket` with `packageFromSearch`; passes the selected id to the form (`preselect`) and the package name to the mail subject; removes `pakket` from the URL (router `navigate({ search: {}, hash: 'contact', replace: true, resetScroll: false })`); moves focus to the heading when `pakket` was present (BR-PARAM-02, BR-FOCUS-01). +- **Layout**: `HomeSection` `id="contact"`, `width="narrow"`, plain background, centred `SectionHeading` "Contact" with lead; the heading has `tabIndex={-1}` for the programmatic focus (no visible ring, theme rule `[tabindex="-1"]:focus`). + +## ContactFormGate (`components/ContactForm/ContactFormGate`) +- **Props**: `{ enabled: boolean; email: EmailAddress; subject: string; children }` +- **Off**: wraps children in a dimmed (`opacity 0.35`, slight blur), `inert`, non-selectable box; renders the notice centred over it: eyebrow "Binnenkort", the text with the address as an underline link, and an accent `LinkButton`-style anchor "Stuur een e-mail" (`mailtoLink`). White panel, hairline border, `shadow` from the design (a theme token). Invalid address β†’ text only. +- **On**: renders children only. + +## ContactForm (`components/ContactForm/ContactForm`) +- **Props**: `{ idPrefix: string; options: ShootOption[]; preselect?: { shoot: string; key: number }; mailSubject: string; email: EmailAddress; submit?: (payload) => Promise }` (`key` changes per "Boek" click so the same package can be applied again) +- **State**: `useReducer(contactFormReducer)`; `shownAt` recorded when the form becomes usable. +- **Fields**: Chakra `Field.Root` + `Field.Label` + control + `Field.ErrorText` (`invalid` from state); square inputs in the design style (theme), `autocomplete` name/email, `maxLength` per limit; the select has the placeholder "Kies een optie..." and the shoot options; the textarea min height 170 px with placeholder "Vul hier je bericht in". +- **Honeypot**: label "Website" + input `name="website"`, off-screen, `aria-hidden`, `tabIndex={-1}`, `autoComplete="off"`. +- **Robot-check slot**: an empty `div` with `data-robot-check` (FR-HP-09). +- **Submit button**: accent `linkButton` style on a `button`, "(Aan)vraag versturen" / "Versturen…" while sending, disabled while sending. +- **Failure**: a status box above the button (`role="alert"`) with the mail link. +- **Sent**: the form is replaced by the thank-you (`role="status"`, `tabIndex={-1}`, focused). +- **Layout**: name and e-mail side by side from `sm`, the rest full width; labels in the eyebrow style (`ink.soft` for contrast). +- **Test ids**: `contact-form`, `contact-form-`, `contact-form-submit`, `contact-form-status`, `contact-form-sent`, `contact-gate-notice`, `contact-gate-mail`. + +## Loading +The form is a lazy chunk, loaded when the section comes within 200 px of the screen or at once when arriving via "Boek …", and it stays once loaded; the heading and the gate's notice render immediately over a placeholder of the form's height (unit 5 code summary, performance). + +## Content +- `HomeContent.contact = { title: 'Contact', lead: 'Wil je meer informatie ontvangen? Neem gerust contact met mij op.' }` +- `siteContent.contactForm = { enabled: false }` + +## Accessibility (NFR-HP-01) +- Labels visible and linked; errors via `aria-errormessage`/`aria-invalid` (Ark's Field) and announced; focus to the first invalid field on submit; thank-you focused; failure announced (`role="alert"`). +- With the gate on, the inert form is skipped by keyboard and screen readers; the notice and its button are reachable. +- Contrast: labels and placeholder text meet 4.5:1 (no `ink.muted` on paper); the dimmed form is decorative while inert. +- Axe clean in both gate states; Lighthouse accessibility stays 1.0. diff --git a/aidlc-docs/features/homepage-sections/construction/lieve-woorden/code/code-summary.md b/aidlc-docs/features/homepage-sections/construction/lieve-woorden/code/code-summary.md index 1c98f0b..19cdf2d 100644 --- a/aidlc-docs/features/homepage-sections/construction/lieve-woorden/code/code-summary.md +++ b/aidlc-docs/features/homepage-sections/construction/lieve-woorden/code/code-summary.md @@ -36,6 +36,9 @@ Plan: [lieve-woorden-code-generation-plan.md](../../plans/lieve-woorden-code-gen ## Change request after testing on test (2026-10-20) The photo was too large on phones (it filled the screen). Now: phones max 180 px wide (Β±75% of a first 240 px step), tablets max 320 px, centred above the quote. Desktop grid `5fr 11fr` after reviewing screenshots of both, so the photo is Β±75% of its earlier size (Β±395Γ—495 px at 1440) and the whole block fits a Β±1000 px high screen. Stacked slides align their content to the top (a short review no longer floats in the middle of the shared height) with a 1.25 rem gap between photo and text. Placeholder heights re-measured. +## Later change (unit 5) +The quote is a plain `figure`/`blockquote`/`figcaption` instead of Chakra's `Blockquote`: its slot recipe pulled a shared chunk into the route bundle on page load (see the unit 5 code summary, performance). + ## Verification (`pnpm check`) - Lint βœ…, Prettier βœ…, build βœ… β€” carousel in its own chunk (`TestimonialCarousel-*.js`, 43 KB raw) - Tests: 42 files, **190 passed**; 100% coverage on the new `lib/` files diff --git a/aidlc-docs/features/homepage-sections/construction/plans/contact-code-generation-plan.md b/aidlc-docs/features/homepage-sections/construction/plans/contact-code-generation-plan.md new file mode 100644 index 0000000..c3855ea --- /dev/null +++ b/aidlc-docs/features/homepage-sections/construction/plans/contact-code-generation-plan.md @@ -0,0 +1,65 @@ +# Code Generation Plan β€” Unit 5: Contact + +**This plan is the single source of truth for Code Generation of unit 5.** + +## Unit context +- **Requirements**: FR-HP-06, FR-HP-07, FR-HP-08, FR-HP-09, NFR-HP-01/02/03/04/05/06 +- **Functional design**: [contact/functional-design/](../contact/functional-design/) β€” BR-FORM-01…13, BR-SEND-01…04, BR-SPAM-01…03, BR-GATE-01…03, BR-MAIL-01, BR-PARAM-02/04, BR-FOCUS-01 +- **Depends on**: unit 1 (`HomeSection`, `SectionHeading`, `Reveal`), unit 3 (`packages`, `visiblePackages`, `packageFromSearch`, `pakket` search), existing `emailAddress`, `linkButton` and `link` recipes +- **PBT**: full β€” all pure helpers plus a stateful test of the form reducer (PBT-06) +- Conventions as in units 1–4. + +## Steps + +### Types and content +- [x] **Step 1** β€” `src/contact/types.ts`: `ContactField`, `ContactValues`, `ContactErrors`, `ContactPayload`, `ShootOption`, `CONTACT_LIMITS` (naam 100, email 254, bericht 2000). `content/types.ts`: `HomeContent.contact { title; lead }`, `SiteContent.contactForm { enabled }`. Content: `homeContent.contact`, `siteContent.contactForm = { enabled: false }`. + +### Pure helpers (`src/lib/`, each with example and property tests) +- [x] **Step 2** β€” `shootOptions.ts`: shown packages (`visiblePackages`) + Overig. +- [x] **Step 3** β€” `validateContact.ts`: `validateField` and `validateContact` with the exact messages of BR-FORM-01…07. +- [x] **Step 4** β€” `toContactPayload.ts`: trimmed payload. +- [x] **Step 5** β€” `isLikelySpam.ts`: honeypot or under `MIN_FILL_MS = 3000`. +- [x] **Step 6** β€” `mailLink.ts`: `mailSubject(packageName?)`, `mailtoLink(address, subject)`. +- [x] **Step 7** β€” `contactFormReducer.ts`: state `{ status, values, touched, errors }`, events `edit`, `blur`, `preselect`, `submit`, `resolved`, `rejected` (BR-FORM-10…12, BR-SEND-01…04, BR-SPAM-02). Stateful property test with random event sequences checking the invariants of business-logic-model.md. +- [x] **Step 8** β€” `test/arbitraries.ts`: `contactValues` (valid), `anyContactValues`, `contactEvent`. + +### Adapter +- [x] **Step 9** β€” `src/contact/submitContactForm.ts` (+ test): `async (payload) => { throw new Error(...) }` today, with a comment pointing to `POST /api/contact` and the captcha token; generic, no details shown to visitors. + +### Styling +- [x] **Step 10** β€” `recipes/formControl.ts`: the design's square fields (white, `line` border, 0.95 Γ— 1.1 rem padding, weight 300, `accent` border + soft ring on focus, error border with sufficient contrast), applied to `Input`, `Textarea` and `NativeSelect.Field`; register in `theme.ts`. Add a `panel` shadow token (design `--shadow-md`) for the notice; error colour token if needed (β‰₯ 4.5:1 on paper). + +### Components +- [x] **Step 11** β€” `components/ContactForm/ContactForm.tsx`: reducer, `shownAt`, Chakra `Field` per field (labels in the eyebrow style, `ink.soft`), name + e-mail side by side from `sm`, select with placeholder, textarea, honeypot, empty `data-robot-check` slot, failure status (`role="alert"`, mail link), submit button (accent `linkButton` style, "Versturen…" while sending), thank-you replacing the form (`role="status"`, focused); `preselect` prop applied on change of its key; injectable `submit`. +- [x] **Step 12** β€” `components/ContactForm/ContactFormGate.tsx`: off β†’ dimmed, `inert` wrapper + notice (eyebrow, text with underline mail link, "Stuur een e-mail" button), text only when the address is invalid; on β†’ children. +- [x] **Step 13** β€” `components/home/ContactSection/ContactSection.tsx`: `HomeSection id="contact" width="narrow"`, heading (`tabIndex={-1}`) and lead, gate + form; resolves `pakket`, preselects, removes it from the URL (`navigate` replace, keep `#contact`, no scroll reset) and focuses the heading (BR-PARAM-02, BR-FOCUS-01). +- [x] **Step 14** β€” Tests: `ContactForm.test.tsx` (labels; blur shows errors only after typing; messages per rule; submit focuses first invalid; errors clear while typing; spam β†’ thank-you, `submit` not called; success β†’ thank-you focused; failure β†’ alert with mail link, values kept; double submit ignored; preselect; axe), `ContactFormGate.test.tsx` (inert form, notice, mailto with subject, invalid address β†’ text only, enabled β†’ form only, axe both), `ContactSection.test.tsx` (preselect from `pakket`, URL cleaned with replace, heading focused, unknown value ignored and cleaned, no focus move without `pakket`). + +### Route +- [x] **Step 15** β€” `routes/index.tsx`: render `ContactSection` after `Testimonials` with `homeContent.contact`, `packages`, `siteContent.contactForm.enabled`, `siteContent.email` and `pakket` from `Route.useSearch()`. +- [x] **Step 16** β€” `app.test.tsx`: "Contact" in the page order; `/?pakket=newborn` β†’ shoot "Newborn" selected, URL without `pakket`, focus on the Contact heading. + +### Verification and wrap-up +- [x] **Step 17** β€” `pnpm check`; Lighthouse home mobile compared with a 5-run median against the unit 4 build. **If the form code costs measurable performance** (as the carousel did), load the form (not the heading and notice) when the section comes near the screen, as in unit 4. Visual check at 1440 / 390 (gate on), and with the gate switched on locally for one screenshot of the working form. +- [x] **Step 18** β€” `construction/contact/code/code-summary.md`. +- [x] **Step 19** β€” Commit ("Adds the Contact section to the homepage" + attribution). Not pushed. + +### Fixes during Step 17 +- [x] **Step 17a** β€” Lighthouse median 0.83 β†’ 0.80: the form moved to its own chunk, loaded when the section is within 200 px of the screen or at once via "Boek …", and stays once loaded; placeholder of the measured height. +- [x] **Step 17b** β€” Remaining 0.81: a new shared chunk (Chakra's slot-recipe factory) was fetched by the route on load. PriceCard's `List` and TestimonialSlide's `Blockquote` replaced by plain elements with the same styling; median back to 0.83. + +## Requirement / rule traceability +| Item | Steps | +|---|---| +| FR-HP-06 / BR-FORM-* | 1–3, 7, 10, 11, 14 | +| FR-HP-07 / BR-GATE-* | 1, 12, 14 | +| FR-HP-08 / BR-SPAM-* | 5, 7, 11, 14 | +| FR-HP-09 | 11 (slot) | +| BR-SEND-* | 4, 7, 9, 11, 14 | +| BR-MAIL-01 | 6, 11, 12, 14 | +| BR-PARAM-02/04, BR-FOCUS-01 | 13, 14, 16 | +| NFR-HP-05 | 17 | + +## Extension compliance (planned) +- **Security**: client-side limits/format checks (server-side in the API feature, SECURITY-05); misuse covered by gate + honeypot + time check (SECURITY-11); generic failure text (SECURITY-15); e-mail never literal in HTML or bundle; no new dependencies or external resources; CSP unchanged. +- **PBT**: PBT-02 (mailto round-trip), PBT-03 (validation invariants), PBT-04 (payload idempotency), PBT-05 (spam and e-mail oracles), PBT-06 (reducer state machine), PBT-07 (generators), PBT-08/09 (existing), PBT-10 (example tests). diff --git a/aidlc-docs/features/homepage-sections/construction/plans/contact-fd-clarification-questions.md b/aidlc-docs/features/homepage-sections/construction/plans/contact-fd-clarification-questions.md new file mode 100644 index 0000000..cfeb60e --- /dev/null +++ b/aidlc-docs/features/homepage-sections/construction/plans/contact-fd-clarification-questions.md @@ -0,0 +1,20 @@ +# Functional Design β€” Vervolgvragen Unit 5: Contact + +## Ontbrekend antwoord: Vraag 6 β€” Versturen mislukt (straks, met de API) +Vraag 6 in [contact-fd-questions.md](contact-fd-questions.md) is nog niet beantwoord. + +- A) Een melding boven de knop: "Versturen lukte niet. Probeer het later nog eens of mail naar info@andreaslop.nl", met het adres als mailto-link. Wat de bezoeker typte blijft staan. (aanbevolen) +- B) Alleen "Versturen lukte niet. Probeer het later nog eens." +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Onduidelijkheid: melding "te lang" bij Vraag 2 +Je gaf voor "te lang": "Het bericht is te lang". Er gelden ook grenzen voor naam (100 tekens) en e-mail (254 tekens). +Let op: de velden krijgen ook een maximum in de browser, zodat je er niet meer in kunt typen of plakken. De melding is dus vooral een vangnet en zal een bezoeker zelden zien. + +- A) Per veld een eigen melding: "De naam is te lang.", "Het e-mailadres is te lang.", "Het bericht is te lang." (aanbevolen) +- B) Overal dezelfde melding: "Het bericht is te lang" +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A diff --git a/aidlc-docs/features/homepage-sections/construction/plans/contact-fd-questions.md b/aidlc-docs/features/homepage-sections/construction/plans/contact-fd-questions.md new file mode 100644 index 0000000..46cf7ee --- /dev/null +++ b/aidlc-docs/features/homepage-sections/construction/plans/contact-fd-questions.md @@ -0,0 +1,63 @@ +# Functional Design Questions β€” Unit 5: Contact + +Vul per vraag de letter in na `[Answer]:` (of geef ze in de chat, bijv. "1A, 2A, …"). Past geen enkele optie, kies dan de laatste (Anders) en licht toe. Waar ik een voorkeur heb staat **(aanbevolen)**. + +Zolang het formulier achter de overlay zit, merkt een bezoeker van vraag 1–3 nog niets; ze bepalen hoe het werkt zodra je het aanzet (of als je het op test even aanzet om te proberen). + +## Vraag 1: Wanneer verschijnen foutmeldingen? + +- A) Pas bij versturen. Daarna wordt per veld opnieuw gecontroleerd zodra de bezoeker het aanpast, zodat een melding verdwijnt zodra het goed is. Niemand krijgt een fout tijdens het typen van een eerste poging. (aanbevolen) +- B) Bij het verlaten van elk veld (tab of klik ergens anders), en bij versturen +- C) Alleen bij versturen; meldingen blijven staan tot de volgende poging +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: B + +## Vraag 2: Foutmeldingen +Voorstel (uit het ontwerp, aangevuld): +- Naam leeg: "Vul je naam in." +- E-mail leeg: "Vul je e-mailadres in." Β· ongeldig: "Dit e-mailadres klopt nog niet." +- Shoot niet gekozen: "Kies een soort shoot." +- Bericht leeg: "Schrijf hier je vraag." +- Te lang (naam 100, e-mail 254, bericht 2000 tekens): "Dit is te lang (maximaal N tekens)." + +- A) Zo overnemen (aanbevolen) +- X) Anders (pas hieronder aan na de [Answer]:-tag) + +[Answer]: X β€” E-mail ongeldig: "Dit e-mailadres is ongeldig." Te lang: "Het bericht is te lang" + +## Vraag 3: Na succesvol versturen + +- A) Het formulier verdwijnt en er komt een bevestiging voor in de plaats: "Bedankt voor je bericht! Andrea reageert binnen 2-3 werkdagen." De focus gaat naar die bevestiging, zodat ook een schermlezer hem hoort. (aanbevolen) +- B) Het formulier blijft staan en wordt leeggemaakt; de bevestiging staat eronder +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +Klopt "binnen 2-3 werkdagen"? Pas het anders aan bij je antwoord. + +[Answer]: A, maar het bericht is: "Bedankt voor je bericht! Ik reageer binnen 1-2 werkdagen." + +## Vraag 4: De mailknop in de overlay + +- A) De mail krijgt alvast een onderwerp: "Vraag via andreaslop.nl", en als de bezoeker via "Boek …" kwam het pakket erbij: "Aanvraag fotoshoot: Newborn". Scheelt de bezoeker typen en Andrea ziet meteen waar het over gaat. (aanbevolen) +- B) Een gewone mailto zonder onderwerp +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Vraag 5: Waar komt de focus na "Boek …"? +Na een klik op "Boek Newborn" scrollt de pagina naar Contact. De toetsenbordfocus staat dan nog op de knop bij Prijzen, buiten beeld: wie daarna op Tab drukt, springt terug omhoog. + +- A) De focus gaat naar de kop "Contact" (onzichtbaar, zonder focusring). Toetsenbord- en schermlezergebruikers zitten dan op de juiste plek; de volgende Tab gaat naar het formulier, of nu naar de mailknop. (aanbevolen) +- B) De focus gaat direct naar het keuzeveld "In welke shoot …" (of nu naar de mailknop) +- C) Niets aan doen +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A + +## Vraag 6: Versturen mislukt (straks, met de API) + +- A) Een melding boven de knop: "Versturen lukte niet. Probeer het later nog eens of mail naar info@andreaslop.nl", met het adres als mailto-link. Wat de bezoeker typte blijft staan. (aanbevolen) +- B) Alleen "Versturen lukte niet. Probeer het later nog eens." +- X) Anders (beschrijf hieronder na de [Answer]:-tag) + +[Answer]: A (via contact-fd-clarification-questions.md) diff --git a/aidlc-docs/features/homepage-sections/construction/plans/contact-functional-design-plan.md b/aidlc-docs/features/homepage-sections/construction/plans/contact-functional-design-plan.md new file mode 100644 index 0000000..15a0d65 --- /dev/null +++ b/aidlc-docs/features/homepage-sections/construction/plans/contact-functional-design-plan.md @@ -0,0 +1,12 @@ +# Functional Design Plan β€” Unit 5: Contact + +Scope: FR-HP-06 (form), FR-HP-07 (coming-soon gate), FR-HP-08 (anti-spam, browser side), FR-HP-09 (robot-check slot), and BR-PARAM-02…04 from unit 3 (applying and removing `?pakket=`). Questions: [contact-fd-questions.md](contact-fd-questions.md). + +Already fixed by requirements and earlier design (no question): fields Naam, E-mail, "In welke shoot heb je interesse?" (package names + Overig), "Stel hier je vraag"; button "(Aan)vraag versturen"; gate on by default via `siteContent.contactForm.enabled = false`, form dimmed and `inert`, notice "Het contactformulier komt binnenkort. Mail me voor nu op info@andreaslop.nl" with a mail button; address assembled in the browser; honeypot + Β±3 s time check, spam gets the normal success and nothing is sent; `submitContactForm` adapter (rejects generically today); Friendly Captcha later; last "Boek" click wins; `?pakket=` removed from the URL once applied. + +- [x] 1. Collect and analyze answers (follow-up questions if needed) +- [x] 2. `domain-entities.md` β€” `ContactValues`, `ContactPayload`, `ContactErrors`, `ShootOption`, field limits, `siteContent.contactForm` +- [x] 3. `business-rules.md` β€” validation rules and messages, when errors appear and disappear, spam rules, submit states (idle, sending, sent, failed), gate on/off, mail link, preselection and URL clean-up, focus after "Boek"; decision flowcharts +- [x] 4. `business-logic-model.md` β€” submit sequence, the form state machine, pure functions (`shootOptions`, `validateContact`, `toContactPayload`, `isLikelySpam`, `mailtoLink`), PBT-01 properties incl. a stateful check of the form states (PBT-06) +- [x] 5. `frontend-components.md` β€” `ContactSection`, `ContactFormGate`, `ContactForm`; props, states, layout, accessibility +- [x] 6. Validate against FR-HP-06…09, BR-PARAM-02…04, NFR-HP-01/03/04 and the Security/PBT extensions diff --git a/aidlc-docs/features/homepage-sections/construction/prijzen/code/code-summary.md b/aidlc-docs/features/homepage-sections/construction/prijzen/code/code-summary.md index 6cb546e..fd4663d 100644 --- a/aidlc-docs/features/homepage-sections/construction/prijzen/code/code-summary.md +++ b/aidlc-docs/features/homepage-sections/construction/prijzen/code/code-summary.md @@ -35,6 +35,9 @@ Plan: [prijzen-code-generation-plan.md](../../plans/prijzen-code-generation-plan ## Change request after testing on test (2026-10-20) The owner removed the hover effect from the cards (lift, accent border, shadow); only the booking button keeps its effects. Removed in `PriceCard.tsx`, the `lift` shadow token in `theme.ts`, the static design (`.price-card:hover`) and the functional design. +## Later change (unit 5) +The feature list is a plain `ul`/`li` instead of Chakra's `List`: its slot recipe pulled a shared chunk into the route bundle on page load (see the unit 5 code summary, performance). + ## Property-based tests (PBT) | Function | Properties | |---|---| diff --git a/web/src/app.test.tsx b/web/src/app.test.tsx index ab15e4b..0692595 100644 --- a/web/src/app.test.tsx +++ b/web/src/app.test.tsx @@ -4,7 +4,7 @@ import { createRouter, RouterProvider, } from '@tanstack/react-router'; -import { render, screen } from '@testing-library/react'; +import { render, screen, waitFor, within } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import lighthouseConfig from '../lighthouserc.cjs'; import ErrorPage from './components/StatusPage/ErrorPage'; @@ -146,6 +146,7 @@ describe('homepage', () => { }), screen.getByRole('region', { name: 'Prijzen' }), screen.getByRole('region', { name: 'Lieve woorden' }), + screen.getByRole('region', { name: 'Contact' }), ]; let previous: Element = hero; @@ -162,6 +163,27 @@ describe('homepage', () => { }); describe('homepage ?pakket=', () => { + it('a "Boek Newborn" link selects Newborn, tidies the URL and focuses Contact', async () => { + const { router } = await renderApp('/?pakket=newborn#contact'); + // The form is lazy; arriving via "Boek" loads it straight away + expect( + await screen.findByTestId('contact-form-shoot', undefined, { + timeout: 10_000, + }), + ).toHaveValue('newborn'); + await waitFor(() => expect(router.state.location.searchStr).toBe('')); + expect(router.state.location.hash).toBe('contact'); + // The form stays once loaded, also now that ?pakket= is gone + expect(screen.getByTestId('contact-form-shoot')).toHaveValue('newborn'); + // within the section: the footer has a "Contact" heading too + expect( + within(screen.getByRole('region', { name: 'Contact' })).getByRole( + 'heading', + { level: 2 }, + ), + ).toHaveFocus(); + }); + it.each(['/?pakket=newborn', '/?pakket=123', '/?pakket=%3Cscript%3E'])( '%s renders the homepage without errors', async (path) => { diff --git a/web/src/components/ContactForm/ContactForm.test.tsx b/web/src/components/ContactForm/ContactForm.test.tsx new file mode 100644 index 0000000..c3004f8 --- /dev/null +++ b/web/src/components/ContactForm/ContactForm.test.tsx @@ -0,0 +1,216 @@ +import { useState } from 'react'; +import { act, fireEvent, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import packages from '@/content/packages'; +import siteContent from '@/content/siteContent'; +import { shootOptions } from '@/lib/shootOptions'; +import { axeResults } from '@/test/axe'; +import { renderWithProviders } from '@/test/renderWithProviders'; +import ContactForm from './ContactForm'; + +const options = shootOptions(packages); + +// The time check needs over 3 s between showing and sending (BR-SPAM-01) +let now = 0; +beforeEach(() => { + now = 0; + vi.spyOn(Date, 'now').mockImplementation(() => now); +}); + +const renderForm = ( + props: Partial> = {}, +) => + renderWithProviders( + , + ); + +const field = (name: string) => screen.getByTestId(`contact-form-${name}`); +const type = (name: string, value: string) => + fireEvent.change(field(name), { target: { value } }); +const fillIn = () => { + type('naam', 'Demi'); + type('email', 'demi@example.nl'); + type('shoot', 'newborn'); + type('bericht', 'Wanneer heb je plek?'); +}; +const send = () => { + now = 10_000; + fireEvent.click(screen.getByTestId('contact-form-submit')); +}; + +describe('ContactForm', () => { + it('shows the four labelled fields and the button', async () => { + const { container } = await renderForm(); + expect(screen.getByLabelText(/Naam/)).toBe(field('naam')); + expect(screen.getByLabelText(/E-mail/)).toBe(field('email')); + expect(screen.getByLabelText(/In welke shoot/)).toBe(field('shoot')); + expect(screen.getByLabelText(/Stel hier je vraag/)).toBe( + field('bericht'), + ); + expect( + screen.getByRole('option', { name: 'Kies een optie...' }), + ).toBeInTheDocument(); + expect( + screen.getByRole('button', { name: '(Aan)vraag versturen' }), + ).toBeInTheDocument(); + expect(await axeResults(container)).toHaveNoViolations(); + }); + + it('shows nothing when tabbing through an untouched field', async () => { + await renderForm(); + fireEvent.blur(field('naam')); + expect(screen.queryByText('Vul je naam in.')).toBeNull(); + }); + + it('checks a field on leaving once typed in, and clears it once fine', async () => { + await renderForm(); + type('email', 'demi@'); + fireEvent.blur(field('email')); + expect( + screen.getByText('Dit e-mailadres is ongeldig.'), + ).toBeInTheDocument(); + expect(field('email')).toHaveAttribute('aria-invalid', 'true'); + + type('email', 'demi@example.nl'); + expect(screen.queryByText('Dit e-mailadres is ongeldig.')).toBeNull(); + }); + + it('stops an incomplete submit and focuses the first invalid field', async () => { + const submit = vi.fn(); + await renderForm({ submit }); + type('naam', 'Demi'); + send(); + expect(screen.getByText('Vul je e-mailadres in.')).toBeInTheDocument(); + expect(screen.getByText('Kies een soort shoot.')).toBeInTheDocument(); + expect(screen.getByText('Schrijf hier je vraag.')).toBeInTheDocument(); + expect(field('email')).toHaveFocus(); + expect(submit).not.toHaveBeenCalled(); + }); + + it('sends the trimmed form and shows the thank-you with focus', async () => { + const submit = vi.fn().mockResolvedValue(undefined); + await renderForm({ submit }); + fillIn(); + type('naam', ' Demi '); + send(); + expect(screen.getByTestId('contact-form-submit')).toHaveTextContent( + 'Versturen…', + ); + expect(submit).toHaveBeenCalledWith({ + naam: 'Demi', + email: 'demi@example.nl', + shoot: 'newborn', + bericht: 'Wanneer heb je plek?', + }); + const thanks = await screen.findByTestId('contact-form-sent'); + expect(thanks).toHaveTextContent( + 'Bedankt voor je bericht! Ik reageer binnen 1-2 werkdagen.', + ); + await waitFor(() => expect(thanks).toHaveFocus()); + expect(screen.queryByTestId('contact-form')).toBeNull(); + }); + + it('keeps the input and offers the mail link when sending fails', async () => { + await renderForm({ submit: vi.fn().mockRejectedValue(new Error('x')) }); + fillIn(); + send(); + const status = await screen.findByRole('alert'); + expect(status).toHaveTextContent( + 'Versturen lukte niet. Probeer het later nog eens of mail naar info@andreaslop.nl', + ); + expect( + screen.getByRole('link', { name: 'info@andreaslop.nl' }), + ).toHaveAttribute( + 'href', + 'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl', + ); + expect(field('naam')).toHaveValue('Demi'); + expect(screen.getByTestId('contact-form-submit')).not.toBeDisabled(); + }); + + it('treats a filled honeypot as spam: thank-you, nothing sent', async () => { + const submit = vi.fn(); + const { container } = await renderForm({ submit }); + fillIn(); + fireEvent.change( + container.querySelector('input[name="website"]') as Element, + { target: { value: 'https://spam.example' } }, + ); + send(); + expect(screen.getByTestId('contact-form-sent')).toBeInTheDocument(); + expect(submit).not.toHaveBeenCalled(); + }); + + it('treats a submit within 3 seconds as spam', async () => { + const submit = vi.fn(); + await renderForm({ submit }); + fillIn(); + now = 1_000; + fireEvent.click(screen.getByTestId('contact-form-submit')); + expect(screen.getByTestId('contact-form-sent')).toBeInTheDocument(); + expect(submit).not.toHaveBeenCalled(); + }); + + it('ignores a second submit while sending', async () => { + let finish = () => {}; + const submit = vi.fn( + () => new Promise((resolve) => (finish = resolve)), + ); + await renderForm({ submit }); + fillIn(); + send(); + fireEvent.click(screen.getByTestId('contact-form-submit')); + expect(submit).toHaveBeenCalledTimes(1); + await act(async () => finish()); + }); + + it('takes over a preselected package, also again after a change', async () => { + // A second "Boek" click for the same package raises the key + function Harness() { + const [preselect, setPreselect] = useState({ + shoot: 'newborn', + key: 1, + }); + return ( + <> + + + + ); + } + await renderWithProviders(); + expect(field('shoot')).toHaveValue('newborn'); + type('shoot', 'gezin'); + expect(field('shoot')).toHaveValue('gezin'); + fireEvent.click(screen.getByRole('button', { name: 'nog eens' })); + expect(field('shoot')).toHaveValue('newborn'); + }); + + it('keeps the honeypot away from people and assistive technology', async () => { + const { container } = await renderForm(); + const honeypot = container.querySelector('input[name="website"]'); + expect(honeypot).toHaveAttribute('tabindex', '-1'); + expect(honeypot?.closest('[aria-hidden="true"]')).not.toBeNull(); + expect(container.querySelector('[data-robot-check]')).not.toBeNull(); + }); +}); diff --git a/web/src/components/ContactForm/ContactForm.tsx b/web/src/components/ContactForm/ContactForm.tsx new file mode 100644 index 0000000..7a235c1 --- /dev/null +++ b/web/src/components/ContactForm/ContactForm.tsx @@ -0,0 +1,304 @@ +import { useEffect, useRef, useState, useReducer } from 'react'; +import { + Box, + chakra, + Field, + Input, + Link, + NativeSelect, + SimpleGrid, + Stack, + Text, + Textarea, + useRecipe, +} from '@chakra-ui/react'; +import { submitContactForm } from '@/contact/submitContactForm'; +import { + CONTACT_LIMITS, + type ContactField, + type ContactPayload, + type ShootOption, +} from '@/contact/types'; +import type { EmailAddress } from '@/content/types'; +import { + contactFormReducer, + INITIAL_CONTACT_STATE, + type ContactFormEvent, +} from '@/lib/contactFormReducer'; +import { emailAddress } from '@/lib/emailAddress'; +import { mailtoLink } from '@/lib/mailLink'; +import { toContactPayload } from '@/lib/toContactPayload'; +import { CONTACT_FIELDS } from '@/lib/validateContact'; + +type ContactFormProps = { + // Prefix for the field ids, so the form can appear on more than one page + idPrefix: string; + options: ShootOption[]; + // A package chosen via "Boek ..."; key changes on every click, so the + // same package can be applied again after the visitor changed it + preselect?: { shoot: string; key: number }; + mailSubject: string; + email: EmailAddress; + submit?: (payload: ContactPayload) => Promise; +}; + +const SENT_MESSAGE = + 'Bedankt voor je bericht! Ik reageer binnen 1-2 werkdagen.'; + +// The contact form (design .form): name and e-mail, the shoot, the question, +// and the browser-side anti-spam. Its behaviour is the pure +// contactFormReducer; this component wires it to the fields. +export default function ContactForm({ + idPrefix, + options, + preselect, + mailSubject, + email, + submit = submitContactForm, +}: ContactFormProps) { + const reduce = ( + state: typeof INITIAL_CONTACT_STATE, + event: ContactFormEvent, + ) => contactFormReducer(state, event, options); + const [state, dispatch] = useReducer(reduce, INITIAL_CONTACT_STATE); + const formControl = useRecipe({ key: 'formControl' }); + const linkButton = useRecipe({ key: 'linkButton' }); + + // When the form became usable, for the time check (BR-SPAM-01) + const [shownAt] = useState(() => Date.now()); + const honeypot = useRef(null); + const sentMessage = useRef(null); + + // Apply a new "Boek ..." choice while rendering (React's pattern for + // reacting to a changed prop), so it never shows a stale value first + const [seenPreselect, setSeenPreselect] = useState(0); + if (preselect && preselect.key !== seenPreselect) { + setSeenPreselect(preselect.key); + dispatch({ type: 'preselect', shoot: preselect.shoot }); + } + + // After a stopped submit, focus the first field with an error + useEffect(() => { + if (state.invalidSubmits === 0) return; + const first = CONTACT_FIELDS.find((field) => state.errors[field]); + if (first) document.getElementById(`${idPrefix}-${first}`)?.focus(); + // Only on a new stopped submit, not on every error change + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [state.invalidSubmits]); + + // The thank-you replaces the form; move focus there (BR-SEND-02) + useEffect(() => { + if (state.status === 'sent') sentMessage.current?.focus(); + }, [state.status]); + + const address = emailAddress(email); + const disabled = state.status === 'sending'; + + if (state.status === 'sent') { + return ( + + {SENT_MESSAGE} + + ); + } + + const onSubmit = (event: React.FormEvent) => { + event.preventDefault(); + const submitEvent: ContactFormEvent = { + type: 'submit', + honeypot: honeypot.current?.value ?? '', + shownAt, + now: Date.now(), + }; + // Sending starts here, not in an effect, so it happens exactly once + const next = reduce(state, submitEvent); + dispatch(submitEvent); + if (next.status === 'sending') { + submit(toContactPayload(state.values)).then( + () => dispatch({ type: 'resolved' }), + () => dispatch({ type: 'rejected' }), + ); + } + }; + + // The control's id comes from Field.Root's id (Ark uses it for the + // control and the label's htmlFor), so label and error stay linked + const fieldProps = (field: ContactField) => ({ + name: field, + value: state.values[field], + onChange: ( + event: React.ChangeEvent< + HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement + >, + ) => dispatch({ type: 'edit', field, value: event.target.value }), + onBlur: () => dispatch({ type: 'blur', field }), + css: formControl(), + 'data-testid': `contact-form-${field}`, + }); + + const label = (text: string) => ( + // ink.soft instead of the design's muted grey: meets 4.5:1 + + {text} + + ); + const error = (field: ContactField) => ( + + {state.errors[field]} + + ); + + return ( + + + + + {label('Naam')} + + {error('naam')} + + + {label('E-mail')} + + {error('email')} + + + + + {label('In welke shoot heb je interesse?')} + + + + {options.map((option) => ( + + ))} + + + + {error('shoot')} + + + + {label('Stel hier je vraag')} +