diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 3797ae7d..524a06a1 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -32,7 +32,7 @@ Set the following in the Cloudflare Pages dashboard (Production and Preview are - `EO_API_KEY` — EmailOctopus donor/member sync - `QGIV_API_TOKEN` — Qgiv reporting API token used to verify completed transactions server-side. Permanent token, scoped to the membership, supporting-member and donation forms. **Required:** without it both completion endpoints fail closed and no member is invited. - `PLAUSIBLE_API_KEY` — Stats API for the admin conversion dashboard -- `NAV_ASSIGNMENT_SECRET` — random string (e.g. `openssl rand -hex 32`) keying the daily, cookie-free visitor hash for the navbar A/B test (`src/lib/navAssignment.ts`). Without it the variant is re-picked on every request and a warning is logged. +- `NAV_ASSIGNMENT_SECRET` — random string (e.g. `openssl rand -hex 32`) keying the daily, cookie-free visitor hash for server-side A/B tests, currently the homepage hero photo test (`src/lib/visitorAssignment.ts`). Without it nobody is assigned (everyone sees the control) and a warning is logged. The name dates from the first test, the navbar label test. - `ADMIN_USERNAME`, `ADMIN_PASSWORD` — HTTP Basic Auth for `/admin/conversions` **Sentry** diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a1214d9b..3f4197f2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -38,6 +38,10 @@ export const onRequest = sequence(sentryInit, securityHeaders, cacheControl, csp | **EmailOctopus** | `api/donation-complete.ts`, `api/membership-complete.ts` | Donor/member mailing list sync | | **Sentry** | `sentry.client.config.js`, `sentry.server.config.js`, `src/lib/report-error.ts`, inbound webhook at `api/sentry-webhook.ts` | Error monitoring + Mattermost alert relay | +## Homepage hero photo A/B test + +The homepage hero photo is a GrowthBook experiment (`homepage-hero-photo`, four variants), assigned server-side in `src/pages/index.astro` via `src/lib/heroPhotoAssignment.ts` and measured in Plausible through the `hero_photo` pageview property and `Homepage Link Click` events. Visitors are assigned with the daily cookieless visitor hash in `src/lib/visitorAssignment.ts`. Any assignment failure falls back to the control photo. See `docs/superpowers/specs/2026-11-25-homepage-hero-photo-ab-test-design.md`. + ## Content collections `src/content/config.ts` currently defines `collections = {}` — empty. Older documentation and some historical plans reference markdown-based `ideas/`/`projects/` content collections; that data now comes from Notion and ProjectHub respectively (see tables above). Don't assume `src/content/` holds live data without checking the collections config first. diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index e372a4d7..c8625c26 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -40,38 +40,38 @@ A few variables are read directly via `process.env` / `import.meta.env` in confi Ground truth = every `getEnv("X", ...)` call in `src/`, plus the build-time reads above. Cross-checked against `.env.example`, `.env`, `.dev.vars` (presence only — I did not read or record any secret values). -| Variable | Read via | In `.env.example`? | In local `.env`? | In local `.dev.vars`? | Consumers | -| ------------------------------ | ---------------------------- | :----------------: | :--------------: | :-------------------: | --------------------------------------------------------------------------------------------------------------------------- | -| `NOTION_SECRET` | `getEnv` | ✅ | ✅ | ❌ | All Notion routes | -| `EVENTS_ICS_URL` | `getEnv` | ✅ | ❌ | ✅ | Events (`fetchEvents` in `eventsClient.ts`) — public ICS feed URL with a token | -| `NOTION_SIGNATORIES_DB_ID` | `getEnv` | ✅ | ✅ | ❌ | E4P pledge/signatories | -| `NOTION_FAQ_DB_ID` | `getEnv` | ✅ | ✅ | ❌ | FAQ | -| `NOTION_IDEAS_DB_ID` | `getEnv` | ✅ | ✅ | ❌ | Ideas | -| `NOTION_AGENDA_DB_ID` | `getEnv` | ✅ | ✅ | ❌ | Agenda/speakers | -| `NOTION_ENDORSEMENTS_DB_ID` | `getEnv` | ✅ | ✅ | ❌ | Endorsement requests | -| `NOTION_COMMUNITY_CALLS_DB_ID` | `getEnv` | ✅ | ❌ **new** | ❌ | Community Call page/banner — add to local `.env` and the Cloudflare Pages dashboard | -| `NOTION_SPEAKERS_DB_ID` | — | ✅ | ✅ | ❌ | **Not read anywhere in code** — see [NOTION.md](NOTION.md) | -| `PROJECTHUB_API_KEY` | `getEnv` | ✅ | ❌ | ✅ | `/api/projects` | -| `PUBLIC_API_URL` | `getEnv` | ❌ **missing** | ❌ | ❌ | `/api/project-proxy` — always 503 locally without it | -| `PUBLIC_SECRET_KEY` | `getEnv` | ❌ **missing** | ❌ | ❌ | `/api/project-proxy` — always 503 locally without it | -| `HUB_API_URL` | `getEnv` | ✅ | ❌ | ✅ | `/api/membership-complete` | -| `HUB_API_KEY` | `getEnv` | ✅ | ❌ | ✅ | `/api/membership-complete` | -| `EO_API_KEY` | `getEnv` | ✅ | ❌ | ❌ | `/api/donation-complete`, `/api/membership-complete` | -| `QGIV_API_TOKEN` | `getEnv` | ✅ | ❌ | ❌ | `/api/membership-complete`, `/api/donation-complete` | -| `PLAUSIBLE_API_KEY` | `getEnv` | ✅ | ❌ | ✅ | `/api/admin/conversion-stats` | -| `NAV_ASSIGNMENT_SECRET` | `getEnv` | ✅ | ❌ | ❌ | **New.** Navbar A/B test: keys the daily visitor hash (`src/lib/navAssignment.ts`). Without it variants re-roll per request | -| `ADMIN_USERNAME` | `getEnv` | ❌ **missing** | ✅ | ✅ | Basic Auth for `/admin/conversions` | -| `ADMIN_PASSWORD` | `getEnv` | ❌ **missing** | ✅ | ✅ | Basic Auth for `/admin/conversions` | -| `SENTRY_WEBHOOK_SECRET` | `getEnv` | ✅ | ❌ | ⚠️ **typo** | `/api/sentry-webhook` — see gap below | -| `MATTERMOST_URL` | `getEnv` | ✅ | ❌ | ❌ | `/api/sentry-webhook` | -| `MATTERMOST_BOT_TOKEN` | `getEnv` | ✅ | ❌ | ❌ | `/api/sentry-webhook` | -| `MATTERMOST_CHANNEL_ID` | `getEnv` | ✅ | ❌ | ❌ | `/api/sentry-webhook` | -| `MEMBERSHIP_LIVE` | `getEnv` | ❌ **missing** | ❌ | ❌ | **Dead** — read only by `HomeLayout` and `-new` pages, none of which are reachable | -| `SENTRY_DSN` | `process.env` (build/server) | ✅ | ✅ | ✅ | `sentry.server.config.js` | -| `SENTRY_ENVIRONMENT` | `process.env` | ✅ | ✅ | ✅ | `sentry.server.config.js` | -| `PUBLIC_SENTRY_DSN` | `import.meta.env` | ✅ | ✅ | ✅ | `sentry.client.config.js` (bundled into browser JS) | -| `PUBLIC_SENTRY_ENVIRONMENT` | `import.meta.env` | ✅ | ✅ | ✅ | `sentry.client.config.js` (bundled into browser JS) | -| `SENTRY_AUTH_TOKEN` | `process.env` (build only) | ✅ | ✅ | ✅ | `astro.config.mjs`, source-map upload during `pnpm build` | +| Variable | Read via | In `.env.example`? | In local `.env`? | In local `.dev.vars`? | Consumers | +| ------------------------------ | ---------------------------- | :----------------: | :--------------: | :-------------------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `NOTION_SECRET` | `getEnv` | ✅ | ✅ | ❌ | All Notion routes | +| `EVENTS_ICS_URL` | `getEnv` | ✅ | ❌ | ✅ | Events (`fetchEvents` in `eventsClient.ts`) — public ICS feed URL with a token | +| `NOTION_SIGNATORIES_DB_ID` | `getEnv` | ✅ | ✅ | ❌ | E4P pledge/signatories | +| `NOTION_FAQ_DB_ID` | `getEnv` | ✅ | ✅ | ❌ | FAQ | +| `NOTION_IDEAS_DB_ID` | `getEnv` | ✅ | ✅ | ❌ | Ideas | +| `NOTION_AGENDA_DB_ID` | `getEnv` | ✅ | ✅ | ❌ | Agenda/speakers | +| `NOTION_ENDORSEMENTS_DB_ID` | `getEnv` | ✅ | ✅ | ❌ | Endorsement requests | +| `NOTION_COMMUNITY_CALLS_DB_ID` | `getEnv` | ✅ | ❌ **new** | ❌ | Community Call page/banner — add to local `.env` and the Cloudflare Pages dashboard | +| `NOTION_SPEAKERS_DB_ID` | — | ✅ | ✅ | ❌ | **Not read anywhere in code** — see [NOTION.md](NOTION.md) | +| `PROJECTHUB_API_KEY` | `getEnv` | ✅ | ❌ | ✅ | `/api/projects` | +| `PUBLIC_API_URL` | `getEnv` | ❌ **missing** | ❌ | ❌ | `/api/project-proxy` — always 503 locally without it | +| `PUBLIC_SECRET_KEY` | `getEnv` | ❌ **missing** | ❌ | ❌ | `/api/project-proxy` — always 503 locally without it | +| `HUB_API_URL` | `getEnv` | ✅ | ❌ | ✅ | `/api/membership-complete` | +| `HUB_API_KEY` | `getEnv` | ✅ | ❌ | ✅ | `/api/membership-complete` | +| `EO_API_KEY` | `getEnv` | ✅ | ❌ | ❌ | `/api/donation-complete`, `/api/membership-complete` | +| `QGIV_API_TOKEN` | `getEnv` | ✅ | ❌ | ❌ | `/api/membership-complete`, `/api/donation-complete` | +| `PLAUSIBLE_API_KEY` | `getEnv` | ✅ | ❌ | ✅ | `/api/admin/conversion-stats` | +| `NAV_ASSIGNMENT_SECRET` | `getEnv` | ✅ | ❌ | ❌ | Keys the daily visitor hash (`src/lib/visitorAssignment.ts`) for the homepage hero photo A/B test. Without it nobody is assigned: everyone sees the control photo and nothing is tracked | +| `ADMIN_USERNAME` | `getEnv` | ❌ **missing** | ✅ | ✅ | Basic Auth for `/admin/conversions` | +| `ADMIN_PASSWORD` | `getEnv` | ❌ **missing** | ✅ | ✅ | Basic Auth for `/admin/conversions` | +| `SENTRY_WEBHOOK_SECRET` | `getEnv` | ✅ | ❌ | ⚠️ **typo** | `/api/sentry-webhook` — see gap below | +| `MATTERMOST_URL` | `getEnv` | ✅ | ❌ | ❌ | `/api/sentry-webhook` | +| `MATTERMOST_BOT_TOKEN` | `getEnv` | ✅ | ❌ | ❌ | `/api/sentry-webhook` | +| `MATTERMOST_CHANNEL_ID` | `getEnv` | ✅ | ❌ | ❌ | `/api/sentry-webhook` | +| `MEMBERSHIP_LIVE` | `getEnv` | ❌ **missing** | ❌ | ❌ | **Dead** — read only by `HomeLayout` and `-new` pages, none of which are reachable | +| `SENTRY_DSN` | `process.env` (build/server) | ✅ | ✅ | ✅ | `sentry.server.config.js` | +| `SENTRY_ENVIRONMENT` | `process.env` | ✅ | ✅ | ✅ | `sentry.server.config.js` | +| `PUBLIC_SENTRY_DSN` | `import.meta.env` | ✅ | ✅ | ✅ | `sentry.client.config.js` (bundled into browser JS) | +| `PUBLIC_SENTRY_ENVIRONMENT` | `import.meta.env` | ✅ | ✅ | ✅ | `sentry.client.config.js` (bundled into browser JS) | +| `SENTRY_AUTH_TOKEN` | `process.env` (build only) | ✅ | ✅ | ✅ | `astro.config.mjs`, source-map upload during `pnpm build` | ## Gaps found in this audit (2026-07-11) diff --git a/docs/superpowers/plans/2026-11-25-homepage-hero-photo-ab-test.md b/docs/superpowers/plans/2026-11-25-homepage-hero-photo-ab-test.md new file mode 100644 index 00000000..0e138b35 --- /dev/null +++ b/docs/superpowers/plans/2026-11-25-homepage-hero-photo-ab-test.md @@ -0,0 +1,186 @@ +# Homepage Hero Photo A/B Test Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Show each homepage visitor one of four hero photos (same photo all day, chosen by GrowthBook on the server) and measure bounce rate, scroll depth, time on page and clicks to `/membership`, `/volunteer`, `/projects`, `/incubator` per photo in Plausible. + +**Architecture:** `index.astro` evaluates a new GrowthBook flag `homepage-hero-photo` during SSR with the existing daily cookieless id (`requestAssignmentId`), renders the assigned photo, and passes `hero_photo` to `Layout.astro`, which emits it in a `` that the Plausible `init()` reads as `customProperties`. A delegated click listener sends `Homepage Link Click`. Separately, load-time Plausible events become `interactive: false` so bounce rate is real. + +**Tech Stack:** Astro 5 SSR on Cloudflare Pages, `@growthbook/growthbook`, Plausible (new `pa-*.js` script with `plausible.init`), Vitest (node env), ImageMagick (`magick`) for WebP conversion. + +**Spec:** `docs/superpowers/specs/2026-11-25-homepage-hero-photo-ab-test-design.md` + +## Global Constraints + +- Package manager `pnpm`; never `npx astro`, never regenerate `package-lock.json`. +- No inline `style=""` attributes and no `'unsafe-inline'` (CSP, `src/middleware/csp.ts`). Crop positions are Tailwind arbitrary classes. +- Nothing stored on the visitor's device: no cookies, no localStorage, no client-side variant choice. +- Unassigned visitors (flag off/missing, CDN down, no id in `pnpm dev`) see `control` and send **no** `hero_photo` property and **no** `Homepage Link Click` event. +- Flag key `homepage-hero-photo`; variant values exactly `control`, `speaker`, `laptops`, `stage`; Plausible property `hero_photo`; event `Homepage Link Click` with prop `destination` ∈ `/membership`, `/volunteer`, `/projects`, `/incubator`. +- Assigned only when GrowthBook's result `source === "experiment"` and the value is a known variant. +- Only the assigned photo is downloaded; it keeps `fetchpriority="high"` and `decoding="async"`. +- Do not start a dev server or curl pages (user verifies in a preview deploy). Run `pnpm prettier --write` only on files you changed, never repo-wide. +- Commits: conventional format with a scope (`feat(home):`, `fix(analytics):`, …), ending with `Co-Authored-By: Claude Opus 5.5 `. + +## Review Focus + +- **Link shapes:** `/membership/`, `/projects?x=1`, `/volunteer#top`, `https://techforpalestine.org/incubator` must count; `/incubator-guide`, `/membership/supporting`, `https://other.org/projects`, `mailto:`, `javascript:` must not, and none may throw. (Task 5) +- **Click target inside the link:** a click on a ``/`` inside the `` counts once. (Task 5) +- **Mouse buttons:** middle-click counts, right-click (`auxclick` button 2) does not. (Task 5) +- **GrowthBook unavailable:** missing payload, flag missing, flag off, unknown value, or `source` other than `"experiment"` → `null` → control photo, no meta, no listener. (Task 4) +- **Malformed analytics meta:** missing meta, invalid JSON, a JSON array, or non-string values → `{}` or only the string entries; never throws, so Plausible init always runs. (Task 2) + +--- + +### Task 1: Hero copy font size (own branch, ships first) + +**Files:** + +- Modify: `src/pages/index.astro` (the "These projects include…" `

`, currently `mt-3 max-w-[58ch] text-[17px] leading-[1.6] text-ink-secondary min-[810px]:text-[18px]`) + +**Interfaces:** none. + +- [ ] **Step 1: Branch from `main`:** `git checkout -b fix/home-hero-copy-size` +- [ ] **Step 2: Change the classes** to `text-[19px]` and `min-[810px]:text-[21px]` (matching the paragraph above); keep `mt-3`, `max-w-[58ch]`, `leading-[1.6]`, `text-ink-secondary`. +- [ ] **Step 3: Verify:** `pnpm lint` → no errors. +- [ ] **Step 4: Commit:** `fix(home): match the hero's second paragraph to the first's font size` +- [ ] **Step 5: Start the feature branch on top of it:** `git checkout -b feat/home-hero-photo-test` (Tasks 2–6 go here; its PR is stacked on this one). + +### Task 2: Pageview custom properties from Layout + +**Files:** + +- Create: `src/utils/analyticsProps.ts` +- Test: `src/utils/analyticsProps.test.ts` +- Modify: `src/layouts/Layout.astro` (`Props`, ``, the `plausible.init({ endpoint: "/api/pipe" })` script) + +**Interfaces:** + +- Produces: `ANALYTICS_PROPS_META = "t4p:analytics-props"`; `readAnalyticsProps(doc: Pick): Record`; Layout prop `analyticsProps?: Record`. + +- [ ] **Step 1: Write the failing tests** (fake `doc` whose `querySelector` returns `{ getAttribute: () => content }` or `null`): + +```ts +describe("readAnalyticsProps", () => { + it("returns {} when there is no meta", () => + expect(readAnalyticsProps(docWith(null))).toEqual({})); + it("parses a JSON object of strings", () => + expect(readAnalyticsProps(docWith('{"hero_photo":"speaker"}'))).toEqual({ + hero_photo: "speaker", + })); + it("returns {} for invalid JSON", () => expect(readAnalyticsProps(docWith("{nope"))).toEqual({})); + it("returns {} for a JSON array", () => expect(readAnalyticsProps(docWith('["a"]'))).toEqual({})); + it("drops non-string values", () => + expect(readAnalyticsProps(docWith('{"a":"x","b":1,"c":null}'))).toEqual({ a: "x" })); +}); +``` + +- [ ] **Step 2: Run:** `pnpm vitest run src/utils/analyticsProps.test.ts` → FAIL (module missing). +- [ ] **Step 3: Implement `readAnalyticsProps`** — selects `meta[name="t4p:analytics-props"]`, reads `content`, `JSON.parse` in try/catch, keeps only string-valued own keys of a plain object. +- [ ] **Step 4: Run** the same command → PASS. +- [ ] **Step 5: Wire Layout.** Add `analyticsProps?: Record` to `Props` (JSDoc: "Custom properties for this page's Plausible pageview and every later event on it"). When non-empty, render `` in `` **before** the analytics scripts. In the init script, import `readAnalyticsProps` and call `init({ endpoint: "/api/pipe", customProperties: readAnalyticsProps(document) })`. +- [ ] **Step 6: Verify:** `pnpm test && pnpm lint` → pass. +- [ ] **Step 7: Commit** (also add the spec and this plan, `docs/superpowers/specs/2026-11-25-homepage-hero-photo-ab-test-design.md` and `docs/superpowers/plans/2026-11-25-homepage-hero-photo-ab-test.md`): `feat(analytics): let a page add custom properties to its Plausible pageview` + +### Task 3: Load-time events stop cancelling bounces + +**Files:** + +- Modify: `src/utils/navLabelExperiment.ts` (+ `src/utils/navLabelExperiment.test.ts`) +- Modify: `src/components/home/NewsletterPopup.tsx:135`, `src/components/home/ChallengePopup.astro` (`track` helper + `"Challenge Popup Shown"` call), `src/components/home/ReportPopup.astro` (`track` helper + `"Report Popup Shown"` call), `src/pages/donate.astro:338`, `src/pages/donate-2.astro:190` +- Modify: `src/lib/navAssignment.ts` (warning text only) + +**Interfaces:** + +- Produces: `TrackEvent = (name: string, props: Record, options?: { interactive?: boolean }) => void` in `navLabelExperiment.ts`. + +- [ ] **Step 1: Write the failing test** in `navLabelExperiment.test.ts`: `trackNavLabel` calls `track(EXPOSURE_EVENT, props, { interactive: false })`, and a click calls `track(CLICK_EVENT, props)` with **no** options (clicks stay interactive). Update existing exposure assertions accordingly. +- [ ] **Step 2: Run:** `pnpm vitest run src/utils/navLabelExperiment.test.ts` → FAIL. +- [ ] **Step 3: Implement:** extend `TrackEvent`; `trackWithPlausible` forwards `interactive` when given; exposure passes `{ interactive: false }`. +- [ ] **Step 4: Run** → PASS. +- [ ] **Step 5: Update the other load-time calls** to send `interactive: false`: `plausible("Newsletter Popup Shown", { interactive: false })`; in Challenge/Report popups give `track` an optional third `options` argument merged into the call, and pass `{ interactive: false }` only from the `…Popup Shown` calls (CTA/dismiss events stay interactive); both `Donate Form` calls add `interactive: false` beside their existing `props`. If `window.plausible`'s type rejects `interactive`, widen it in `src/env.d.ts`. +- [ ] **Step 6: Warning text:** in `requestAssignmentId`, change the message to `` `${ASSIGNMENT_SECRET_ENV} is not set: server-side A/B tests are inactive` ``; update `docs/ENVIRONMENT.md`'s `NAV_ASSIGNMENT_SECRET` row to say it keys the daily visitor hash for the nav and homepage hero photo tests. +- [ ] **Step 7: Verify:** `pnpm test && pnpm lint && pnpm check` → pass. +- [ ] **Step 8: Commit:** `fix(analytics): send load-time events as non-interactive so bounce rate is real` (body: site-wide bounce rates, including `/donate`, will rise from this deploy). + +### Task 4: Photos, variant record and server assignment + +**Files:** + +- Create: `public/images/hero/{speaker,laptops,stage}-{800,1600}.webp` +- Create: `src/utils/heroPhotoExperiment.ts`, `src/lib/heroPhotoAssignment.ts` +- Test: `src/utils/heroPhotoExperiment.test.ts`, `src/lib/heroPhotoAssignment.test.ts` + +**Interfaces:** + +- Consumes: `requestAssignmentId(request, locals, now?)` from `src/lib/navAssignment.ts`; `loadFeaturePayload`, `evalServerFeature` from `src/lib/growthbookServer.ts`. +- Produces (in `heroPhotoExperiment.ts`): `HERO_PHOTO_EXPERIMENT = "homepage-hero-photo"`; `type HeroPhotoVariant = "control" | "speaker" | "laptops" | "stage"`; `interface HeroPhoto { src: string; srcset: string; width: number; height: number; alt: string; credit: string; position: string }`; `HERO_PHOTOS: Readonly>`; `variantFromFeature({ value, source }: { value: unknown; source: string }): HeroPhotoVariant | null`. +- Produces (in `heroPhotoAssignment.ts`): `assignHeroPhoto(request: Request, locals: unknown, now?: () => Date): Promise`. + +- [ ] **Step 1: Convert the photos.** Sources (scratchpad, not committed): `/tmp/claude-1000/-home-magnus-Desktop-t4p-website/addd46b2-e985-4c03-93ba-2b792996c213/images/2.png` = speaker, `3.png` = laptops, `4.png` = stage. For each: `magick -resize 1600x -quality 80 public/images/hero/-1600.webp` and `-resize 800x … -800.webp`. Keep each photo's own aspect ratio. Aim for sizes near `happy-kids-1600.webp` (129 KB) / `-800.webp` (54 KB); lower quality if a 1600 file exceeds ~250 KB. Record each 1600 file's height for `HERO_PHOTOS`. +- [ ] **Step 2: Write failing tests** in `heroPhotoExperiment.test.ts`: + - `variantFromFeature` returns each of the four values for `source: "experiment"`; returns `null` for `source: "force"`, `"defaultValue"`, `"unknownFeature"`, and for `{ value: "other", source: "experiment" }`. + - every `HERO_PHOTOS` entry has non-empty `alt` and `credit`, a `srcset` with `800w` and `1600w`, and every file it references exists under `public/` (`fs.existsSync`). + - `HERO_PHOTOS.control` keeps today's values: `src "/happy-kids-1600.webp"`, `width 1600`, `height 1200`, alt `"Children in Gaza smiling for the camera"`, credit `"© Motaz Azaiza"`. +- [ ] **Step 3: Write failing tests** in `heroPhotoAssignment.test.ts`, mocking `./growthbookServer` and `./navAssignment` the way `navAssignment.test.ts` mocks: returns `null` when there is no client key, no payload, or no id; returns the variant when `evalServerFeature` gives `{ value: "laptops", source: "experiment" }`; returns `null` for `{ value: "laptops", source: "force" }`. Plus one unmocked test that builds a real payload `{ features: { "homepage-hero-photo": { defaultValue: "control", rules: [{ key: "homepage-hero-photo", variations: ["control","speaker","laptops","stage"], weights: [0.25,0.25,0.25,0.25], hashAttribute: "id" }] } } }`, evaluates 4,000 random ids with `evalServerFeature`, and asserts every result has `source: "experiment"` and each variant gets between 22% and 28%. +- [ ] **Step 4: Run:** `pnpm vitest run src/utils/heroPhotoExperiment.test.ts src/lib/heroPhotoAssignment.test.ts` → FAIL. +- [ ] **Step 5: Implement `HERO_PHOTOS`** with the spec's alt text verbatim: + - `speaker`: "A man reads from a sheet of paper to a seated group, with an embroidered map of Palestine hanging on the wall behind him" + - `laptops`: "Three people work together at laptops covered in Palestinian flag and watermelon stickers" + - `stage`: "Two people on stage applaud between a Thaura banner and a Tech for Palestine banner" + - `credit: "TODO credit"` for the three new photos, with a `// TODO(launch): photographer credit from the team` comment. + - `position`: Tailwind classes, phone first then `lg:` — start from `object-center` (speaker), `object-[50%_50%] lg:object-[52%_50%]` (laptops, centred on the woman), `object-[50%_50%]` (stage). Final values are judged in the preview deploy (Task 6). +- [ ] **Step 6: Implement `variantFromFeature` and `assignHeroPhoto`** — same shape as `assignNavLabelVariant` (client key via `getEnv("PUBLIC_GROWTHBOOK_CLIENT_KEY", locals)` → payload → id → evaluate → `variantFromFeature`). +- [ ] **Step 7: Run** the Step 4 command → PASS. +- [ ] **Step 8: Commit:** `feat(home): hero photo variants and server-side assignment for the photo A/B test` + +### Task 5: Homepage link click tracking + +**Files:** + +- Modify: `src/utils/heroPhotoExperiment.ts` +- Test: `src/utils/heroPhotoExperiment.test.ts` + +**Interfaces:** + +- Produces: `LINK_CLICK_EVENT = "Homepage Link Click"`; `type HomepageDestination = "/membership" | "/volunteer" | "/projects" | "/incubator"`; `destinationFor(href: string, origin: string): HomepageDestination | null`; `trackHomepageLinks(options?: { track?: (name: string, props: Record) => void; doc?: Pick; origin?: string }): void`. + +- [ ] **Step 1: Write failing tests** (origin `"https://techforpalestine.org"`): + - `destinationFor` → `/membership` for `/membership`, `/membership/`, `/membership?ref=x`, `/membership#join`, `https://techforpalestine.org/membership`; `/incubator` for `/incubator/`. + - → `null` for `/incubator-guide`, `/membership/supporting`, `/get-involved`, `https://other.org/projects`, `mailto:a@b.c`, `javascript:void(0)`, `""`, and does not throw on any of them. + - `trackHomepageLinks` with a fake doc: a `click` whose `target.closest("a[href]")` returns a link to `/projects` → `track("Homepage Link Click", { destination: "/projects" })` once; a target that is a `` inside that link → same single call; `auxclick` with `button: 1` → tracked; `auxclick` with `button: 2` → not tracked; a link to `/get-involved` → not tracked; a target with no `closest` (e.g. text node fake) → not tracked, no throw. +- [ ] **Step 2: Run:** `pnpm vitest run src/utils/heroPhotoExperiment.test.ts` → FAIL. +- [ ] **Step 3: Implement.** `destinationFor`: `new URL(href, origin)` in try/catch; require `url.origin === origin`; strip one trailing slash from `pathname`; exact match against the four paths. `trackHomepageLinks`: one `click` and one `auxclick` listener on `doc` (delegation, so the on-demand mobile menu counts); ignore `auxclick` unless `button === 1`; default `track` is `window.plausible?.(name, { props })` (interactive — a click is a real interaction); default `origin` is `location.origin`. `hero_photo` is not added here: `customProperties` attaches it. +- [ ] **Step 4: Run** → PASS. +- [ ] **Step 5: Commit:** `feat(home): track homepage clicks to membership, volunteer, projects and incubator` + +### Task 6: Wire the experiment into the homepage + +**Files:** + +- Modify: `src/pages/index.astro` (frontmatter, hero `

`, `` props, page ` diff --git a/src/components/donate/OtherWaysToGive.astro b/src/components/donate/OtherWaysToGive.astro new file mode 100644 index 00000000..fd12a58b --- /dev/null +++ b/src/components/donate/OtherWaysToGive.astro @@ -0,0 +1,45 @@ +--- +// "Other ways to give": stock and crypto, corporate match, major gifts. +// Shared by /donate and /supporting-member so the two never drift apart. +--- + +
+

Other ways to give

+
+
diff --git a/src/components/home/ChallengePopup.astro b/src/components/home/ChallengePopup.astro index 52a5729c..30e147b2 100644 --- a/src/components/home/ChallengePopup.astro +++ b/src/components/home/ChallengePopup.astro @@ -414,9 +414,13 @@ const sessions = [ if (shouldShowPopup(readPopupState(safeLocalStorage()), Date.now())) schedule(dialog); } - function track(event: string, props?: Record) { + function track( + event: string, + props?: Record, + options?: { interactive?: boolean } + ) { if (typeof window.plausible === "undefined") return; - window.plausible(event, props ? { props } : undefined); + window.plausible(event, props || options ? { props, ...options } : undefined); } function schedule(dialog: HTMLDialogElement) { @@ -475,7 +479,7 @@ const sessions = [ dialog.showModal(); document.documentElement.setAttribute(SHOWN_ATTRIBUTE, ""); window.dispatchEvent(new Event(SHOWN_EVENT)); - track("Challenge Popup Shown", { challenge: "2026-11" }); + track("Challenge Popup Shown", { challenge: "2026-11" }, { interactive: false }); }; const onScroll = () => { const docHeight = document.documentElement.scrollHeight; diff --git a/src/components/home/NewsletterPopup.tsx b/src/components/home/NewsletterPopup.tsx index 9d0c5806..6d9e8ef8 100644 --- a/src/components/home/NewsletterPopup.tsx +++ b/src/components/home/NewsletterPopup.tsx @@ -132,7 +132,7 @@ function Popup() { useEffect(() => { if (!visible || shownRef.current) return; shownRef.current = true; - window.plausible("Newsletter Popup Shown"); + window.plausible("Newsletter Popup Shown", { interactive: false }); }, [visible]); // Auto-collapse the open card/bar after COLLAPSE_IDLE_MS of no activity. diff --git a/src/components/home/ReportPopup.astro b/src/components/home/ReportPopup.astro index 6a0746e1..067de33f 100644 --- a/src/components/home/ReportPopup.astro +++ b/src/components/home/ReportPopup.astro @@ -260,9 +260,13 @@ const live = isReportPopupLive(); } } - function track(event: string, props?: Record) { + function track( + event: string, + props?: Record, + options?: { interactive?: boolean } + ) { if (typeof window.plausible === "undefined") return; - window.plausible(event, props ? { props } : undefined); + window.plausible(event, props || options ? { props, ...options } : undefined); } function schedule(dialog: HTMLDialogElement) { @@ -314,7 +318,7 @@ const live = isReportPopupLive(); dialog.showModal(); document.documentElement.setAttribute(REPORT_SHOWN_ATTRIBUTE, ""); window.dispatchEvent(new Event(REPORT_SHOWN_EVENT)); - track("Report Popup Shown"); + track("Report Popup Shown", undefined, { interactive: false }); }; const onScroll = () => { const docHeight = document.documentElement.scrollHeight; diff --git a/src/components/membership/JoinFlow.tsx b/src/components/membership/JoinFlow.tsx index 3ffea524..98829971 100644 --- a/src/components/membership/JoinFlow.tsx +++ b/src/components/membership/JoinFlow.tsx @@ -46,6 +46,10 @@ interface JoinFlowProps { * /supporting-member. Without it the calculator still only shows for the * Member tier. */ hideCalculator?: boolean; + /** When set, the payment step shows an "I want to make a one-time donation" link to this + * address under its step header, for visitors who came to give once rather than join. + * Used on /supporting-member (→ /donate). */ + oneTimeDonationHref?: string; /** Uses the design system's ts-* typography scale (Fraunces/Outfit) instead * of plain Tailwind sizes — only correct where `design-system.css` is * loaded (HomeLayout, i.e. /membership-new). The legacy /membership page @@ -311,6 +315,7 @@ export default function JoinFlow({ designSystem = false, fixedTier, hideCalculator, + oneTimeDonationHref, }: JoinFlowProps) { const styles = getStyles(designSystem); const steps = fixedTier ? STEPS.filter((s) => s.id !== "tier") : STEPS; @@ -358,6 +363,14 @@ export default function JoinFlow({ Step {stepIndex + 1} of {steps.length}: {steps[stepIndex]?.label}

+ {step === "payment" && oneTimeDonationHref && ( +

+ + I want to make a one-time donation + +

+ )} + {step === "about-you" && ( []; + /** Custom properties for this page's Plausible pageview and every later event on it. */ + analyticsProps?: Record; } const { @@ -37,6 +39,7 @@ const { noindex = false, hideDonatePopout = false, schema = [], + analyticsProps = {}, } = Astro.props; // /page and /page/ both resolve, so both must name the same no-slash canonical. @@ -86,8 +89,15 @@ const structuredData = [organizationSchema(), ...schema]; + { + Object.keys(analyticsProps).length > 0 && ( + + ) + } diff --git a/src/lib/heroPhotoAssignment.test.ts b/src/lib/heroPhotoAssignment.test.ts new file mode 100644 index 00000000..38a74fc9 --- /dev/null +++ b/src/lib/heroPhotoAssignment.test.ts @@ -0,0 +1,67 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("./growthbookServer", () => ({ + loadFeaturePayload: vi.fn(), + evalServerFeature: vi.fn(), +})); +vi.mock("./visitorAssignment", () => ({ + requestAssignmentId: vi.fn(), +})); + +const { loadFeaturePayload, evalServerFeature } = await import("./growthbookServer"); +const { requestAssignmentId } = await import("./visitorAssignment"); +const { assignHeroPhoto } = await import("./heroPhotoAssignment"); + +describe("assignHeroPhoto", () => { + const locals = { runtime: { env: { PUBLIC_GROWTHBOOK_CLIENT_KEY: "sdk-test" } } }; + const req = () => new Request("https://techforpalestine.org/"); + + beforeEach(() => { + vi.mocked(loadFeaturePayload).mockResolvedValue({ features: {} }); + vi.mocked(requestAssignmentId).mockResolvedValue("visitor-id"); + vi.mocked(evalServerFeature).mockReturnValue({ + value: "laptops", + source: "experiment", + } as never); + }); + afterEach(() => vi.clearAllMocks()); + + it("returns the variant GrowthBook assigned, evaluated on the assignment id", async () => { + expect(await assignHeroPhoto(req(), locals)).toBe("laptops"); + expect(vi.mocked(evalServerFeature).mock.calls[0].slice(1)).toEqual([ + "homepage-hero-photo", + "visitor-id", + ]); + }); + + it("returns null when the result is not from the experiment", async () => { + vi.mocked(evalServerFeature).mockReturnValue({ value: "laptops", source: "force" } as never); + expect(await assignHeroPhoto(req(), locals)).toBeNull(); + }); + + it("returns null without a client key", async () => { + expect(await assignHeroPhoto(req(), {})).toBeNull(); + expect(evalServerFeature).not.toHaveBeenCalled(); + }); + + it("returns null when the payload is unavailable", async () => { + vi.mocked(loadFeaturePayload).mockResolvedValue(undefined); + expect(await assignHeroPhoto(req(), locals)).toBeNull(); + }); + + it("returns null without an assignment id", async () => { + vi.mocked(requestAssignmentId).mockResolvedValue(null); + expect(await assignHeroPhoto(req(), locals)).toBeNull(); + expect(evalServerFeature).not.toHaveBeenCalled(); + }); + + it("returns null and logs when evaluation throws", async () => { + const spy = vi.spyOn(console, "error").mockImplementation(() => {}); + vi.mocked(evalServerFeature).mockImplementation(() => { + throw new Error("boom"); + }); + expect(await assignHeroPhoto(req(), locals)).toBeNull(); + expect(spy).toHaveBeenCalledWith("Hero photo assignment failed", expect.any(Error)); + spy.mockRestore(); + }); +}); diff --git a/src/lib/heroPhotoAssignment.ts b/src/lib/heroPhotoAssignment.ts new file mode 100644 index 00000000..361e9f1f --- /dev/null +++ b/src/lib/heroPhotoAssignment.ts @@ -0,0 +1,28 @@ +import { getEnv } from "../utils/getEnv"; +import { + HERO_PHOTO_EXPERIMENT, + type HeroPhotoVariant, + variantFromFeature, +} from "../utils/heroPhotoExperiment"; +import { evalServerFeature, loadFeaturePayload } from "./growthbookServer"; +import { requestAssignmentId } from "./visitorAssignment"; + +/** The hero photo variant GrowthBook assigns this visitor, or null when they are not in the + * test (flag off, CDN down, or no stable id). `now` is for tests. */ +export async function assignHeroPhoto( + request: Request, + locals: unknown, + now?: () => Date +): Promise { + try { + const clientKey = getEnv("PUBLIC_GROWTHBOOK_CLIENT_KEY", locals); + const payload = clientKey ? await loadFeaturePayload(clientKey) : undefined; + if (!payload) return null; + const id = await requestAssignmentId(request, locals, now); + if (!id) return null; + return variantFromFeature(evalServerFeature(payload, HERO_PHOTO_EXPERIMENT, id)); + } catch (error) { + console.error("Hero photo assignment failed", error); + return null; + } +} diff --git a/src/lib/heroPhotoSplit.test.ts b/src/lib/heroPhotoSplit.test.ts new file mode 100644 index 00000000..ceb57894 --- /dev/null +++ b/src/lib/heroPhotoSplit.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest"; +import { evalServerFeature } from "./growthbookServer"; + +// No mocks: runs the real GrowthBook SDK to check the experiment rule shape splits evenly. +describe("homepage-hero-photo split", () => { + const payload = { + features: { + "homepage-hero-photo": { + defaultValue: "control", + rules: [ + { + key: "homepage-hero-photo", + variations: ["control", "speaker", "laptops", "stage"], + weights: [0.25, 0.25, 0.25, 0.25], + coverage: 1, + hashAttribute: "id", + }, + ], + }, + }, + }; + + it("buckets every visitor into the experiment, about a quarter per variant", () => { + const total = 4000; + const counts: Record = {}; + for (let i = 0; i < total; i++) { + const result = evalServerFeature(payload, "homepage-hero-photo", crypto.randomUUID()); + expect(result.source).toBe("experiment"); + const value = String(result.value); + counts[value] = (counts[value] ?? 0) + 1; + } + expect(Object.keys(counts).sort()).toEqual(["control", "laptops", "speaker", "stage"]); + for (const count of Object.values(counts)) { + expect(count / total).toBeGreaterThan(0.22); + expect(count / total).toBeLessThan(0.28); + } + }); +}); diff --git a/src/lib/navAssignment.test.ts b/src/lib/visitorAssignment.test.ts similarity index 65% rename from src/lib/navAssignment.test.ts rename to src/lib/visitorAssignment.test.ts index 557eb1ff..d570bd45 100644 --- a/src/lib/navAssignment.test.ts +++ b/src/lib/visitorAssignment.test.ts @@ -1,18 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -vi.mock("./growthbookServer", () => ({ - loadFeaturePayload: vi.fn(), - evalServerFeature: vi.fn(), -})); - -const { loadFeaturePayload, evalServerFeature } = await import("./growthbookServer"); -const { - assignNavLabelVariant, +import { computeAssignmentId, normalizeIp, requestAssignmentId, resetAssignmentWarning, -} = await import("./navAssignment"); +} from "./visitorAssignment"; const base = { secret: "test-secret", @@ -94,35 +87,3 @@ describe("requestAssignmentId", () => { expect(warn).toHaveBeenCalledOnce(); }); }); - -describe("assignNavLabelVariant", () => { - const env = { NAV_ASSIGNMENT_SECRET: "test-secret", PUBLIC_GROWTHBOOK_CLIENT_KEY: "sdk-test" }; - const locals = { runtime: { env } }; - const headers = { "cf-connecting-ip": base.ip, "user-agent": base.userAgent }; - const req = () => new Request("https://techforpalestine.org/", { headers }); - const now = () => base.date; - - beforeEach(() => { - resetAssignmentWarning(); - vi.mocked(loadFeaturePayload).mockResolvedValue({ features: {} }); - vi.mocked(evalServerFeature).mockReturnValue({ value: "B", source: "force" } as never); - }); - afterEach(() => vi.clearAllMocks()); - - it("returns the variant GrowthBook assigned, evaluated on the daily id", async () => { - expect(await assignNavLabelVariant(req(), locals, now)).toBe("B"); - expect(vi.mocked(evalServerFeature).mock.calls[0][2]).toBe(await computeAssignmentId(base)); - }); - - it("is inactive without the secret: no assignment, GrowthBook is never asked", async () => { - vi.spyOn(console, "warn").mockImplementation(() => {}); - const noSecret = { runtime: { env: { PUBLIC_GROWTHBOOK_CLIENT_KEY: "sdk-test" } } }; - expect(await assignNavLabelVariant(req(), noSecret, now)).toBeNull(); - expect(evalServerFeature).not.toHaveBeenCalled(); - }); - - it("returns null when the GrowthBook payload is unavailable", async () => { - vi.mocked(loadFeaturePayload).mockResolvedValue(undefined); - expect(await assignNavLabelVariant(req(), locals, now)).toBeNull(); - }); -}); diff --git a/src/lib/navAssignment.ts b/src/lib/visitorAssignment.ts similarity index 70% rename from src/lib/navAssignment.ts rename to src/lib/visitorAssignment.ts index 802a95e3..0d9c9b6a 100644 --- a/src/lib/navAssignment.ts +++ b/src/lib/visitorAssignment.ts @@ -1,24 +1,20 @@ import { getEnv } from "../utils/getEnv"; -import { - NAV_LABEL_EXPERIMENT, - type NavLabelVariant, - variantFromFeature, -} from "../utils/navLabelExperiment"; -import { evalServerFeature, loadFeaturePayload } from "./growthbookServer"; // A/B test id that is stable for one visitor for one UTC day, without storing anything on // the visitor's device. Same idea as Plausible's own visitor id: a keyed hash of the date, // the IP and the User-Agent. The IP and User-Agent are only read here, in memory, and never // stored; the hash never leaves the server (GrowthBook evaluates it in-process, see -// src/lib/growthbookServer.ts). +// src/lib/growthbookServer.ts). Used by the homepage hero photo test +// (src/lib/heroPhotoAssignment.ts). // // The date is part of the hash input, so the id rotates daily with no stored salt. // -// The test is only meaningful if a visitor keeps one label, because the sign-up on /membership -// is credited to the label on that page. So without the secret, or without an IP (pnpm dev), -// there is no assignment at all: everyone sees "Get Involved" and nothing is tracked, rather -// than a random label per page that would make the result noise. +// A test is only meaningful if a visitor keeps one variant. So without the secret, or without +// an IP (pnpm dev), there is no id at all: callers show their control and track nothing, +// rather than a random variant per page that would make the result noise. +// The name predates the hero photo test (it was first used by the navbar label test) and is +// kept because it is what the Cloudflare Pages environment sets. export const ASSIGNMENT_SECRET_ENV = "NAV_ASSIGNMENT_SECRET"; const IPV6_PREFIX_GROUPS = 4; @@ -92,7 +88,7 @@ export async function requestAssignmentId( if (!secret) { if (ip && !warnedMissingSecret) { warnedMissingSecret = true; - console.warn(`${ASSIGNMENT_SECRET_ENV} is not set: the nav label A/B test is inactive`); + console.warn(`${ASSIGNMENT_SECRET_ENV} is not set: server-side A/B tests are inactive`); } return null; } @@ -104,18 +100,3 @@ export async function requestAssignmentId( date: now(), }); } - -/** The nav label variant GrowthBook assigns this visitor, or null when they are not in the - * test (flag off, CDN down, or no stable id). `now` is for tests. */ -export async function assignNavLabelVariant( - request: Request, - locals: unknown, - now?: () => Date -): Promise { - const clientKey = getEnv("PUBLIC_GROWTHBOOK_CLIENT_KEY", locals); - const payload = clientKey ? await loadFeaturePayload(clientKey) : undefined; - if (!payload) return null; - const id = await requestAssignmentId(request, locals, now); - if (!id) return null; - return variantFromFeature(evalServerFeature(payload, NAV_LABEL_EXPERIMENT, id)); -} diff --git a/src/middleware/cache-control.ts b/src/middleware/cache-control.ts index 89f8e267..24ffa509 100644 --- a/src/middleware/cache-control.ts +++ b/src/middleware/cache-control.ts @@ -3,9 +3,10 @@ import { defineMiddleware } from "astro:middleware"; export const cacheControl = defineMiddleware(async (context, next) => { const response = await next(); - // Pages are `private`: the navbar label is an A/B test picked per request - // (src/components/Navigation.astro), so a shared cache must not store one - // visitor's variant and serve it to everyone. Browsers may still cache for 10 minutes. + // Pages are `private`: the homepage hero photo A/B test (src/pages/index.astro, + // src/lib/heroPhotoAssignment.ts) picks a variant per visitor, so a shared cache must not + // store one visitor's variant and serve it to everyone. Browsers may still cache for + // 10 minutes. const pathname = context.url.pathname; const isApi = pathname.startsWith("/api/"); diff --git a/src/pages/donate-2.astro b/src/pages/donate-2.astro index 59c43b6b..cde03d63 100644 --- a/src/pages/donate-2.astro +++ b/src/pages/donate-2.astro @@ -189,6 +189,7 @@ import "../styles/base.css"; if (typeof (window as any).plausible !== "undefined") { (window as any).plausible("Donate Form", { props: { donate_form_variant: "charitystack" }, + interactive: false, }); } diff --git a/src/pages/donate.astro b/src/pages/donate.astro index 8b4967b0..1934d984 100644 --- a/src/pages/donate.astro +++ b/src/pages/donate.astro @@ -1,5 +1,6 @@ --- import Layout from "../layouts/Layout.astro"; +import OtherWaysToGive from "../components/donate/OtherWaysToGive.astro"; import "../styles/base.css"; // Get country from Cloudflare headers @@ -166,44 +167,7 @@ const isUK = country === "GB"; -
-

Other ways to give

-
    -
  • -

    Stock & Cryptocurrency

    -

    - To make a gift via stock or cryptocurrency, visit our form here. -

    -
  • -
  • -

    Corporate Match

    -

    - If your employer uses Benevity to match your contribution, find us on the Benevity Causes Portal. -

    -
  • -
  • -

    Major Gifts

    -

    - For more information about making a major gift or for other questions about - donations, please contact - donations@techforpalestine.org -

    -
  • -
-
+ @@ -335,7 +299,10 @@ const isUK = country === "GB"; // Track form variant (safely) if (typeof window.plausible !== "undefined") { - window.plausible("Donate Form", { props: { donate_form_variant: trackingVariant } }); + window.plausible("Donate Form", { + props: { donate_form_variant: trackingVariant }, + interactive: false, + }); } const presetAmount = urlParams.get("amount"); diff --git a/src/pages/index.astro b/src/pages/index.astro index e900c824..7993427a 100644 --- a/src/pages/index.astro +++ b/src/pages/index.astro @@ -7,6 +7,14 @@ import NewsletterPopup from "../components/home/NewsletterPopup"; import ChallengePopup from "../components/home/ChallengePopup.astro"; import ReportPopup from "../components/home/ReportPopup.astro"; import "../styles/base.css"; +import { assignHeroPhoto } from "../lib/heroPhotoAssignment"; +import { HERO_PHOTOS } from "../utils/heroPhotoExperiment"; + +// The assignment id is a daily hash, so a visitor sees one photo per day. `/` must stay out of +// shared caches (cache-control.ts sends `private, max-age=600`) or one visitor's photo would be +// served to everyone. +const heroVariant = await assignHeroPhoto(Astro.request, Astro.locals); +const hero = HERO_PHOTOS[heroVariant ?? "control"]; const stats = [ { value: "100+", label: "Projects incubated" }, @@ -164,6 +172,7 @@ const cardBase = `group relative flex flex-col rounded-lg border border-ink-divi description="A 501(c)(3) coalition of founders, engineers and tech workers behind 100+ projects for Palestine. Become a member or build with the T4P Incubator." schema={[websiteSchema()]} image="https://techforpalestine.org/happy-kids.jpg" + analyticsProps={heroVariant ? { hero_photo: heroVariant } : undefined} >
@@ -193,7 +202,7 @@ const cardBase = `group relative flex flex-col rounded-lg border border-ink-divi that support the movement for Palestine.

These projects include: protest apps, tools for boycotting, support for Palestinian students & businesses, ethical tech alternatives, and many more. @@ -207,22 +216,25 @@ const cardBase = `group relative flex flex-col rounded-lg border border-ink-divi -

+
Children in Gaza smiling for the camera
- © Motaz Azaiza + {hero.credit}
@@ -501,6 +513,9 @@ const cardBase = `group relative flex flex-col rounded-lg border border-ink-divi writePopupState, } from "../utils/newsletterPopup"; import { watchSignupSuccess } from "../utils/watchSignupSuccess"; + import { trackHomepageLinks } from "../utils/heroPhotoExperiment"; + + if (document.querySelector("[data-hero-photo]")) trackHomepageLinks(); const bottomForm = document.getElementById(FOOTER_SECTION_ID); if (bottomForm) { diff --git a/src/pages/supporting-member.astro b/src/pages/supporting-member.astro index 630a469d..3da2a620 100644 --- a/src/pages/supporting-member.astro +++ b/src/pages/supporting-member.astro @@ -2,6 +2,7 @@ import Layout from "../layouts/Layout.astro"; import JoinFlow from "../components/membership/JoinFlow"; import DuesUsage from "../components/membership/DuesUsage.astro"; +import OtherWaysToGive from "../components/donate/OtherWaysToGive.astro"; import { showcaseProjects } from "../data/membershipBenefits"; import { getTestimonials } from "../data/testimonials"; import "../styles/base.css"; @@ -257,17 +258,29 @@ const logoWallLabel = `Projects supported by Tech for Palestine: ${showcaseProje
-
- -
-

- How does T4P use dues? -

- -
+ +
+
+ +
+

+ How does T4P use dues? +

+ +
+
+
diff --git a/src/utils/analyticsProps.test.ts b/src/utils/analyticsProps.test.ts new file mode 100644 index 00000000..a92e991e --- /dev/null +++ b/src/utils/analyticsProps.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { ANALYTICS_PROPS_META, readAnalyticsProps } from "./analyticsProps"; + +// Vitest runs in node, so the document is a minimal fake. +function docWith(content: string | null) { + return { + querySelector: () => (content === null ? null : { getAttribute: () => content }), + } as unknown as Pick; +} + +describe("readAnalyticsProps", () => { + it("names the meta tag", () => expect(ANALYTICS_PROPS_META).toBe("t4p:analytics-props")); + it("returns {} when there is no meta", () => + expect(readAnalyticsProps(docWith(null))).toEqual({})); + it("parses a JSON object of strings", () => + expect(readAnalyticsProps(docWith('{"hero_photo":"speaker"}'))).toEqual({ + hero_photo: "speaker", + })); + it("returns {} for invalid JSON", () => expect(readAnalyticsProps(docWith("{nope"))).toEqual({})); + it("returns {} for a JSON array", () => expect(readAnalyticsProps(docWith('["a"]'))).toEqual({})); + it("drops non-string values", () => + expect(readAnalyticsProps(docWith('{"a":"x","b":1,"c":null}'))).toEqual({ a: "x" })); +}); diff --git a/src/utils/analyticsProps.ts b/src/utils/analyticsProps.ts new file mode 100644 index 00000000..0b555bbc --- /dev/null +++ b/src/utils/analyticsProps.ts @@ -0,0 +1,25 @@ +/** Meta tag Layout renders so the analytics init script can read a page's custom properties. */ +export const ANALYTICS_PROPS_META = "t4p:analytics-props"; + +/** + * Reads the page's Plausible custom properties from the analytics meta tag. + * Returns {} when the tag is missing or malformed; non-string values are dropped. + */ +export function readAnalyticsProps(doc: Pick): Record { + const content = doc + .querySelector(`meta[name="${ANALYTICS_PROPS_META}"]`) + ?.getAttribute("content"); + if (!content) return {}; + let parsed: unknown; + try { + parsed = JSON.parse(content); + } catch { + return {}; + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; + return Object.fromEntries( + Object.entries(parsed).filter( + (entry): entry is [string, string] => typeof entry[1] === "string" + ) + ); +} diff --git a/src/utils/heroPhotoExperiment.test.ts b/src/utils/heroPhotoExperiment.test.ts new file mode 100644 index 00000000..4c8d0e1c --- /dev/null +++ b/src/utils/heroPhotoExperiment.test.ts @@ -0,0 +1,148 @@ +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it, vi } from "vitest"; +import { + HERO_PHOTOS, + type HeroPhotoVariant, + LINK_CLICK_EVENT, + destinationFor, + trackHomepageLinks, + variantFromFeature, +} from "./heroPhotoExperiment"; + +const VARIANTS: HeroPhotoVariant[] = ["control", "speaker", "laptops", "stage"]; + +describe("variantFromFeature", () => { + it.each(VARIANTS)("returns %s for an experiment result", (value) => { + expect(variantFromFeature({ value, source: "experiment" })).toBe(value); + }); + + it.each(["force", "defaultValue", "unknownFeature"])("returns null for source %s", (source) => { + expect(variantFromFeature({ value: "laptops", source })).toBeNull(); + }); + + it("returns null for an unknown value", () => { + expect(variantFromFeature({ value: "other", source: "experiment" })).toBeNull(); + }); +}); + +describe("HERO_PHOTOS", () => { + it.each(VARIANTS)("%s has alt, credit and both srcset widths", (variant) => { + const photo = HERO_PHOTOS[variant]; + expect(photo.alt).not.toBe(""); + expect(photo.credit).not.toBe(""); + expect(photo.credit).not.toMatch(/TODO/i); + expect(photo.srcset).toContain("800w"); + expect(photo.srcset).toContain("1600w"); + }); + + it.each(VARIANTS)("%s references files that exist under public/", (variant) => { + const photo = HERO_PHOTOS[variant]; + const paths = [photo.src, ...photo.srcset.split(",").map((part) => part.trim().split(" ")[0])]; + for (const path of paths) { + expect(existsSync(join(process.cwd(), "public", path)), path).toBe(true); + } + }); + + it("keeps today's hero photo for the control", () => { + expect(HERO_PHOTOS.control).toMatchObject({ + src: "/happy-kids-1600.webp", + srcset: "/happy-kids-800.webp 800w, /happy-kids-1600.webp 1600w", + width: 1600, + height: 1200, + alt: "Children in Gaza smiling for the camera", + credit: "© Motaz Azaiza", + }); + }); +}); + +const ORIGIN = "https://techforpalestine.org"; + +describe("destinationFor", () => { + it.each([ + "/membership", + "/membership/", + "/membership?ref=x", + "/membership#join", + "https://techforpalestine.org/membership", + ])("maps %s to /membership", (href) => { + expect(destinationFor(href, ORIGIN)).toBe("/membership"); + }); + + it("maps /incubator/ to /incubator", () => { + expect(destinationFor("/incubator/", ORIGIN)).toBe("/incubator"); + }); + + it.each([ + "/incubator-guide", + "/membership/supporting", + "/get-involved", + "https://other.org/projects", + "mailto:a@b.c", + "javascript:void(0)", + "", + ])("returns null for %j without throwing", (href) => { + expect(destinationFor(href, ORIGIN)).toBeNull(); + }); +}); + +describe("trackHomepageLinks", () => { + type Listener = (event: MouseEvent) => void; + + function setup() { + const listeners = new Map(); + const track = vi.fn(); + const doc = { + addEventListener: (type: string, listener: Listener) => { + listeners.set(type, [...(listeners.get(type) ?? []), listener]); + }, + } as Pick; + trackHomepageLinks({ track, doc, origin: ORIGIN }); + const fire = (type: string, target: unknown, button = 0) => { + const event = { type, button, target } as unknown as MouseEvent; + listeners.get(type)?.forEach((listener) => listener(event)); + }; + return { track, fire }; + } + + const linkTo = (href: string) => ({ getAttribute: () => href }); + const insideLink = (href: string) => ({ + closest: (selector: string) => (selector === "a[href]" ? linkTo(href) : null), + }); + + it("tracks a click on a link once", () => { + const { track, fire } = setup(); + fire("click", insideLink("/projects")); + expect(track).toHaveBeenCalledOnce(); + expect(track).toHaveBeenCalledWith(LINK_CLICK_EVENT, { destination: "/projects" }); + expect(LINK_CLICK_EVENT).toBe("Homepage Link Click"); + }); + + it("tracks a click on an element inside the link", () => { + const { track, fire } = setup(); + fire("click", { closest: () => linkTo("/projects") }); + expect(track).toHaveBeenCalledOnce(); + expect(track).toHaveBeenCalledWith(LINK_CLICK_EVENT, { destination: "/projects" }); + }); + + it("counts middle-clicks but not right-clicks", () => { + const { track, fire } = setup(); + fire("auxclick", insideLink("/projects"), 2); + expect(track).not.toHaveBeenCalled(); + fire("auxclick", insideLink("/projects"), 1); + expect(track).toHaveBeenCalledOnce(); + }); + + it("ignores links to other pages", () => { + const { track, fire } = setup(); + fire("click", insideLink("/get-involved")); + expect(track).not.toHaveBeenCalled(); + }); + + it("ignores targets without closest", () => { + const { track, fire } = setup(); + expect(() => fire("click", {})).not.toThrow(); + expect(() => fire("click", null)).not.toThrow(); + expect(track).not.toHaveBeenCalled(); + }); +}); diff --git a/src/utils/heroPhotoExperiment.ts b/src/utils/heroPhotoExperiment.ts new file mode 100644 index 00000000..55722ea0 --- /dev/null +++ b/src/utils/heroPhotoExperiment.ts @@ -0,0 +1,121 @@ +export const HERO_PHOTO_EXPERIMENT = "homepage-hero-photo"; + +export type HeroPhotoVariant = "control" | "speaker" | "laptops" | "stage"; + +export interface HeroPhoto { + src: string; + srcset: string; + width: number; + height: number; + alt: string; + credit: string; + /** Tailwind object-position classes, written as complete literals so the content scan finds them. */ + position: string; +} + +const VARIANTS: readonly HeroPhotoVariant[] = ["control", "speaker", "laptops", "stage"]; + +// The hero photo for each variant. "control" is the photo the homepage has always shown. +export const HERO_PHOTOS: Readonly> = { + control: { + src: "/happy-kids-1600.webp", + srcset: "/happy-kids-800.webp 800w, /happy-kids-1600.webp 1600w", + width: 1600, + height: 1200, + alt: "Children in Gaza smiling for the camera", + credit: "© Motaz Azaiza", + position: "object-center", + }, + speaker: { + src: "/images/hero/speaker-1600.webp", + srcset: "/images/hero/speaker-800.webp 800w, /images/hero/speaker-1600.webp 1600w", + width: 1600, + height: 1600, + alt: "A man reads from a sheet of paper to a seated group, with an embroidered map of Palestine hanging on the wall behind him", + credit: "© Tech for Palestine", + position: "object-center", + }, + laptops: { + src: "/images/hero/laptops-1600.webp", + srcset: "/images/hero/laptops-800.webp 800w, /images/hero/laptops-1600.webp 1600w", + width: 1600, + height: 1600, + alt: "Two people work together at laptops covered in Palestinian flag and watermelon stickers", + credit: "© Tech for Palestine", + position: "object-center", + }, + stage: { + src: "/images/hero/stage-1600.webp", + srcset: "/images/hero/stage-800.webp 800w, /images/hero/stage-1600.webp 1600w", + width: 1600, + height: 1600, + alt: "Two people on stage applaud beside a Tech for Palestine banner", + credit: "© Tech for Palestine", + position: "object-center", + }, +}; + +export interface FeatureOutcome { + value: unknown; + source: string; +} + +// The variant comes from the "homepage-hero-photo" GrowthBook experiment rule, evaluated on +// the server (src/lib/heroPhotoAssignment.ts). A bucketed visitor reports source +// "experiment"; a disabled flag, a missing flag or an unreachable CDN reports something else, +// and returns null: show the control photo and track nothing. +export function variantFromFeature({ value, source }: FeatureOutcome): HeroPhotoVariant | null { + if (source !== "experiment") return null; + return VARIANTS.find((variant) => variant === value) ?? null; +} + +export const LINK_CLICK_EVENT = "Homepage Link Click"; + +export type HomepageDestination = "/membership" | "/volunteer" | "/projects" | "/incubator"; + +const DESTINATIONS: readonly HomepageDestination[] = [ + "/membership", + "/volunteer", + "/projects", + "/incubator", +]; +const MIDDLE_BUTTON = 1; + +/** The tracked homepage destination an href points at, or null for any other link. */ +export function destinationFor(href: string, origin: string): HomepageDestination | null { + let url: URL; + try { + url = new URL(href, origin); + } catch { + return null; + } + if (url.origin !== origin) return null; + const path = url.pathname.replace(/\/$/, ""); + return DESTINATIONS.find((destination) => destination === path) ?? null; +} + +export interface TrackHomepageLinksOptions { + track?: (name: string, props: Record) => void; + doc?: Pick; + origin?: string; +} + +const trackWithPlausible: NonNullable = (name, props) => { + window.plausible?.(name, { props }); +}; + +// Records clicks on links to the four pages the experiment measures. Delegated on the +// document so the on-demand mobile menu counts too; middle-clicks (new tab) count, other +// buttons do not. `hero_photo` is attached to every event by Plausible's customProperties. +export function trackHomepageLinks(options: TrackHomepageLinksOptions = {}): void { + const { track = trackWithPlausible, doc = document, origin = location.origin } = options; + + const onClick = (event: MouseEvent): void => { + if (event.type === "auxclick" && event.button !== MIDDLE_BUTTON) return; + const link = (event.target as Element | null)?.closest?.("a[href]"); + const destination = destinationFor(link?.getAttribute("href") ?? "", origin); + if (destination) track(LINK_CLICK_EVENT, { destination }); + }; + doc.addEventListener("click", onClick); + doc.addEventListener("auxclick", onClick); +} diff --git a/src/utils/navLabelExperiment.test.ts b/src/utils/navLabelExperiment.test.ts deleted file mode 100644 index 61dbc9c1..00000000 --- a/src/utils/navLabelExperiment.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import { - CLICK_EVENT, - EXPOSURE_EVENT, - trackNavLabel, - type ExperimentDocument, - navExperimentProps, - variantFromFeature, -} from "./navLabelExperiment"; - -describe("variantFromFeature", () => { - it("returns the variant a GrowthBook rule assigned", () => { - expect(variantFromFeature({ value: "A", source: "force" })).toBe("A"); - expect(variantFromFeature({ value: "B", source: "force" })).toBe("B"); - }); - - it("returns null when no rule assigned a variant", () => { - expect(variantFromFeature({ value: "A", source: "defaultValue" })).toBeNull(); - expect(variantFromFeature({ value: null, source: "unknownFeature" })).toBeNull(); - }); - - it("returns null for a value that is not a known variant", () => { - expect(variantFromFeature({ value: "C", source: "force" })).toBeNull(); - }); -}); - -// Vitest runs in node, so the document and link are minimal fakes. -type Listener = (event: MouseEvent) => void; - -const props = { experiment: "nav-get-involved-label", variant: "B" }; - -function fakeDocument({ - prerendering = false, - dataset = props as Record, -}: { prerendering?: boolean; dataset?: Record | null } = {}) { - const listeners = new Map(); - const link = dataset ? { dataset } : null; - const doc: ExperimentDocument = { - prerendering, - querySelector: () => link as unknown as Element | null, - addEventListener: (type, listener) => { - listeners.set(type, [...(listeners.get(type) ?? []), listener]); - }, - }; - const fire = (type: string, onLink: boolean, button = 0) => { - const target = { closest: () => (onLink ? link : null) }; - const event = { type, button, target } as unknown as MouseEvent; - listeners.get(type)?.forEach((listener) => listener(event)); - }; - return { doc, fire }; -} - -describe("trackNavLabel", () => { - it("records one exposure straight away when the page is visible", () => { - const track = vi.fn(); - trackNavLabel({ track, doc: fakeDocument().doc }); - - expect(track).toHaveBeenCalledOnce(); - expect(track).toHaveBeenCalledWith(EXPOSURE_EVENT, props); - }); - - it("waits for a prerendered page to be shown before recording the exposure", () => { - const track = vi.fn(); - const { doc, fire } = fakeDocument({ prerendering: true }); - - trackNavLabel({ track, doc }); - expect(track).not.toHaveBeenCalled(); - - fire("prerenderingchange", false); - expect(track).toHaveBeenCalledWith(EXPOSURE_EVENT, props); - }); - - it("does nothing when the nav has no experiment link", () => { - const track = vi.fn(); - const { doc, fire } = fakeDocument({ dataset: null }); - - trackNavLabel({ track, doc }); - fire("click", true); - - expect(track).not.toHaveBeenCalled(); - }); - - it("records clicks on the experiment link and ignores other clicks", () => { - const track = vi.fn(); - const { doc, fire } = fakeDocument(); - - trackNavLabel({ track, doc }); - fire("click", false); - fire("click", true); - - expect(track).toHaveBeenCalledTimes(2); - expect(track).toHaveBeenLastCalledWith(CLICK_EVENT, props); - }); - - it("counts middle-clicks but not right-clicks", () => { - const track = vi.fn(); - const { doc, fire } = fakeDocument(); - - trackNavLabel({ track, doc }); - fire("auxclick", true, 2); - expect(track).toHaveBeenCalledOnce(); - - fire("auxclick", true, 1); - expect(track).toHaveBeenLastCalledWith(CLICK_EVENT, props); - }); -}); - -describe("navExperimentProps", () => { - it("returns the experiment and variant from the navbar link", () => { - expect(navExperimentProps(fakeDocument().doc)).toEqual(props); - }); - - it("returns nothing when the visitor is not in the test", () => { - expect(navExperimentProps(fakeDocument({ dataset: null }).doc)).toEqual({}); - }); -}); diff --git a/src/utils/navLabelExperiment.ts b/src/utils/navLabelExperiment.ts deleted file mode 100644 index 25467ccd..00000000 --- a/src/utils/navLabelExperiment.ts +++ /dev/null @@ -1,121 +0,0 @@ -export const NAV_LABEL_EXPERIMENT = "nav-get-involved-label"; -export const EXPOSURE_EVENT = "Nav Label Shown"; -export const CLICK_EVENT = "Nav Label Click"; - -export type NavLabelVariant = "A" | "B"; - -export interface NavLabelItem { - label: string; - href: string; - submenu: [string, string][] | null; -} - -// A: "Get Involved" with its full submenu (the control). B: "Member Opportunities", a single -// link straight to /volunteer with no submenu. -export const NAV_VARIANTS: Readonly> = { - A: { - label: "Get Involved", - href: "/get-involved", - submenu: [ - ["Become a Member", "/membership"], - ["Donate", "/donate"], - ["Join the Incubator", "https://techforpalestine.org/project-application-form"], - ["Volunteer", "/volunteer"], - ["Entrepreneurs for Palestine", "/e4p"], - ["Hire Palestinians", "/help/hire"], - ["Join our Discord", "https://techforpalestine.org/discord-invite"], - ], - }, - B: { - label: "Member Opportunities", - href: "/volunteer", - submenu: null, - }, -}; - -const MIDDLE_BUTTON = 1; -const VARIANTS: readonly NavLabelVariant[] = ["A", "B"]; - -export interface FeatureOutcome { - value: unknown; - source: string; -} - -// The variant comes from the "nav-get-involved-label" GrowthBook flag, evaluated on the server -// (src/lib/navAssignment.ts) with an id that is a keyed hash of the day, IP and User-Agent: -// a visitor keeps one label all day and nothing is stored on their device. -// -// The flag is a percentage rollout to "B" followed by a catch-all force to "A", so a bucketed -// visitor always reports source "force". A disabled flag, a missing flag or an unreachable -// CDN reports something else, and returns null: show "A" and track nothing. -export function variantFromFeature({ value, source }: FeatureOutcome): NavLabelVariant | null { - if (source !== "force") return null; - return VARIANTS.find((variant) => variant === value) ?? null; -} - -export type TrackEvent = (name: string, props: Record) => void; - -// The parts of Document this needs. `prerendering` is not in TypeScript's DOM lib yet. -export interface ExperimentDocument { - prerendering?: boolean; - querySelector(selector: string): Element | null; - addEventListener( - type: "prerenderingchange" | "click" | "auxclick", - listener: (event: MouseEvent) => void, - options?: AddEventListenerOptions - ): void; -} - -export interface TrackNavLabelOptions { - track?: TrackEvent; - doc?: ExperimentDocument; -} - -const LINK_SELECTOR = "a[data-experiment][data-variant]"; - -/** The nav label test props for the page's navbar, to attach to conversion events - * (About You Complete, Membership-complete). Empty when the visitor is not in the test. - * The navbar is in the DOM on every Layout page, including when it is hidden by CSS. */ -export function navExperimentProps( - doc: Pick = document -): Record { - const link = doc.querySelector(LINK_SELECTOR) as HTMLElement | null; - const experiment = link?.dataset.experiment; - const variant = link?.dataset.variant; - return experiment && variant ? { experiment, variant } : {}; -} - -const trackWithPlausible: TrackEvent = (name, props) => { - window.plausible?.(name, { props }); -}; - -// Records one exposure per page view when the nav carries an experiment link, and every -// click on that link or, for variant A, on any of its submenu links (desktop or mobile menu). The mobile menu is rendered on demand, so -// clicks are caught by delegation on the document. -// -// Layout prerenders some pages via speculation rules, and prerendered pages run their -// scripts, so the exposure waits until the page is actually shown. Middle-clicks (open in -// new tab) count too. -export function trackNavLabel(options: TrackNavLabelOptions = {}): void { - const { track = trackWithPlausible, doc = document as unknown as ExperimentDocument } = options; - const link = doc.querySelector(LINK_SELECTOR) as HTMLElement | null; - const experiment = link?.dataset.experiment; - const variant = link?.dataset.variant; - if (!experiment || !variant) return; - - const props = { experiment, variant }; - const recordExposure = (): void => track(EXPOSURE_EVENT, props); - if (doc.prerendering) { - doc.addEventListener("prerenderingchange", recordExposure, { once: true }); - } else { - recordExposure(); - } - - const onClick = (event: MouseEvent): void => { - if (event.type === "auxclick" && event.button !== MIDDLE_BUTTON) return; - const clicked = (event.target as Element | null)?.closest?.(LINK_SELECTOR); - if (clicked) track(CLICK_EVENT, props); - }; - doc.addEventListener("click", onClick); - doc.addEventListener("auxclick", onClick); -}