fix(auth): type code boxes through one real field

The boxes were one input each, with script moving focus between them.
That worked in a clean browser and failed in an ordinary one: on the
emailed code, whose first box is marked as a one-time-code field, typing
and pasting did nothing, while the device code, which is not marked,
worked. A password manager or autofill prompt hooking that field and a
script moving focus between six fields were working against each other.
It also left gaps: pasting into the third box with the second one empty
produced a code with a character missing.

Now the real input is stretched invisibly over the boxes and is the only
thing typed into, pasted into or autofilled; the boxes only display what
it holds, with the next one ringed and showing a caret. With nothing
moving focus there is nothing to fight, and a code cannot have a gap.
The browser's own validation message works again too, since the field
it points at is where the boxes are.
This commit is contained in:
Wanjohi
2026-10-02 06:03:48 +03:00
parent 39e4bebf64
commit 890ada8ead
2 changed files with 79 additions and 88 deletions
+41 -11
View File
@@ -487,8 +487,8 @@ form:has([data-component='input']:invalid) [data-component='button']:hover {
}
/* A code field drawn as one box per character, by \`segments.ts\`. The real
field is still the one that submits and the one the button's dimming reads,
so it is hidden from sight and not removed. */
field is stretched invisibly over the boxes and takes every keystroke,
paste and autofill; the boxes only show what it holds. */
[data-component='segments'] {
position: relative;
width: 100%;
@@ -497,8 +497,10 @@ form:has([data-component='input']:invalid) [data-component='button']:hover {
[data-component='segments'][data-enhanced] > [data-component='input'] {
position: absolute;
inset: 0;
z-index: 1;
height: 100%;
opacity: 0;
pointer-events: none;
cursor: text;
}
[data-component='segments'] [data-slot='boxes'] {
@@ -509,22 +511,48 @@ form:has([data-component='input']:invalid) [data-component='button']:hover {
}
[data-component='input'][data-variant='box'] {
display: flex;
flex: 1 1 0%;
min-width: 0;
padding: 0.9rem 0;
text-align: center;
/* The height of a one-line field: line, padding and border. A box is a
div, and an empty div has no line to be the height of. */
height: calc(2rem + 1.8rem + 2px);
padding: 0;
align-items: center;
justify-content: center;
font-family: var(--font-mona);
font-size: 1.5rem;
line-height: 2rem;
font-weight: 700;
font-variant-numeric: tabular-nums;
text-transform: uppercase;
}
/* A box selects its character on focus so typing replaces it; that is
behaviour, not something to show. */
[data-component='input'][data-variant='box']::selection {
background: transparent;
/* The box the next character goes into: the focus ring, grey until the code
is whole and white once it is — the same rule as every other field. */
[data-component='input'][data-variant='box'][data-active] {
border-color: var(--color-gray-600);
box-shadow: 0 0 0 1px var(--color-gray-600);
}
[data-component='segments'][data-complete] [data-variant='box'][data-active] {
border-color: var(--color-gray-1000);
box-shadow: 0 0 0 1px var(--color-gray-1000);
}
/* The real caret is invisible with its field, so the empty box it is in
draws one. */
[data-component='input'][data-variant='box'][data-active]:empty::after {
content: '';
width: 2px;
height: 1.5rem;
background: var(--color-foreground);
animation: blink 1s steps(1) infinite;
}
@keyframes blink {
50% {
opacity: 0;
}
}
[data-component='segments'] [data-slot='separator'] {
@@ -536,6 +564,7 @@ form:has([data-component='input']:invalid) [data-component='button']:hover {
user-select: none;
}
/* A wrong answer shakes the field it came from, once. Every error is a new
page, so an animation that runs on load runs exactly when one arrives —
no script needed to trigger it. */
@@ -586,7 +615,8 @@ form:has([data-component='form-alert'][data-color='danger']) [data-component='in
scale: 1;
}
form:has([data-component='form-alert'][data-color='danger']) [data-component='input'] {
form:has([data-component='form-alert'][data-color='danger']) [data-component='input'],
[data-component='input'][data-variant='box'][data-active]:empty::after {
animation: none;
}
}
+38 -77
View File
@@ -1,14 +1,18 @@
/**
* Turns a code field into one box per character.
* Draws a code field as one box per character.
*
* An enhancement, not the field. The server sends a single plain input that
* is complete on its own — it validates, submits and autofills — and this
* draws boxes over it when script runs. With script off, or if this throws,
* draws boxes under it when script runs. With script off, or if this throws,
* the person gets the plain field and loses nothing but the look.
*
* The real input stays the one that submits and the one the stylesheet reads
* validity from, so the button still dims on the same rule. The boxes carry no
* `name` and are never sent.
* The boxes are pictures. The real input is stretched invisibly over them and
* is the only thing that is ever typed into, pasted into or autofilled. This
* is deliberate, and replaced a version with one input per box: that one
* worked in a clean browser and broke in a real one, because a password
* manager or an autofill prompt that hooks a one-time-code field fights any
* script moving focus between six fields. One ordinary field gives them
* nothing to fight.
*
* Runs once per field: it is emitted directly after the input's wrapper and
* enhances `document.currentScript`'s previous sibling, so two code fields on
@@ -26,104 +30,61 @@ export default `(() => {
const numeric = root.dataset.numeric === 'true';
if (!real || !length) return;
// What one box accepts. A pasted \`BCDF-3467\` is cleaned to its characters
// here, so the dash is something the boxes draw and never something typed.
// What the field may hold. A pasted \`bcdf-3467\` is cleaned to its
// characters here, so the dash is something the boxes draw and never
// something typed.
const clean = (text) => {
const kept = numeric ? text.replace(/[^0-9]/g, '') : text.replace(/[^0-9a-zA-Z]/g, '');
return numeric ? kept : kept.toUpperCase();
return (numeric ? kept : kept.toUpperCase()).slice(0, length);
};
const boxes = [];
const row = document.createElement('div');
row.setAttribute('data-slot', 'boxes');
row.setAttribute('aria-hidden', 'true');
for (let i = 0; i < length; i++) {
if (i > 0 && i % group === 0) {
const dash = document.createElement('span');
dash.setAttribute('data-slot', 'separator');
dash.setAttribute('aria-hidden', 'true');
dash.textContent = '-';
row.appendChild(dash);
}
const box = document.createElement('input');
box.type = 'text';
const box = document.createElement('div');
box.setAttribute('data-component', 'input');
box.setAttribute('data-variant', 'box');
box.setAttribute('aria-label', real.getAttribute('aria-label') + ', character ' + (i + 1) + ' of ' + length);
box.inputMode = numeric ? 'numeric' : 'text';
box.autocapitalize = 'characters';
box.spellcheck = false;
// Only the first box offers the one-time-code autofill, and it may be
// handed the whole code at once — which \`spread\` below deals out.
box.autocomplete = i === 0 ? real.autocomplete || 'one-time-code' : 'off';
boxes.push(box);
row.appendChild(box);
}
const sync = () => {
real.value = boxes.map((b) => b.value).join('');
// The button dims on the real field's validity, so it must hear this.
real.dispatchEvent(new Event('input', { bubbles: true }));
// The caret lives at the end. Editing in the middle of a code is rarer than
// retyping its tail, and a caret that could sit anywhere would need its
// position drawn on boxes that do not have one.
const toEnd = () => {
const end = real.value.length;
if (real.selectionStart !== end || real.selectionEnd !== end) real.setSelectionRange(end, end);
};
// The first empty box, or the last one if the code is complete.
const next = () => {
const empty = boxes.findIndex((b) => !b.value);
return boxes[empty === -1 ? length - 1 : empty];
const render = () => {
const value = real.value;
const focused = document.activeElement === real;
boxes.forEach((box, i) => {
box.textContent = value[i] || '';
box.toggleAttribute('data-active', focused && i === Math.min(value.length, length - 1));
});
root.toggleAttribute('data-complete', value.length === length);
};
// Put \`text\` into the boxes from \`from\` onwards and move to what is next.
const spread = (from, text) => {
const chars = clean(text).split('');
for (let i = from; i < length && chars.length; i++) boxes[i].value = chars.shift();
sync();
next().focus();
};
boxes.forEach((box, i) => {
// Typing into a filled box replaces it, rather than leaving two
// characters for \`spread\` to guess the order of.
box.addEventListener('focus', () => box.select());
box.addEventListener('input', () => {
const text = box.value;
box.value = '';
if (text) spread(i, text);
else sync();
});
box.addEventListener('paste', (event) => {
event.preventDefault();
spread(i, (event.clipboardData || window.clipboardData).getData('text'));
});
box.addEventListener('keydown', (event) => {
if (event.key === 'Backspace' && !box.value && i > 0) {
event.preventDefault();
boxes[i - 1].value = '';
boxes[i - 1].focus();
sync();
} else if (event.key === 'ArrowLeft' && i > 0) {
event.preventDefault();
boxes[i - 1].focus();
} else if (event.key === 'ArrowRight' && i < length - 1) {
event.preventDefault();
boxes[i + 1].focus();
}
});
real.addEventListener('input', () => {
const cleaned = clean(real.value);
if (cleaned !== real.value) real.value = cleaned;
toEnd();
render();
});
for (const event of ['focus', 'click', 'keyup', 'select']) real.addEventListener(event, () => (toEnd(), render()));
real.addEventListener('blur', render);
// The real field is hidden from here on, so the browser's own message
// would point at nothing. Pressing the button early moves to the first
// empty box instead, which says what is missing just as plainly.
real.addEventListener('invalid', (event) => {
event.preventDefault();
next().focus();
});
real.tabIndex = -1;
real.setAttribute('aria-hidden', 'true');
real.autocomplete = 'off';
root.setAttribute('data-enhanced', '');
root.appendChild(row);
const prefilled = clean(real.value).split('');
boxes.forEach((b) => (b.value = prefilled.shift() || ''));
sync();
if (real.autofocus) next().focus();
real.value = clean(real.value);
render();
})();`;