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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | 17x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 18x 37x 18x 18x 18x 70x 139x 70x 70x 70x 26x 104x 104x 45x 180x 180x 180x 180x 180x 180x 45x 46x 46x 2x 2x 2x 2x 44x 45x 6x 6x 3x 3x 3x 3x 3x 6x 6x 6x 6x 2x 2x 2x 45x 39x 2x 2x 2x 45x 45x 66x 66x 45x 45x 45x 45x 5x 5x 5x 5x 1x 4x 45x 45x 4x 4x 4x 4x 45x 4x 3x 3x 1x 1x 1x 1x 45x 1x 45x 45x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 45x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 9x 9x 9x 9x 25x 25x 25x 5x 5x 25x 25x 6x 6x 25x 5x 5x 25x 1x 1x 25x 9x 9x 16x 16x 16x 7x 7x 1x 16x 25x 25x 16x 16x 16x 13x 13x 11x 11x 11x 11x 11x 4x 4x 4x 1x 3x 7x 11x 11x 11x 11x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 16x 16x 16x 16x | /**
* Unified Contact Form - Client-side behavior for all placement variants
* (sidebar, inline, sticky-mobile).
*
* Reads widget configuration from data attributes on .unified-contact-widget
* containers and wires up CTA triggers, form validation, submission, duplicate
* detection, success/reset flows, and analytics tracking.
*/
import { getCachedHomeownerUser } from "../components/homeowner/auth-check";
import { pushDataLayerEvent } from "../lib/gtm";
import {
extractPhoneDigits,
validateCustomerName,
validateIndianPhoneNumber,
} from "../lib/validation";
function getTracker(): DRTracker | undefined {
return window.DRTracker;
}
document
.querySelectorAll<HTMLElement>(".unified-contact-widget")
.forEach((widget) => {
// Prefer the container's data-pro-id; fall back to the form's hidden
// proId input so the value survives even if the dataset attr is missing
// (#794).
const proId =
widget.dataset.proId ||
(
widget.querySelector(
'input[name="proId"]',
) as HTMLInputElement | null
)?.value ||
"";
const proName = widget.dataset.proName ?? "";
const proWhatsapp = widget.dataset.proWhatsapp ?? "";
const placement = widget.dataset.placement ?? "sidebar";
const ctaTrigger = widget.querySelector(
".ucf-cta-trigger",
) as HTMLElement | null;
const formContainer = widget.querySelector(
".ucf-form-container",
) as HTMLElement | null;
const form = widget.querySelector(".ucf-form") as HTMLFormElement | null;
const successDiv = widget.querySelector(
".ucf-success",
) as HTMLElement | null;
const errorDiv = widget.querySelector(".ucf-error") as HTMLElement | null;
const fallbackLink = widget.querySelector(
".ucf-fallback-link",
) as HTMLElement | null;
const duplicateWarning = widget.querySelector(
".ucf-duplicate-warning",
) as HTMLElement | null;
const resetBtn = widget.querySelector(
".ucf-reset-btn",
) as HTMLElement | null;
const successMessage = widget.querySelector(
".ucf-success-message",
) as HTMLElement | null;
const otherDescContainer = widget.querySelector(
".ucf-other-description",
) as HTMLElement | null;
const submitActionInput = form?.querySelector(
'input[name="submitAction"]',
) as HTMLInputElement | null;
const requirementSelect = form?.querySelector(
'select[name="requirementType"]',
) as HTMLSelectElement | null;
const requirementDesc = form?.querySelector(
'textarea[name="requirementDescription"]',
) as HTMLTextAreaElement | null;
// Sticky-mobile specific elements
const overlay = widget.querySelector(".ucf-overlay") as HTMLElement | null;
const panel = widget.querySelector(".ucf-panel") as HTMLElement | null;
const panelClose = widget.querySelector(
".ucf-panel-close",
) as HTMLElement | null;
const btnWhatsapp = widget.querySelector(
".ucf-btn-whatsapp",
) as HTMLButtonElement | null;
const btnCallback = widget.querySelector(
".ucf-btn-callback",
) as HTMLButtonElement | null;
Iif (!form || !errorDiv) return;
// --- Field-level inline errors ---
const fieldErrors = form.querySelectorAll<HTMLElement>(".ucf-field-error");
function showFieldError(fieldName: string, message: string): void {
for (const el of fieldErrors) {
if (el.dataset.field === fieldName) {
el.textContent = message;
el.classList.remove("hidden");
return;
}
}
// Fallback to central error div if inline element is missing
if (errorDiv) {
errorDiv.textContent = message;
errorDiv.classList.remove("hidden");
}
}
function clearFieldError(fieldName: string): void {
for (const el of fieldErrors) {
if (el.dataset.field === fieldName) {
el.textContent = "";
el.classList.add("hidden");
return;
}
}
}
function clearFieldErrors(): void {
for (const el of fieldErrors) {
el.textContent = "";
el.classList.add("hidden");
}
}
// --- Accessibility: associate labels with inputs via for/id ---
form.querySelectorAll<HTMLElement>("label").forEach((label) => {
const input = label.parentElement?.querySelector(
"input, select, textarea",
) as HTMLElement | null;
Eif (input && !input.id) {
const fieldName =
(input as HTMLInputElement).name || crypto.randomUUID().slice(0, 8);
const uid = `ucf-${placement}-${fieldName}`;
input.id = uid;
label.setAttribute("for", uid);
}
});
// --- Duplicate check ---
let isDuplicate = false;
function checkDuplicate(): void {
const ts = localStorage.getItem(`inquiry_${proId}`);
if (ts && Date.now() - parseInt(ts, 10) < 86400000) {
isDuplicate = true;
Eif (duplicateWarning) {
duplicateWarning.textContent = `You\u2019ve already reached out to ${proName}. They should get back to you soon!`;
duplicateWarning.classList.remove("hidden");
}
} else {
isDuplicate = false;
}
}
// --- CTA trigger (inline + sticky-mobile) ---
if (ctaTrigger && placement !== "sidebar") {
function handleCtaActivate(): void {
if (placement === "sticky-mobile") {
// Open slide-up panel
overlay?.classList.remove("hidden");
panel?.classList.remove("hidden");
document.body.style.overflow = "hidden";
} else {
// Inline: hide CTA, show form
ctaTrigger?.classList.add("hidden");
formContainer?.classList.remove("hidden");
}
getTracker()?.click("pro", proId, proId, "contact_cta_click");
checkDuplicate();
}
ctaTrigger.addEventListener("click", handleCtaActivate);
ctaTrigger.addEventListener("keydown", (e: KeyboardEvent) => {
Eif (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handleCtaActivate();
}
});
}
// Sidebar: check duplicate immediately since form is always visible
if (placement === "sidebar") {
checkDuplicate();
}
// --- Sticky-mobile close ---
function closePanel(): void {
overlay?.classList.add("hidden");
panel?.classList.add("hidden");
document.body.style.overflow = "";
}
panelClose?.addEventListener("click", closePanel);
overlay?.addEventListener("click", closePanel);
// --- Clear inline error on field interaction ---
function handleFieldInteraction(e: Event): void {
const fieldName = (e.target as HTMLElement as HTMLInputElement).name;
Eif (fieldName) clearFieldError(fieldName);
}
form.addEventListener("input", handleFieldInteraction);
form.addEventListener("change", handleFieldInteraction);
// --- Live name validation on blur ---
// Uses the canonical validateCustomerName so live feedback always matches
// the submit-time verdict. (The previous inline `oninput` handler in
// ContactFormFields.astro hand-rolled a regex that Astro's attribute
// compilation mangled — see git history.) The clear-on-input listener
// above wipes the error as the user types; this re-validates on blur.
const nameInput = form.querySelector(
'input[name="customerName"]',
) as HTMLInputElement | null;
nameInput?.addEventListener("blur", () => {
const value = nameInput.value.trim().replace(/\s+/g, " ");
Iif (!value) {
clearFieldError("customerName");
return;
}
const error = validateCustomerName(value);
if (error) {
showFieldError("customerName", error);
} else {
clearFieldError("customerName");
}
});
// --- Normalize the phone field on blur ---
// Inquiries accept any Indian-mobile format (with/without +91, spaces, or a
// leading 0). ContactFormFields.astro used to carry an inline
// `oninput="...replace(/\D/g,'')"` digit-strip, but Astro's attribute
// compilation mangled the regex (\D -> D) so it stripped nothing; combined
// with the old maxlength="10" a pasted "+91 …" was truncated to garbage and
// the inquiry POST 500'd with no success shown. extractPhoneDigits (backed
// by libphonenumber) collapses every accepted format to the 10-digit
// national number, so blur leaves a clean value and submit always sends
// digits. Unparseable input (mid-typed, too short) falls back to a plain
// digit-strip — harmless, since submit re-normalizes and validation rejects
// anything that isn't a valid mobile.
const phoneInput = form.querySelector(
'input[name="customerPhone"]',
) as HTMLInputElement | null;
phoneInput?.addEventListener("blur", () => {
Iif (!phoneInput.value.trim()) return;
const normalized = extractPhoneDigits(phoneInput.value);
Eif (normalized && normalized !== phoneInput.value)
phoneInput.value = normalized;
});
// --- Show/hide "Other" description field ---
requirementSelect?.addEventListener("change", () => {
if (requirementSelect.value === "other") {
otherDescContainer?.classList.remove("hidden");
Eif (requirementDesc) requirementDesc.required = true;
} else {
otherDescContainer?.classList.add("hidden");
Eif (requirementDesc) {
requirementDesc.required = false;
requirementDesc.value = "";
}
}
});
// --- Button click handlers to set submitAction ---
btnWhatsapp?.addEventListener("click", () => {
Eif (submitActionInput) submitActionInput.value = "whatsapp";
});
btnCallback?.addEventListener("click", () => {
if (submitActionInput) submitActionInput.value = "callback";
});
// --- Reset button ---
resetBtn?.addEventListener("click", () => {
successDiv?.classList.add("hidden");
form?.classList.remove("hidden");
form?.reset();
errorDiv?.classList.add("hidden");
Eif (errorDiv) errorDiv.textContent = "";
clearFieldErrors();
fallbackLink?.classList.add("hidden");
otherDescContainer?.classList.add("hidden");
Eif (requirementDesc) {
requirementDesc.required = false;
requirementDesc.value = "";
}
duplicateWarning?.classList.add("hidden");
checkDuplicate();
});
// --- Form submission ---
form.addEventListener("submit", async (e: SubmitEvent) => {
e.preventDefault();
// Block duplicate submissions
Iif (isDuplicate) {
if (successMessage) {
successMessage.textContent = `You've already sent an inquiry to ${proName}. They'll get back to you soon!`;
}
form.classList.add("hidden");
successDiv?.classList.remove("hidden");
return;
}
const action = submitActionInput?.value ?? "callback";
const isWhatsapp = action === "whatsapp";
// Determine which button was clicked
const activeBtn = isWhatsapp
? (btnWhatsapp ?? btnCallback)
: (btnCallback ?? btnWhatsapp);
Iif (!activeBtn) return;
const activeBtnLabel = activeBtn.querySelector(
".ucf-btn-label",
) as HTMLElement | null;
const activeBtnIcon = activeBtn.querySelector(
".ucf-btn-icon",
) as HTMLElement | null;
const originalLabel = activeBtnLabel?.textContent ?? "";
activeBtn.disabled = true;
Eif (activeBtnLabel) activeBtnLabel.textContent = "Sending...";
Eif (activeBtnIcon) activeBtnIcon.classList.add("hidden");
// Disable the other button too
const otherBtn = isWhatsapp ? btnCallback : btnWhatsapp;
Eif (otherBtn) otherBtn.disabled = true;
errorDiv.classList.add("hidden");
errorDiv.textContent = "";
clearFieldErrors();
fallbackLink?.classList.add("hidden");
const formData = new FormData(form);
const phone = extractPhoneDigits(
(formData.get("customerPhone") as string) ?? "",
);
const name = ((formData.get("customerName") as string) ?? "").trim();
const reqType = (formData.get("requirementType") as string) ?? "";
const otherDesc =
reqType === "other"
? ((formData.get("requirementDescription") as string) ?? "").trim()
: undefined;
// Validate all fields and show inline errors
let hasError = false;
function restoreButtons(): void {
Eif (activeBtn) activeBtn.disabled = false;
Eif (activeBtnLabel) activeBtnLabel.textContent = originalLabel;
Eif (activeBtnIcon) activeBtnIcon.classList.remove("hidden");
Eif (otherBtn) otherBtn.disabled = false;
}
const normalizedName = name.replace(/\s+/g, " ");
const nameError = validateCustomerName(normalizedName);
if (nameError) {
showFieldError("customerName", nameError);
hasError = true;
}
const phoneError = validateIndianPhoneNumber(phone);
if (phoneError) {
showFieldError("customerPhone", phoneError);
hasError = true;
}
if (!reqType) {
showFieldError(
"requirementType",
"Please select what you are looking for.",
);
hasError = true;
}
if (reqType === "other" && !otherDesc) {
showFieldError(
"requirementDescription",
"Please describe your requirement.",
);
hasError = true;
}
if (hasError) {
restoreButtons();
return;
}
// Pre-open the WhatsApp tab synchronously, while we still hold the
// submit's user-activation. Opening it after `await fetch` below would
// be blocked as an unsolicited popup on desktop. Mobile redirects the
// current tab instead, so it doesn't need a pre-opened window.
const isDesktop = window.innerWidth >= 768;
let waWindow: Window | null = null;
if (isWhatsapp && isDesktop) {
// window.open can throw under strict sandbox/iframe policies — never
// let that crash the submission (a callback request must still go
// through). A null window is handled by the success branch below.
try {
waWindow = window.open("about:blank", "_blank");
} catch (err) {
console.error("[UnifiedContactForm] Failed to pre-open window:", err);
}
}
const email = ((formData.get("customerEmail") as string) ?? "").trim();
const data: Record<string, string | undefined> = {
proId,
customerName: normalizedName,
customerPhone: phone,
type: isWhatsapp ? "whatsapp" : "form_submit",
requirementType: reqType,
sourceType: "marketplace",
sourcePage: window.location.pathname,
};
Iif (email) data.customerEmail = email;
Iif (otherDesc) {
data.requirementDescription = otherDesc;
data.requirement = otherDesc;
}
try {
const response = await fetch("/api/inquiry", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
const result = (await response.json()) as {
success: boolean;
data?: { id?: string; whatsapp_redirect_url?: string };
error?: string;
};
if (result.success) {
// Store in localStorage for duplicate detection
localStorage.setItem(`inquiry_${proId}`, String(Date.now()));
const tracker = getTracker();
tracker?.click(
"pro",
proId,
proId,
isWhatsapp ? "whatsapp_form_submit" : "callback_form_submit",
);
// GA4 conversion (via GTM). Coexists with DRTracker above.
// logged_in: optimistic (cached, no network) homeowner auth state
// so GA4 can segment conversions by authenticated vs anonymous.
pushDataLayerEvent("generate_lead", {
lead_type: isWhatsapp ? "whatsapp" : "callback",
pro_id: proId,
pro_name: proName,
// Canonical page dimension shared across all conversion events
// so GA can slice every conversion by page. See
// apps/marketplace/CLAUDE.md §Analytics.
page_path: window.location.pathname,
logged_in: getCachedHomeownerUser() != null,
});
if (isWhatsapp && result.data?.whatsapp_redirect_url) {
tracker?.click("pro", proId, proId, "whatsapp_redirect");
Iif (!isDesktop) {
window.location.href = result.data.whatsapp_redirect_url;
} else if (waWindow && !waWindow.closed) {
waWindow.location.href = result.data.whatsapp_redirect_url;
} else {
// Pre-open was blocked: surface the direct link instead.
fallbackLink?.classList.remove("hidden");
}
} else {
// No redirect URL came back — discard the placeholder tab.
waWindow?.close();
}
// Show success state
form.classList.add("hidden");
Eif (successMessage) {
successMessage.textContent = isWhatsapp
? `Request sent to ${proName}!`
: `We\u2019ve shared your details with ${proName}. They\u2019ll call you back shortly!`;
}
successDiv?.classList.remove("hidden");
} else {
waWindow?.close();
const msg =
typeof result.error === "string"
? result.error
: "Something went wrong. Please try again.";
errorDiv.textContent = msg;
errorDiv.classList.remove("hidden");
Eif (proWhatsapp) fallbackLink?.classList.remove("hidden");
}
} catch (err) {
waWindow?.close();
console.error("[UnifiedContactForm] Submission failed:", err);
errorDiv.textContent =
"Something went wrong. You can try again or use the direct link below.";
errorDiv.classList.remove("hidden");
if (proWhatsapp) fallbackLink?.classList.remove("hidden");
} finally {
activeBtn.disabled = false;
Eif (activeBtnLabel) activeBtnLabel.textContent = originalLabel;
Eif (activeBtnIcon) activeBtnIcon.classList.remove("hidden");
Eif (otherBtn) otherBtn.disabled = false;
}
});
});
|