-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpersistent-forms.js
More file actions
571 lines (489 loc) · 19.2 KB
/
Copy pathpersistent-forms.js
File metadata and controls
571 lines (489 loc) · 19.2 KB
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/**
* Persistent Forms - Form Input Persistence & Formatting Patterns
* Automatically caches user inputs, pre-fills website URLs, and formats phone numbers.
*/
const STORAGE_PREFIX = 'pf_user_';
const CONSENT_KEY = 'pf_ip_consent';
/**
* Initializes form persistence and formatting on all elements matching the selector.
* @param {string} selector - CSS selector for inputs to bind to. Default: 'input, textarea, select'
*/
function initPersistentForms(selector = 'input, textarea, select') {
if (typeof window === 'undefined' || !window.localStorage) return;
const inputs = document.querySelectorAll(selector);
// Initialize advanced features
populateCountryDropdown();
setupCookieConsent();
setupAntiSpam();
setupMessageGenerator();
setupEmailAutocomplete();
// If already consented, run location detection immediately
if (localStorage.getItem(CONSENT_KEY) === 'true') {
autoDetectLocation();
}
inputs.forEach(input => {
// 1. Hydrate from localStorage
const key = input.name || input.id;
if (!key) return; // Must have a name or id to persist
// Don't persist honeypot or captcha
if (key === 'website_url_hp' || key === 'captcha') return;
const storageKey = `${STORAGE_PREFIX}${key}`;
const savedValue = localStorage.getItem(storageKey);
if (savedValue !== null) {
if (input.type === 'checkbox') {
input.checked = savedValue === 'true';
} else if (!input.value) {
input.value = savedValue;
}
}
// 1.5 Real-time phone input validation
if (input.type === 'tel' || key.toLowerCase().includes('phone') || key.toLowerCase().includes('tel')) {
input.addEventListener('input', (e) => {
const cleaned = e.target.value.replace(/[^\d\+\-\(\)\s]/g, '');
if (e.target.value !== cleaned) {
e.target.value = cleaned;
}
});
}
// 2. Cross-Form Synchronization (Save on input/change)
const saveValue = (e) => {
const val = e.target.type === 'checkbox' ? e.target.checked.toString() : e.target.value;
localStorage.setItem(storageKey, val);
};
input.addEventListener('input', saveValue);
input.addEventListener('change', saveValue);
// 3. Formatting & Prefilling on Blur
input.addEventListener('blur', (e) => {
let val = e.target.value;
const type = input.type.toLowerCase();
const name = key.toLowerCase();
// Protocol Prefill for URLs/Websites
if (type === 'url' || name.includes('website') || name.includes('url')) {
// Show a loading visual while checking
const originalBg = e.target.style.backgroundColor;
e.target.style.opacity = '0.7';
formatUrlPrefixAsync(val).then(resolvedUrl => {
e.target.style.opacity = '1';
if (e.target.value !== resolvedUrl) {
e.target.value = resolvedUrl;
localStorage.setItem(storageKey, resolvedUrl);
e.target.dispatchEvent(new Event('input', { bubbles: true }));
}
});
}
// Telephone formatting
if (type === 'tel' || name.includes('phone') || name.includes('mobile') || name.includes('tel')) {
val = formatPhoneAndSyncDropdown(val);
}
// Update input and storage if modified
if (val !== e.target.value) {
e.target.value = val;
localStorage.setItem(storageKey, val);
}
});
});
}
function setupCookieConsent() {
const banner = document.getElementById('pf-cookie-banner');
if (!banner) return;
if (!localStorage.getItem(CONSENT_KEY)) {
banner.style.display = 'flex';
}
const acceptBtn = document.getElementById('pf-accept-cookies');
if (acceptBtn) {
acceptBtn.addEventListener('click', () => {
localStorage.setItem(CONSENT_KEY, 'true');
banner.style.display = 'none';
autoDetectLocation();
});
}
const declineBtn = document.getElementById('pf-decline-cookies');
if (declineBtn) {
declineBtn.addEventListener('click', () => {
localStorage.setItem(CONSENT_KEY, 'false');
banner.style.display = 'none';
});
}
}
let targetRotation = 0;
function setupAntiSpam() {
const captchaSlider = document.getElementById('captcha-slider');
const captchaImage = document.getElementById('captcha-image');
const captchaValid = document.getElementById('captcha-valid');
if (captchaSlider && captchaImage && captchaValid) {
// Generate a random initial rotation between 60 and 300 degrees
targetRotation = Math.floor(Math.random() * 240) + 60;
captchaImage.style.transform = `rotate(${targetRotation}deg)`;
captchaSlider.addEventListener('input', (e) => {
const userRotation = parseInt(e.target.value);
const totalRotation = targetRotation + userRotation;
captchaImage.style.transform = `rotate(${totalRotation}deg)`;
// If total rotation is close to a multiple of 360, it's upright
const normalized = totalRotation % 360;
if (normalized < 15 || normalized > 345) {
captchaValid.value = 'true';
captchaImage.parentElement.style.borderColor = '#10b981'; // Green border
} else {
captchaValid.value = 'false';
captchaImage.parentElement.style.borderColor = 'var(--pf-surface-border)';
}
});
}
const form = document.getElementById('pf_main_form') || document.querySelector('form');
if (form) {
form.addEventListener('submit', (e) => {
// Honeypot check
const honeypot = document.getElementById('website_url_hp');
if (honeypot && honeypot.value) {
e.preventDefault();
alert('Bot detected!');
return;
}
// Captcha check
const valid = document.getElementById('captcha-valid');
if (valid && valid.value !== 'true') {
e.preventDefault();
alert('Please rotate the image to the upright position to verify you are human.');
return;
}
// If checks pass, let form submit (or alert for demo)
e.preventDefault();
alert('Form submitted successfully!');
});
}
}
const AUTO_MESSAGES = [
"Hello. I am interested in your services, please reach out.",
"Hi, this is interesting, please contact me back.",
"Greetings! I would like to request more information about what you offer.",
"Hello, could we schedule a brief call to discuss this further?",
"Hi there, I have a few questions and would love to connect."
];
let currentMsgIndex = -1;
function setupMessageGenerator() {
const msgInput = document.getElementById('message');
const prevBtn = document.getElementById('msg-prev');
const nextBtn = document.getElementById('msg-next');
if (!msgInput || !prevBtn || !nextBtn) return;
const cycleMessage = (direction) => {
if (direction === 'next') {
currentMsgIndex = (currentMsgIndex + 1) % AUTO_MESSAGES.length;
} else {
currentMsgIndex = (currentMsgIndex - 1 + AUTO_MESSAGES.length) % AUTO_MESSAGES.length;
}
msgInput.value = AUTO_MESSAGES[currentMsgIndex];
msgInput.dispatchEvent(new Event('input', { bubbles: true })); // Trigger persistence
};
prevBtn.addEventListener('click', (e) => {
e.preventDefault();
cycleMessage('prev');
});
nextBtn.addEventListener('click', (e) => {
e.preventDefault();
cycleMessage('next');
});
}
const COMMON_DOMAINS = [
"gmail.com", "yahoo.com", "hotmail.com", "outlook.com", "aol.com", "icloud.com", "protonmail.com"
];
function setupEmailAutocomplete() {
const emailInput = document.getElementById('email');
const suggestionInput = document.getElementById('email-suggestion');
if (!emailInput || !suggestionInput) return;
emailInput.addEventListener('input', (e) => {
const val = e.target.value;
suggestionInput.value = '';
if (!val || val.includes(' ')) return;
if (val.includes('@')) {
const parts = val.split('@');
const prefix = parts[0];
const domainPart = parts[1];
// If typing domain after @
if (domainPart.length > 0) {
// Try to find a matching common domain
const match = COMMON_DOMAINS.find(d => d.startsWith(domainPart.toLowerCase()));
if (match) {
// Check case so it aligns with what the user already typed
const userTypedDomain = val.substring(val.indexOf('@') + 1);
const completion = match.substring(userTypedDomain.length);
suggestionInput.value = val + completion;
return;
}
}
// If there's a dot but no match (business email), suggest .com
if (domainPart.includes('.')) {
const domainSplit = domainPart.split('.');
const tld = domainSplit[domainSplit.length - 1];
if (tld.length > 0 && "com".startsWith(tld.toLowerCase()) && tld.toLowerCase() !== 'com') {
const completion = "com".substring(tld.length);
suggestionInput.value = val + completion;
return;
}
}
}
});
emailInput.addEventListener('keydown', (e) => {
if (e.key === 'Tab' || e.key === 'ArrowRight') {
if (suggestionInput.value && suggestionInput.value.toLowerCase().startsWith(emailInput.value.toLowerCase())) {
e.preventDefault();
emailInput.value = suggestionInput.value;
suggestionInput.value = '';
emailInput.dispatchEvent(new Event('input', { bubbles: true })); // trigger persistence
}
}
});
}
/**
* Fetch IP location to auto-detect City and Country if empty
*/
async function autoDetectLocation() {
try {
const cityInput = document.getElementById('city') || document.querySelector('input[name="city"]');
const countryInput = document.getElementById('country') || document.querySelector('input[name="country"]');
// Fetch if either is empty
if ((cityInput && !cityInput.value) || (countryInput && !countryInput.value)) {
const res = await fetch('http://ip-api.com/json/');
if (res.ok) {
const data = await res.json();
if (cityInput && !cityInput.value && data.city) {
cityInput.value = data.city;
cityInput.dispatchEvent(new Event('input', { bubbles: true }));
}
if (countryInput && !countryInput.value && data.country) {
countryInput.value = data.country;
countryInput.dispatchEvent(new Event('input', { bubbles: true }));
}
}
}
} catch (e) {
console.error('IP location detection failed', e);
}
}
/**
* Fetch country codes and populate the dropdown badge
*/
async function populateCountryDropdown() {
const customSelect = document.getElementById('pf-country-select');
const trigger = document.getElementById('pf-country-trigger');
const searchInput = document.getElementById('pf-country-search');
const listContainer = document.getElementById('country_code_list');
const hiddenInput = document.getElementById('country_code_hidden');
if (!customSelect || !listContainer) return;
try {
const res = await fetch('https://restcountries.com/v3.1/all?fields=name,idd,flag,cca2');
const countries = await res.json();
const options = [];
countries.forEach(c => {
if (!c.idd || !c.idd.root) return;
const code = c.idd.suffixes && c.idd.suffixes.length === 1 ? c.idd.root + c.idd.suffixes[0] : c.idd.root;
options.push({
name: c.name.common,
flag: c.flag || '🌍',
code: code,
cca2: c.cca2
});
});
options.sort((a, b) => a.name.localeCompare(b.name));
listContainer.innerHTML = '';
const dataList = document.getElementById('pf_country_list');
if (dataList) dataList.innerHTML = '';
const updateTriggerAndHidden = (o) => {
trigger.innerText = `${o.flag} ${o.code}`;
hiddenInput.value = o.code;
hiddenInput.dataset.cca2 = o.cca2;
localStorage.setItem('pf_last_country_cca2', o.cca2);
const countryInput = document.getElementById('country') || document.querySelector('input[name="country"]');
if (countryInput) {
countryInput.value = o.name;
countryInput.dispatchEvent(new Event('input', { bubbles: true }));
}
};
let allLiElements = [];
options.forEach(o => {
const li = document.createElement('li');
li.innerHTML = `<span>${o.flag}</span> <span>${o.name}</span> <span style="color:var(--pf-text-muted); margin-left:auto;">${o.code}</span>`;
li.dataset.name = o.name.toLowerCase();
li.dataset.cca2 = o.cca2;
li.dataset.code = o.code;
li.dataset.flag = o.flag;
li.dataset.rawname = o.name;
li.addEventListener('click', () => {
updateTriggerAndHidden(o);
customSelect.classList.remove('pf-open');
});
listContainer.appendChild(li);
allLiElements.push(li);
if (dataList) {
const dlOpt = document.createElement('option');
dlOpt.value = o.name;
dataList.appendChild(dlOpt);
}
});
const lastUsedCca2 = localStorage.getItem('pf_last_country_cca2');
const defaultOpt = (lastUsedCca2 ? options.find(o => o.cca2 === lastUsedCca2) : null) || options.find(o => o.cca2 === 'US') || options[0];
if (defaultOpt) {
updateTriggerAndHidden(defaultOpt);
}
// Toggle dropdown
trigger.addEventListener('click', () => {
customSelect.classList.toggle('pf-open');
if (customSelect.classList.contains('pf-open')) {
searchInput.value = '';
searchInput.focus();
allLiElements.forEach(li => li.style.display = 'flex');
}
});
// Close when clicking outside
document.addEventListener('click', (e) => {
if (!customSelect.contains(e.target)) {
customSelect.classList.remove('pf-open');
}
});
// Search filter to shorten list natively
searchInput.addEventListener('input', (e) => {
const term = e.target.value.toLowerCase().trim();
allLiElements.forEach(li => {
if (!term) {
li.style.display = 'flex';
return;
}
const isPlus = term.startsWith('+');
const matchCode = li.dataset.code.includes(term);
const matchName = li.dataset.name.includes(term);
if (isPlus ? matchCode : matchName) {
li.style.display = 'flex';
} else {
li.style.display = 'none';
}
});
});
// Keyboard support for custom select
customSelect.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
if (!customSelect.classList.contains('pf-open')) {
e.preventDefault();
trigger.click();
}
} else if (e.key === 'Escape') {
customSelect.classList.remove('pf-open');
customSelect.focus();
}
});
} catch (e) {
console.error('Failed to populate dropdown', e);
}
}
/**
* Automatically prefixes `https://` or `http://` by pinging the website to see what resolves.
* @param {string} url
* @returns {Promise<string>} Formatted URL
*/
async function formatUrlPrefixAsync(url) {
if (!url) return url;
let formatted = url.trim();
// If it's empty or doesn't look like a domain at all, return it
if (formatted.length === 0 || !/[a-zA-Z0-9]/.test(formatted)) {
return formatted;
}
// Extract core domain
let domain = formatted.replace(/^https?:\/\//i, '').replace(/^www\./i, '');
if (!domain) return formatted;
const checkUrl = async (testUrl) => {
try {
// no-cors prevents CORS blocking and throws a TypeError only if network/DNS/SSL fails
await fetch(testUrl, { method: 'HEAD', mode: 'no-cors' });
return true;
} catch (e) {
return false;
}
};
// Ping in order of preference
if (await checkUrl(`https://${domain}`)) {
return `https://${domain}`;
} else if (await checkUrl(`https://www.${domain}`)) {
return `https://www.${domain}`;
} else if (await checkUrl(`http://${domain}`)) {
return `http://${domain}`;
} else if (await checkUrl(`http://www.${domain}`)) {
return `http://www.${domain}`;
}
// Fallback if domain is unreachable or invalid
return `https://${domain}`;
}
const CANADIAN_AREA_CODES = ["204", "226", "236", "249", "250", "263", "289", "306", "343", "365", "367", "368", "403", "416", "418", "431", "437", "438", "450", "474", "506", "514", "519", "548", "579", "581", "587", "604", "613", "639", "647", "672", "683", "705", "709", "742", "778", "780", "807", "819", "825", "867", "873", "902", "905", "942"];
/**
* Standardize telephone formats, detect/strip country prefixes, and guess NA area codes.
* @param {string} value
* @returns {string} Formatted local phone number
*/
function formatPhoneAndSyncDropdown(value) {
let digits = value.replace(/\D/g, '');
const hiddenInput = document.getElementById('country_code_hidden');
const trigger = document.getElementById('pf-country-trigger');
const listItems = document.querySelectorAll('#country_code_list li');
if (!hiddenInput || !listItems.length) return value;
const selectLi = (li) => {
hiddenInput.value = li.dataset.code;
hiddenInput.dataset.cca2 = li.dataset.cca2;
trigger.innerText = `${li.dataset.flag} ${li.dataset.code}`;
localStorage.setItem('pf_last_country_cca2', li.dataset.cca2);
};
// 1. If user typed a '+' prefix, detect country, update dropdown, and STRIP the prefix from `digits`
if (value.trim().startsWith('+') && digits.length > 0) {
const possibleCodes = [digits.substring(0, 3), digits.substring(0, 2), digits.substring(0, 1)].filter(Boolean);
for (let code of possibleCodes) {
let matched = false;
for (let li of listItems) {
if (li.dataset.code === `+${code}`) {
selectLi(li);
matched = true;
break;
}
}
if (matched) {
digits = digits.substring(code.length); // Strip country code
break;
}
}
}
// 2. Or, if no '+', check if it's 10 digits or 11 digits starting with 1
else {
if (digits.length === 11 && digits.startsWith('1')) {
digits = digits.substring(1); // Strip the '1' country code
}
if (digits.length === 10) {
const areaCode = digits.substring(0, 3);
const isCanada = CANADIAN_AREA_CODES.includes(areaCode);
const targetCca2 = isCanada ? 'CA' : 'US';
if (hiddenInput.dataset.cca2 !== targetCca2) {
for (let li of listItems) {
if (li.dataset.cca2 === targetCca2) {
selectLi(li);
break;
}
}
}
}
}
// Determine if the selected country uses NANP (North American Numbering Plan)
const isNanp = hiddenInput.value === '+1';
// 3. Format the remaining local digits
if (isNanp && digits.length === 10) {
return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
} else if (digits.length > 0) {
// Generic spaced format for international (e.g. 7911 123 456)
const match = digits.match(/^(\d{3,4})(\d{3,4})(\d{3,4})?$/);
if (match) {
return match.slice(1).filter(Boolean).join(' ');
}
return digits; // Fallback
}
return value;
}
// Auto-initialize if running in a standard browser environment and script is loaded normally
if (typeof document !== 'undefined') {
document.addEventListener('DOMContentLoaded', () => {
// Only auto-bind if they have data-persist attribute, otherwise let user call initPersistentForms manually
initPersistentForms('[data-persist="true"]');
});
}