All files / src/scripts landing-form.ts

95.67% Statements 155/162
82.82% Branches 82/99
100% Functions 16/16
97.24% Lines 141/145

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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306                                                                1x     55x       34x 34x 34x 34x 34x 34x 34x   31x 31x 31x 31x 1x 1x 1x   34x 423x         34x 34x 34x 217x 217x 186x 10x 9x 9x         186x 4x 4x 4x 3x 3x               31x   6x 6x   6x     6x 24x 24x 24x           6x 6x     31x     31x 31x 1x                   31x   69x 19x 19x   50x 50x     31x     14x 13x 13x     16x             22x 22x   22x     22x 22x 5x 5x     22x 22x 22x 1x 1x       22x 1x 1x   22x 5x 5x       22x 22x 2x 2x   22x 22x 1x 1x   22x       34x     34x 5x 1x   4x       31x 1x     31x 31x 22x 22x   22x 22x 10x 80x 80x 68x 68x   10x   10x 10x       10x   12x       12x 12x 12x 12x   12x                 22x 22x 22x 22x 22x 22x     12x 12x 12x 12x 12x   12x 12x         9x       9x 2x 2x     7x         7x 6x   7x 7x   7x   2x   11x 11x 11x         1x              
/**
 * Landing-page lead form — client-side behavior for standalone campaign
 * pages (e.g. /landing/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 { LEAD_CONSENT_VERSION } from "@interioring/utils/constants/consent";
import { OTHER_CITY_VALUE, resolveSubmittedCity } from "../lib/lead-city";
import { pushDataLayerEvent } from "../lib/gtm";
import {
	validateCustomerName,
	validateIndianPhoneNumber,
} from "../lib/validation";
import { firstTouch } from "./attribution";
 
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", "city", "cityOther"] as const;
	const citySelect = form.querySelector<HTMLSelectElement>('select[name="city"]');
	const cityOther = form.querySelector<HTMLInputElement>('input[name="cityOther"]');
	citySelect?.addEventListener("change", () => {
		const show = citySelect.value === OTHER_CITY_VALUE;
		cityOther?.classList.toggle("hidden", !show);
		Iif (!show && cityOther) cityOther.value = "";
	});
	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 ────────────────────────────────────────────────────────
	// The banner (role="alert") is announced; each rejected field is marked
	// aria-invalid and described by it, and typing in a field unmarks it.
	if (errorBanner && !errorBanner.id) errorBanner.id = `lf-error-${source}`;
	function markInvalid(el: Element, bad: boolean): void {
		if (bad) {
			el.setAttribute("aria-invalid", "true");
			if (errorBanner) el.setAttribute("aria-describedby", errorBanner.id);
		} else {
			el.removeAttribute("aria-invalid");
			el.removeAttribute("aria-describedby");
		}
	}
	form.addEventListener("input", (e) => markInvalid(e.target as Element, false));
 
	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() ?? "";
		// The wrapper words each failure on its own: a name with digits is told
		// about the digits, not "at least 2 letters".
		const nameError = validateCustomerName(name);
		if (nameError) {
			errors.push("name");
			problems.push(nameError);
		}
 
		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.",
			);
		}
		const consent = form?.querySelector<HTMLInputElement>('[name="consent"]');
		if (!consent?.checked) {
			errors.push("consent");
			problems.push("Please tick the box to agree to be contacted.");
		}
		const city = readCity();
		if (!city.ok) {
			errors.push(citySelect?.value === OTHER_CITY_VALUE ? "cityOther" : "city");
			problems.push(city.message);
		}
		return { errors, message: problems.join(" ") };
	}
 
	function readCity(): ReturnType<typeof resolveSubmittedCity> {
		const hidden = form?.querySelector<HTMLInputElement>(
			'input[type="hidden"][name="city"]',
		);
		if (hidden) return resolveSubmittedCity(hidden.value);
		if (!citySelect) {
			return { ok: false, message: "Please choose your city." };
		}
		return resolveSubmittedCity(citySelect.value, cityOther?.value ?? "");
	}
 
	// ── 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, "consent"]) {
				const el = input(name);
				if (!el) continue;
				el.classList.toggle("bad", errors.includes(name));
				markInvalid(el, errors.includes(name));
			}
			showError(message);
			// First rejected field in page order, so focus never falls to <body>.
			form.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus();
			pushDataLayerEvent("lp_form_error", {
				...eventBase(source),
				fields: errors.join(","),
			});
			return;
		}
		hideError();
 
		// aria-disabled, not disabled: disabling the focused button drops focus
		// to <body>. `submitting` already blocks a second submit.
		submitting = true;
		submitBtn.setAttribute("aria-disabled", "true");
		const originalLabel = submitBtn.textContent;
		submitBtn.textContent = "Sending…";
 
		const payload: Record<string, string | boolean> = {
			...firstTouch(),
			consent: true,
			consentVersion: LEAD_CONSENT_VERSION,
			entryType: "form",
			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();
		const city = readCity();
		Iif (!city.ok) {
			throw new Error(city.message);
		}
		payload.city = city.city;
		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 = String(payload.name).split(/\s+/)[0] || "there";
			}
			form.classList.add("hidden");
			successDiv.classList.remove("hidden");
			// The form just vanished: focus the thank-you heading instead.
			successDiv.querySelector<HTMLElement>('[tabindex="-1"]')?.focus();
		} catch {
			showError("Something went wrong. Please check your connection and try again.");
		} finally {
			submitting = false;
			submitBtn.removeAttribute("aria-disabled");
			submitBtn.textContent = originalLabel;
		}
	});
}
 
for (const rootEl of document.querySelectorAll<HTMLElement>("[data-landing-form]")) {
	if (rootEl.dataset.lfReady === "1") continue;
	rootEl.dataset.lfReady = "1";
	initLandingForm(rootEl);
}
 
export { initLandingForm };