digitojs 1.2.2 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,898 +0,0 @@
1
- /**
2
- * digito/web-component
3
- * ─────────────────────────────────────────────────────────────────────────────
4
- * Framework-agnostic Web Component — <digito-input>
5
- * Uses single hidden-input architecture for correct SMS autofill + a11y.
6
- *
7
- * Attributes:
8
- * length Number of slots (default: 6)
9
- * type Character set: numeric | alphabet | alphanumeric | any (default: numeric)
10
- * timer Countdown seconds (default: 0 = no timer)
11
- * resend-after Cooldown seconds before the built-in Resend re-enables (default: 30)
12
- * disabled Boolean attribute — disables all input when present
13
- * separator-after Slot index (1-based) or comma-separated list, e.g. "3" or "2,4" (default: none)
14
- * separator Separator character to render (default: —)
15
- * name Sets the hidden input's name attr for native form submission
16
- * placeholder Character shown in empty slots (e.g. "○" or "_")
17
- * auto-focus Boolean attribute — focus input on mount (default: true when absent)
18
- * select-on-focus Boolean attribute — selects the current slot char on focus
19
- * blur-on-complete Boolean attribute — blurs the input when all slots are filled
20
- *
21
- * Events:
22
- * complete CustomEvent<{ code: string }> — fired when all slots filled
23
- * expire CustomEvent — fired when timer reaches zero
24
- * change CustomEvent<{ code: string }> — fired on every input change
25
- *
26
- * DOM API:
27
- * el.reset()
28
- * el.setError(boolean)
29
- * el.setSuccess(boolean)
30
- * el.setDisabled(boolean)
31
- * el.getCode() -> string
32
- * el.pattern = /^[0-9A-F]$/ (JS property, not attribute)
33
- * el.pasteTransformer = fn (JS property)
34
- * el.onComplete = code => {} (JS property)
35
- * el.onResend = () => {} (JS property)
36
- * el.onFocus = () => {} (JS property)
37
- * el.onBlur = () => {} (JS property)
38
- * el.onInvalidChar = (char, i) => {} (JS property)
39
- *
40
- * @author Olawale Balo — Product Designer + Design Engineer
41
- * @license MIT
42
- */
43
-
44
- import {
45
- createDigito,
46
- createTimer,
47
- filterString,
48
- formatCountdown,
49
- type InputType,
50
- } from '../core/index.js'
51
-
52
- // ─────────────────────────────────────────────────────────────────────────────
53
- // SHADOW DOM STYLES
54
- // ─────────────────────────────────────────────────────────────────────────────
55
-
56
- const STYLES = `
57
- :host {
58
- display: inline-block;
59
- position: relative;
60
- line-height: 1;
61
- }
62
-
63
- .digito-wc-root {
64
- position: relative;
65
- display: inline-block;
66
- }
67
-
68
- .digito-wc-slots {
69
- display: inline-flex;
70
- gap: var(--digito-gap, 12px);
71
- align-items: center;
72
- position: relative;
73
- }
74
-
75
- .digito-wc-hidden {
76
- position: absolute;
77
- inset: 0;
78
- width: 100%;
79
- height: 100%;
80
- opacity: 0;
81
- border: none;
82
- outline: none;
83
- background: transparent;
84
- color: transparent;
85
- caret-color: transparent;
86
- z-index: 1;
87
- cursor: text;
88
- font-size: 1px;
89
- }
90
-
91
- .digito-wc-slot {
92
- position: relative;
93
- width: var(--digito-size, 56px);
94
- height: var(--digito-size, 56px);
95
- border: 1px solid var(--digito-border-color, #E5E5E5);
96
- border-radius: var(--digito-radius, 10px);
97
- font-size: var(--digito-font-size, 24px);
98
- font-weight: 600;
99
- display: flex;
100
- align-items: center;
101
- justify-content: center;
102
- background: var(--digito-bg, #FAFAFA);
103
- color: var(--digito-color, #0A0A0A);
104
- font-family: inherit;
105
- cursor: text;
106
- user-select: none;
107
- transition: border-color 150ms ease, box-shadow 150ms ease, background 150ms ease, opacity 150ms ease;
108
- }
109
- .digito-wc-slot.is-active {
110
- border-color: var(--digito-active-color, #3D3D3D);
111
- box-shadow: 0 0 0 3px color-mix(in srgb, var(--digito-active-color, #3D3D3D) 10%, transparent);
112
- background: var(--digito-bg-filled, #FFFFFF);
113
- }
114
- .digito-wc-slot.is-filled { background: var(--digito-bg-filled, #FFFFFF); }
115
- .digito-wc-slot.is-error {
116
- border-color: var(--digito-error-color, #FB2C36);
117
- box-shadow: 0 0 0 3px color-mix(in srgb, var(--digito-error-color, #FB2C36) 12%, transparent);
118
- }
119
- .digito-wc-slot.is-success {
120
- border-color: var(--digito-success-color, #00C950);
121
- box-shadow: 0 0 0 3px color-mix(in srgb, var(--digito-success-color, #00C950) 12%, transparent);
122
- }
123
- .digito-wc-slot.is-disabled {
124
- opacity: 0.45;
125
- cursor: not-allowed;
126
- pointer-events: none;
127
- }
128
- .digito-wc-slot:not(.is-filled) {
129
- font-size: var(--digito-placeholder-size, 16px);
130
- color: var(--digito-placeholder-color, #D3D3D3);
131
- }
132
- .digito-wc-slot.is-masked.is-filled {
133
- font-size: var(--digito-masked-size, 16px);
134
- }
135
-
136
- .digito-wc-separator {
137
- display: flex;
138
- align-items: center;
139
- justify-content: center;
140
- color: var(--digito-separator-color, #A1A1A1);
141
- font-size: var(--digito-separator-size, 18px);
142
- font-weight: 400;
143
- user-select: none;
144
- flex-shrink: 0;
145
- padding: 0 2px;
146
- }
147
-
148
- .digito-wc-caret {
149
- position: absolute;
150
- width: 2px;
151
- height: 52%;
152
- background: var(--digito-caret-color, #3D3D3D);
153
- border-radius: 1px;
154
- animation: wc-blink 1s step-start infinite;
155
- pointer-events: none;
156
- display: none;
157
- }
158
- @keyframes wc-blink { 0%,100%{opacity:1} 50%{opacity:0} }
159
-
160
- .digito-wc-timer {
161
- display: flex;
162
- align-items: center;
163
- gap: 8px;
164
- font-size: 14px;
165
- padding: 12px 0 0;
166
- }
167
- .digito-wc-timer-label {
168
- color: var(--digito-timer-color, #5C5C5C);
169
- font-size: 14px;
170
- }
171
- .digito-wc-timer-badge {
172
- display: inline-flex;
173
- align-items: center;
174
- background: color-mix(in srgb, var(--digito-error-color, #FB2C36) 10%, transparent);
175
- color: var(--digito-error-color, #FB2C36);
176
- font-weight: 500;
177
- font-size: 14px;
178
- padding: 2px 10px;
179
- border-radius: 99px;
180
- height: 24px;
181
- font-variant-numeric: tabular-nums;
182
- }
183
-
184
- .digito-wc-resend {
185
- display: none;
186
- align-items: center;
187
- gap: 8px;
188
- font-size: 14px;
189
- color: var(--digito-timer-color, #5C5C5C);
190
- padding: 12px 0 0;
191
- }
192
- .digito-wc-resend.is-visible { display: flex; }
193
- .digito-wc-resend-btn {
194
- display: inline-flex;
195
- align-items: center;
196
- background: #E8E8E8;
197
- border: none;
198
- padding: 2px 10px;
199
- border-radius: 99px;
200
- color: #0A0A0A;
201
- font-weight: 500;
202
- font-size: 14px;
203
- transition: background 150ms ease;
204
- cursor: pointer;
205
- height: 24px;
206
- font-family: inherit;
207
- }
208
- .digito-wc-resend-btn:hover { background: #E5E5E5; }
209
- .digito-wc-resend-btn:disabled { color: #A1A1A1; cursor: not-allowed; background: #F5F5F5; }
210
- `
211
-
212
- // ─────────────────────────────────────────────────────────────────────────────
213
- // WEB COMPONENT
214
- // ─────────────────────────────────────────────────────────────────────────────
215
-
216
- class DigitoInput extends HTMLElement {
217
- /**
218
- * HTML attribute names whose changes trigger `attributeChangedCallback`.
219
- * Any change to these attributes causes a full shadow DOM rebuild so the
220
- * component always reflects its attribute state without manual reconciliation.
221
- */
222
- static observedAttributes = ['length', 'type', 'timer', 'resend-after', 'disabled', 'readonly', 'separator-after', 'separator', 'masked', 'mask-char', 'name', 'placeholder', 'auto-focus', 'select-on-focus', 'blur-on-complete', 'default-value']
223
-
224
- // Shadow DOM references — rebuilt in full on every attributeChangedCallback.
225
- private slotEls: HTMLDivElement[] = []
226
- private caretEls: HTMLDivElement[] = []
227
- private hiddenInput: HTMLInputElement | null = null
228
- private timerEl: HTMLDivElement | null = null
229
- private timerBadgeEl: HTMLSpanElement | null = null
230
- private resendEl: HTMLDivElement | null = null
231
- private timerCtrl: ReturnType<typeof createTimer> | null = null
232
- private resendCountdown: ReturnType<typeof createTimer> | null = null
233
- private digito: ReturnType<typeof createDigito> | null = null
234
- private shadow: ShadowRoot
235
-
236
- // Runtime mutable state — toggled by setDisabled() without a full rebuild.
237
- private _isDisabled = false
238
- private _isSuccess = false
239
- private _isReadOnly = false
240
-
241
- // JS-property-only options. These cannot be expressed as HTML attributes
242
- // (RegExp and functions are not serialisable to strings), so they are stored
243
- // here and applied on every build().
244
- private _pattern: RegExp | undefined = undefined
245
- private _pasteTransformer: ((raw: string) => string) | undefined = undefined
246
- private _onComplete: ((code: string) => void) | undefined = undefined
247
- private _onResend: (() => void) | undefined = undefined
248
- private _onFocus: (() => void) | undefined = undefined
249
- private _onBlur: (() => void) | undefined = undefined
250
- private _onInvalidChar: ((char: string, index: number) => void) | undefined = undefined
251
-
252
- /** Called when all slots are filled. Also dispatches the `complete` CustomEvent. */
253
- set onComplete(fn: ((code: string) => void) | undefined) {
254
- if (fn !== undefined && typeof fn !== 'function') {
255
- console.warn('[digito] onComplete must be a function, got:', typeof fn); return
256
- }
257
- this._onComplete = fn
258
- }
259
- /** Called when the built-in Resend button is clicked. */
260
- set onResend(fn: (() => void) | undefined) {
261
- if (fn !== undefined && typeof fn !== 'function') {
262
- console.warn('[digito] onResend must be a function, got:', typeof fn); return
263
- }
264
- this._onResend = fn
265
- }
266
- /** Fires when the hidden input receives focus. Set as JS property. */
267
- set onFocus(fn: (() => void) | undefined) {
268
- if (fn !== undefined && typeof fn !== 'function') {
269
- console.warn('[digito] onFocus must be a function, got:', typeof fn); return
270
- }
271
- this._onFocus = fn
272
- }
273
- /** Fires when the hidden input loses focus. Set as JS property. */
274
- set onBlur(fn: (() => void) | undefined) {
275
- if (fn !== undefined && typeof fn !== 'function') {
276
- console.warn('[digito] onBlur must be a function, got:', typeof fn); return
277
- }
278
- this._onBlur = fn
279
- }
280
- /**
281
- * Fires when a typed character is rejected by type/pattern validation.
282
- * Receives the character and the slot index it was attempted on.
283
- * Set as JS property.
284
- */
285
- set onInvalidChar(fn: ((char: string, index: number) => void) | undefined) {
286
- if (fn !== undefined && typeof fn !== 'function') {
287
- console.warn('[digito] onInvalidChar must be a function, got:', typeof fn); return
288
- }
289
- this._onInvalidChar = fn
290
- if (this.shadow.children.length > 0) this.build()
291
- }
292
-
293
- /**
294
- * Arbitrary per-character regex. When set, each typed/pasted character must
295
- * match to be accepted. Takes precedence over the type attribute for
296
- * character validation. Cannot be expressed as an HTML attribute — set as a
297
- * JS property instead.
298
- * @example el.pattern = /^[0-9A-F]$/
299
- */
300
- set pattern(re: RegExp | undefined) {
301
- if (re !== undefined && !(re instanceof RegExp)) {
302
- console.warn('[digito] pattern must be a RegExp, got:', typeof re); return
303
- }
304
- this._pattern = re
305
- if (this.shadow.children.length > 0) this.build()
306
- }
307
-
308
- /**
309
- * Optional paste transformer function. Applied to raw clipboard text before
310
- * filtering. Use to strip formatting (e.g. `"G-123456"` → `"123456"`).
311
- * Cannot be expressed as an HTML attribute — set as a JS property.
312
- * @example el.pasteTransformer = (raw) => raw.replace(/\s+|-/g, '')
313
- */
314
- set pasteTransformer(fn: ((raw: string) => string) | undefined) {
315
- if (fn !== undefined && typeof fn !== 'function') {
316
- console.warn('[digito] pasteTransformer must be a function, got:', typeof fn); return
317
- }
318
- this._pasteTransformer = fn
319
- if (this.shadow.children.length > 0) this.build()
320
- }
321
-
322
- constructor() {
323
- super()
324
- // Open shadow root so external CSS custom properties (--digito-*) cascade in.
325
- this.shadow = this.attachShadow({ mode: 'open' })
326
- }
327
-
328
- /** Called when the element is inserted into the DOM. Triggers the initial build. */
329
- connectedCallback(): void { this.build() }
330
-
331
- /**
332
- * Called when the element is removed from the DOM.
333
- * Stops both timers and cancels any pending `onComplete` timeout to avoid
334
- * callbacks firing after the element is detached.
335
- */
336
- disconnectedCallback(): void {
337
- this.timerCtrl?.stop()
338
- this.resendCountdown?.stop()
339
- this.digito?.resetState()
340
- }
341
-
342
- /**
343
- * Called when any observed attribute changes after the initial connection.
344
- * Guards on `shadow.children.length > 0` so it does not fire before
345
- * `connectedCallback` has completed the first build.
346
- */
347
- attributeChangedCallback(): void {
348
- if (this.shadow.children.length > 0) this.build()
349
- }
350
-
351
- // ── Attribute accessors ─────────────────────────────────────────────────────
352
- // Each getter reads directly from the live attribute to stay in sync with
353
- // external attribute mutations. All values are snapshotted at the top of
354
- // build() so a single rebuild is always internally consistent.
355
-
356
- private get _length(): number {
357
- const v = parseInt(this.getAttribute('length') ?? '6', 10)
358
- return isNaN(v) || v < 1 ? 6 : Math.floor(v)
359
- }
360
- private get _type(): InputType { return (this.getAttribute('type') ?? 'numeric') as InputType }
361
- private get _timer(): number {
362
- const v = parseInt(this.getAttribute('timer') ?? '0', 10)
363
- return isNaN(v) || v < 0 ? 0 : Math.floor(v)
364
- }
365
- private get _resendAfter(): number {
366
- const v = parseInt(this.getAttribute('resend-after') ?? '30', 10)
367
- return isNaN(v) || v < 1 ? 30 : Math.floor(v)
368
- }
369
- private get _disabledAttr(): boolean { return this.hasAttribute('disabled') }
370
- private get _readOnlyAttr(): boolean { return this.hasAttribute('readonly') }
371
- private get _defaultValue(): string { return this.getAttribute('default-value') ?? '' }
372
- /** Parses `separator-after="2,4"` into `[2, 4]`. Filters NaN and zero values. */
373
- private get _separatorAfter(): number[] {
374
- const v = this.getAttribute('separator-after')
375
- if (!v) return []
376
- return v.split(',').map(s => parseInt(s.trim(), 10)).filter(n => !isNaN(n) && n > 0)
377
- }
378
- private get _separator(): string { return this.getAttribute('separator') ?? '—' }
379
- /** `masked` is a boolean attribute — present means true, absent means false. */
380
- private get _masked(): boolean { return this.hasAttribute('masked') }
381
- private get _maskChar(): string { return this.getAttribute('mask-char') ?? '\u25CF' }
382
- private get _name(): string { return this.getAttribute('name') ?? '' }
383
- private get _placeholder(): string { return this.getAttribute('placeholder') ?? '' }
384
- /**
385
- * `auto-focus` defaults to `true` when the attribute is absent.
386
- * Setting `auto-focus="false"` explicitly suppresses focus on mount.
387
- */
388
- private get _autoFocus(): boolean { return !this.hasAttribute('auto-focus') || this.getAttribute('auto-focus') !== 'false' }
389
- private get _selectOnFocus(): boolean { return this.hasAttribute('select-on-focus') }
390
- private get _blurOnComplete(): boolean { return this.hasAttribute('blur-on-complete') }
391
-
392
- // ── Build ───────────────────────────────────────────────────────────────────
393
- /**
394
- * Constructs the entire shadow DOM from scratch.
395
- *
396
- * Called on first connect, on every observed attribute change, and when
397
- * certain JS-property setters (`pattern`, `pasteTransformer`, `onInvalidChar`)
398
- * are assigned after mount. Tears down any running timer and resets the
399
- * state machine before rebuilding to prevent duplicate intervals or stale
400
- * closure references from the previous build.
401
- */
402
- private build(): void {
403
- const length = this._length
404
- const type = this._type
405
- const timerSecs = this._timer
406
- const resendCooldown = this._resendAfter
407
- const separatorPositions = this._separatorAfter
408
- const separator = this._separator
409
- const masked = this._masked
410
- const inputName = this._name
411
- const autoFocus = this._autoFocus
412
- const selectOnFocus = this._selectOnFocus
413
- const blurOnComplete = this._blurOnComplete
414
- this._isDisabled = this._disabledAttr
415
- this._isReadOnly = this._readOnlyAttr
416
-
417
- this.timerCtrl?.stop()
418
- this.resendCountdown?.stop()
419
- this.digito?.resetState()
420
-
421
- // Clear shadow DOM using safe child removal
422
- while (this.shadow.firstChild) this.shadow.removeChild(this.shadow.firstChild)
423
- this.slotEls = []
424
- this.caretEls = []
425
- this.timerEl = null
426
- this.timerBadgeEl = null
427
- this.resendEl = null
428
- this.timerCtrl = null
429
- this.resendCountdown = null
430
-
431
- // Styles
432
- const styleEl = document.createElement('style')
433
- styleEl.textContent = STYLES
434
- this.shadow.appendChild(styleEl)
435
-
436
- // Root
437
- const rootEl = document.createElement('div')
438
- rootEl.className = 'digito-wc-root'
439
-
440
- // Slot row
441
- const slotRowEl = document.createElement('div')
442
- slotRowEl.className = 'digito-wc-slots'
443
-
444
- // Visual slots + optional separator
445
- for (let i = 0; i < length; i++) {
446
- const slotEl = document.createElement('div')
447
- slotEl.className = 'digito-wc-slot'
448
- slotEl.setAttribute('aria-hidden', 'true')
449
-
450
- const caretEl = document.createElement('div')
451
- caretEl.className = 'digito-wc-caret'
452
- slotEl.appendChild(caretEl)
453
-
454
- this.caretEls.push(caretEl)
455
- this.slotEls.push(slotEl)
456
- slotRowEl.appendChild(slotEl)
457
-
458
- if (separatorPositions.some(pos => i === pos - 1)) {
459
- const sepEl = document.createElement('div')
460
- sepEl.className = 'digito-wc-separator'
461
- sepEl.textContent = separator
462
- sepEl.setAttribute('aria-hidden', 'true')
463
- slotRowEl.appendChild(sepEl)
464
- }
465
- }
466
-
467
- // Hidden input
468
- const hiddenInput = document.createElement('input')
469
- hiddenInput.type = masked ? 'password' : 'text'
470
- hiddenInput.inputMode = type === 'numeric' ? 'numeric' : 'text'
471
- hiddenInput.autocomplete = 'one-time-code'
472
- hiddenInput.maxLength = length
473
- hiddenInput.disabled = this._isDisabled
474
- hiddenInput.className = 'digito-wc-hidden'
475
- hiddenInput.setAttribute('aria-label', `Enter your ${length}-${type === 'numeric' ? 'digit' : 'character'} code`)
476
- hiddenInput.setAttribute('spellcheck', 'false')
477
- hiddenInput.setAttribute('autocorrect', 'off')
478
- hiddenInput.setAttribute('autocapitalize', 'off')
479
- if (inputName) hiddenInput.name = inputName
480
- this.hiddenInput = hiddenInput
481
-
482
- rootEl.appendChild(slotRowEl)
483
- rootEl.appendChild(hiddenInput)
484
- this.shadow.appendChild(rootEl)
485
-
486
- // Core
487
- this.digito = createDigito({
488
- length,
489
- type,
490
- pattern: this._pattern,
491
- pasteTransformer: this._pasteTransformer,
492
- onInvalidChar: this._onInvalidChar,
493
- readOnly: this._isReadOnly,
494
- onComplete: (code) => {
495
- // Call JS property setter AND dispatch CustomEvent
496
- this._onComplete?.(code)
497
- this.dispatchEvent(
498
- new CustomEvent('complete', { detail: { code }, bubbles: true, composed: true })
499
- )
500
- },
501
- })
502
-
503
- // ── Built-in timer + resend (mirrors vanilla/alpine adapters) ──────────────
504
- if (timerSecs > 0) {
505
- // Timer footer — "Code expires in [0:45]"
506
- const timerFooterEl = document.createElement('div')
507
- timerFooterEl.className = 'digito-wc-timer'
508
- this.timerEl = timerFooterEl
509
-
510
- const timerLabel = document.createElement('span')
511
- timerLabel.className = 'digito-wc-timer-label'
512
- timerLabel.textContent = 'Code expires in'
513
-
514
- const timerBadge = document.createElement('span')
515
- timerBadge.className = 'digito-wc-timer-badge'
516
- timerBadge.textContent = formatCountdown(timerSecs)
517
- this.timerBadgeEl = timerBadge
518
-
519
- timerFooterEl.appendChild(timerLabel)
520
- timerFooterEl.appendChild(timerBadge)
521
- rootEl.appendChild(timerFooterEl)
522
-
523
- // Resend row — "Didn't receive the code? [Resend]"
524
- const resendRowEl = document.createElement('div')
525
- resendRowEl.className = 'digito-wc-resend'
526
- this.resendEl = resendRowEl
527
-
528
- const resendLabel = document.createElement('span')
529
- resendLabel.textContent = 'Didn\u2019t receive the code?'
530
-
531
- const resendBtn = document.createElement('button')
532
- resendBtn.className = 'digito-wc-resend-btn'
533
- resendBtn.textContent = 'Resend'
534
- resendBtn.type = 'button'
535
-
536
- resendRowEl.appendChild(resendLabel)
537
- resendRowEl.appendChild(resendBtn)
538
- rootEl.appendChild(resendRowEl)
539
-
540
- // Main countdown
541
- this.timerCtrl = createTimer({
542
- totalSeconds: timerSecs,
543
- onTick: (r) => { if (this.timerBadgeEl) this.timerBadgeEl.textContent = formatCountdown(r) },
544
- onExpire: () => {
545
- if (this.timerEl) this.timerEl.style.display = 'none'
546
- if (this.resendEl) this.resendEl.classList.add('is-visible')
547
- this.dispatchEvent(new CustomEvent('expire', { bubbles: true, composed: true }))
548
- },
549
- })
550
- this.timerCtrl.start()
551
-
552
- // Resend button click — restart with resend cooldown
553
- resendBtn.addEventListener('click', () => {
554
- if (!this.timerEl || !this.timerBadgeEl || !this.resendEl) return
555
- this.resendEl.classList.remove('is-visible')
556
- this.timerEl.style.display = 'flex'
557
- this.timerBadgeEl.textContent = formatCountdown(resendCooldown)
558
- this.resendCountdown?.stop()
559
- this.resendCountdown = createTimer({
560
- totalSeconds: resendCooldown,
561
- onTick: (r) => { if (this.timerBadgeEl) this.timerBadgeEl.textContent = formatCountdown(r) },
562
- onExpire: () => {
563
- if (this.timerEl) this.timerEl.style.display = 'none'
564
- if (this.resendEl) this.resendEl.classList.add('is-visible')
565
- },
566
- })
567
- this.resendCountdown.start()
568
- this._onResend?.()
569
- })
570
- }
571
-
572
- if (this._isReadOnly) hiddenInput.setAttribute('aria-readonly', 'true')
573
-
574
- // Apply defaultValue once on build — no onComplete, no change event
575
- const dv = this._defaultValue
576
- if (dv) {
577
- const filtered = filterString(dv.slice(0, length), type, this._pattern)
578
- if (filtered) {
579
- for (let i = 0; i < filtered.length; i++) this.digito!.inputChar(i, filtered[i])
580
- this.digito!.cancelPendingComplete()
581
- hiddenInput.value = filtered
582
- }
583
- }
584
-
585
- this.attachEvents(selectOnFocus, blurOnComplete)
586
-
587
- if (this._isDisabled) this.applyDisabledDOM(true)
588
-
589
- hiddenInput.addEventListener('click', (e: MouseEvent) => {
590
- if (this._isDisabled) return
591
- // click fires after the browser places cursor (always 0 due to font-size:1px).
592
- // Coordinate hit-test determines which slot was visually clicked, then
593
- // setSelectionRange overrides the browser's placement.
594
- let rawSlot = this.slotEls.length - 1
595
- for (let i = 0; i < this.slotEls.length; i++) {
596
- if (e.clientX <= this.slotEls[i].getBoundingClientRect().right) { rawSlot = i; break }
597
- }
598
- // Clamp to filled count so the visual active slot matches the actual cursor position.
599
- const clickedSlot = Math.min(rawSlot, hiddenInput.value.length)
600
- this.digito?.moveFocusTo(clickedSlot)
601
- const char = this.digito?.state.slotValues[clickedSlot] ?? ''
602
- if (selectOnFocus && char) {
603
- hiddenInput.setSelectionRange(clickedSlot, clickedSlot + 1)
604
- } else {
605
- hiddenInput.setSelectionRange(clickedSlot, clickedSlot)
606
- }
607
- this.syncSlotsToDOM()
608
- })
609
-
610
- requestAnimationFrame(() => {
611
- if (!this._isDisabled && autoFocus) hiddenInput.focus()
612
- hiddenInput.setSelectionRange(0, 0)
613
- this.syncSlotsToDOM()
614
- })
615
- }
616
-
617
- // ── DOM sync ────────────────────────────────────────────────────────────────
618
- /**
619
- * Reconcile the shadow slot divs with the current core state using CSS class
620
- * toggles. Called after every user action (input, keydown, paste, focus, click).
621
- *
622
- * Uses `this.shadow.activeElement` instead of `document.activeElement` to
623
- * correctly detect focus within the shadow root across all browsers — the
624
- * document active element is the host `<digito-input>` element, not the
625
- * internal hidden input.
626
- */
627
- private syncSlotsToDOM(): void {
628
- if (!this.digito || !this.hiddenInput) return
629
- const { slotValues, activeSlot, hasError } = this.digito.state
630
- const focused = this.shadow.activeElement === this.hiddenInput
631
-
632
- this.slotEls.forEach((slotEl, i) => {
633
- const char = slotValues[i] ?? ''
634
- const isActive = i === activeSlot && focused
635
-
636
- let textNode = slotEl.childNodes[1] as Text | undefined
637
- if (!textNode || textNode.nodeType !== Node.TEXT_NODE) {
638
- textNode = document.createTextNode('')
639
- slotEl.appendChild(textNode)
640
- }
641
- textNode.nodeValue = this._masked && char ? this._maskChar : char || this._placeholder
642
-
643
- slotEl.classList.toggle('is-active', isActive && !this._isDisabled)
644
- slotEl.classList.toggle('is-filled', !!char)
645
- slotEl.classList.toggle('is-masked', this._masked)
646
- slotEl.classList.toggle('is-error', hasError)
647
- slotEl.classList.toggle('is-success', this._isSuccess)
648
- slotEl.classList.toggle('is-disabled', this._isDisabled)
649
-
650
- this.caretEls[i].style.display = isActive && !char && !this._isDisabled ? 'block' : 'none'
651
- })
652
-
653
- // Only update value when it actually differs — assigning the same string
654
- // resets selectionStart/End in some browsers, clobbering the cursor.
655
- const newValue = slotValues.join('')
656
- if (this.hiddenInput.value !== newValue) this.hiddenInput.value = newValue
657
-
658
- this.toggleAttribute('data-complete', this.digito.state.isComplete)
659
- this.toggleAttribute('data-invalid', this.digito.state.hasError)
660
- this.toggleAttribute('data-disabled', this._isDisabled)
661
- this.toggleAttribute('data-readonly', this._isReadOnly)
662
- }
663
-
664
- /**
665
- * Apply or remove the disabled state directly on existing DOM nodes without
666
- * triggering a full rebuild. Used by both `build()` (initial disabled attr)
667
- * and `setDisabled()` (runtime toggle).
668
- */
669
- private applyDisabledDOM(value: boolean): void {
670
- if (this.hiddenInput) this.hiddenInput.disabled = value
671
- this.slotEls.forEach(s => s.classList.toggle('is-disabled', value))
672
- }
673
-
674
- // ── Events ──────────────────────────────────────────────────────────────────
675
- /**
676
- * Wire all event listeners to the hidden input element.
677
- * Called once at the end of each `build()`. Because `build()` creates a fresh
678
- * `hiddenInput` element, there is no need to `removeEventListener` — the old
679
- * element is discarded and its listeners are garbage-collected with it.
680
- *
681
- * @param selectOnFocus When `true`, focusing a filled slot selects its character.
682
- * @param blurOnComplete When `true`, blurs the input after the last slot is filled.
683
- */
684
- private attachEvents(selectOnFocus: boolean, blurOnComplete: boolean): void {
685
- const input = this.hiddenInput!
686
- const digito = this.digito!
687
- const length = this._length
688
- const type = this._type
689
- const pattern = this._pattern
690
-
691
- input.addEventListener('keydown', (e) => {
692
- if (this._isDisabled) return
693
- const pos = input.selectionStart ?? 0
694
- if (e.key === 'Backspace') {
695
- e.preventDefault()
696
- if (this._isReadOnly) return
697
- digito.deleteChar(pos)
698
- this.syncSlotsToDOM()
699
- this.dispatchChange()
700
- const next = digito.state.activeSlot
701
- requestAnimationFrame(() => input.setSelectionRange(next, next))
702
- } else if (e.key === 'Delete') {
703
- e.preventDefault()
704
- if (this._isReadOnly) return
705
- digito.clearSlot(pos)
706
- this.syncSlotsToDOM()
707
- this.dispatchChange()
708
- requestAnimationFrame(() => input.setSelectionRange(pos, pos))
709
- } else if (e.key === 'ArrowLeft') {
710
- e.preventDefault()
711
- digito.moveFocusLeft(pos)
712
- this.syncSlotsToDOM()
713
- requestAnimationFrame(() => input.setSelectionRange(digito.state.activeSlot, digito.state.activeSlot))
714
- } else if (e.key === 'ArrowRight') {
715
- e.preventDefault()
716
- digito.moveFocusRight(pos)
717
- this.syncSlotsToDOM()
718
- requestAnimationFrame(() => input.setSelectionRange(digito.state.activeSlot, digito.state.activeSlot))
719
- } else if (e.key === 'Tab') {
720
- if (e.shiftKey) {
721
- if (pos === 0) return
722
- e.preventDefault()
723
- digito.moveFocusLeft(pos)
724
- } else {
725
- if (!digito.state.slotValues[pos]) return
726
- if (pos >= length - 1) return
727
- e.preventDefault()
728
- digito.moveFocusRight(pos)
729
- }
730
- this.syncSlotsToDOM()
731
- const next = digito.state.activeSlot
732
- requestAnimationFrame(() => input.setSelectionRange(next, next))
733
- }
734
- })
735
-
736
- input.addEventListener('input', () => {
737
- if (this._isDisabled || this._isReadOnly) return
738
- const raw = input.value
739
- if (!raw) {
740
- digito.resetState()
741
- input.value = ''
742
- input.setSelectionRange(0, 0)
743
- this.syncSlotsToDOM()
744
- this.dispatchChange()
745
- return
746
- }
747
- const valid = filterString(raw, type, pattern).slice(0, length)
748
- digito.resetState()
749
- for (let i = 0; i < valid.length; i++) digito.inputChar(i, valid[i])
750
- const next = Math.min(valid.length, length - 1)
751
- input.value = valid
752
- input.setSelectionRange(next, next)
753
- digito.moveFocusTo(next)
754
- this.syncSlotsToDOM()
755
- this.dispatchChange()
756
- if (blurOnComplete && digito.state.isComplete) {
757
- requestAnimationFrame(() => input.blur())
758
- }
759
- })
760
-
761
- input.addEventListener('paste', (e) => {
762
- if (this._isDisabled || this._isReadOnly) return
763
- e.preventDefault()
764
- const text = e.clipboardData?.getData('text') ?? ''
765
- const pos = input.selectionStart ?? 0
766
- digito.pasteString(pos, text)
767
- const { slotValues, activeSlot } = digito.state
768
- input.value = slotValues.join('')
769
- input.setSelectionRange(activeSlot, activeSlot)
770
- this.syncSlotsToDOM()
771
- this.dispatchChange()
772
- if (blurOnComplete && digito.state.isComplete) {
773
- requestAnimationFrame(() => input.blur())
774
- }
775
- })
776
-
777
- input.addEventListener('focus', () => {
778
- this._onFocus?.()
779
- requestAnimationFrame(() => {
780
- const pos = digito.state.activeSlot
781
- const char = digito.state.slotValues[pos]
782
- if (selectOnFocus && char) {
783
- input.setSelectionRange(pos, pos + 1)
784
- } else {
785
- input.setSelectionRange(pos, pos)
786
- }
787
- this.syncSlotsToDOM()
788
- })
789
- })
790
-
791
- input.addEventListener('blur', () => {
792
- this._onBlur?.()
793
- this.slotEls.forEach(s => { s.classList.remove('is-active') })
794
- this.caretEls.forEach(c => { c.style.display = 'none' })
795
- })
796
-
797
- }
798
-
799
- /**
800
- * Dispatch a `change` CustomEvent carrying the current code string.
801
- * Fired after every input, paste, and backspace action.
802
- * `composed: true` lets the event cross the shadow root boundary so host-page
803
- * listeners registered with `el.addEventListener('change', ...)` receive it.
804
- */
805
- private dispatchChange(): void {
806
- this.dispatchEvent(new CustomEvent('change', {
807
- detail: { code: this.digito?.getCode() ?? '' },
808
- bubbles: true,
809
- composed: true,
810
- }))
811
- }
812
-
813
- // ── Public DOM API ──────────────────────────────────────────────────────────
814
-
815
- /** Clear all slots, reset the timer display, and re-focus the hidden input. */
816
- reset(): void {
817
- this._isSuccess = false
818
- this.digito?.resetState()
819
- if (this.hiddenInput) {
820
- this.hiddenInput.value = ''
821
- if (!this._isDisabled) this.hiddenInput.focus()
822
- this.hiddenInput.setSelectionRange(0, 0)
823
- }
824
- if (this.timerBadgeEl) this.timerBadgeEl.textContent = formatCountdown(this._timer)
825
- if (this.timerEl) this.timerEl.style.display = 'flex'
826
- if (this.resendEl) this.resendEl.classList.remove('is-visible')
827
- this.resendCountdown?.stop()
828
- this.timerCtrl?.restart()
829
- this.syncSlotsToDOM()
830
- }
831
-
832
- /** Apply or clear the error state on all visual slots. */
833
- setError(isError: boolean): void {
834
- if (isError) this._isSuccess = false
835
- this.digito?.setError(isError)
836
- this.syncSlotsToDOM()
837
- }
838
-
839
- /** Apply or clear the success state on all visual slots. Stops the timer on success. */
840
- setSuccess(isSuccess: boolean): void {
841
- this._isSuccess = isSuccess
842
- if (isSuccess) {
843
- this.digito?.setError(false)
844
- this.timerCtrl?.stop()
845
- this.resendCountdown?.stop()
846
- if (this.timerEl) this.timerEl.style.display = 'none'
847
- if (this.resendEl) this.resendEl.style.display = 'none'
848
- }
849
- this.syncSlotsToDOM()
850
- }
851
-
852
- /**
853
- * Enable or disable the input at runtime.
854
- * Equivalent to toggling the `disabled` HTML attribute but without triggering
855
- * a full rebuild. Re-enabling automatically restores focus to the active slot.
856
- */
857
- setDisabled(value: boolean): void {
858
- this._isDisabled = value
859
- this.digito?.setDisabled(value)
860
- this.applyDisabledDOM(value)
861
- this.syncSlotsToDOM()
862
- if (!value && this.hiddenInput) {
863
- requestAnimationFrame(() => {
864
- this.hiddenInput?.focus()
865
- this.hiddenInput?.setSelectionRange(this.digito?.state.activeSlot ?? 0, this.digito?.state.activeSlot ?? 0)
866
- })
867
- }
868
- }
869
-
870
- /**
871
- * Toggle readOnly at runtime. When `true`, all slot mutations are blocked
872
- * but focus, navigation, and copy remain fully functional.
873
- * Distinct from `disabled` — no opacity/cursor change, `aria-readonly` is set.
874
- */
875
- setReadOnly(value: boolean): void {
876
- this._isReadOnly = value
877
- this.digito?.setReadOnly(value)
878
- if (this.hiddenInput) {
879
- if (value) {
880
- this.hiddenInput.setAttribute('aria-readonly', 'true')
881
- } else {
882
- this.hiddenInput.removeAttribute('aria-readonly')
883
- }
884
- }
885
- this.syncSlotsToDOM()
886
- }
887
-
888
- /** Returns the current code as a joined string (e.g. `"123456"`). */
889
- getCode(): string {
890
- return this.digito?.getCode() ?? ''
891
- }
892
- }
893
-
894
- if (typeof customElements !== 'undefined' && !customElements.get('digito-input')) {
895
- customElements.define('digito-input', DigitoInput)
896
- }
897
-
898
- export { DigitoInput }