digitojs 1.2.2 → 1.2.5

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,491 +0,0 @@
1
- /**
2
- * digito/vue
3
- * ─────────────────────────────────────────────────────────────────────────────
4
- * Vue 3 adapter — useOTP composable (single hidden-input architecture)
5
- *
6
- * @author Olawale Balo — Product Designer + Design Engineer
7
- * @license MIT
8
- */
9
-
10
- import {
11
- ref,
12
- computed,
13
- watch,
14
- onMounted,
15
- onUnmounted,
16
- isRef,
17
- type Ref,
18
- } from 'vue'
19
-
20
- import {
21
- createDigito,
22
- createTimer,
23
- filterString,
24
- type DigitoOptions,
25
- type InputType,
26
- } from '../core/index.js'
27
-
28
-
29
- // ─────────────────────────────────────────────────────────────────────────────
30
- // TYPES
31
- // ─────────────────────────────────────────────────────────────────────────────
32
-
33
- /**
34
- * Extended options for the Vue useOTP composable.
35
- * Adds controlled-input, separator, and disabled support on top of DigitoOptions.
36
- */
37
- export type VueOTPOptions = DigitoOptions & {
38
- /**
39
- * Controlled value — pre-fills and drives the slot state from outside the composable.
40
- *
41
- * Reactive mode (recommended): pass a Ref<string>. The composable watches it
42
- * via Vue's reactivity system — changes propagate automatically, making it
43
- * fully equivalent to React's controlled-input pattern.
44
- * ```ts
45
- * const code = ref('')
46
- * const otp = useOTP({ value: code, length: 6 })
47
- * // Clearing from parent:
48
- * code.value = ''
49
- * ```
50
- *
51
- * Static mode: pass a plain string to pre-fill slots once on creation.
52
- * Subsequent changes to the string will NOT be reactive (composables run
53
- * once during setup()). Use reset() or the Ref pattern for runtime updates.
54
- */
55
- value?: string | Ref<string>
56
- /**
57
- * Fires exactly ONCE per user interaction with the current joined code string.
58
- * Receives partial values too — not just when the code is complete.
59
- */
60
- onChange?: (code: string) => void
61
- /**
62
- * Insert a purely visual separator after this slot index (0-based).
63
- * Accepts a single position or an array for multiple separators.
64
- * aria-hidden, never part of the value, no effect on the state machine.
65
- * Default: 0 (no separator).
66
- * @example separatorAfter: 3 -> [*][*][*] — [*][*][*]
67
- * @example separatorAfter: [2, 4] -> [*][*] — [*][*] — [*][*]
68
- */
69
- separatorAfter?: number | number[]
70
- /**
71
- * The character or string to render as the separator.
72
- * Default: '—'
73
- */
74
- separator?: string
75
- /**
76
- * When `true`, slot templates should display a mask glyph instead of the real
77
- * character. The hidden input switches to `type="password"` via `hiddenInputAttrs`.
78
- *
79
- * `getCode()` and `onComplete` always return real characters.
80
- * Use for PIN entry or any sensitive input flow.
81
- *
82
- * Default: `false`.
83
- */
84
- masked?: boolean
85
- /**
86
- * The glyph displayed in filled slots when `masked` is `true`.
87
- * Returned as a reactive `Ref<string>` so templates can bind to it directly.
88
- *
89
- * Default: `'●'` (U+25CF BLACK CIRCLE).
90
- * @example maskChar: '*'
91
- */
92
- maskChar?: string
93
- }
94
-
95
- export type UseOTPResult = {
96
- /** Current value of each slot. Empty string = unfilled. */
97
- slotValues: Ref<string[]>
98
- /** Index of the currently active slot. */
99
- activeSlot: Ref<number>
100
- /** Computed joined code string. */
101
- value: Ref<string>
102
- /** True when every slot is filled. */
103
- isComplete: Ref<boolean>
104
- /** True when error state is active. */
105
- hasError: Ref<boolean>
106
- /** True when the field is disabled. Mirrors the disabled option. */
107
- isDisabled: Ref<boolean>
108
- /** Remaining timer seconds. */
109
- timerSeconds: Ref<number>
110
- /** True while the hidden input has browser focus. */
111
- isFocused: Ref<boolean>
112
- /** The separator slot index/indices for template rendering. */
113
- separatorAfter: Ref<number | number[]>
114
- /** The separator character/string to render. */
115
- separator: Ref<string>
116
- /**
117
- * Whether masked mode is enabled. When true, templates should display
118
- * `maskChar.value` instead of the real character. `getCode()` still returns real chars.
119
- */
120
- masked: Ref<boolean>
121
- /**
122
- * The configured mask glyph. Use in templates instead of a hard-coded `●`:
123
- * `{{ masked.value && char ? maskChar.value : char }}`
124
- */
125
- maskChar: Ref<string>
126
- /** The placeholder character for empty slots. Empty string when not set. */
127
- placeholder: string
128
- /** Ref to bind to the hidden input element via :ref. */
129
- inputRef: Ref<HTMLInputElement | null>
130
- /** Attribute object to spread onto the hidden input via v-bind. */
131
- hiddenInputAttrs: Ref<Record<string, unknown>>
132
- /** Spread onto the wrapper element to expose state as data attributes for CSS/Tailwind targeting. */
133
- wrapperAttrs: Ref<Record<string, string | undefined>>
134
- /** Returns the current joined code string. */
135
- getCode: () => string
136
- /** Clear all slots, restart timer, return focus to input. */
137
- reset: () => void
138
- /** Apply or clear the error state. */
139
- setError: (isError: boolean) => void
140
- /** Programmatically move focus to a slot index. */
141
- focus: (slotIndex: number) => void
142
- /** Event handlers to bind on the hidden input. */
143
- onKeydown: (e: KeyboardEvent) => void
144
- onChange: (e: Event) => void
145
- onPaste: (e: ClipboardEvent) => void
146
- onFocus: () => void
147
- onBlur: () => void
148
- }
149
-
150
-
151
- // ─────────────────────────────────────────────────────────────────────────────
152
- // COMPOSABLE
153
- // ─────────────────────────────────────────────────────────────────────────────
154
-
155
- /**
156
- * Vue 3 composable for OTP input — single hidden-input architecture.
157
- *
158
- * @example
159
- * ```vue
160
- * <script setup>
161
- * import { useOTP } from 'digito/vue'
162
- * const otp = useOTP({ length: 6, onComplete: (code) => verify(code) })
163
- * </script>
164
- *
165
- * <template>
166
- * <div style="position:relative; display:inline-flex; gap:8px; align-items:center">
167
- * <input
168
- * :ref="(el) => otp.inputRef.value = el"
169
- * v-bind="otp.hiddenInputAttrs.value"
170
- * style="position:absolute;inset:0;opacity:0;z-index:1;cursor:text"
171
- * @keydown="otp.onKeydown"
172
- * @input="otp.onChange"
173
- * @paste="otp.onPaste"
174
- * @focus="otp.onFocus"
175
- * @blur="otp.onBlur"
176
- * />
177
- * <template v-for="(char, i) in otp.slotValues.value" :key="i">
178
- * <span v-if="otp.separatorAfter.value > 0 && i === otp.separatorAfter.value" aria-hidden="true">
179
- * {{ otp.separator.value }}
180
- * </span>
181
- * <div :class="['slot',
182
- * i === otp.activeSlot.value && otp.isFocused.value ? 'is-active' : '',
183
- * char ? 'is-filled' : '',
184
- * otp.hasError.value ? 'is-error' : '',
185
- * otp.isComplete.value && !otp.hasError.value ? 'is-success' : '',
186
- * otp.isDisabled.value ? 'is-disabled' : '',
187
- * ]">{{ char }}</div>
188
- * </template>
189
- * </div>
190
- * </template>
191
- * ```
192
- */
193
- export function useOTP(options: VueOTPOptions = {}): UseOTPResult {
194
- const {
195
- length = 6,
196
- type = 'numeric' as InputType,
197
- timer: timerSecs = 0,
198
- disabled: initialDisabled = false,
199
- onComplete,
200
- onExpire,
201
- onResend,
202
- haptic = true,
203
- sound = false,
204
- pattern,
205
- pasteTransformer,
206
- onInvalidChar,
207
- value: controlledValue,
208
- defaultValue,
209
- readOnly: readOnlyOpt = false,
210
- onChange: onChangeProp,
211
- onFocus: onFocusProp,
212
- onBlur: onBlurProp,
213
- separatorAfter: separatorAfterOpt = 0,
214
- separator: separatorOpt = '—',
215
- masked: maskedOpt = false,
216
- maskChar: maskCharOpt = '\u25CF',
217
- autoFocus: autoFocusOpt = true,
218
- name: nameOpt,
219
- placeholder: placeholderOpt = '',
220
- selectOnFocus: selectOnFocusOpt = false,
221
- blurOnComplete: blurOnCompleteOpt = false,
222
- } = options
223
-
224
- // ── Core instance ──────────────────────────────────────────────────────────
225
- const digito = createDigito({ length, type, pattern, pasteTransformer, onInvalidChar, onComplete, onExpire, onResend, haptic, sound, readOnly: readOnlyOpt })
226
-
227
- // ── Reactive state ─────────────────────────────────────────────────────────
228
- const slotValues = ref<string[]>(Array(length).fill(''))
229
- const activeSlot = ref(0)
230
- const isComplete = ref(false)
231
- const hasError = ref(false)
232
- const isDisabled = ref(initialDisabled)
233
- const timerSeconds = ref(timerSecs)
234
- const isFocused = ref(false)
235
- const inputRef = ref<HTMLInputElement | null>(null)
236
- const separatorAfter = ref<number | number[]>(separatorAfterOpt)
237
- const separator = ref(separatorOpt)
238
- const masked = ref(maskedOpt)
239
- const maskChar = ref(maskCharOpt)
240
-
241
- const value = computed(() => slotValues.value.join(''))
242
-
243
- const hiddenInputAttrs = computed<Record<string, unknown>>(() => ({
244
- type: masked.value ? 'password' : 'text',
245
- inputmode: type === 'numeric' ? 'numeric' : 'text',
246
- autocomplete: 'one-time-code',
247
- maxlength: length,
248
- disabled: isDisabled.value,
249
- ...(nameOpt ? { name: nameOpt } : {}),
250
- ...(autoFocusOpt ? { autofocus: true } : {}),
251
- 'aria-label': `Enter your ${length}-${type === 'numeric' ? 'digit' : 'character'} code`,
252
- spellcheck: 'false',
253
- autocorrect: 'off',
254
- autocapitalize: 'off',
255
- ...(readOnlyOpt ? { 'aria-readonly': 'true' } : {}),
256
- }))
257
-
258
- const wrapperAttrs = computed<Record<string, string | undefined>>(() => ({
259
- ...(isComplete.value ? { 'data-complete': '' } : {}),
260
- ...(hasError.value ? { 'data-invalid': '' } : {}),
261
- ...(isDisabled.value ? { 'data-disabled': '' } : {}),
262
- ...(readOnlyOpt ? { 'data-readonly': '' } : {}),
263
- }))
264
-
265
- // ── sync() ─────────────────────────────────────────────────────────────────
266
- function sync(suppressOnChange = false): void {
267
- const s = digito.state
268
- slotValues.value = [...s.slotValues]
269
- activeSlot.value = s.activeSlot
270
- isComplete.value = s.isComplete
271
- hasError.value = s.hasError
272
- if (!suppressOnChange) {
273
- onChangeProp?.(s.slotValues.join(''))
274
- }
275
- }
276
-
277
- // ── Controlled value sync ──────────────────────────────────────────────────
278
- // When value is a Ref<string>, watch it reactively so parent changes
279
- // propagate automatically. When it's a plain string, the arrow-function
280
- // source returns a constant — watch fires once via { immediate: true }
281
- // and never again (documented static-pre-fill behaviour).
282
- if (controlledValue !== undefined) {
283
- const watchSource = isRef(controlledValue)
284
- ? controlledValue
285
- : () => controlledValue as string
286
-
287
- watch(
288
- watchSource,
289
- (incoming: string) => {
290
- const filtered = filterString(incoming.slice(0, length), type, pattern)
291
- const current = digito.state.slotValues.join('')
292
- if (filtered === current) return
293
-
294
- digito.resetState()
295
- for (let i = 0; i < filtered.length; i++) {
296
- digito.inputChar(i, filtered[i])
297
- }
298
- sync(true)
299
- if (inputRef.value) {
300
- inputRef.value.value = filtered
301
- inputRef.value.setSelectionRange(filtered.length, filtered.length)
302
- }
303
- onChangeProp?.(filtered)
304
- },
305
- { immediate: true }
306
- )
307
- }
308
-
309
- // ── Timer ──────────────────────────────────────────────────────────────────
310
- let timerControls: ReturnType<typeof createTimer> | null = null
311
-
312
- onMounted(() => {
313
- if (controlledValue === undefined && defaultValue) {
314
- const filtered = filterString(defaultValue.slice(0, length), type, pattern)
315
- if (filtered) {
316
- for (let i = 0; i < filtered.length; i++) digito.inputChar(i, filtered[i])
317
- digito.cancelPendingComplete()
318
- sync(true)
319
- if (inputRef.value) { inputRef.value.value = filtered; inputRef.value.setSelectionRange(filtered.length, filtered.length) }
320
- }
321
- }
322
- if (autoFocusOpt && !initialDisabled && inputRef.value) {
323
- inputRef.value.focus()
324
- inputRef.value.setSelectionRange(0, 0)
325
- }
326
- if (!timerSecs) return
327
- timerControls = createTimer({
328
- totalSeconds: timerSecs,
329
- onTick: (r) => { timerSeconds.value = r },
330
- onExpire: () => { timerSeconds.value = 0; onExpire?.() },
331
- })
332
- timerControls.start()
333
- })
334
-
335
- onUnmounted(() => timerControls?.stop())
336
-
337
- // ── Event handlers ─────────────────────────────────────────────────────────
338
-
339
- function onKeydown(e: KeyboardEvent): void {
340
- if (isDisabled.value) return
341
- const pos = inputRef.value?.selectionStart ?? 0
342
- if (e.key === 'Backspace') {
343
- e.preventDefault()
344
- if (readOnlyOpt) return
345
- digito.deleteChar(pos)
346
- sync()
347
- const next = digito.state.activeSlot
348
- requestAnimationFrame(() => inputRef.value?.setSelectionRange(next, next))
349
- } else if (e.key === 'Delete') {
350
- e.preventDefault()
351
- if (readOnlyOpt) return
352
- digito.clearSlot(pos)
353
- sync()
354
- requestAnimationFrame(() => inputRef.value?.setSelectionRange(pos, pos))
355
- } else if (e.key === 'ArrowLeft') {
356
- e.preventDefault()
357
- digito.moveFocusLeft(pos)
358
- sync()
359
- const next = digito.state.activeSlot
360
- requestAnimationFrame(() => inputRef.value?.setSelectionRange(next, next))
361
- } else if (e.key === 'ArrowRight') {
362
- e.preventDefault()
363
- digito.moveFocusRight(pos)
364
- sync()
365
- const next = digito.state.activeSlot
366
- requestAnimationFrame(() => inputRef.value?.setSelectionRange(next, next))
367
- } else if (e.key === 'Tab') {
368
- if (e.shiftKey) {
369
- if (pos === 0) return
370
- e.preventDefault()
371
- digito.moveFocusLeft(pos)
372
- } else {
373
- if (!digito.state.slotValues[pos]) return
374
- if (pos >= length - 1) return
375
- e.preventDefault()
376
- digito.moveFocusRight(pos)
377
- }
378
- sync()
379
- const next = digito.state.activeSlot
380
- requestAnimationFrame(() => inputRef.value?.setSelectionRange(next, next))
381
- }
382
- }
383
-
384
- function onChange(e: Event): void {
385
- if (isDisabled.value || readOnlyOpt) return
386
- const raw = (e.target as HTMLInputElement).value
387
- if (!raw) {
388
- digito.resetState()
389
- if (inputRef.value) { inputRef.value.value = ''; inputRef.value.setSelectionRange(0, 0) }
390
- sync()
391
- return
392
- }
393
- const valid = filterString(raw, type, pattern).slice(0, length)
394
- digito.resetState()
395
- for (let i = 0; i < valid.length; i++) digito.inputChar(i, valid[i])
396
- const next = Math.min(valid.length, length - 1)
397
- if (inputRef.value) { inputRef.value.value = valid; inputRef.value.setSelectionRange(next, next) }
398
- digito.moveFocusTo(next)
399
- sync()
400
- if (blurOnCompleteOpt && digito.state.isComplete) {
401
- requestAnimationFrame(() => inputRef.value?.blur())
402
- }
403
- }
404
-
405
- function onPaste(e: ClipboardEvent): void {
406
- if (isDisabled.value || readOnlyOpt) return
407
- e.preventDefault()
408
- const text = e.clipboardData?.getData('text') ?? ''
409
- const pos = inputRef.value?.selectionStart ?? 0
410
- digito.pasteString(pos, text)
411
- const { slotValues: sv, activeSlot: as } = digito.state
412
- if (inputRef.value) { inputRef.value.value = sv.join(''); inputRef.value.setSelectionRange(as, as) }
413
- sync()
414
- if (blurOnCompleteOpt && digito.state.isComplete) {
415
- requestAnimationFrame(() => inputRef.value?.blur())
416
- }
417
- }
418
-
419
- function onFocus(): void {
420
- isFocused.value = true
421
- onFocusProp?.()
422
- const pos = digito.state.activeSlot
423
- requestAnimationFrame(() => {
424
- const char = digito.state.slotValues[pos]
425
- if (selectOnFocusOpt && char) {
426
- inputRef.value?.setSelectionRange(pos, pos + 1)
427
- } else {
428
- inputRef.value?.setSelectionRange(pos, pos)
429
- }
430
- })
431
- }
432
-
433
- function onBlur(): void {
434
- isFocused.value = false
435
- onBlurProp?.()
436
- }
437
-
438
- // ── Public API ─────────────────────────────────────────────────────────────
439
-
440
- function reset(): void {
441
- digito.resetState()
442
- if (inputRef.value) { inputRef.value.value = ''; inputRef.value.focus(); inputRef.value.setSelectionRange(0, 0) }
443
- timerSeconds.value = timerSecs
444
- timerControls?.restart()
445
- sync()
446
- }
447
-
448
- function setError(isError: boolean): void {
449
- digito.setError(isError)
450
- sync(true)
451
- }
452
-
453
- function focus(slotIndex: number): void {
454
- digito.moveFocusTo(slotIndex)
455
- inputRef.value?.focus()
456
- requestAnimationFrame(() => inputRef.value?.setSelectionRange(slotIndex, slotIndex))
457
- sync(true)
458
- }
459
-
460
- function getCode(): string {
461
- return digito.getCode()
462
- }
463
-
464
- return {
465
- slotValues,
466
- activeSlot,
467
- value,
468
- isComplete,
469
- hasError,
470
- isDisabled,
471
- timerSeconds,
472
- isFocused,
473
- separatorAfter,
474
- separator,
475
- masked,
476
- maskChar,
477
- placeholder: placeholderOpt,
478
- inputRef,
479
- hiddenInputAttrs,
480
- wrapperAttrs,
481
- getCode,
482
- reset,
483
- setError,
484
- focus,
485
- onKeydown,
486
- onChange,
487
- onPaste,
488
- onFocus,
489
- onBlur,
490
- }
491
- }