maskarajs 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +338 -0
- package/mask.cjs.js +874 -0
- package/mask.d.ts +291 -0
- package/mask.js +874 -0
- package/mask.mjs +874 -0
- package/package.json +31 -0
package/mask.d.ts
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mask.d.ts
|
|
3
|
+
*
|
|
4
|
+
* Tipagens com parâmetro de registry para autocomplete de nomes registrados.
|
|
5
|
+
*
|
|
6
|
+
* Uso básico (sem generics — funciona, sem autocomplete de nomes):
|
|
7
|
+
* import mask from './mask.js'
|
|
8
|
+
* mask('cpf', value)
|
|
9
|
+
*
|
|
10
|
+
* Uso tipado (com autocomplete de nomes):
|
|
11
|
+
* const m = mask.create<{ cpf: string; date: Date | null; money: number }>({
|
|
12
|
+
* cpf: { pattern: '###[.]###[.]###[-]##' },
|
|
13
|
+
* date: { pattern: '##[/]##[/]####', transform: ... },
|
|
14
|
+
* money: { pattern: '########[,]##', transform: ... },
|
|
15
|
+
* })
|
|
16
|
+
* m('cpf', value) // ← autocomplete sugere 'cpf' | 'date' | 'money'
|
|
17
|
+
* m.raw('date', value) // ← retorno inferido: Date | null
|
|
18
|
+
* m.raw('money', value) // ← retorno inferido: number
|
|
19
|
+
* m.raw('cpf', value) // ← retorno inferido: string
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
// ─── Primitivos ───────────────────────────────────────────────────────────
|
|
23
|
+
|
|
24
|
+
/** String de padrão declarativo ou array para padrões dinâmicos */
|
|
25
|
+
export type MaskPattern = string | string[]
|
|
26
|
+
|
|
27
|
+
/** Função de transformação — recebe (raw, masked, complete) e retorna T */
|
|
28
|
+
export type MaskTransform<T> = (raw: string, masked: string, complete: boolean) => T
|
|
29
|
+
|
|
30
|
+
/** Validação incremental — retorna false para recusar o próximo caractere */
|
|
31
|
+
export type MaskValidate = (raw: string, masked: string, complete: boolean) => boolean
|
|
32
|
+
|
|
33
|
+
/** Predicado usado por um slot customizado */
|
|
34
|
+
export type MaskSlotTest = (ch: string) => boolean
|
|
35
|
+
|
|
36
|
+
/** Definição completa de um slot customizado */
|
|
37
|
+
export interface MaskSlotDefinition {
|
|
38
|
+
test: MaskSlotTest
|
|
39
|
+
hint?: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Formas aceitas para registrar um slot customizado */
|
|
43
|
+
export type MaskSlotInput = MaskSlotTest | RegExp | MaskSlotDefinition
|
|
44
|
+
|
|
45
|
+
/** Definição de uma máscara nomeada */
|
|
46
|
+
export interface MaskDefinition<T = string> {
|
|
47
|
+
pattern: MaskPattern
|
|
48
|
+
transform?: MaskTransform<T>
|
|
49
|
+
validate?: MaskValidate
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Opções de mask.on */
|
|
53
|
+
export interface MaskOnOptions<T> {
|
|
54
|
+
/** Chamado a cada keystroke com o valor limpo / resultado do transform */
|
|
55
|
+
onValue?: (value: T) => void
|
|
56
|
+
/** Chamado a cada keystroke com o valor mascarado (display) */
|
|
57
|
+
onMasked?: (masked: string) => void
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ─── Registry map ─────────────────────────────────────────────────────────
|
|
61
|
+
//
|
|
62
|
+
// R = Record dos nomes registrados com seus tipos de retorno do transform.
|
|
63
|
+
//
|
|
64
|
+
// Exemplo:
|
|
65
|
+
// type MyRegistry = {
|
|
66
|
+
// cpf: string // sem transform → string
|
|
67
|
+
// date: Date | null // transform retorna Date | null
|
|
68
|
+
// money: number // transform retorna number
|
|
69
|
+
// }
|
|
70
|
+
//
|
|
71
|
+
// Usado para inferir o tipo de retorno de raw() a partir do nome.
|
|
72
|
+
|
|
73
|
+
/** Extrai o tipo de retorno de raw() para um nome de máscara */
|
|
74
|
+
type RawReturn<R extends Record<string, unknown>, K extends keyof R | MaskPattern> =
|
|
75
|
+
K extends keyof R ? R[K] : string
|
|
76
|
+
|
|
77
|
+
/** Union de nomes registrados + MaskPattern (para aceitar padrão literal também) */
|
|
78
|
+
type PatternOrName<R extends Record<string, unknown>> = keyof R | MaskPattern
|
|
79
|
+
|
|
80
|
+
// ─── MaskInstance ─────────────────────────────────────────────────────────
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Instância tipada retornada por mask.create<R>(presets).
|
|
84
|
+
*
|
|
85
|
+
* R = mapa de nomes para tipos de retorno do transform.
|
|
86
|
+
* Autocomplete sugere os nomes registrados em todos os métodos.
|
|
87
|
+
*/
|
|
88
|
+
export interface MaskInstance<R extends Record<string, unknown> = Record<string, string>> {
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Aplica máscara — retorna string formatada para exibição.
|
|
92
|
+
* @param pattern nome registrado (autocomplete) ou padrão literal
|
|
93
|
+
*/
|
|
94
|
+
<K extends PatternOrName<R>>(pattern: K, value: string | null | undefined): string
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Retorna o raw value passado pelo transform.
|
|
98
|
+
* O tipo de retorno é inferido automaticamente pelo nome registrado.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* m.raw('date', v) // → Date | null (inferido do registry)
|
|
102
|
+
* m.raw('money', v) // → number (inferido do registry)
|
|
103
|
+
* m.raw('cpf', v) // → string (inferido do registry)
|
|
104
|
+
*/
|
|
105
|
+
raw<K extends PatternOrName<R>>(
|
|
106
|
+
pattern: K,
|
|
107
|
+
value: string | null | undefined
|
|
108
|
+
): RawReturn<R, K>
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Verifica se o valor preenche completamente o padrão.
|
|
112
|
+
*/
|
|
113
|
+
is<K extends PatternOrName<R>>(pattern: K, value: string | null | undefined): boolean
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Retorna o placeholder legível do padrão.
|
|
117
|
+
* @example m.hint('cpf') // → '000.000.000-00'
|
|
118
|
+
*/
|
|
119
|
+
hint<K extends PatternOrName<R>>(pattern: K): string
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Formata um valor vindo da API para exibição. Alias semântico de apply.
|
|
123
|
+
* @example m.format('cpf', user.cpf) // → '123.456.789-09'
|
|
124
|
+
*/
|
|
125
|
+
format<K extends PatternOrName<R>>(pattern: K, value: string | null | undefined): string
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Comprimento do raw atual — chars de input preenchidos (sem literais).
|
|
129
|
+
* Nunca passa pelo transform. Útil para progress bars.
|
|
130
|
+
* @example
|
|
131
|
+
* const pct = m.rawLength('cpf', v) / m.patternLength('cpf') * 100
|
|
132
|
+
*/
|
|
133
|
+
rawLength<K extends PatternOrName<R>>(pattern: K, value: string | null | undefined): number
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Comprimento total do valor mascarado completo.
|
|
137
|
+
* Conta slots como 1 caractere e literais pelo tamanho real.
|
|
138
|
+
* Para arrays, retorna o maior valor mascarado possível.
|
|
139
|
+
*/
|
|
140
|
+
patternLength<K extends PatternOrName<R>>(pattern: K): number
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Registra uma nova máscara nesta instância.
|
|
144
|
+
* Não afeta outras instâncias nem o registry global.
|
|
145
|
+
*/
|
|
146
|
+
define<N extends string, T = string>(name: N, definition: MaskDefinition<T>): void
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Remove uma máscara desta instância.
|
|
150
|
+
*/
|
|
151
|
+
undefine<K extends keyof R>(name: K): void
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Lista os nomes registrados nesta instância.
|
|
155
|
+
*/
|
|
156
|
+
names(): Array<keyof R & string>
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Cria ou sobrescreve um símbolo de slot apenas nesta instância.
|
|
160
|
+
* Use [N] quando precisar tratar um símbolo registrado como literal.
|
|
161
|
+
*/
|
|
162
|
+
defineSlot(symbol: string, definition: MaskSlotInput): void
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Remove um slot desta instância.
|
|
166
|
+
* Slots padrão (#, @, *) voltam ao comportamento original.
|
|
167
|
+
*/
|
|
168
|
+
undefineSlot(symbol: string): void
|
|
169
|
+
|
|
170
|
+
/** Lista os símbolos de slot disponíveis nesta instância */
|
|
171
|
+
slots(): string[]
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Vincula máscara a um input DOM. Retorna cleanup().
|
|
175
|
+
* Framework-agnostic — funciona em React, Vue, Svelte, Vanilla.
|
|
176
|
+
*
|
|
177
|
+
* @example
|
|
178
|
+
* // React
|
|
179
|
+
* useEffect(() => m.on(ref.current, 'date', { onValue: setDate }), [])
|
|
180
|
+
*
|
|
181
|
+
* // Vue
|
|
182
|
+
* onMounted(() => m.on(inputRef.value, 'phone', { onValue: v => emit('update:modelValue', v) }))
|
|
183
|
+
*
|
|
184
|
+
* // Svelte action
|
|
185
|
+
* const maskAction = (node, name) => ({ destroy: m.on(node, name) })
|
|
186
|
+
*/
|
|
187
|
+
on<K extends PatternOrName<R>>(
|
|
188
|
+
input: HTMLInputElement,
|
|
189
|
+
pattern: K,
|
|
190
|
+
options?: MaskOnOptions<RawReturn<R, K>>
|
|
191
|
+
): () => void
|
|
192
|
+
|
|
193
|
+
/** Cria uma sub-instância com registry próprio */
|
|
194
|
+
create<S extends Record<string, unknown>>(
|
|
195
|
+
presets?: { [K in keyof S]: MaskDefinition<S[K]> }
|
|
196
|
+
): MaskInstance<S>
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// ─── Função principal (registry global, sem generics de nome) ─────────────
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Aplica máscara a um valor.
|
|
203
|
+
*
|
|
204
|
+
* @example
|
|
205
|
+
* mask('###[.]###[.]###[-]##', '12345678909') // → '123.456.789-09'
|
|
206
|
+
* mask(['[(]##[)] ####[-]####', '[(]##[)] #####[-]####'], '11987654321')
|
|
207
|
+
*/
|
|
208
|
+
export declare function mask(pattern: MaskPattern, value: string | null | undefined): string
|
|
209
|
+
|
|
210
|
+
export declare namespace mask {
|
|
211
|
+
|
|
212
|
+
/** Retorna o raw value / resultado do transform */
|
|
213
|
+
function raw<T = string>(pattern: MaskPattern, value: string | null | undefined): T
|
|
214
|
+
|
|
215
|
+
/** Verifica se o valor preenche completamente o padrão */
|
|
216
|
+
function is(pattern: MaskPattern, value: string | null | undefined): boolean
|
|
217
|
+
|
|
218
|
+
/** Retorna o placeholder legível do padrão */
|
|
219
|
+
function hint(pattern: MaskPattern): string
|
|
220
|
+
|
|
221
|
+
/** Alias semântico de mask() para formatar valores da API */
|
|
222
|
+
function format(pattern: MaskPattern, value: string | null | undefined): string
|
|
223
|
+
|
|
224
|
+
/** Chars de input preenchidos — sem literais, sem transform */
|
|
225
|
+
function rawLength(pattern: MaskPattern, value: string | null | undefined): number
|
|
226
|
+
|
|
227
|
+
/** Comprimento total do valor mascarado completo */
|
|
228
|
+
function patternLength(pattern: MaskPattern): number
|
|
229
|
+
|
|
230
|
+
/** Registra máscara nomeada no registry global */
|
|
231
|
+
function define<T = string>(name: string, definition: MaskDefinition<T>): void
|
|
232
|
+
|
|
233
|
+
/** Remove máscara do registry global */
|
|
234
|
+
function undefine(name: string): void
|
|
235
|
+
|
|
236
|
+
/** Lista nomes do registry global */
|
|
237
|
+
function names(): string[]
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Cria ou sobrescreve um símbolo de slot no engine global.
|
|
241
|
+
* Use [N] quando precisar tratar um símbolo registrado como literal.
|
|
242
|
+
*/
|
|
243
|
+
function defineSlot(symbol: string, definition: MaskSlotInput): void
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Remove um slot global.
|
|
247
|
+
* Slots padrão (#, @, *) voltam ao comportamento original.
|
|
248
|
+
*/
|
|
249
|
+
function undefineSlot(symbol: string): void
|
|
250
|
+
|
|
251
|
+
/** Lista os símbolos de slot disponíveis no engine global */
|
|
252
|
+
function slots(): string[]
|
|
253
|
+
|
|
254
|
+
/** Vincula máscara a input DOM — retorna cleanup() */
|
|
255
|
+
function on<T = string>(
|
|
256
|
+
input: HTMLInputElement,
|
|
257
|
+
pattern: MaskPattern,
|
|
258
|
+
options?: MaskOnOptions<T>
|
|
259
|
+
): () => void
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Cria uma instância isolada com registry próprio e tipos inferidos.
|
|
263
|
+
*
|
|
264
|
+
* O generic R mapeia cada nome ao tipo de retorno do seu transform —
|
|
265
|
+
* isso habilita autocomplete de nomes e inferência de tipo em raw().
|
|
266
|
+
*
|
|
267
|
+
* @example
|
|
268
|
+
* const m = mask.create<{
|
|
269
|
+
* cpf: string
|
|
270
|
+
* date: Date | null
|
|
271
|
+
* money: number
|
|
272
|
+
* }>({
|
|
273
|
+
* cpf: { pattern: '###[.]###[.]###[-]##' },
|
|
274
|
+
* date: { pattern: '##[/]##[/]####', transform: (r,_,c) => c ? new Date(...) : null },
|
|
275
|
+
* money: { pattern: '########[,]##', transform: r => parseInt(r||'0',10)/100 },
|
|
276
|
+
* })
|
|
277
|
+
*
|
|
278
|
+
* m('cpf', v) // autocomplete: 'cpf' | 'date' | 'money'
|
|
279
|
+
* m.raw('date', v) // → Date | null ✓
|
|
280
|
+
* m.raw('money', v) // → number ✓
|
|
281
|
+
* m.rawLength('cpf', v) // → number ✓
|
|
282
|
+
* m.on(el, 'date', {
|
|
283
|
+
* onValue: date => ... // date: Date | null ✓ (inferido)
|
|
284
|
+
* })
|
|
285
|
+
*/
|
|
286
|
+
function create<R extends Record<string, unknown> = Record<string, string>>(
|
|
287
|
+
presets?: { [K in keyof R]: MaskDefinition<R[K]> }
|
|
288
|
+
): MaskInstance<R>
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export default mask
|