-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
index.js
192 lines (148 loc) · 6.26 KB
/
index.js
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
export default function (Alpine) {
Alpine.directive('mask', (el, { value, expression }, { effect, evaluateLater, cleanup }) => {
let templateFn = () => expression
let lastInputValue = ''
queueMicrotask(() => {
if (['function', 'dynamic'].includes(value)) {
// This is an x-mask:function directive.
let evaluator = evaluateLater(expression)
effect(() => {
templateFn = input => {
let result
// We need to prevent "auto-evaluation" of functions like
// x-on expressions do so that we can use them as mask functions.
Alpine.dontAutoEvaluateFunctions(() => {
evaluator(value => {
result = typeof value === 'function' ? value(input) : value
}, { scope: {
// These are "magics" we'll make available to the x-mask:function:
'$input': input,
'$money': formatMoney.bind({ el }),
}})
})
return result
}
// Run on initialize which serves a dual purpose:
// - Initializing the mask on the input if it has an initial value.
// - Running the template function to set up reactivity, so that
// when a dependency inside it changes, the input re-masks.
processInputValue(el, false)
})
} else {
processInputValue(el, false)
}
// Override x-model's initial value...
if (el._x_model) el._x_model.set(el.value)
})
const controller = new AbortController()
cleanup(() => {
controller.abort()
})
el.addEventListener('input', () => processInputValue(el), {
signal: controller.signal,
// Setting this as a capture phase listener to ensure it runs
// before wire:model or x-model added as a latent binding...
capture: true,
})
// Don't "restoreCursorPosition" on "blur", because Safari
// will re-focus the input and cause a focus trap.
el.addEventListener('blur', () => processInputValue(el, false), { signal: controller.signal })
function processInputValue (el, shouldRestoreCursor = true) {
let input = el.value
let template = templateFn(input)
// If a template value is `falsy`, then don't process the input value
if(!template || template === 'false') return false
// If they hit backspace, don't process input.
if (lastInputValue.length - el.value.length === 1) {
return lastInputValue = el.value
}
let setInput = () => {
lastInputValue = el.value = formatInput(template,input)
}
if (shouldRestoreCursor) {
// When an input element's value is set, it moves the cursor to the end
// therefore we need to track, estimate, and restore the cursor after
// a change was made.
restoreCursorPosition(el, template, () => {
setInput()
})
} else {
setInput()
}
}
}).before('model')
}
export function restoreCursorPosition(el, template, callback) {
let cursorPosition = el.selectionStart
let unformattedValue = el.value
callback()
let beforeLeftOfCursorBeforeFormatting = unformattedValue.slice(0, cursorPosition)
let newPosition = formatInput(
template, beforeLeftOfCursorBeforeFormatting
).length
el.setSelectionRange(newPosition, newPosition)
}
let regexes = {
'9': /[0-9]/,
'a': /[a-zA-Z]/,
'*': /[a-zA-Z0-9]/,
}
export function formatInput(template, input) {
let templateMark = 0
let inputMark = 0
let output = ''
// Walk the template and input chars simultaneously one by one...
while (templateMark < template.length && inputMark < input.length) {
let templateChar = template[templateMark]
let inputChar = input[inputMark]
// We've encountered a template placeholder...
if (templateChar in regexes) {
// If the input is "allowed" based on the placeholder...
if (regexes[templateChar].test(inputChar)) {
output += inputChar
templateMark++
}
inputMark++
} else { // We've encountered a template literal...
output += templateChar
templateMark++
if (templateChar === input[inputMark]) inputMark++
}
}
return output
}
export function formatMoney(input, delimiter = '.', thousands, precision = 2) {
if (input === '-') return '-'
if (/^\D+$/.test(input)) return '9'
if (thousands === null || thousands === undefined) {
thousands = delimiter === "," ? "." : ","
}
let addThousands = (input, thousands) => {
let output = ''
let counter = 0
for (let i = input.length - 1; i >= 0; i--) {
if (input[i] === thousands) continue;
if (counter === 3) {
output = input[i] + thousands + output
counter = 0
} else {
output = input[i] + output
}
counter++
}
return output
}
let minus = input.startsWith('-') ? '-' : ''
let strippedInput = input.replaceAll(new RegExp(`[^0-9\\${delimiter}]`, 'g'), '')
let template = Array.from({length: strippedInput.split(delimiter)[0].length}).fill('9').join('')
template = `${minus}${addThousands(template, thousands)}`
if (precision > 0 && input.includes(delimiter))
template += `${delimiter}` + '9'.repeat(precision)
queueMicrotask(() => {
if (this.el.value.endsWith(delimiter)) return
if (this.el.value[this.el.selectionStart - 1] === delimiter) {
this.el.setSelectionRange(this.el.selectionStart - 1, this.el.selectionStart - 1)
}
})
return template
}