Update OTP Field with Resend OTP

This commit is contained in:
2025-08-21 14:11:02 +05:30
parent bc81380ebf
commit 9226cbadc3
2 changed files with 286 additions and 225 deletions
+275 -214
View File
@@ -1,279 +1,340 @@
--- ---
import type { HTMLAttributes } from "astro/types"; import type { HTMLAttributes } from "astro/types";
import { cn } from "../utils/cn";
type Size = "sm" | "md" | "lg";
interface Props extends HTMLAttributes<"div"> { interface Props extends HTMLAttributes<"div"> {
id?: string; id?: string;
name: string; name: string; // hidden input name (what Zod receives)
label?: string; label?: string;
description?: string; description?: string;
error?: string; // SSR error (optional) error?: string;
required?: boolean;
disabled?: boolean;
value?: string; // initial value (e.g., from server)
length?: number; // number of boxes length?: number; // number of boxes
placeholder?: string | string[]; placeholderChar?: string; // shown in each box
onlyDigits?: boolean; // restrict to 0-9
size?: "sm" | "md" | "lg"; // box sizes
autoFocus?: boolean; autoFocus?: boolean;
class?: string; disabled?: boolean;
size?: Size;
// Resend (optional)
resendEnabled?: boolean; // show/hide resend UI
resendLabel?: string; // button label
resendCooldown?: number; // seconds
onResend?: string; // window function name to call (may be async)
} }
const p = Astro.props as Props; const p = Astro.props as Props;
const fieldId = p.id ?? p.name; const fieldId = p.id ?? p.name;
const descId = p.description ? `${fieldId}-desc` : undefined;
const errId = `${fieldId}-err`; const errId = `${fieldId}-err`;
const len = Math.max(1, p.length ?? 6); const LEN = Math.max(4, Math.min(p.length ?? 6, 10));
const initial = (p.value ?? "").slice(0, len); const SIZE = p.size ?? "md";
const boxesSSR = Array.from({ length: len }, (_, i) => initial[i] ?? "");
const sizeCls = const boxCls =
p.size === "sm" SIZE === "sm"
? "wr:h-10 wr:w-10 wr:text-base" ? "wr:h-10 wr:w-10 wr:text-base"
: p.size === "lg" : SIZE === "lg"
? "wr:h-14 wr:w-14 wr:text-xl" ? "wr:h-14 wr:w-14 wr:text-xl"
: "wr:h-12 wr:w-12 wr:text-lg"; : "wr:h-12 wr:w-12 wr:text-lg";
const boxBase = const ringErr = "wr:border-danger wr:focus-visible:ring-danger/40";
"wr:rounded-lg wr:border wr:border-gray-200 wr:bg-background wr:text-center wr:tracking-widest " + const ringOk = "wr:border-border wr:focus-visible:ring-primary/40";
"wr:focus-visible:outline-none wr:focus-visible:ring-2 wr:focus-visible:ring-primary/40 " +
"wr:disabled:opacity-50 wr:disabled:pointer-events-none " +
"wr:dark:bg-neutral-900 wr:dark:border-neutral-700 wr:dark:text-neutral-100";
const groupCls = "wr:flex wr:items-center wr:gap-2 wr:select-none"; const showResend = !!p.resendEnabled;
const resendLabel = p.resendLabel ?? "Resend code";
const resendCooldown = Math.max(5, p.resendCooldown ?? 30);
const containerId = `otp-${Math.random().toString(36).slice(2)}`;
--- ---
<div class={cn("wr:space-y-1.5", p.class)} data-field={p.name}> <div
id={containerId}
class="wr:space-y-2"
data-field={p.name}
aria-live="polite"
>
{ {
p.label && ( p.label && (
<label <label
for={fieldId} for={fieldId}
class="wr:block wr:text-sm wr:font-medium wr:mb-1.5 wr:text-foreground" class="wr:block wr:text-sm wr:font-medium wr:text-foreground"
> >
{p.label} {p.required && <span class="wr:text-danger">*</span>} {p.label}
</label> </label>
) )
} }
<!-- Hidden form value (drives validation & submission) --> <!-- Inputs row + optional resend button -->
<input
id={fieldId}
type="hidden"
name={p.name}
value={initial}
data-control
aria-invalid={!!p.error}
aria-describedby={[descId, p.error ? errId : undefined]
.filter(Boolean)
.join(" ") || undefined}
/>
<!-- Visible boxes -->
<div <div
class={groupCls} class="wr:flex wr:flex-wrap wr:items-center wr:gap-2 wr:justify-between"
role="group"
aria-labelledby={p.label ? fieldId : undefined}
aria-describedby={[descId, p.error ? errId : undefined]
.filter(Boolean)
.join(" ") || undefined}
data-otp-group
data-name={p.name}
data-length={len}
data-only-digits={p.onlyDigits !== false ? "1" : ""}
data-autofocus={p.autoFocus ? "1" : ""}
data-placeholder={Array.isArray(p.placeholder)
? ""
: (p.placeholder ?? "")}
data-disabled={p.disabled ? "1" : ""}
> >
<div class="wr:flex wr:flex-wrap wr:gap-2 wr:items-center">
{
Array.from({ length: LEN }).map((_, i) => (
<input
type="text"
inputmode="numeric"
pattern="[0-9]*"
maxlength="1"
class={[
"wr:text-center wr:rounded-lg wr:border wr:bg-background wr:text-foreground wr:shadow-xs",
"wr:focus-visible:outline-none wr:focus-visible:ring-2",
p.error ? ringErr : ringOk,
"wr:transition wr:duration-150 wr:placeholder:text-muted-foreground/50",
boxCls,
].join(" ")}
aria-label={`OTP digit ${i + 1}`}
placeholder={p.placeholderChar ?? "•"}
data-otp-cell
data-idx={i}
disabled={p.disabled}
/>
))
}
</div>
{ {
boxesSSR.map((ch, i) => ( p.resendEnabled && (
<input <div class="wr:mt-3 wr:flex wr:items-center wr:justify-between wr:text-sm">
aria-label={`Code digit ${i + 1}`} <button
inputmode={p.onlyDigits === false ? "text" : "numeric"} type="button"
pattern={p.onlyDigits === false ? undefined : "[0-9]*"} data-otp-resend
maxlength="1" class="wr:text-primary wr:hover:underline wr:disabled:opacity-50"
class={cn(boxBase, sizeCls)} aria-live="polite"
placeholder={ >
Array.isArray(p.placeholder) {resendLabel ?? "Resend code"}
? (p.placeholder[i] ?? "") </button>
: (p.placeholder ?? "") <span
} data-otp-timer
value={ch} class="wr:text-muted-foreground wr:ml-2"
data-otp-box />
data-idx={i} </div>
disabled={p.disabled} )
autocomplete="one-time-code"
/>
))
} }
</div> </div>
<!-- Hidden field that your form/Zod consumes -->
<input type="hidden" id={fieldId} name={p.name} value="" data-otp-hidden />
{ {
p.description && ( p.description && (
<p id={descId} class="wr:mt-1 wr:text-sm wr:text-muted-foreground"> <p class="wr:text-sm wr:text-muted-foreground">{p.description}</p>
{p.description}
</p>
) )
} }
<p id={errId} class="wr:mt-1 wr:text-xs wr:text-danger" hidden={!p.error}>
<p id={errId} class="wr:mt-1 wr:text-xs wr:text-danger" hidden>
{p.error ?? ""} {p.error ?? ""}
</p> </p>
</div> </div>
<script is:inline> <script
is:inline
define:vars={{
containerId,
fieldId,
LEN,
autoFocus: p.autoFocus ?? false,
onResend: p.onResend ?? "",
showResend,
resendCooldown,
}}
>
(() => { (() => {
// Find all OTP groups on the page (component is safe to repeat) const host = document.getElementById(containerId);
document.querySelectorAll("[data-otp-group]").forEach((group) => { if (!host) return;
if (group.__otpInit) return;
group.__otpInit = true;
const hidden = group.parentElement.querySelector( const cells = Array.from(
'input[type="hidden"][data-control]', host.querySelectorAll<HTMLInputElement>("[data-otp-cell]"),
); );
const boxes = Array.from( const hidden =
group.querySelectorAll("input[data-otp-box]"), host.querySelector<HTMLInputElement>("[data-otp-hidden]");
); const err = host.querySelector<HTMLElement>('[id$="-err"]');
const onlyDigits = !!group.getAttribute("data-only-digits");
const autoFocus = !!group.getAttribute("data-autofocus");
const toValue = () => boxes.map((b) => b.value || "").join(""); let values = Array(LEN).fill("");
const setHidden = (v, bubble = true) => {
if (!hidden) return;
hidden.value = v;
// bubble an input event so your per-field validation runs
if (bubble)
hidden.dispatchEvent(new Event("input", { bubbles: true }));
};
// Keep boxes styled when form sets aria-invalid on the hidden input function val() {
if (hidden) { return values.join("");
const applyInvalid = () => { }
const invalid = function renderHidden() {
hidden.getAttribute("aria-invalid") === "true"; if (!hidden) return;
boxes.forEach((b) => { hidden.value = val();
b.classList.toggle("wr:border-danger", invalid); // Fire an input event so your form validator (validateOn=input) can react
b.classList.toggle( hidden.dispatchEvent(new Event("input", { bubbles: true }));
"wr:focus-visible:ring-danger/40", }
invalid, function focusAt(i) {
); const next = cells[i];
}); next?.focus();
}; next?.select?.();
applyInvalid(); }
const mo = new MutationObserver(applyInvalid); function clearError() {
mo.observe(hidden, { if (!err) return;
attributes: true, err.textContent = "";
attributeFilter: ["aria-invalid"], err.hidden = true;
}); }
}
// Helpers // Fill a cell and move
const clampIdx = (i) => Math.max(0, Math.min(i, boxes.length - 1)); function setAt(i, d) {
const focusIdx = (i, select = true) => { if (i < 0 || i >= LEN) return;
const el = boxes[clampIdx(i)]; values[i] = (d || "").replace(/\D/g, "").slice(0, 1);
el?.focus(); cells[i].value = values[i];
if (select) el?.select?.(); }
};
function handleInput(e) { // Paste handler
const el = e.target; function pasteInto(startIdx, text) {
const idx = Number(el.getAttribute("data-idx") || "0"); const digits = (text || "")
.replace(/\D/g, "")
.slice(0, LEN - startIdx)
.split("");
digits.forEach((ch, j) => setAt(startIdx + j, ch));
const last = Math.min(LEN - 1, startIdx + digits.length);
renderHidden();
focusAt(Math.min(last + 1, LEN - 1));
}
let v = el.value || ""; // Init
// Normalize: keep only first acceptable char cells.forEach((cell, idx) => {
if (v.length > 1) v = v.slice(-1); cell.addEventListener("keydown", (e) => {
if (onlyDigits) v = v.replace(/\D/g, ""); const key = e.key;
el.value = v; if (key === "Backspace") {
// Move forward on valid single char
if (v) focusIdx(idx + 1);
setHidden(toValue());
}
function handleKeydown(e) {
const el = e.target;
const idx = Number(el.getAttribute("data-idx") || "0");
if (e.key === "ArrowLeft") {
e.preventDefault(); e.preventDefault();
focusIdx(idx - 1); if (values[idx]) {
} setAt(idx, "");
if (e.key === "ArrowRight") { renderHidden();
e.preventDefault(); } else if (idx > 0) {
focusIdx(idx + 1); setAt(idx - 1, "");
} renderHidden();
if (e.key === "Home") { focusAt(idx - 1);
e.preventDefault();
focusIdx(0);
}
if (e.key === "End") {
e.preventDefault();
focusIdx(boxes.length - 1);
}
if (e.key === "Backspace") {
// If box has a value, clear it; else move back and clear previous
if (el.value) {
el.value = "";
setHidden(toValue());
} else {
const j = Math.max(0, idx - 1);
const prev = boxes[j];
if (prev) {
prev.value = "";
prev.focus();
setHidden(toValue());
}
} }
return;
}
if (key === "ArrowLeft") {
e.preventDefault(); e.preventDefault();
focusAt(Math.max(0, idx - 1));
return;
} }
} if (key === "ArrowRight") {
e.preventDefault();
function handlePaste(e) { focusAt(Math.min(LEN - 1, idx + 1));
e.preventDefault(); return;
const startBox = e.target.closest("input[data-otp-box]"); }
const startIdx = Number( if (key.length === 1 && /\d/.test(key)) {
startBox?.getAttribute("data-idx") || "0", e.preventDefault();
); setAt(idx, key);
let text = (e.clipboardData?.getData("text") || "").trim(); renderHidden();
if (onlyDigits) text = text.replace(/\D/g, ""); if (idx < LEN - 1) focusAt(idx + 1);
if (!text) return; else cells[idx].blur();
return;
let j = startIdx; }
for (const ch of text.slice(0, boxes.length - startIdx)) { if (key === " ") {
boxes[j].value = ch.slice(0, 1); e.preventDefault();
j++; return;
if (j >= boxes.length) break;
} }
setHidden(toValue());
focusIdx(j < boxes.length ? j : boxes.length - 1);
}
boxes.forEach((b, i) => {
b.addEventListener("input", handleInput);
b.addEventListener("keydown", handleKeydown);
b.addEventListener("paste", handlePaste);
b.addEventListener("focus", () => b.select?.());
}); });
// Initial sync cell.addEventListener("input", (e) => {
setHidden(toValue(), false); const v = e.target.value || "";
const d = v.replace(/\D/g, "");
if (!d) {
values[idx] = "";
cells[idx].value = "";
renderHidden();
return;
}
values[idx] = d[0];
cells[idx].value = d[0];
renderHidden();
if (idx < LEN - 1) focusAt(idx + 1);
});
// Optional autofocus cell.addEventListener("paste", (e) => {
if (autoFocus) { e.preventDefault();
const firstEmpty = boxes.findIndex((b) => !b.value); const text = e.clipboardData?.getData("text") || "";
focusIdx( pasteInto(idx, text);
firstEmpty === -1 ? boxes.length - 1 : firstEmpty, });
true,
);
}
// Respect disabled on the group
if (group.getAttribute("data-disabled")) {
boxes.forEach((b) => (b.disabled = true));
}
}); });
if (autoFocus) focusAt(0);
// Resend
const btnSel = "[data-otp-resend]";
const timerEl = host.querySelector("[data-otp-timer]");
let cooldownTimer = 0;
let remaining = 0;
const baseLabel =
host.querySelector(btnSel)?.textContent?.trim() || "Resend";
function setResendState({ disabled, label }) {
const btn = host.querySelector(btnSel);
if (!btn) return;
btn.disabled = !!disabled;
if (label != null) btn.textContent = label;
}
function tick() {
if (!timerEl) return;
if (remaining <= 0) {
timerEl.textContent = "";
setResendState({ disabled: false, label: baseLabel });
cooldownTimer && clearInterval(cooldownTimer);
cooldownTimer = 0;
return;
}
const m = Math.floor(remaining / 60);
const s = remaining % 60;
timerEl.textContent = `Available in ${m}:${String(s).padStart(2, "0")}`;
remaining -= 1;
}
function startCooldown(seconds) {
remaining = Number(seconds) || 60;
setResendState({ disabled: true, label: "Sending…" });
// small delay to show “Sending…”, then start the countdown
setTimeout(() => {
setResendState({ disabled: true, label: "Resend" });
tick();
cooldownTimer && clearInterval(cooldownTimer);
cooldownTimer = window.setInterval(tick, 1000);
}, 500);
}
// Delegate click so it works even if button is conditionally rendered
host.addEventListener("click", async (e) => {
const btn = e.target?.closest?.(btnSel);
if (!btn || !host.contains(btn)) return;
// Do nothing if already cooling down
if (btn.disabled) return;
// Optional user hook (string name -> function on window)
let ok = true;
try {
const fnName = onResend; // e.g. "submit"
const fn = fnName ? window[fnName] : null;
if (typeof fn === "function") {
// you can pass context if you like
const value = Array.from(
host.querySelectorAll("[data-otp-slot]"),
)
.map((i) => i.value || "")
.join("");
const res = await fn({ host, length, value });
if (res === false) ok = false; // let user cancel cooldown
} else {
// fire a custom event as a fallback
host.dispatchEvent(new CustomEvent("wr:otp-resend"));
}
} catch {
ok = false;
}
if (ok) startCooldown(resendCooldown); // <-- uses injected var properly
});
// Keep hidden up to date initially
renderHidden();
// Clear form-level error when typing
host.addEventListener("input", () => clearError());
})(); })();
</script> </script>
+11 -11
View File
@@ -10,19 +10,19 @@ import ComponentLayout from "../layouts/ComponentLayout.astro";
label="Verification code" label="Verification code"
description="Enter the 6-digit code we sent to your email." description="Enter the 6-digit code we sent to your email."
length={6} length={6}
placeholder="" placeholderChar="-"
onlyDigits={true}
size="md" size="md"
autoFocus={true} autoFocus={true}
required resendEnabled={true}
/> resendCooldown={120}
resendLabel="Resend"
<OtpField onResend="submit"
name="pin"
label="Security PIN"
length={4}
placeholder={["P", "I", "N", "_"]}
size="lg"
/> />
</section> </section>
</ComponentLayout> </ComponentLayout>
<script>
window.submit = () => {
return true;
};
</script>