All files / src/scripts landing-form.ts

98.3% Statements 116/118
84.93% Branches 62/73
100% Functions 12/12
100% Lines 107/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237                                                          1x     39x       23x 23x 23x 23x 23x 23x 23x   20x 20x 212x         20x 20x 20x 100x 100x 99x 2x 1x 1x         99x 3x 3x 3x 2x 2x               20x   6x 6x   6x     6x 24x 24x 24x           6x 6x     20x     20x 20x 1x                 10x 9x 9x     11x             14x 14x   14x 14x 4x 4x     14x 14x 14x 1x 1x       14x 1x 1x   14x 4x 4x       14x       20x 1x     20x 20x 14x 14x   14x 14x 6x 30x   6x 6x       6x   8x   8x 8x 8x 8x   8x         14x 14x 14x 14x 14x 8x 8x 8x   8x 8x         6x       6x 2x 2x     4x         4x 3x   4x 4x   2x   8x 8x 8x         1x 1x      
/**
 * Landing-page lead form — client-side behavior for standalone campaign
 * pages (e.g. /get-matched).
 *
 * Validation contract (mirrors /api/landing-lead): name required, and at
 * least one of phone/email must be valid; a filled-but-invalid contact is an
 * error, never silently dropped.
 *
 * GA4/GTM engagement taxonomy (all pushed to dataLayer, all deduped
 * client-side so GA sees first-occurrence signals, not keystroke noise):
 * - lp_field_focus  {field}    — user clicked/tabbed into a field
 * - lp_field_input  {field}    — user actually typed in a field
 * - lp_cta_click               — submit button pressed (fires even when
 *                                validation then fails)
 * - lp_form_error   {fields}   — client validation rejected the submit
 * - lp_scroll_depth {percent}  — 25/50/75/100, reading signal
 * - lp_link_click   {link}     — footer/subtle links
 * - generate_lead              — canonical conversion event (lead_type:
 *                                "landing") so the existing GA4 lead tag
 *                                fires without GTM changes
 * Every event carries page_path (canonical page dimension) + source.
 */
 
import { pushDataLayerEvent } from "../lib/gtm";
import {
	validateCustomerName,
	validateIndianPhoneNumber,
} from "../lib/validation";
 
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
 
function eventBase(source: string): Record<string, unknown> {
	return { page_path: window.location.pathname, source };
}
 
