Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/dsoc/apply/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';

import { sendEvent } from '@/lib/analytics';
import Link from "next/link";
import { useState, useEffect, use } from "react";
import { useForm } from "react-hook-form";
Expand Down Expand Up @@ -216,6 +217,7 @@ export default function ApplyPage({ params }: { params: Promise<{ id: string }>

if (data.success) {
setSuccess(true);
sendEvent('application_submitted', { program: 'dsoc', project_id: resolvedParams.id, page_path: window.location.pathname });
} else {
setError(data.error || 'Failed to submit application');
}
Expand Down
2 changes: 2 additions & 0 deletions app/dsoc/register/mentee/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';

import { sendEvent } from '@/lib/analytics';
import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
Expand Down Expand Up @@ -64,6 +65,7 @@ export default function MenteeRegisterPage() {

if (data.success) {
setSuccess(true);
sendEvent('registration_submitted', { program: 'dsoc', role: 'mentee', page_path: window.location.pathname });
} else {
setError(data.error || 'Registration failed');
}
Expand Down
2 changes: 2 additions & 0 deletions app/dsoc/register/mentor/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';

import { sendEvent } from '@/lib/analytics';
import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
Expand Down Expand Up @@ -66,6 +67,7 @@ export default function MentorRegisterPage() {

if (data.success) {
setSuccess(true);
sendEvent('registration_submitted', { program: 'dsoc', role: 'mentor', page_path: window.location.pathname });
} else {
setError(data.error || 'Registration failed');
}
Expand Down
5 changes: 5 additions & 0 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ThemeProvider } from "@/components/theme-provider"
import { SiteFooter } from "@/components/site-footer"
import Script from 'next/script'
import { Analytics } from "@/components/analytics"
import { LeadTracker } from "@/components/lead-tracker"
import { SiteHeader } from "@/components/site-header"
import { EmailChooser } from "@/components/email-chooser"
import { dwosiThemeScript } from "@/app/dwosi/theme"
Expand Down Expand Up @@ -120,6 +121,9 @@ export default function RootLayout({
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gaId}');
// Events that happened before this tag loaded (see sendEvent in lib/analytics.ts)
(window.__dwEvents || []).forEach(function (e) { gtag('event', e[0], e[1]); });
window.__dwEvents = [];
`,
}}
/>
Expand All @@ -141,6 +145,7 @@ export default function RootLayout({
<SiteHeader />
<main className="flex-1">
<Analytics />
<LeadTracker />
{children}
</main>
<SiteFooter />
Expand Down
2 changes: 2 additions & 0 deletions components/home/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ function GetInvolvedPanel({ onNavigate }: { onNavigate: () => void }) {
key={program.name}
href={program.href}
onClick={onNavigate}
data-lead="apply_program"
data-lead-program={program.name}
className="flex min-h-11 items-center justify-between gap-3 rounded-[10px] p-3 hover:bg-[#F7F7F7]"
>
<span>
Expand Down
76 changes: 76 additions & 0 deletions components/lead-tracker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"use client"

import { useEffect } from "react"

import { sendEvent } from "@/lib/analytics"

/**
* Counts the clicks that turn a visitor into a lead, as Google Analytics events:
*
* - `join_community_click`: a link to one of the community groups (Discord,
* WhatsApp, LinkedIn or Facebook group), such as "Join the community".
* - `apply_program_click`: an "Apply ..." button, or a program in an
* "Apply to a program" list (those are marked with `data-lead="apply_program"`
* because their text is the program's name).
*
* One listener on the document covers every page and every button, including
* ones added later, so no button needs its own code. The groups and most
* application forms live on other sites, so for those the click is the last
* thing this site can see.
*/

function communityPlatform(url: URL): string | undefined {
const host = url.hostname.replace(/^www\./, "")
if (host === "discord.gg" || (host === "discord.com" && url.pathname.startsWith("/invite"))) return "discord"
if (host === "chat.whatsapp.com" || (host === "whatsapp.com" && url.pathname.startsWith("/channel"))) return "whatsapp"
if (host === "linkedin.com" && url.pathname.startsWith("/groups")) return "linkedin"
if (host === "facebook.com" && url.pathname.startsWith("/groups")) return "facebook"
return undefined
}

/** Where on the page the link sits: header, footer, or the id of its section */
function placementOf(link: HTMLAnchorElement): string {
if (link.closest("header")) return "header"
if (link.closest("footer")) return "footer"
return link.closest("section[id], [role='dialog'], nav[aria-label]")?.id || "page"
}

export function LeadTracker() {
useEffect(() => {
const onClick = (event: MouseEvent) => {
const link = (event.target as Element | null)?.closest?.("a[href]") as HTMLAnchorElement | null
if (!link) return

let url: URL
try {
url = new URL(link.href, window.location.href)
} catch {
return
}

const text = (link.innerText || link.getAttribute("aria-label") || "").replace(/\s+/g, " ").trim().slice(0, 80)
const marked = link.closest<HTMLElement>("[data-lead]")
const platform = communityPlatform(url)
const isApply = marked?.dataset.lead === "apply_program" || /^apply\b/i.test(text)

const name = platform ? "join_community_click" : isApply ? "apply_program_click" : undefined
if (!name) return

sendEvent(name, {
link_text: text,
link_url: url.href.slice(0, 100),
link_domain: url.hostname,
placement: placementOf(link),
page_path: window.location.pathname,
...(platform ? { platform } : {}),
...(marked?.dataset.leadProgram ? { program: marked.dataset.leadProgram } : {}),
})
}

// Capture phase: runs before a menu that closes on click removes the link from the page
document.addEventListener("click", onClick, true)
return () => document.removeEventListener("click", onClick, true)
}, [])

return null
}
7 changes: 6 additions & 1 deletion components/site/start-here.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,12 @@ export function StartHere() {
<ul className="mt-3">
{applyPrograms.map((program) => (
<li key={program.name} data-reveal className="border-b border-[#E6E6E6] last:border-b-0">
<SmartLink href={program.href} className="flex flex-wrap items-center gap-x-4 gap-y-1 py-4 hover:bg-[#FAFAFA]">
<SmartLink
href={program.href}
data-lead="apply_program"
data-lead-program={program.name}
className="flex flex-wrap items-center gap-x-4 gap-y-1 py-4 hover:bg-[#FAFAFA]"
>
<span className="min-w-0 flex-1 basis-[200px]">
<span className="block text-base font-semibold sm:text-lg">{program.name}</span>
<span className="mt-0.5 block text-sm text-[#5C5C5C]">{program.when}</span>
Expand Down
19 changes: 17 additions & 2 deletions lib/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ declare global {
[key: string]: any;
}
) => void;
/** Events sent before the analytics tag has loaded, kept until it has */
__dwEvents?: [string, Record<string, unknown>][];
}
}

Expand All @@ -26,10 +28,23 @@ export const pageview = (url: string) => {
}
};

export const event = ({ action, params }: { action: string; params: any }) => {
if (typeof window !== 'undefined' && window.gtag) {
/**
* Sends a named event to Google Analytics. The tag loads late on purpose (after
* the page is idle), so an event that happens before then is kept in a short
* queue, which the tag's start-up script in app/layout.tsx sends on.
*/
export function sendEvent(action: string, params: Record<string, unknown> = {}) {
if (typeof window === 'undefined') return;
if (window.gtag) {
window.gtag('event', action, params);
return;
}
const queue = (window.__dwEvents = window.__dwEvents ?? []);
if (queue.length < 50) queue.push([action, params]);
}

export const event = ({ action, params }: { action: string; params: any }) => {
sendEvent(action, params);
};

// Custom event tracking functions
Expand Down
Loading