Lettersail: online English school for kids on MODX 3 (templates, chunks, snippets, plugins, scripts)
This commit is contained in:
commit
3799cf8de5
96 files changed
+4423
No files matched your search
@@ -0,0 +1,340 @@
|
||||
(() => {
|
||||
const dialog = document.querySelector("[data-signup]");
|
||||
if (!dialog) return;
|
||||
const ui = JSON.parse(document.querySelector("[data-ui]").textContent);
|
||||
const vendor = new URL("vendor/intl-tel-input/js/", document.currentScript.src);
|
||||
const form = dialog.querySelector(".signup__form");
|
||||
const error = dialog.querySelector(".signup__error");
|
||||
const phone = form.elements.phone;
|
||||
const fields = { name: form.elements.name, phone, age: form.elements.age, consent: form.elements.consent };
|
||||
|
||||
const PARENS = { ru: 1, kz: 1, by: 1, ua: 1, us: 1, ca: 1 };
|
||||
const MASKS = { ru: "(XXX) XXX-XX-XX", kz: "(XXX) XXX XXXX" };
|
||||
const AUTO_MASKS = {};
|
||||
|
||||
const maskFill = (digits, mask, keepRest) => {
|
||||
let out = "";
|
||||
let di = 0;
|
||||
for (const ch of mask) {
|
||||
if (di >= digits.length) break;
|
||||
out += ch === "X" ? digits[di++] : ch;
|
||||
}
|
||||
if (keepRest && di < digits.length) out += digits.slice(di);
|
||||
return out;
|
||||
};
|
||||
|
||||
const rememberMask = (example, iso2) => {
|
||||
const match = /^\+\d+\s(.+)$/.exec(example || "");
|
||||
if (match && iso2) AUTO_MASKS[iso2] = match[1].replace(/\d/g, "X");
|
||||
};
|
||||
|
||||
const formatFallback = (value, country) => {
|
||||
if (!value || !country) return value;
|
||||
const auto = !MASKS[country.iso2];
|
||||
const mask = auto ? AUTO_MASKS[country.iso2] : MASKS[country.iso2];
|
||||
if (!mask || value[0] !== "+") return value;
|
||||
const dial = String(country.dialCode);
|
||||
const all = value.replace(/\D/g, "");
|
||||
if (!all.startsWith(dial) || all.length <= dial.length) return value;
|
||||
if (auto && /[\s()-]/.test(value.slice(1 + dial.length).replace(/^\s/, ""))) return value;
|
||||
return `+${dial} ${maskFill(all.slice(dial.length), mask, auto)}`;
|
||||
};
|
||||
|
||||
const withParens = (value, iso2) => {
|
||||
if (!value || !iso2 || !PARENS[iso2]) return value;
|
||||
const match = value.match(/^(\+\d+)\s(\d+)[\s-](.*)$/);
|
||||
return match ? `${match[1]} (${match[2]}) ${match[3]}` : value;
|
||||
};
|
||||
|
||||
let itiPromise = null;
|
||||
const ensurePhone = () => {
|
||||
if (itiPromise) return itiPromise;
|
||||
const utils = import(new URL("utils.js", vendor).href);
|
||||
const library = new Promise((resolve, reject) => {
|
||||
const style = document.createElement("link");
|
||||
style.rel = "stylesheet";
|
||||
style.href = new URL("../css/intlTelInput.min.css?v=1", vendor).href;
|
||||
document.head.append(style);
|
||||
const script = document.createElement("script");
|
||||
script.src = new URL("intlTelInput.min.js?v=1", vendor).href;
|
||||
script.onload = resolve;
|
||||
script.onerror = reject;
|
||||
document.head.append(script);
|
||||
});
|
||||
itiPromise = Promise.all([import(new URL(`${ui.lang}.js`, vendor).href), library]).then(([locale]) => {
|
||||
const known = new Set((window.intlTelInput.getCountryData?.() || []).map(c => c.iso2));
|
||||
const byLang = { ru: "ru", pl: "pl", kk: "kz", be: "by", uk: "ua", en: "gb", de: "de", fr: "fr", es: "es", it: "it" };
|
||||
const guess = [...(navigator.languages || [navigator.language || ""]), document.documentElement.lang || "ru"]
|
||||
.map(tag => {
|
||||
const [lang, region] = tag.toLowerCase().split("-");
|
||||
return region && region.length === 2 ? region : byLang[lang];
|
||||
})
|
||||
.find(code => code && (!known.size || known.has(code))) || "ru";
|
||||
const iti = window.intlTelInput(phone, {
|
||||
initialCountry: guess,
|
||||
countryOrder: [guess],
|
||||
countrySearch: true,
|
||||
countryNameLocale: ui.lang,
|
||||
uiTranslations: locale.default,
|
||||
separateDialCode: false,
|
||||
strictMode: true,
|
||||
strictRejectAnimation: false,
|
||||
fullscreenParent: dialog,
|
||||
customPlaceholder: (example, country) => {
|
||||
const placeholder = withParens(example, country?.iso2);
|
||||
rememberMask(placeholder, country?.iso2);
|
||||
return placeholder;
|
||||
},
|
||||
loadUtils: () => utils,
|
||||
});
|
||||
|
||||
const prefixLength = () => {
|
||||
const country = iti.getSelectedCountry();
|
||||
if (!country) return 0;
|
||||
const prefix = `+${country.dialCode}`;
|
||||
if (phone.value.startsWith(`${prefix} `)) return prefix.length + 1;
|
||||
return phone.value.startsWith(prefix) ? prefix.length : 0;
|
||||
};
|
||||
|
||||
const applyFormat = () => {
|
||||
const country = iti.getSelectedCountry();
|
||||
if (!country) return;
|
||||
const value = phone.value;
|
||||
let next = formatFallback(value, country);
|
||||
if (next === value) next = withParens(value, country.iso2);
|
||||
if (next === value) return;
|
||||
const position = phone.selectionStart ?? value.length;
|
||||
const atEnd = position >= value.length;
|
||||
const digitsBefore = value.slice(0, position).replace(/\D/g, "").length;
|
||||
phone.value = next;
|
||||
let i = 0;
|
||||
let d = 0;
|
||||
while (i < next.length && d < digitsBefore) {
|
||||
if (/\d/.test(next[i])) d++;
|
||||
i++;
|
||||
}
|
||||
if (atEnd) i = next.length;
|
||||
if (document.activeElement === phone) phone.setSelectionRange(i, i);
|
||||
};
|
||||
|
||||
const keepSpace = () => {
|
||||
const country = iti.getSelectedCountry();
|
||||
if (!country || phone.value !== `+${country.dialCode}`) return;
|
||||
phone.value += " ";
|
||||
if (document.activeElement === phone) phone.setSelectionRange(phone.value.length, phone.value.length);
|
||||
};
|
||||
|
||||
const keepCaret = () => {
|
||||
const length = prefixLength();
|
||||
if (length && phone.selectionStart === phone.selectionEnd && phone.selectionStart < length) phone.setSelectionRange(length, length);
|
||||
};
|
||||
|
||||
["click", "focus", "keyup", "select"].forEach((type) => phone.addEventListener(type, () => setTimeout(keepCaret, 0)));
|
||||
|
||||
phone.addEventListener("beforeinput", (event) => {
|
||||
if (event.inputType === "insertFromPaste") {
|
||||
const text = event.dataTransfer?.getData("text") ?? event.data ?? "";
|
||||
let digits = text.replace(/\D/g, "");
|
||||
if (digits.length >= 10) {
|
||||
event.preventDefault();
|
||||
const country = iti.getSelectedCountry();
|
||||
if (text.trim().startsWith("+")) {
|
||||
iti.setNumber(`+${digits}`);
|
||||
} else {
|
||||
if (country?.iso2 === "ru" && digits.length === 11 && /^[78]/.test(digits)) digits = digits.slice(1);
|
||||
iti.setNumber(`+${country ? country.dialCode : ""}${digits}`);
|
||||
}
|
||||
applyFormat();
|
||||
phone.setSelectionRange(phone.value.length, phone.value.length);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const length = prefixLength();
|
||||
if (!length) return;
|
||||
const start = phone.selectionStart;
|
||||
const end = phone.selectionEnd;
|
||||
const type = event.inputType || "";
|
||||
if (start === 0 && end === phone.value.length) {
|
||||
if (type.startsWith("delete")) {
|
||||
event.preventDefault();
|
||||
phone.value = `+${iti.getSelectedCountry().dialCode} `;
|
||||
phone.setSelectionRange(phone.value.length, phone.value.length);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (type === "deleteContentBackward") {
|
||||
if (start === end ? start <= length : start < length) event.preventDefault();
|
||||
} else if (start < length) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
let userPick = false;
|
||||
let previousDial = iti.getSelectedCountry()?.dialCode ?? null;
|
||||
phone.addEventListener("open:countryselector", () => {
|
||||
userPick = true;
|
||||
});
|
||||
|
||||
phone.addEventListener("input", (event) => {
|
||||
if (event.detail && (event.detail.isCountryChange || event.detail.isSetNumber)) {
|
||||
applyFormat();
|
||||
return;
|
||||
}
|
||||
userPick = false;
|
||||
if (phone.value && phone.value[0] !== "+") {
|
||||
const country = iti.getSelectedCountry();
|
||||
let digits = phone.value.replace(/\D/g, "");
|
||||
if (country?.iso2 === "ru" && digits.length === 11 && /^[78]/.test(digits)) digits = digits.slice(1);
|
||||
if (country) iti.setNumber(`+${country.dialCode}${digits}`);
|
||||
}
|
||||
applyFormat();
|
||||
keepSpace();
|
||||
});
|
||||
|
||||
phone.addEventListener("countrychange", () => {
|
||||
const country = iti.getSelectedCountry();
|
||||
if (!country) return;
|
||||
const digits = phone.value.replace(/\D/g, "");
|
||||
if (userPick && (!digits || digits === String(previousDial))) phone.value = `+${country.dialCode} `;
|
||||
previousDial = country.dialCode;
|
||||
userPick = false;
|
||||
applyFormat();
|
||||
keepSpace();
|
||||
});
|
||||
|
||||
return iti;
|
||||
}).catch(() => null);
|
||||
return itiPromise;
|
||||
};
|
||||
|
||||
const open = (event) => {
|
||||
event.preventDefault();
|
||||
if (!dialog.open) dialog.showModal();
|
||||
ensurePhone();
|
||||
};
|
||||
document.querySelectorAll('a[href="#signup"]').forEach((link) => link.addEventListener("click", open));
|
||||
|
||||
dialog.querySelector(".signup__close").addEventListener("click", () => dialog.close());
|
||||
dialog.addEventListener("click", (event) => {
|
||||
if (event.target === dialog) dialog.close();
|
||||
});
|
||||
|
||||
const phoneValid = () => {
|
||||
const iti = window.intlTelInput?.getInstance?.(phone);
|
||||
const digits = phone.value.replace(/\D/g, "");
|
||||
if (iti && window.intlTelInput.utils) return iti.isValidNumber();
|
||||
return digits.length >= 10 && digits.length <= 15;
|
||||
};
|
||||
|
||||
const mark = (field, bad) => field.classList.toggle("signup__input--error", bad);
|
||||
const check = () => {
|
||||
const problems = [
|
||||
["name", fields.name.value.trim().length < 2, ui.name],
|
||||
["phone", !phoneValid(), ui.phone],
|
||||
["age", !fields.age.value, ui.age],
|
||||
["consent", !fields.consent.checked, ui.consent],
|
||||
];
|
||||
problems.forEach(([key, bad]) => key !== "consent" && mark(fields[key], bad));
|
||||
dialog.querySelector(".signup__consent").classList.toggle("signup__consent--error", !fields.consent.checked);
|
||||
return problems.find(([, bad]) => bad);
|
||||
};
|
||||
|
||||
Object.values(fields).forEach((field) => field.addEventListener("change", () => {
|
||||
if (error.textContent) error.textContent = check()?.[2] ?? "";
|
||||
}));
|
||||
|
||||
const widget = form.querySelector("altcha-widget");
|
||||
const done = dialog.querySelector(".signup__done");
|
||||
const submitButton = form.querySelector(".signup__btn");
|
||||
const altchaSrc = document.currentScript ? new URL("vendor/altcha/altcha.min.js", document.currentScript.src).href : "";
|
||||
|
||||
const armWidget = () => {
|
||||
if (!widget || document.querySelector("script[data-altcha]")) return;
|
||||
const script = document.createElement("script");
|
||||
script.type = "module";
|
||||
script.src = form.dataset.altchaScript || altchaSrc;
|
||||
script.setAttribute("data-altcha", "");
|
||||
document.head.append(script);
|
||||
};
|
||||
document.querySelectorAll('a[href="#signup"]').forEach((link) => link.addEventListener("click", armWidget));
|
||||
|
||||
const proof = () => new Promise((resolve) => {
|
||||
let tick = 0;
|
||||
const poll = () => {
|
||||
const state = widget && typeof widget.getState === "function" ? widget.getState() : "";
|
||||
if (state === "verified") {
|
||||
resolve(widget.value || form.elements.namedItem("altcha")?.value || "");
|
||||
return;
|
||||
}
|
||||
if ((state === "error" || state === "expired" || (state === "unverified" && tick >= 20)) && tick % 30 === 0 && typeof widget.verify === "function") widget.verify();
|
||||
if (++tick > 150) {
|
||||
resolve("");
|
||||
return;
|
||||
}
|
||||
setTimeout(poll, 100);
|
||||
};
|
||||
poll();
|
||||
});
|
||||
|
||||
const rearm = () => {
|
||||
if (widget && typeof widget.reset === "function") {
|
||||
widget.reset();
|
||||
widget.verify();
|
||||
}
|
||||
};
|
||||
|
||||
const text = { guard: ui.guard, limit: ui.limit, network: ui.network };
|
||||
|
||||
dialog.addEventListener("close", () => {
|
||||
form.hidden = false;
|
||||
done.hidden = true;
|
||||
submitButton.disabled = false;
|
||||
error.textContent = "";
|
||||
});
|
||||
dialog.querySelector("[data-signup-done]").addEventListener("click", () => dialog.close());
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const problem = check();
|
||||
error.textContent = problem ? problem[2] : "";
|
||||
if (problem) {
|
||||
fields[problem[0]].focus();
|
||||
return;
|
||||
}
|
||||
submitButton.disabled = true;
|
||||
submitButton.setAttribute("aria-busy", "true");
|
||||
try {
|
||||
armWidget();
|
||||
const token = await proof();
|
||||
if (!token) {
|
||||
error.textContent = text.guard;
|
||||
rearm();
|
||||
return;
|
||||
}
|
||||
const body = new FormData(form);
|
||||
body.set("altcha", token);
|
||||
const iti = window.intlTelInput?.getInstance?.(phone);
|
||||
if (iti) body.set("phone", iti.getNumber());
|
||||
const response = await fetch(form.action, { method: "POST", credentials: "same-origin", headers: { Accept: "application/json" }, body });
|
||||
rearm();
|
||||
if (response.status === 429) {
|
||||
error.textContent = text.limit;
|
||||
return;
|
||||
}
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (!response.ok || !result.ok) {
|
||||
error.textContent = result.code && result.code !== "" ? text.guard : (result.message || text.network);
|
||||
if (result.field && fields[result.field]) fields[result.field].focus();
|
||||
return;
|
||||
}
|
||||
form.reset();
|
||||
form.hidden = true;
|
||||
done.hidden = false;
|
||||
} catch (failure) {
|
||||
error.textContent = text.network;
|
||||
} finally {
|
||||
submitButton.disabled = false;
|
||||
submitButton.removeAttribute("aria-busy");
|
||||
}
|
||||
});
|
||||
})();
|
||||
Reference in new issue
Block a user