function initLandingForm(root: HTMLElement): void {
	const source = root.dataset.source ?? "landing";
	const form = root.querySelector<HTMLFormElement>(".lf-form");
	const successDiv = root.querySelector<HTMLElement>(".lf-success");
	const successName = root.querySelector<HTMLElement>(".lf-success-name");
	const errorBanner = root.querySelector<HTMLElement>(".lf-error");
	const submitBtn = root.querySelector<HTMLButtonElement>(".lf-submit");
	if (!form || !successDiv || !submitBtn) return;
 
	const fields = ["name", "phone", "email", "locality", "notes"] as const;
	const input = (name: string) =>
		form.querySelector<HTMLInputElement | HTMLTextAreaElement>(
			`[name="${name}"]`,
		);
 
	// ── Engagement: typing ────────────────────────────────────────────────
	const focused = new Set<string>();
	const typed = new Set<string>();
	for (const name of fields) {
		const el = input(name);
		if (!el) continue;
		el.addEventListener("focus", () => {
			if (focused.has(name)) return;
			focused.add(name);
			pushDataLayerEvent("lp_field_focus", {
				...eventBase(source),
				field: name,
			});
		});
		el.addEventListener("input", () => {
			el.classList.remove("bad");
			hideError();
			if (typed.has(name)) return;
			typed.add(name);
			pushDataLayerEvent("lp_field_input", {
				...eventBase(source),
				field: name,
			});
		});
	}
 
	// ── Engagement: reading (scroll depth) ────────────────────────────────
	const firedDepths = new Set<number>();
	function onScroll(): void {
		const doc = document.documentElement;
		const scrollable = doc.scrollHeight - window.innerHeight;
		const percent =
			scrollable <= 0
				? 100
				: Math.round((window.scrollY / scrollable) * 100);
		for (const threshold of [25, 50, 75, 100]) {
			Eif (percent >= threshold && !firedDepths.has(threshold)) {
				firedDepths.add(threshold);
				pushDataLayerEvent("lp_scroll_depth", {
					...eventBase(source),
					percent: threshold,
				});
			}
		}
		Eif (firedDepths.size === 4) {
			window.removeEventListener("scroll", onScroll);
		}
	}
	window.addEventListener("scroll", onScroll, { passive: true });
 
	// ── Engagement: clicking (subtle links) ───────────────────────────────
	for (const link of root.querySelectorAll<HTMLAnchorElement>("a[href]")) {
		link.addEventListener("click", () => {
			pushDataLayerEvent("lp_link_click", {
				...eventBase(source),
				link: link.getAttribute("href") ?? "",
			});
		});
	}
 
	// ── Validation ────────────────────────────────────────────────────────
	function showError(message: string): void {
		if (!errorBanner) return;
		errorBanner.textContent = message;
		errorBanner.classList.remove("hidden");
	}
	function hideError(): void {
		errorBanner?.classList.add("hidden");
	}
 
	function validate(): { errors: string[]; message: string } {
		// Each failing field gets its own sentence so the banner never blames a
		// field the user filled correctly (e.g. a bad phone must not read as
		// "check your name").
		const errors: string[] = [];
		const problems: string[] = [];
 
		const name = input("name")?.value.trim() ?? "";
		if (!name || validateCustomerName(name)) {
			errors.push("name");
			problems.push("Please enter your name (at least 2 letters).");
		}
 
		const phone = input("phone")?.value.trim() ?? "";
		const email = input("email")?.value.trim() ?? "";
		if (phone !== "" && validateIndianPhoneNumber(phone)) {
			errors.push("phone");
			problems.push(
				"That mobile number doesn't look right — Indian mobiles are 10 digits starting with 6, 7, 8 or 9.",
			);
		}
		if (email !== "" && !EMAIL_RE.test(email)) {
			errors.push("email");
			problems.push("That email address doesn't look right.");
		}
		if (!phone && !email) {
			errors.push("phone", "email");
			problems.push(
				"Please share at least one way to reach you — a 10-digit mobile number or an email address.",
			);
		}
		return { errors, message: problems.join(" ") };
	}
 
	// ── Submit ────────────────────────────────────────────────────────────
	submitBtn.addEventListener("click", () => {
		pushDataLayerEvent("lp_cta_click", eventBase(source));
	});
 
	let submitting = false;
	form.addEventListener("submit", async (e) => {
		e.preventDefault();
		Iif (submitting) return;
 
		const { errors, message } = validate();
		if (errors.length > 0) {
			for (const name of fields) {
				input(name)?.classList.toggle("bad", errors.includes(name));
			}
			showError(message);
			pushDataLayerEvent("lp_form_error", {
				...eventBase(source),
				fields: errors.join(","),
			});
			return;
		}
		hideError();
 
		submitting = true;
		submitBtn.disabled = true;
		const originalLabel = submitBtn.textContent;
		submitBtn.textContent = "Sending…";
 
		const payload: Record<string, string> = {
			name: input("name")?.value.trim() ?? "",
			source,
			pagePath: window.location.pathname,
		};
		const phone = input("phone")?.value.trim();
		const email = input("email")?.value.trim();
		const locality = input("locality")?.value.trim();
		const notes = input("notes")?.value.trim();
		if (phone) payload.phone = phone;
		if (email) payload.email = email;
		if (locality) payload.locality = locality;
		if (notes) payload.notes = notes;
 
		try {
			const response = await fetch("/api/landing-lead", {
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify(payload),
			});
			const result = (await response.json()) as {
				success?: boolean;
				error?: string;
			};
			if (!response.ok || !result.success) {
				showError(result.error ?? "Something went wrong. Please try again.");
				return;
			}
 
			pushDataLayerEvent("generate_lead", {
				...eventBase(source),
				lead_type: "landing",
			});
 
			if (successName) {
				successName.textContent = payload.name.split(/\s+/)[0] || "there";
			}
			form.classList.add("hidden");
			successDiv.classList.remove("hidden");
		} catch {
			showError("Something went wrong. Please check your connection and try again.");
		} finally {
			submitting = false;
			submitBtn.disabled = false;
			submitBtn.textContent = originalLabel;
		}
	});
}
 
const rootEl = document.querySelector<HTMLElement>("[data-landing-form]");
Iif (rootEl) initLandingForm(rootEl);
 
export { initLandingForm };