mirror of
https://github.com/tenrok/maska.git
synced 2026-05-15 11:59:38 +03:00
48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
import { Directive } from 'vue'
|
|
import { MaskaDetail, MaskInput, MaskInputOptions } from './mask-input'
|
|
|
|
type MaskaDirective = Directive<HTMLElement, MaskaDetail | undefined>
|
|
|
|
const masks = new WeakMap<HTMLInputElement, MaskInput>()
|
|
|
|
export const vMaska: MaskaDirective = (el, binding) => {
|
|
const input = el instanceof HTMLInputElement ? el : el.querySelector('input')
|
|
const opts = { ...(binding.arg as MaskInputOptions) } ?? {}
|
|
|
|
if (input == null) return
|
|
|
|
const existed = masks.get(input)
|
|
if (existed != null) {
|
|
if (!existed.needUpdate(input, opts)) {
|
|
return
|
|
}
|
|
|
|
existed.destroy()
|
|
}
|
|
|
|
if (binding.value != null) {
|
|
const binded = binding.value
|
|
const onMaska = (detail: MaskaDetail): void => {
|
|
binded.masked = detail.masked
|
|
binded.unmasked = detail.unmasked
|
|
binded.completed = detail.completed
|
|
}
|
|
|
|
opts.onMaska =
|
|
opts.onMaska == null
|
|
? onMaska
|
|
: Array.isArray(opts.onMaska)
|
|
? [...opts.onMaska, onMaska]
|
|
: [opts.onMaska, onMaska]
|
|
}
|
|
|
|
masks.set(input, new MaskInput(input, opts))
|
|
|
|
// check initial value for v-model
|
|
setTimeout(() => {
|
|
if (input.value !== '') {
|
|
input.dispatchEvent(new InputEvent('input'))
|
|
}
|
|
})
|
|
}
|