-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathuui-input-otp.element.ts
328 lines (274 loc) · 7.96 KB
/
uui-input-otp.element.ts
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
import {
LabelMixin,
UUIFormControlMixin,
} from '@umbraco-ui/uui-base/lib/mixins';
import { defineElement } from '@umbraco-ui/uui-base/lib/registration';
import { UUIInputEvent, type InputType } from '@umbraco-ui/uui-input/lib';
import { css, html, LitElement } from 'lit';
import { property, state } from 'lit/decorators.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { repeat } from 'lit/directives/repeat.js';
/**
* @element uui-input-otp
*/
@defineElement('uui-input-otp')
export class UUIInputOtpElement extends UUIFormControlMixin(
LabelMixin('', LitElement),
'',
) {
/**
* This is a static class field indicating that the element is can be used inside a native form and participate in its events. It may require a polyfill, check support here https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/attachInternals. Read more about form controls here https://web.dev/more-capable-form-controls/
*/
static readonly formAssociated = true;
/**
* Accepts only numbers
* @default false
* @attr
*/
@property({ type: Boolean, attribute: 'integer-only' })
set integerOnly(value: boolean) {
this.inputMode = value ? 'numeric' : 'text';
}
get integerOnly() {
return this.inputMode === 'numeric';
}
/**
* If true, the input will be masked
* @default false
* @attr
*/
@property({ type: Boolean })
set masked(value: boolean) {
this._input = value ? 'password' : 'text';
}
get masked() {
return this._input === 'password';
}
/**
* The number of characters in the input
* @default 6
* @attr
*/
@property({ type: Number })
length = 6;
/**
* The template for the item label
*/
@property({ type: String, attribute: false })
itemLabelTemplate = (index: number) => `Character number ${index + 1}`;
/**
* Set to true to make this input readonly.
* @attr
* @default false
*/
@property({ type: Boolean, reflect: true })
readonly = false;
/**
* Set to true to disable this input.
* @attr
* @default false
*/
@property({ type: Boolean, reflect: true })
disabled = false;
/**
* Set to true to autofocus this input.
* @attr
* @default false
*/
@property({ type: Boolean, reflect: true, attribute: 'autofocus' })
autoFocus = false;
/**
* Add a placeholder to the inputs in the group
* @remark The placeholder should be a string with the same length as the `length` attribute and will be distributed to each input in the group
* @attr
* @default ''
*/
@property()
placeholder = '';
/**
* The autocomplete attribute specifies whether or not an input field should have autocomplete enabled.
* @remark Set the autocomplete attribute to "one-time-code" to enable autofill of one-time-code inputs
* @attr
* @default ''
* @type {string}
*/
@property({ type: String, reflect: true })
autocomplete?: string;
/**
* Min length validation message.
* @attr
* @default
*/
@property({ type: String, attribute: 'minlength-message' })
minlengthMessage = 'This field need more characters';
@state()
_input: InputType = 'text';
@state()
_tokens: string[] = [];
set value(value: string) {
this._tokens = value.split('');
super.value = value;
this.dispatchEvent(new UUIInputEvent(UUIInputEvent.CHANGE));
}
get value() {
return super.value.toString();
}
constructor() {
super();
this.addEventListener('paste', this.onPaste.bind(this));
this.addValidator(
'tooShort',
() => this.minlengthMessage,
() => !!this.length && String(this.value).length < this.length,
);
}
protected getFormElement(): HTMLElement | null | undefined {
return this;
}
protected onFocus(event: FocusEvent) {
(event.target as HTMLInputElement)?.select();
this.dispatchEvent(event);
}
protected onBlur(event: FocusEvent) {
this.dispatchEvent(event);
}
protected onInput(event: InputEvent, index: number) {
const target = event.target as HTMLInputElement;
this._tokens[index] = target?.value;
this.value = this._tokens.join('');
if (event.inputType === 'deleteContentBackward') {
this.moveToPrev(event);
} else if (
event.inputType === 'insertText' ||
event.inputType === 'deleteContentForward'
) {
this.moveToNext(event);
}
}
protected onKeyDown(event: KeyboardEvent) {
if (event.ctrlKey || event.metaKey) {
return;
}
switch (event.code) {
case 'ArrowLeft':
this.moveToPrev(event);
event.preventDefault();
break;
case 'ArrowUp':
case 'ArrowDown':
event.preventDefault();
break;
case 'Backspace':
if ((event.target as HTMLInputElement)?.value.length === 0) {
this.moveToPrev(event);
event.preventDefault();
}
break;
case 'ArrowRight':
this.moveToNext(event);
event.preventDefault();
break;
default:
if (
(this.integerOnly &&
!(Number(event.key) >= 0 && Number(event.key) <= 9)) ||
(this._tokens.join('').length >= this.length &&
event.code !== 'Delete')
) {
event.preventDefault();
}
break;
}
}
protected onPaste(event: ClipboardEvent) {
const paste = event.clipboardData?.getData('text');
if (paste?.length) {
const pastedCode = paste.substring(0, this.length + 1);
if (!this.integerOnly || !isNaN(pastedCode as any)) {
this.value = pastedCode;
}
}
event.preventDefault();
}
protected moveToPrev(event: Event) {
if (!event.target) return;
const prevInput = this.findPrevInput(event.target);
if (prevInput) {
prevInput.focus();
prevInput.select();
}
}
protected moveToNext(event: Event) {
if (!event.target) return;
const nextInput = this.findNextInput(event.target);
if (nextInput) {
nextInput.focus();
nextInput.select();
}
}
protected findNextInput(element: EventTarget): HTMLInputElement | null {
const nextElement = (element as Element).nextElementSibling;
if (!nextElement) return null;
return nextElement.nodeName === 'INPUT'
? (nextElement as HTMLInputElement)
: this.findNextInput(nextElement);
}
protected findPrevInput(element: EventTarget): HTMLInputElement | null {
const prevElement = (element as Element).previousElementSibling;
if (!prevElement) return null;
return prevElement.nodeName === 'INPUT'
? (prevElement as HTMLInputElement)
: this.findPrevInput(prevElement);
}
protected renderInput(index: number) {
return html`
<input
class="otp-input"
type=${this._input}
.value=${this._tokens[index] || ''}
.placeholder=${this.placeholder.charAt(index) || ''}
.inputMode=${this.inputMode}
?readonly=${this.readonly}
?disabled=${this.disabled}
?autofocus=${this.autoFocus && index === 0}
aria-label=${this.itemLabelTemplate(index)}
@input=${(e: InputEvent) => this.onInput(e, index)}
@keydown=${this.onKeyDown} />
`;
}
render() {
return html`
<fieldset id="otp-input-group" aria-label=${ifDefined(this.label)}>
${repeat(Array.from({ length: this.length }), (_, i) =>
this.renderInput(i),
)}
</fieldset>
`;
}
static readonly styles = [
css`
:host(:not([pristine]):invalid) .otp-input,
:host(:not([pristine])) .otp-input:invalid,
/* polyfill support */
:host(:not([pristine])[internals-invalid]) .otp-input:invalid {
border-color: var(--uui-color-danger);
}
#otp-input-group {
display: flex;
border: 0; /* Reset fieldset */
}
.otp-input {
width: 3em;
height: 3em;
text-align: center;
font-size: 1.5em;
margin-right: 0.5em;
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
'uui-input-otp': UUIInputOtpElement;
}
}