import type { ValidationState } from '../../common/static-wrappers/interfaces/validation-interface'; import { Prop, toNative } from 'vue-facing-decorator'; import TsxComponent, { Component } from '../../app/vuetsx'; import { isNullOrEmpty } from '../../common/utils/is-null-or-empty'; import TextBox, { TextBoxTextType } from './textbox'; import './css/pin.css'; export enum PinInputType { Alpha = 'alpha', Numeric = 'numeric', AlphaNumeric = 'alphanumeric', } interface PinInputArgs { showValue?: boolean; length: number; cssClass?: string; inputType?: PinInputType; value: string[]; changed: (value: string[]) => void; validationState?: ValidationState; /** * Fired once every cell carries a valid character (typed OR pasted). Use this * to auto-submit the form so the user doesn't have to also click a button * after entering the last digit / pasting a code. */ completed?: (value: string[]) => void; /** Accessible name of the whole code (the cells form a `group`): "Verification code". */ ariaLabel?: string; /** * Accessible name of each cell, with `{0}` for the cell's number and `{1}` for the number of cells — * "Digit {0} of {1}". Without it the cells are announced as unnamed edit fields. */ cellAriaLabel?: string; } @Component class PinInputComponent extends TsxComponent implements PinInputArgs { @Prop() showValue: boolean; @Prop() length: number; @Prop() cssClass!: string; @Prop() inputType: PinInputType; @Prop() value: string[]; @Prop() changed: (value: string[]) => void; @Prop() completed?: (value: string[]) => void; @Prop() ariaLabel?: string; @Prop() cellAriaLabel?: string; currentValue: string[] = null; mounted(): void { this.currentValue = Array.from({ length: this.length }).fill('') as any; } getCssClass(): string { return `pin ${this.cssClass || ''}`; } getInputType(): PinInputType { return this.inputType ?? PinInputType.Numeric; } get isFullyFilled(): boolean { return this.currentValue?.every(p => !isNullOrEmpty(p)); } isValidInput(value: string): boolean { const type = this.getInputType(); switch (type) { case PinInputType.Alpha: return /^[a-z]$/i.test(value); case PinInputType.Numeric: return /^\d$/.test(value); case PinInputType.AlphaNumeric: return /^[a-z0-9]$/i.test(value); default: return false; } } focusNext(index: number): void { if (index < this.length - 1) { const nextInput = this.getElement(index + 1); (nextInput.$el as HTMLElement)?.querySelector('input')?.focus(); } } focusPrev(index: number): void { if (index > 0) { const prevInput = this.getElement(index - 1); (prevInput.$el as HTMLElement)?.querySelector('input')?.focus(); } } updatePin(value: string, index: number): void { if (value.length > 1) { this.spreadCode(value, index); return; } // A cell emptied by the keyboard itself (a soft keyboard's deletion, a cut) empties its character too. if (value === '') { if (!isNullOrEmpty(this.currentValue[index])) { this.currentValue[index] = ''; this.changed(this.currentValue); } return; } // The character the cell holds already: the `change` a cell fires as the completed code blurs it reported it // twice — and `completed` with it. if (!this.isValidInput(value) || value === this.currentValue[index]) { return; } this.setCell(index, value); } /** * Puts `char` into the cell and moves on: to the next cell, or — the code complete — out of the code, which is * then reported as `completed` (with the characters the cells hold now). */ private setCell(index: number, char: string): void { this.currentValue[index] = char.slice(-1); const isComplete = this.isFullyFilled; if (isComplete) { this.blurAllInputs(); } else { this.focusNext(index); } this.changed(this.currentValue); if (isComplete) { this.completed?.(this.currentValue); } } /** * Backspace edits the code in place: a filled cell is emptied, an empty one steps back and empties the cell before * it. The browser's own deletion is held back — it deleted again in the cell the focus had just moved to, two cells * per press. A valid character typed into a filled cell replaces it (a cell holds one, so the browser dropped it) * and moves on; an invalid one is kept out. */ private handleCellKeydown(e: KeyboardEvent, index: number): void { if (e.key === 'Backspace') { e.preventDefault(); if (!isNullOrEmpty(this.currentValue[index])) { this.currentValue[index] = ''; } else if (index > 0) { this.currentValue[index - 1] = ''; this.focusPrev(index); } this.changed(this.currentValue); return; } // Let clipboard/selection shortcuts (Ctrl/Cmd+V/C/A/X) and non-printable // keys (Tab, arrows) pass through - only block single printable chars // that aren't valid for this pin type. Blocking the Ctrl+V keydown here // cancelled the browser paste before the paste event could fire (QA_AT-103). if (e.ctrlKey || e.metaKey || e.altKey || e.key.length !== 1) { return; } if (!this.isValidInput(e.key)) { e.preventDefault(); e.stopPropagation(); return; } if (!isNullOrEmpty(this.currentValue[index])) { e.preventDefault(); this.setCell(index, e.key); } } /** A cell taking the focus has its character selected: what is typed next replaces it — on a soft keyboard too. */ private selectCellOnFocus(e: FocusEvent): void { const target = e.target; if (target instanceof HTMLInputElement && target.value !== '') { target.select(); } } /** * Distribute a multi-character paste across the inputs. Filters by * `inputType` (so a numeric pin ignores non-digit chars), trims to * `length`, fills from index 0, then focuses the next-empty input — or * blurs all + fires `completed` when the paste fills every cell. */ handlePaste(event: ClipboardEvent): void { const pasted = event.clipboardData?.getData('text') ?? ''; const chars = pasted.split('').filter(c => this.isValidInput(c)).slice(0, this.length); if (chars.length === 0) { return; } event.preventDefault(); event.stopPropagation(); const next = Array.from({ length: this.length }).fill('') as string[]; for (let i = 0; i < chars.length; i++) { next[i] = chars[i]; } this.currentValue = next; const isComplete = this.isFullyFilled; if (isComplete) { this.blurAllInputs(); } else { const focusIndex = Math.min(chars.length, this.length - 1); const target = this.getElement(focusIndex); (target?.$el as HTMLElement)?.querySelector('input')?.focus(); } this.changed(this.currentValue); if (isComplete) { this.completed?.(this.currentValue); } } /** * A one-time code the phone autofills (or a keyboard suggestion inserts) arrives in one cell as a whole — * the first cell accepts that many characters for it. Spread it over the cells from that one, the way a * paste is spread. */ spreadCode(value: string, index: number): void { const chars = value.split('').filter(c => this.isValidInput(c)).slice(0, this.length - index); const next = [...this.currentValue]; for (let i = 0; i < chars.length; i++) { next[index + i] = chars[i]; } // The cell's input still shows everything that arrived, and its value prop may not change (it can // already hold that first character), so show the cell's own character directly. const input = (this.getElement(index)?.$el as HTMLElement)?.querySelector('input'); if (input != null) { input.value = next[index] ?? ''; } if (chars.length === 0) { return; } this.currentValue = next; const isComplete = this.isFullyFilled; if (isComplete) { this.blurAllInputs(); } else { const focusIndex = Math.min(index + chars.length, this.length - 1); (this.getElement(focusIndex)?.$el as HTMLElement)?.querySelector('input')?.focus(); } this.changed(this.currentValue); if (isComplete) { this.completed?.(this.currentValue); } } blurAllInputs(): void { for (let index = 0; index < this.currentValue?.length; index++) { const input = this.getElement(index); (input.$el as HTMLElement)?.querySelector('input')?.blur(); } } getElement(index: number) { if (index < 0 || index >= this.length) { return null; } return this.$refs[`pin-${index}`] as typeof TextBox.prototype; } getTextType(): TextBoxTextType { return this.showValue ? TextBoxTextType.Text : TextBoxTextType.Password; } /** The cell's accessible name: {@link cellAriaLabel} with the cell's number and the cell count filled in. */ getCellLabel(index: number): string | undefined { if (isNullOrEmpty(this.cellAriaLabel)) { return undefined; } return this.cellAriaLabel.replace('{0}', String(index + 1)).replace('{1}', String(this.length)); } render(h) { if (!this.currentValue) { return null; } const textType = this.getTextType(); // A numeric pin opens the phone's number pad. The first cell offers the one-time code the phone // received (SMS / e-mail autofill) and takes all of it at once; `spreadCode` fills the other cells. const inputMode = this.getInputType() === PinInputType.Numeric ? 'numeric' : undefined; return (
{ this.handlePaste(e); }} onFocusin={(e: FocusEvent) => { this.selectCellOnFocus(e); }} > {Array.from({ length: this.length }, (_, index) => ( { this.handleCellKeydown(e, index); }} changed={(e) => { this.updatePin(e, index); }} /> ))}
); } } const PinInput = toNative(PinInputComponent); export default PinInput;