wulf.js 1.9.1 → 1.9.3

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.
Files changed (71) hide show
  1. package/README.md +160 -21
  2. package/changelog.md +66 -0
  3. package/dist/focus-trap.esm.js +62 -9
  4. package/dist/focus-trap.esm.js.map +2 -2
  5. package/dist/focus-trap.global.js +64 -11
  6. package/dist/focus-trap.global.js.map +2 -2
  7. package/dist/focus-trap.global.min.js +3 -3
  8. package/dist/focus-trap.global.min.js.map +3 -3
  9. package/dist/index.esm.js +947 -101
  10. package/dist/index.esm.js.map +4 -4
  11. package/dist/index.global.js +949 -103
  12. package/dist/index.global.js.map +4 -4
  13. package/dist/index.global.min.js +3 -3
  14. package/dist/index.global.min.js.map +4 -4
  15. package/dist/mask.esm.js +66 -22
  16. package/dist/mask.esm.js.map +2 -2
  17. package/dist/mask.global.js +68 -24
  18. package/dist/mask.global.js.map +2 -2
  19. package/dist/mask.global.min.js +3 -3
  20. package/dist/mask.global.min.js.map +3 -3
  21. package/dist/masonry.esm.js +96 -40
  22. package/dist/masonry.esm.js.map +2 -2
  23. package/dist/masonry.global.js +98 -42
  24. package/dist/masonry.global.js.map +2 -2
  25. package/dist/masonry.global.min.js +3 -3
  26. package/dist/masonry.global.min.js.map +3 -3
  27. package/dist/scroll.esm.js +66 -28
  28. package/dist/scroll.esm.js.map +2 -2
  29. package/dist/scroll.global.js +68 -30
  30. package/dist/scroll.global.js.map +2 -2
  31. package/dist/scroll.global.min.js +4 -4
  32. package/dist/scroll.global.min.js.map +3 -3
  33. package/dist/shortcut.esm.js +631 -0
  34. package/dist/shortcut.esm.js.map +7 -0
  35. package/dist/shortcut.global.js +657 -0
  36. package/dist/shortcut.global.js.map +7 -0
  37. package/dist/shortcut.global.min.js +3 -0
  38. package/dist/shortcut.global.min.js.map +7 -0
  39. package/dist/toast.css +1 -1
  40. package/dist/toast.css.map +2 -2
  41. package/dist/toast.esm.js +109 -44
  42. package/dist/toast.esm.js.map +2 -2
  43. package/dist/toast.global.js +111 -46
  44. package/dist/toast.global.js.map +2 -2
  45. package/dist/toast.global.min.js +4 -4
  46. package/dist/toast.global.min.js.map +3 -3
  47. package/dist/types/focus-trap/FocusTrap.d.ts +2 -0
  48. package/dist/types/index.d.ts +2 -0
  49. package/dist/types/mask/AmountEngine.d.ts +1 -0
  50. package/dist/types/mask/BaseInputMask.d.ts +4 -0
  51. package/dist/types/mask/InputAmountMask.d.ts +1 -0
  52. package/dist/types/mask/InputMask.d.ts +1 -0
  53. package/dist/types/shortcut/ShortcutFormatter.d.ts +31 -0
  54. package/dist/types/shortcut/ShortcutManager.d.ts +95 -0
  55. package/dist/types/shortcut/index.d.ts +4 -0
  56. package/dist/types/shortcut/types.d.ts +101 -0
  57. package/dist/types/toast/ToastInstance.d.ts +1 -1
  58. package/dist/types/toast/types.d.ts +5 -0
  59. package/package.json +20 -11
  60. package/dist/focus-trap.cjs.js +0 -430
  61. package/dist/focus-trap.cjs.js.map +0 -7
  62. package/dist/index.cjs.js +0 -5365
  63. package/dist/index.cjs.js.map +0 -7
  64. package/dist/mask.cjs.js +0 -3086
  65. package/dist/mask.cjs.js.map +0 -7
  66. package/dist/masonry.cjs.js +0 -858
  67. package/dist/masonry.cjs.js.map +0 -7
  68. package/dist/scroll.cjs.js +0 -823
  69. package/dist/scroll.cjs.js.map +0 -7
  70. package/dist/toast.cjs.js +0 -715
  71. package/dist/toast.cjs.js.map +0 -7
package/dist/mask.cjs.js DELETED
@@ -1,3086 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/mask/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- AmountEngine: () => AmountEngine,
24
- BaseInputMask: () => BaseInputMask,
25
- EmailEngine: () => EmailEngine,
26
- InputAmountMask: () => InputAmountMask,
27
- InputEmailMask: () => InputEmailMask,
28
- InputMask: () => InputMask,
29
- Mask: () => Mask,
30
- MaskEngine: () => MaskEngine,
31
- MaskHistory: () => MaskHistory,
32
- MaskKeyboard: () => MaskKeyboard,
33
- default: () => index_default,
34
- resolveMaskConstructorArgs: () => resolveMaskConstructorArgs
35
- });
36
- module.exports = __toCommonJS(index_exports);
37
-
38
- // src/common/AuditableComponent.ts
39
- var AuditableComponent = class {
40
- /**
41
- * Indication affichée en pied de warning pour expliquer comment désactiver l'audit.
42
- */
43
- getAuditDisableHint() {
44
- return "Passez { audit: false } dans les options pour d\xE9sactiver cet avertissement";
45
- }
46
- /**
47
- * Exécute l'audit d'accessibilité et émet un avertissement standardisé dans la console
48
- * si l'audit est activé et que des contraintes manquent.
49
- */
50
- runAuditWarning(enabled = true) {
51
- if (!enabled) return [];
52
- const warnings = this.audit();
53
- if (warnings.length > 0 && typeof console !== "undefined" && typeof console.warn === "function") {
54
- console.warn(
55
- `[${this.getAuditPrefix()}] Audit d'accessibilit\xE9 \u2014 ${warnings.length} contrainte(s) manquante(s) sur ${this.getAuditTargetLabel()} :
56
- ` + warnings.map((w) => ` - ${w}`).join("\n") + `
57
- (${this.getAuditDisableHint()})`
58
- );
59
- }
60
- return warnings;
61
- }
62
- /**
63
- * Vérifie si un attribut de référence d'IDs ARIA (ex: aria-labelledby, aria-describedby)
64
- * pointe vers des éléments réellement présents dans le document.
65
- */
66
- checkAriaIdReferences(element, attrName, warnings) {
67
- const rawValue = element.getAttribute(attrName)?.trim();
68
- if (!rawValue) return false;
69
- const doc = element.ownerDocument || document;
70
- const ids = rawValue.split(/\s+/).filter(Boolean);
71
- const isValid = ids.length > 0 && ids.every((id) => Boolean(doc.getElementById(id)));
72
- if (!isValid) {
73
- warnings.push(
74
- `Attribut ${attrName}="${rawValue}" invalide : l'\xE9l\xE9ment cible est introuvable dans le DOM.`
75
- );
76
- }
77
- return isValid;
78
- }
79
- };
80
-
81
- // src/mask/BaseInputMask.ts
82
- function resolveMaskConstructorArgs(targetOrWrapper, inputOrOptions, maybeOptions) {
83
- const isSecondArgInput = Boolean(
84
- inputOrOptions && typeof inputOrOptions === "object" && "tagName" in inputOrOptions && inputOrOptions.tagName === "INPUT"
85
- );
86
- if (isSecondArgInput) {
87
- return {
88
- wrapper: targetOrWrapper || null,
89
- input: inputOrOptions,
90
- options: maybeOptions || {}
91
- };
92
- }
93
- return {
94
- wrapper: null,
95
- input: targetOrWrapper,
96
- options: inputOrOptions && typeof inputOrOptions === "object" && !("tagName" in inputOrOptions) ? inputOrOptions : {}
97
- };
98
- }
99
- var BaseInputMask = class extends AuditableComponent {
100
- constructor(targetOrWrapper, inputOrOptions, maybeOptions) {
101
- super();
102
- this.ghost = null;
103
- this.isWrapperCreated = false;
104
- this.isDestroyed = false;
105
- this.isFocused = false;
106
- this.isDispatchingNativeInput = false;
107
- this.lastTrackedValue = "";
108
- this.nativeValueDescriptor = null;
109
- this.onCutHandler = () => {
110
- };
111
- this.mutationObserver = null;
112
- this.focusSelectTimerId = null;
113
- this.onBaseCopy = (e) => {
114
- if (!this.options.copyRaw || this.options.disabled || this.input.type === "password") return;
115
- const start = this.input.selectionStart ?? 0;
116
- const end = this.input.selectionEnd ?? start;
117
- let textToCopy = "";
118
- if (start !== end) {
119
- textToCopy = this.extractRawSnippet(this.input.value.slice(start, end));
120
- } else {
121
- textToCopy = this.getRawValue();
122
- }
123
- if (textToCopy && e.clipboardData) {
124
- e.preventDefault();
125
- e.clipboardData.setData("text/plain", textToCopy);
126
- }
127
- };
128
- this.onBaseFocus = () => {
129
- this.isFocused = true;
130
- if (this.options.selectAllOnFocus && this.input.value.length > 0) {
131
- if (this.focusSelectTimerId !== null) {
132
- clearTimeout(this.focusSelectTimerId);
133
- }
134
- this.focusSelectTimerId = window.setTimeout(() => {
135
- this.focusSelectTimerId = null;
136
- if (!this.isDestroyed && document.activeElement === this.input) {
137
- this.input.select();
138
- }
139
- }, 0);
140
- }
141
- };
142
- this.onBaseBlur = () => {
143
- this.isFocused = false;
144
- };
145
- /**
146
- * Synchronise le défilement horizontal du ghost avec celui du champ d'entrée natif.
147
- */
148
- this.onScroll = () => {
149
- if (this.ghost) {
150
- this.ghost.scrollLeft = this.input.scrollLeft;
151
- }
152
- };
153
- const { wrapper: providedWrapper, input, options } = resolveMaskConstructorArgs(targetOrWrapper, inputOrOptions, maybeOptions);
154
- if (!input || typeof input !== "object" || input.nodeType !== 1 || input.tagName !== "INPUT") {
155
- throw new Error(`[${new.target.name || "InputMask"}] input (HTMLInputElement) est requis.`);
156
- }
157
- this.input = input;
158
- const dataCreateWrapper = this.input.getAttribute("data-mask-create-wrapper") === "true";
159
- const shouldCreateWrapper = Boolean(options.createWrapper ?? dataCreateWrapper);
160
- let effectiveWrapper = providedWrapper;
161
- if (!effectiveWrapper && shouldCreateWrapper) {
162
- const span = document.createElement("span");
163
- span.className = "wulf-mask-wrapper";
164
- span.style.display = "inline-grid";
165
- span.style.gridTemplateColumns = "1fr";
166
- span.style.gridTemplateRows = "1fr";
167
- span.style.verticalAlign = "middle";
168
- span.style.boxSizing = "border-box";
169
- span.style.position = "relative";
170
- if (this.input.parentNode) {
171
- this.input.parentNode.insertBefore(span, this.input);
172
- }
173
- span.appendChild(this.input);
174
- this.input.style.gridArea = "1 / 1 / 2 / 2";
175
- this.input.style.boxSizing = "border-box";
176
- effectiveWrapper = span;
177
- this.isWrapperCreated = true;
178
- }
179
- if (!effectiveWrapper) {
180
- throw new Error(`[${new.target.name || "InputMask"}] wrapper (HTMLElement) et input (HTMLInputElement) sont requis, ou activez l'option createWrapper: true.`);
181
- }
182
- this.wrapper = effectiveWrapper;
183
- this.normalizeInputType();
184
- const dataFocusOnly = this.getAttr("data-mask-focus-only") === "true";
185
- const dataDisabled = this.hasAttr("data-disabled");
186
- const dataSelectAll = this.getAttr("data-mask-select-on-focus") === "true";
187
- const dataCopyRaw = this.getAttr("data-mask-copy-raw") === "true";
188
- const dataAlign = this.getAttr("data-mask-align") || this.getAttr("data-align");
189
- const dataAudit = this.getAttr("data-mask-audit");
190
- const { disabled: optDisabled, align: optAlign, ...otherOptions } = options;
191
- const resolvedDisabled = optDisabled !== void 0 ? optDisabled : dataDisabled ? true : false;
192
- const resolvedAudit = options.audit ?? (dataAudit !== null ? dataAudit !== "false" : true);
193
- const isPassword = this.input.type === "password";
194
- this.options = {
195
- ...otherOptions,
196
- createWrapper: shouldCreateWrapper,
197
- showMaskOnFocus: options.showMaskOnFocus ?? dataFocusOnly ?? false,
198
- selectAllOnFocus: options.selectAllOnFocus ?? dataSelectAll ?? false,
199
- copyRaw: isPassword ? false : options.copyRaw ?? dataCopyRaw ?? false,
200
- disabled: resolvedDisabled,
201
- align: optAlign ?? (dataAlign || void 0),
202
- emitNativeInput: options.emitNativeInput ?? true,
203
- audit: resolvedAudit
204
- };
205
- if (this.options.showMaskOnFocus) {
206
- this.wrapper.classList.add("mask-focus-only");
207
- }
208
- if (this.options.disabled) {
209
- this.wrapper.setAttribute("data-disabled", "true");
210
- }
211
- if (this.options.align) {
212
- this.setAlign(this.options.align);
213
- }
214
- this.createGhost();
215
- this.hookValueProperty();
216
- this.bindBaseEvents();
217
- this.initMutationObserver();
218
- }
219
- /**
220
- * Récupère un attribut depuis le wrapper ou l'input natif.
221
- */
222
- getAttr(name) {
223
- return this.input.getAttribute(name) || this.wrapper.getAttribute(name);
224
- }
225
- /**
226
- * Vérifie la présence d'un attribut sur le wrapper ou l'input natif.
227
- */
228
- hasAttr(name) {
229
- return this.wrapper.hasAttribute(name) || this.input.hasAttribute(name);
230
- }
231
- /**
232
- * Indique si un placeholder natif non vide est configuré sur l'input.
233
- */
234
- hasNativePlaceholder() {
235
- return Boolean(this.input.placeholder && this.input.placeholder.trim().length > 0);
236
- }
237
- /**
238
- * Détermine si le masque fantôme doit s'effacer pour laisser place au placeholder natif
239
- * lorsque le champ est vide et n'a pas le focus.
240
- */
241
- shouldHideGhostForPlaceholder(isInputEmpty) {
242
- return !this.isFocused && isInputEmpty && this.hasNativePlaceholder();
243
- }
244
- /**
245
- * Attache les écouteurs de base pour focus/blur, copie brute et sélection.
246
- */
247
- bindBaseEvents() {
248
- this.input.addEventListener("copy", this.onBaseCopy);
249
- this.input.addEventListener("focus", this.onBaseFocus);
250
- this.input.addEventListener("blur", this.onBaseBlur);
251
- }
252
- /**
253
- * Extrait la valeur brute d'un extrait de chaîne sélectionné.
254
- */
255
- extractRawSnippet(snippet) {
256
- return snippet;
257
- }
258
- /**
259
- * Initialise l'observation des modifications dynamiques des attributs data-* et placeholder.
260
- */
261
- initMutationObserver() {
262
- if (typeof MutationObserver === "undefined") return;
263
- this.mutationObserver = new MutationObserver((mutations) => {
264
- for (const m of mutations) {
265
- if (m.type === "attributes" && m.attributeName) {
266
- this.handleAttributeMutation(m.attributeName);
267
- }
268
- }
269
- });
270
- const config = {
271
- attributes: true,
272
- attributeFilter: [
273
- "data-mask",
274
- "data-mask-placeholder",
275
- "data-mask-focus-only",
276
- "data-mask-strict",
277
- "data-mask-select-on-focus",
278
- "data-mask-copy-raw",
279
- "data-mask-pad-decimals",
280
- "data-mask-auto-lowercase",
281
- "data-mask-cycle-suggestions",
282
- "data-mask-default-tld",
283
- "data-mask-tlds",
284
- "data-disabled",
285
- "data-mask-align",
286
- "data-align",
287
- "placeholder"
288
- ]
289
- };
290
- this.mutationObserver.observe(this.wrapper, config);
291
- if (this.input !== this.wrapper) {
292
- this.mutationObserver.observe(this.input, config);
293
- }
294
- }
295
- /**
296
- * Modifie dynamiquement l'alignement du champ et du masque fantôme.
297
- */
298
- setAlign(align) {
299
- const targetAlign = align || void 0;
300
- const currentAttr = this.wrapper.getAttribute("data-align");
301
- if (this.options.align === targetAlign && currentAttr === (align || null)) {
302
- return;
303
- }
304
- this.options.align = targetAlign;
305
- this.wrapper.classList.remove("align-left", "align-right", "align-center");
306
- if (align) {
307
- this.wrapper.classList.add(`align-${align}`);
308
- if (this.wrapper.getAttribute("data-align") !== align) {
309
- this.wrapper.setAttribute("data-align", align);
310
- }
311
- } else {
312
- if (this.wrapper.hasAttribute("data-align")) {
313
- this.wrapper.removeAttribute("data-align");
314
- }
315
- }
316
- this.syncGhostStyles();
317
- }
318
- /**
319
- * Crochet appelé lorsqu'un attribut pertinent a été modifié dynamiquement à la volée.
320
- */
321
- handleAttributeMutation(attrName) {
322
- if (attrName === "data-disabled") {
323
- const isDisabled = this.hasAttr("data-disabled");
324
- if (isDisabled !== Boolean(this.options.disabled)) {
325
- this.setDisabled(isDisabled);
326
- }
327
- } else if (attrName === "data-mask-focus-only") {
328
- const focusOnly = this.getAttr("data-mask-focus-only") === "true";
329
- if (focusOnly !== Boolean(this.options.showMaskOnFocus)) {
330
- this.setShowMaskOnFocus(focusOnly);
331
- }
332
- } else if (attrName === "data-mask-select-on-focus") {
333
- this.options.selectAllOnFocus = this.getAttr("data-mask-select-on-focus") === "true";
334
- } else if (attrName === "data-mask-copy-raw") {
335
- this.options.copyRaw = this.getAttr("data-mask-copy-raw") === "true";
336
- } else if (attrName === "data-mask-align" || attrName === "data-align") {
337
- const align = this.getAttr("data-mask-align") || this.getAttr("data-align");
338
- if (align !== (this.options.align ?? null)) {
339
- this.setAlign(align);
340
- }
341
- }
342
- }
343
- /**
344
- * Corrige les types d'input natifs incompatibles avec setSelectionRange (ex: number, email, date).
345
- */
346
- normalizeInputType() {
347
- const incompatibleTypes = ["number", "email", "date", "datetime-local", "month", "week", "time", "color", "file", "range"];
348
- if (this.input.type && incompatibleTypes.includes(this.input.type.toLowerCase())) {
349
- const origType = this.input.type.toLowerCase();
350
- this.input.type = "text";
351
- if (origType === "number") {
352
- this.input.inputMode = "numeric";
353
- }
354
- }
355
- }
356
- /**
357
- * Crée l'élément d'arrière-plan fantôme garantissant un rendu sans superposition
358
- * ni altération de couleur, compatible avec les polices proportionnelles et monospaces.
359
- */
360
- createGhost() {
361
- const existing = this.wrapper.querySelector(".mask-ghost");
362
- if (existing) {
363
- existing.remove();
364
- }
365
- this.ghost = document.createElement("div");
366
- this.ghost.className = "mask-ghost";
367
- this.ghost.setAttribute("aria-hidden", "true");
368
- this.ghost.style.display = "flex";
369
- this.ghost.style.alignItems = "center";
370
- this.wrapper.appendChild(this.ghost);
371
- this.wrapper.classList.add("has-ghost");
372
- this.syncGhostStyles();
373
- }
374
- /**
375
- * Clone fidèlement la géométrie typographique et les espacements de l'input natif
376
- * sur le conteneur fantôme pour garantir un alignement sub-pixel absolu quel que soit
377
- * le style imposé par le framework parent (police, taille, padding, letter-spacing).
378
- */
379
- syncGhostStyles() {
380
- if (!this.ghost || typeof window === "undefined") return;
381
- const style = window.getComputedStyle(this.input);
382
- if (!style) return;
383
- this.ghost.style.fontFamily = style.fontFamily;
384
- this.ghost.style.fontSize = style.fontSize;
385
- this.ghost.style.fontWeight = style.fontWeight;
386
- this.ghost.style.fontStyle = style.fontStyle;
387
- this.ghost.style.letterSpacing = style.letterSpacing;
388
- this.ghost.style.lineHeight = style.lineHeight;
389
- this.ghost.style.paddingTop = style.paddingTop;
390
- this.ghost.style.paddingBottom = style.paddingBottom;
391
- this.ghost.style.paddingLeft = style.paddingLeft;
392
- this.ghost.style.paddingRight = style.paddingRight;
393
- this.ghost.style.borderTopWidth = style.borderTopWidth;
394
- this.ghost.style.borderBottomWidth = style.borderBottomWidth;
395
- this.ghost.style.borderLeftWidth = style.borderLeftWidth;
396
- this.ghost.style.borderRightWidth = style.borderRightWidth;
397
- this.ghost.style.borderTopStyle = style.borderTopStyle === "none" ? "none" : "solid";
398
- this.ghost.style.borderBottomStyle = style.borderBottomStyle === "none" ? "none" : "solid";
399
- this.ghost.style.borderLeftStyle = style.borderLeftStyle === "none" ? "none" : "solid";
400
- this.ghost.style.borderRightStyle = style.borderRightStyle === "none" ? "none" : "solid";
401
- this.ghost.style.borderColor = "transparent";
402
- this.ghost.style.boxSizing = style.boxSizing;
403
- this.ghost.style.textAlign = style.textAlign;
404
- this.ghost.style.direction = style.direction;
405
- const isRtl = style.direction === "rtl" || this.input.getAttribute("dir") === "rtl" || this.wrapper.getAttribute("dir") === "rtl";
406
- if (style.textAlign === "right" || style.textAlign === "end" || isRtl && style.textAlign !== "left" && style.textAlign !== "center") {
407
- this.ghost.style.justifyContent = "flex-end";
408
- } else if (style.textAlign === "center") {
409
- this.ghost.style.justifyContent = "center";
410
- } else {
411
- this.ghost.style.justifyContent = "flex-start";
412
- }
413
- }
414
- /**
415
- * Affecte directement la valeur native sans boucler sur le setter surchargé.
416
- */
417
- setNativeValue(val) {
418
- if (this.nativeValueDescriptor && this.nativeValueDescriptor.set) {
419
- this.nativeValueDescriptor.set.call(this.input, val);
420
- } else {
421
- this.input.value = val;
422
- }
423
- }
424
- /**
425
- * Émet l'événement 'input' natif W3C avec bulles pour synchroniser
426
- * les observateurs standards et les frameworks (React, Vue, Svelte, Angular).
427
- * Synchronise également le tracker de valeur interne de React (_valueTracker).
428
- */
429
- dispatchNativeInput() {
430
- if (this.isDestroyed || typeof window === "undefined") return;
431
- if (this.options.emitNativeInput === false) return;
432
- this.isDispatchingNativeInput = true;
433
- try {
434
- const tracker = this.input._valueTracker;
435
- if (tracker && typeof tracker.setValue === "function") {
436
- tracker.setValue(this.lastTrackedValue);
437
- }
438
- this.lastTrackedValue = this.input.value;
439
- this.input.dispatchEvent(new Event("input", { bubbles: true, cancelable: false }));
440
- } finally {
441
- this.isDispatchingNativeInput = false;
442
- }
443
- }
444
- /**
445
- * Intercepte les modifications directes de la propriété input.value (ex: input.value = '').
446
- */
447
- hookValueProperty() {
448
- try {
449
- const proto = HTMLInputElement.prototype;
450
- const desc = Object.getOwnPropertyDescriptor(proto, "value");
451
- if (!desc || !desc.set || !desc.get) return;
452
- this.nativeValueDescriptor = desc;
453
- const self = this;
454
- Object.defineProperty(this.input, "value", {
455
- get() {
456
- return desc.get.call(this);
457
- },
458
- set(newVal) {
459
- const strVal = String(newVal ?? "");
460
- desc.set.call(this, strVal);
461
- if (self.isDestroyed) return;
462
- self.onNativeValueSet(strVal);
463
- },
464
- configurable: true
465
- });
466
- } catch {
467
- }
468
- }
469
- /**
470
- * Supprime l'interception de input.value et restaure le comportement natif.
471
- */
472
- unhookValueProperty() {
473
- try {
474
- delete this.input.value;
475
- } catch {
476
- }
477
- }
478
- /**
479
- * Active ou désactive l'affichage du masque uniquement au focus.
480
- */
481
- setShowMaskOnFocus(enable) {
482
- this.options.showMaskOnFocus = enable;
483
- this.wrapper.classList.toggle("mask-focus-only", enable);
484
- }
485
- /**
486
- * Active ou désactive le masquage de saisie (getter / setter fluide).
487
- */
488
- disabled(disabledVal) {
489
- if (disabledVal === void 0) {
490
- return Boolean(this.options.disabled);
491
- }
492
- this.setDisabled(disabledVal);
493
- }
494
- /**
495
- * Active ou désactive le masquage / l'assistance de saisie.
496
- */
497
- setDisabled(disabled) {
498
- this.options.disabled = Boolean(disabled);
499
- if (this.options.disabled) {
500
- this.wrapper.setAttribute("data-disabled", "true");
501
- } else {
502
- this.wrapper.removeAttribute("data-disabled");
503
- }
504
- this.onDisabledChange(this.options.disabled);
505
- }
506
- /**
507
- /**
508
- * Retourne l'élément conteneur (wrapper).
509
- */
510
- getWrapper() {
511
- return this.wrapper;
512
- }
513
- /**
514
- * Retourne l'élément input natif sous-jacent.
515
- */
516
- getInput() {
517
- return this.input;
518
- }
519
- /**
520
- * Retourne l'élément fantôme (ghost) affichant le masque en arrière-plan.
521
- */
522
- getGhost() {
523
- return this.ghost;
524
- }
525
- /**
526
- * Retourne l'ensemble des éléments DOM associés au masque (wrapper, input, ghost).
527
- */
528
- getElements() {
529
- return {
530
- wrapper: this.wrapper,
531
- input: this.input,
532
- ghost: this.ghost
533
- };
534
- }
535
- /**
536
- * Retourne la valeur actuelle affichée dans l'input (formatée).
537
- */
538
- getValue() {
539
- return this.input.value;
540
- }
541
- /**
542
- * Retourne la valeur brute sans séparateurs.
543
- * Par défaut retourne la valeur de l'input si non surchargée.
544
- */
545
- getRawValue() {
546
- return this.input.value;
547
- }
548
- /**
549
- * Vérifie la conformité d'accessibilité WAI-ARIA du champ de saisie (étiquetage, format attendu)
550
- * et retourne la liste des contraintes manquantes.
551
- */
552
- audit() {
553
- const warnings = [];
554
- const doc = this.input.ownerDocument || document;
555
- const ariaLabel = this.input.getAttribute("aria-label")?.trim();
556
- const hasValidLabelledby = this.checkAriaIdReferences(this.input, "aria-labelledby", warnings);
557
- const hasWrappingLabel = Boolean(this.input.closest("label"));
558
- const hasNativeLabels = Boolean(this.input.labels && this.input.labels.length > 0);
559
- let hasExplicitLabelFor = false;
560
- if (this.input.id && typeof CSS !== "undefined" && typeof CSS.escape === "function") {
561
- hasExplicitLabelFor = Boolean(doc.querySelector(`label[for="${CSS.escape(this.input.id)}"]`));
562
- } else if (this.input.id) {
563
- hasExplicitLabelFor = Boolean(doc.querySelector(`label[for="${this.input.id}"]`));
564
- }
565
- if (!ariaLabel && !hasValidLabelledby && !hasWrappingLabel && !hasNativeLabels && !hasExplicitLabelFor) {
566
- warnings.push(
567
- `\xC9tiquetage accessible manquant : associez un <label for="id"> (ou d\xE9finissez aria-label / aria-labelledby) sur l'input (WCAG 4.1.2).`
568
- );
569
- }
570
- this.checkAriaIdReferences(this.input, "aria-describedby", warnings);
571
- const extraWarnings = this.getSpecificAuditWarnings();
572
- warnings.push(...extraWarnings);
573
- return warnings;
574
- }
575
- getAuditPrefix() {
576
- return `Wulf.Mask.${this.constructor.name || "InputMask"}`;
577
- }
578
- getAuditTargetLabel() {
579
- return this.input.id ? `#${this.input.id}` : this.input.name ? `input[name="${this.input.name}"]` : "<input>";
580
- }
581
- getAuditDisableHint() {
582
- return 'Passez { audit: false } ou data-mask-audit="false" pour d\xE9sactiver cet avertissement';
583
- }
584
- /**
585
- * Crochet permettant aux classes filles d'ajouter des vérifications d'audit spécifiques.
586
- */
587
- getSpecificAuditWarnings() {
588
- return [];
589
- }
590
- /**
591
- * Supprime les éléments fantômes, restaure les propriétés et nettoie les attributs.
592
- */
593
- destroy() {
594
- if (this.isDestroyed) return;
595
- this.isDestroyed = true;
596
- if (this.focusSelectTimerId !== null) {
597
- clearTimeout(this.focusSelectTimerId);
598
- this.focusSelectTimerId = null;
599
- }
600
- if (this.mutationObserver) {
601
- this.mutationObserver.disconnect();
602
- this.mutationObserver = null;
603
- }
604
- this.input.removeEventListener("copy", this.onBaseCopy);
605
- this.input.removeEventListener("focus", this.onBaseFocus);
606
- this.input.removeEventListener("blur", this.onBaseBlur);
607
- this.unhookValueProperty();
608
- if (this.ghost) {
609
- this.ghost.remove();
610
- this.ghost = null;
611
- }
612
- if (this.isWrapperCreated && this.wrapper) {
613
- this.input.style.gridArea = "";
614
- this.input.style.boxSizing = "";
615
- if (this.wrapper.parentNode) {
616
- this.wrapper.parentNode.insertBefore(this.input, this.wrapper);
617
- }
618
- this.wrapper.remove();
619
- } else if (this.wrapper) {
620
- this.wrapper.removeAttribute("data-mask");
621
- this.wrapper.removeAttribute("data-disabled");
622
- this.wrapper.classList.remove("is-complete", "is-focused", "mask-focus-only", "has-selection", "has-ghost");
623
- }
624
- }
625
- };
626
-
627
- // src/mask/MaskEngine.ts
628
- var DEFAULT_TOKENS = {
629
- "9": { pattern: /[0-9]/ },
630
- "a": { pattern: /[a-zA-Z]/ },
631
- "A": { pattern: /[a-zA-Z]/, transform: (c) => c.toUpperCase() },
632
- "*": { pattern: /[a-zA-Z0-9]/ },
633
- "#": { pattern: /[a-zA-Z0-9]/, transform: (c) => c.toUpperCase() }
634
- };
635
- var MaskEngine = class _MaskEngine {
636
- constructor(pattern, options = {}) {
637
- this.patterns = [];
638
- this.subEngines = [];
639
- this.activeEngine = null;
640
- this.slots = [];
641
- this.fullMaskTemplate = "";
642
- this.prefixSlotsCount = 0;
643
- this.prefixString = "";
644
- this.strict = true;
645
- this.autoLowercase = false;
646
- const opts = options || {};
647
- this.placeholderChar = opts.placeholderChar || "_";
648
- this.tokens = { ...DEFAULT_TOKENS, ...opts.tokens || {} };
649
- this.strict = opts.strict !== false;
650
- this.autoLowercase = opts.autoLowercase ?? false;
651
- this.pattern = "";
652
- this.compile(pattern);
653
- }
654
- /**
655
- * Formate une valeur selon un gabarit de masque donné.
656
- * Fonction statique utilitaire permettant un formatage direct sans instanciation manuelle.
657
- *
658
- * @param value Valeur à formater (brute ou partiellement formatée)
659
- * @param pattern Masque à appliquer (ex: "99 99 99 99 99" ou tableau de masques)
660
- * @param options Options facultatives (placeholderChar, tokens, strict, autoLowercase)
661
- * @returns La valeur formatée selon le masque
662
- */
663
- static format(value, pattern, options = {}) {
664
- if (!pattern || Array.isArray(pattern) && pattern.length === 0) return value ?? "";
665
- const engine = new _MaskEngine(pattern, options || {});
666
- return engine.format(value ?? "");
667
- }
668
- /**
669
- * Analyse le ou les gabarits statiques et compile la liste des slots.
670
- */
671
- compile(newPattern) {
672
- if (newPattern !== void 0) {
673
- if (Array.isArray(newPattern)) {
674
- this.patterns = [...newPattern];
675
- this.pattern = this.patterns[0] || "";
676
- } else {
677
- this.patterns = [];
678
- this.pattern = newPattern;
679
- }
680
- }
681
- if (this.patterns.length > 0) {
682
- this.subEngines = this.patterns.map((p) => new _MaskEngine(p, {
683
- placeholderChar: this.placeholderChar,
684
- tokens: this.tokens,
685
- strict: this.strict,
686
- autoLowercase: this.autoLowercase
687
- }));
688
- this.activeEngine = this.subEngines[0];
689
- this.slots = this.activeEngine.slots;
690
- this.fullMaskTemplate = this.activeEngine.fullMaskTemplate;
691
- this.prefixSlotsCount = this.activeEngine.prefixSlotsCount;
692
- this.prefixString = this.activeEngine.prefixString;
693
- return this.slots;
694
- }
695
- this.subEngines = [];
696
- this.activeEngine = null;
697
- this.slots = [];
698
- let templateBuilder = "";
699
- let isPrefixMode = true;
700
- for (let i = 0; i < this.pattern.length; i++) {
701
- let char = this.pattern[i];
702
- let isEscaped = false;
703
- if (char === "\\" && i + 1 < this.pattern.length) {
704
- isEscaped = true;
705
- i++;
706
- char = this.pattern[i];
707
- }
708
- const token = !isEscaped ? this.tokens[char] : void 0;
709
- if (token) {
710
- isPrefixMode = false;
711
- this.slots.push({
712
- char,
713
- isStatic: false,
714
- isPrefix: false,
715
- token,
716
- placeholder: this.placeholderChar
717
- });
718
- templateBuilder += this.placeholderChar;
719
- } else {
720
- this.slots.push({
721
- char,
722
- isStatic: true,
723
- isPrefix: isPrefixMode,
724
- placeholder: char
725
- });
726
- templateBuilder += char;
727
- }
728
- }
729
- this.fullMaskTemplate = templateBuilder;
730
- this.prefixSlotsCount = 0;
731
- this.prefixString = "";
732
- for (const slot of this.slots) {
733
- if (slot.isPrefix) {
734
- this.prefixSlotsCount++;
735
- this.prefixString += slot.char;
736
- } else {
737
- break;
738
- }
739
- }
740
- return this.slots;
741
- }
742
- /**
743
- * Sélectionne dynamiquement le meilleur sous-moteur en fonction de la valeur passée.
744
- */
745
- selectEngine(input) {
746
- if (this.subEngines.length <= 1) {
747
- return this;
748
- }
749
- const trimmed = String(input ?? "");
750
- const withMatchingPrefix = this.subEngines.filter((e) => {
751
- const p = e.getPrefix();
752
- return p.length > 0 && trimmed.toLowerCase().startsWith(p.trim().toLowerCase());
753
- });
754
- const candidates = withMatchingPrefix.length > 0 ? withMatchingPrefix : this.subEngines;
755
- const maxCandidate = [...candidates].sort((a, b) => b.getEditableCount() - a.getEditableCount())[0];
756
- const raw = maxCandidate ? maxCandidate.extractRaw(trimmed) : trimmed;
757
- const rawLen = raw.length;
758
- for (const eng of candidates) {
759
- if (eng.getEditableCount() >= rawLen) {
760
- this.activeEngine = eng;
761
- return eng;
762
- }
763
- }
764
- this.activeEngine = candidates[candidates.length - 1];
765
- return this.activeEngine;
766
- }
767
- /**
768
- * Retourne la chaîne du préfixe statique initial (ex: "+33 ").
769
- */
770
- getPrefix() {
771
- return this.activeEngine ? this.activeEngine.getPrefix() : this.prefixString;
772
- }
773
- /**
774
- * Retourne la longueur en caractères du préfixe statique initial.
775
- */
776
- getPrefixLength() {
777
- return this.activeEngine ? this.activeEngine.getPrefixLength() : this.prefixSlotsCount;
778
- }
779
- /**
780
- * Retourne le gabarit complet du masque avec ses placeholders (ex: "FR76 ____ ____").
781
- */
782
- getFullMaskTemplate() {
783
- return this.activeEngine ? this.activeEngine.getFullMaskTemplate() : this.fullMaskTemplate;
784
- }
785
- /**
786
- * Nombre total de positions éditables dans le masque.
787
- */
788
- getEditableCount() {
789
- if (this.subEngines.length > 0) {
790
- return Math.max(...this.subEngines.map((e) => e.getEditableCount()));
791
- }
792
- return this.activeEngine ? this.activeEngine.getEditableCount() : this.slots.filter((s) => !s.isStatic).length;
793
- }
794
- /**
795
- * Indique si tous les emplacements éditables du masque acceptent exclusivement des chiffres numériques.
796
- */
797
- isNumericOnly() {
798
- if (this.subEngines.length > 0) {
799
- return this.subEngines.every((e) => e.isNumericOnly());
800
- }
801
- const targetSlots = this.activeEngine ? this.activeEngine.slots : this.slots;
802
- const editable = targetSlots.filter((s) => !s.isStatic);
803
- if (editable.length === 0) return false;
804
- return editable.every((s) => s.char === "9" || s.token && s.token.pattern.test("0") && !s.token.pattern.test("a") && !s.token.pattern.test("Z"));
805
- }
806
- /**
807
- * Définit si le masque bloque strictement les entrées non conformes.
808
- */
809
- setStrict(strict) {
810
- this.strict = strict;
811
- }
812
- /**
813
- * Indique si le masque est en mode strict.
814
- */
815
- isStrict() {
816
- return this.strict;
817
- }
818
- /**
819
- * Filtre et extrait uniquement les caractères éditables valides d'une chaîne.
820
- * Gère intelligemment la présence ou l'absence des séparateurs statiques et du préfixe.
821
- */
822
- extractRaw(input) {
823
- if (this.subEngines.length > 0) {
824
- const engine = this.selectEngine(input);
825
- if (engine !== this) {
826
- return engine.extractRaw(input);
827
- }
828
- }
829
- const str = String(input ?? "");
830
- if (!str) return "";
831
- let raw = "";
832
- let inputIdx = 0;
833
- let slotIdx = 0;
834
- if (this.prefixSlotsCount > 0) {
835
- while (inputIdx < str.length && (str[inputIdx] === " " || str[inputIdx] === " ")) {
836
- inputIdx++;
837
- }
838
- let pIdx = 0;
839
- while (inputIdx < str.length && pIdx < this.prefixSlotsCount) {
840
- const pChar = this.slots[pIdx].char;
841
- const inChar = str[inputIdx];
842
- if (inChar.toUpperCase() === pChar.toUpperCase()) {
843
- inputIdx++;
844
- pIdx++;
845
- } else if (pChar === " " && inChar !== " ") {
846
- pIdx++;
847
- } else {
848
- break;
849
- }
850
- }
851
- slotIdx = this.prefixSlotsCount;
852
- }
853
- while (inputIdx < str.length && slotIdx < this.slots.length) {
854
- const slot = this.slots[slotIdx];
855
- const char = str[inputIdx];
856
- if (slot.isStatic) {
857
- if (char.toUpperCase() === slot.char.toUpperCase()) {
858
- inputIdx++;
859
- slotIdx++;
860
- } else {
861
- slotIdx++;
862
- }
863
- } else {
864
- if (slot.token && slot.token.pattern.test(char)) {
865
- let transformed = slot.token.transform ? slot.token.transform(char) : char;
866
- if (this.autoLowercase && !slot.token.transform) {
867
- transformed = transformed.toLowerCase();
868
- }
869
- raw += transformed;
870
- inputIdx++;
871
- slotIdx++;
872
- } else if (!this.strict) {
873
- raw += this.autoLowercase ? char.toLowerCase() : char;
874
- inputIdx++;
875
- slotIdx++;
876
- } else {
877
- inputIdx++;
878
- }
879
- }
880
- }
881
- if (!this.strict && inputIdx < str.length) {
882
- const remaining = str.slice(inputIdx);
883
- raw += this.autoLowercase ? remaining.toLowerCase() : remaining;
884
- }
885
- return raw;
886
- }
887
- /**
888
- * Formate une chaîne brute en appliquant le gabarit avec ses séparateurs statiques.
889
- * Si aucune donnée éditable n'est présente, retourne le préfixe statique fixe s'il existe.
890
- */
891
- format(rawValue) {
892
- if (this.subEngines.length > 0) {
893
- const engine = this.selectEngine(rawValue);
894
- if (engine !== this) {
895
- return engine.format(rawValue);
896
- }
897
- }
898
- const rawStr = String(rawValue ?? "");
899
- if (!this.slots.length) return rawStr;
900
- const cleanRaw = this.extractRaw(rawStr);
901
- if (cleanRaw.length === 0) {
902
- return this.prefixString;
903
- }
904
- let formatted = "";
905
- let rawIdx = 0;
906
- for (let i = 0; i < this.slots.length; i++) {
907
- const slot = this.slots[i];
908
- if (slot.isStatic) {
909
- const hasRemainingRaw = rawIdx < cleanRaw.length;
910
- const isPrefix = rawIdx === 0 && Boolean(slot.isPrefix);
911
- const isCompletedSegmentTrailingSep = rawIdx > 0 && rawIdx === cleanRaw.length;
912
- if (hasRemainingRaw || isPrefix || isCompletedSegmentTrailingSep) {
913
- formatted += slot.char;
914
- } else {
915
- break;
916
- }
917
- } else {
918
- if (rawIdx < cleanRaw.length) {
919
- const char = cleanRaw[rawIdx];
920
- let transformed = slot.token?.transform ? slot.token.transform(char) : char;
921
- if (this.autoLowercase && !slot.token?.transform) {
922
- transformed = transformed.toLowerCase();
923
- }
924
- formatted += transformed;
925
- rawIdx++;
926
- } else {
927
- break;
928
- }
929
- }
930
- }
931
- if (!this.strict && rawIdx < cleanRaw.length) {
932
- const extra = cleanRaw.substring(rawIdx);
933
- formatted += this.autoLowercase ? extra.toLowerCase() : extra;
934
- }
935
- return formatted;
936
- }
937
- /**
938
- * Calcule le gabarit restant aligné au texte formaté (supporte les polices proportionnelles non-monospace).
939
- */
940
- getRemainingMask(formatted) {
941
- if (this.activeEngine && this.activeEngine !== this) {
942
- return this.activeEngine.getRemainingMask(formatted);
943
- }
944
- if (!this.fullMaskTemplate) return "";
945
- if (formatted.length >= this.fullMaskTemplate.length) {
946
- return formatted;
947
- }
948
- return formatted + this.fullMaskTemplate.substring(formatted.length);
949
- }
950
- /**
951
- * Mappe la position du curseur en préservant le nombre exact de caractères éditables
952
- * saisis avant le curseur, et en garantissant que le curseur ne recule jamais dans le préfixe statique.
953
- */
954
- mapCursorPosition(inputValue, inputCursor, formatted) {
955
- if (this.activeEngine && this.activeEngine !== this) {
956
- return this.activeEngine.mapCursorPosition(inputValue, inputCursor, formatted);
957
- }
958
- const minPos = this.prefixSlotsCount;
959
- const safeInput = String(inputValue ?? "");
960
- const safeFormatted = String(formatted ?? "");
961
- if (inputCursor <= 0 || !safeFormatted) return minPos;
962
- const rawBeforeCursor = this.extractRaw(safeInput.slice(0, inputCursor));
963
- const targetRawCount = rawBeforeCursor.length;
964
- if (targetRawCount === 0) {
965
- return Math.max(minPos, Math.min(this.getNextEditablePosition(0), safeFormatted.length));
966
- }
967
- let currentRawCount = 0;
968
- let targetPos = safeFormatted.length;
969
- for (let i = 0; i < safeFormatted.length && i < this.slots.length; i++) {
970
- const slot = this.slots[i];
971
- if (!slot.isStatic) {
972
- currentRawCount++;
973
- if (currentRawCount === targetRawCount) {
974
- targetPos = i + 1;
975
- break;
976
- }
977
- }
978
- }
979
- while (targetPos < safeFormatted.length && this.slots[targetPos] && this.slots[targetPos].isStatic) {
980
- targetPos++;
981
- }
982
- return Math.max(minPos, Math.min(targetPos, safeFormatted.length));
983
- }
984
- /**
985
- * Vérifie si le slot à l'index donné est un séparateur statique.
986
- */
987
- isSeparatorAt(displayIdx) {
988
- if (this.activeEngine && this.activeEngine !== this) {
989
- return this.activeEngine.isSeparatorAt(displayIdx);
990
- }
991
- if (displayIdx >= 0 && displayIdx < this.slots.length) {
992
- return this.slots[displayIdx].isStatic;
993
- }
994
- return false;
995
- }
996
- /**
997
- * Trouve le prochain emplacement éditable après un index donné.
998
- */
999
- getNextEditablePosition(fromIdx) {
1000
- if (this.activeEngine && this.activeEngine !== this) {
1001
- return this.activeEngine.getNextEditablePosition(fromIdx);
1002
- }
1003
- const start = Math.max(0, fromIdx);
1004
- for (let i = start; i < this.slots.length; i++) {
1005
- if (!this.slots[i].isStatic) {
1006
- return i;
1007
- }
1008
- }
1009
- return this.slots.length;
1010
- }
1011
- /**
1012
- * Retourne le slot à l'index donné.
1013
- */
1014
- getSlotAt(displayIdx) {
1015
- if (this.activeEngine && this.activeEngine !== this) {
1016
- return this.activeEngine.getSlotAt(displayIdx);
1017
- }
1018
- return this.slots[displayIdx];
1019
- }
1020
- /**
1021
- * Retourne les slots complets.
1022
- */
1023
- getSlots() {
1024
- if (this.activeEngine && this.activeEngine !== this) {
1025
- return this.activeEngine.getSlots();
1026
- }
1027
- return this.slots;
1028
- }
1029
- };
1030
-
1031
- // src/mask/MaskHistory.ts
1032
- var MaskHistory = class {
1033
- constructor(maxDepth = 50) {
1034
- this.stack = [];
1035
- this.index = -1;
1036
- this.maxDepth = maxDepth;
1037
- }
1038
- /**
1039
- * Enregistre un nouvel état si la valeur brute a changé.
1040
- * Si la valeur brute est identique, met simplement à jour la position du curseur de l'état courant.
1041
- */
1042
- push(raw, cursor) {
1043
- const current = this.getCurrent();
1044
- if (current && current.raw === raw) {
1045
- current.cursor = cursor;
1046
- return;
1047
- }
1048
- this.stack = this.stack.slice(0, this.index + 1);
1049
- this.stack.push({ raw, cursor });
1050
- if (this.stack.length > this.maxDepth) {
1051
- this.stack.shift();
1052
- }
1053
- this.index = this.stack.length - 1;
1054
- }
1055
- /**
1056
- * Met à jour la position du curseur de l'état courant sans modifier la pile.
1057
- */
1058
- updateCurrentCursor(cursor) {
1059
- const current = this.getCurrent();
1060
- if (current) {
1061
- current.cursor = cursor;
1062
- }
1063
- }
1064
- /**
1065
- * Recule d'un cran dans l'historique et retourne l'état restauré.
1066
- */
1067
- undo() {
1068
- if (this.canUndo()) {
1069
- this.index--;
1070
- return this.stack[this.index];
1071
- }
1072
- return null;
1073
- }
1074
- /**
1075
- * Avance d'un cran dans l'historique et retourne l'état restauré.
1076
- */
1077
- redo() {
1078
- if (this.canRedo()) {
1079
- this.index++;
1080
- return this.stack[this.index];
1081
- }
1082
- return null;
1083
- }
1084
- /**
1085
- * Indique si une annulation est possible.
1086
- */
1087
- canUndo() {
1088
- return this.index > 0;
1089
- }
1090
- /**
1091
- * Indique si un rétablissement est possible.
1092
- */
1093
- canRedo() {
1094
- return this.index >= 0 && this.index < this.stack.length - 1;
1095
- }
1096
- /**
1097
- * Retourne l'état courant.
1098
- */
1099
- getCurrent() {
1100
- return this.index >= 0 && this.index < this.stack.length ? this.stack[this.index] : null;
1101
- }
1102
- /**
1103
- * Réinitialise entièrement l'historique.
1104
- */
1105
- clear() {
1106
- this.stack = [];
1107
- this.index = -1;
1108
- }
1109
- };
1110
-
1111
- // src/mask/MaskKeyboard.ts
1112
- var MaskKeyboard = class {
1113
- constructor(delegate) {
1114
- this.delegate = delegate;
1115
- }
1116
- /**
1117
- * Analyse et traite l'événement keydown de l'input.
1118
- */
1119
- handleKeyDown(e) {
1120
- const input = this.delegate.getInput();
1121
- const engine = this.delegate.getEngine();
1122
- const history = this.delegate.getHistory();
1123
- const minPos = engine.getPrefixLength();
1124
- const cursor = input.selectionStart ?? 0;
1125
- const selectionEnd = input.selectionEnd ?? cursor;
1126
- if ((e.ctrlKey || e.metaKey) && (e.key === "z" || e.key === "Z") && !e.shiftKey) {
1127
- e.preventDefault();
1128
- this.delegate.undo();
1129
- return;
1130
- }
1131
- if ((e.ctrlKey || e.metaKey) && (e.key === "y" || e.key === "Y") || (e.ctrlKey || e.metaKey) && e.shiftKey && (e.key === "z" || e.key === "Z")) {
1132
- e.preventDefault();
1133
- this.delegate.redo();
1134
- return;
1135
- }
1136
- history.updateCurrentCursor(cursor);
1137
- const isPrintableChar = e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey;
1138
- const hasSelection = selectionEnd > cursor;
1139
- if (isPrintableChar && !hasSelection) {
1140
- const slots = engine.getSlots();
1141
- const isAlreadyOnSep = cursor < slots.length && slots[cursor].isStatic && slots[cursor].char === e.key;
1142
- const isJustAfterSep = cursor > 0 && cursor - 1 < slots.length && slots[cursor - 1].isStatic && slots[cursor - 1].char === e.key;
1143
- if (isAlreadyOnSep || isJustAfterSep) {
1144
- e.preventDefault();
1145
- const baseIdx = isAlreadyOnSep ? cursor : cursor - 1;
1146
- const nextEditable = engine.getNextEditablePosition(baseIdx + 1);
1147
- this.delegate.applyMask(input.value, nextEditable, true);
1148
- return;
1149
- }
1150
- let nextSepIdx = -1;
1151
- for (let i = cursor; i < slots.length; i++) {
1152
- if (slots[i].isStatic) {
1153
- if (slots[i].char === e.key) {
1154
- nextSepIdx = i;
1155
- }
1156
- break;
1157
- }
1158
- }
1159
- if (nextSepIdx !== -1) {
1160
- e.preventDefault();
1161
- let segStart = nextSepIdx - 1;
1162
- while (segStart >= minPos && !slots[segStart].isStatic) {
1163
- segStart--;
1164
- }
1165
- segStart++;
1166
- const segLength = nextSepIdx - segStart;
1167
- const currentSegVal = input.value.slice(segStart, cursor);
1168
- const isNumericSegment = slots.slice(segStart, nextSepIdx).every((s) => !s.token || s.token.pattern.test("0"));
1169
- if (isNumericSegment && segLength > currentSegVal.length && currentSegVal.length > 0) {
1170
- const missingCount = segLength - currentSegVal.length;
1171
- const paddedSeg = "0".repeat(missingCount) + currentSegVal;
1172
- const remainingTail = input.value.slice(nextSepIdx);
1173
- const padded = input.value.slice(0, segStart) + paddedSeg + remainingTail;
1174
- const nextEditable2 = engine.getNextEditablePosition(nextSepIdx + 1);
1175
- this.delegate.applyMask(padded, nextEditable2, true);
1176
- return;
1177
- }
1178
- const nextEditable = engine.getNextEditablePosition(nextSepIdx + 1);
1179
- this.delegate.applyMask(input.value, nextEditable, true);
1180
- return;
1181
- }
1182
- }
1183
- if (isPrintableChar && engine.isStrict()) {
1184
- const totalSlots = engine.getEditableCount();
1185
- if (totalSlots > 0) {
1186
- const currentRaw = engine.extractRaw(input.value);
1187
- let availableCapacity = totalSlots - currentRaw.length;
1188
- if (selectionEnd > cursor) {
1189
- const selectedRaw = engine.extractRaw(input.value.slice(cursor, selectionEnd));
1190
- availableCapacity = totalSlots - (currentRaw.length - selectedRaw.length);
1191
- }
1192
- if (availableCapacity <= 0) {
1193
- e.preventDefault();
1194
- return;
1195
- }
1196
- }
1197
- }
1198
- if (selectionEnd > cursor) {
1199
- if (e.key === "Backspace" || e.key === "Delete") {
1200
- e.preventDefault();
1201
- const val = input.value;
1202
- const updated = val.slice(0, cursor) + val.slice(selectionEnd);
1203
- this.delegate.applyMask(updated, Math.max(minPos, cursor));
1204
- return;
1205
- }
1206
- return;
1207
- }
1208
- if (e.key === "ArrowLeft" && !e.shiftKey && cursor <= minPos) {
1209
- e.preventDefault();
1210
- input.setSelectionRange(minPos, minPos);
1211
- return;
1212
- }
1213
- if (e.key === "Home" && !e.shiftKey) {
1214
- e.preventDefault();
1215
- input.setSelectionRange(minPos, minPos);
1216
- return;
1217
- }
1218
- if (e.key === "Backspace" && cursor <= minPos) {
1219
- e.preventDefault();
1220
- input.setSelectionRange(minPos, minPos);
1221
- return;
1222
- }
1223
- if (e.key === "Delete" && cursor < minPos) {
1224
- e.preventDefault();
1225
- input.setSelectionRange(minPos, minPos);
1226
- return;
1227
- }
1228
- const isWordDeleteBack = e.key === "Backspace" && (e.ctrlKey || e.altKey || e.metaKey);
1229
- if (isWordDeleteBack) {
1230
- e.preventDefault();
1231
- if (cursor <= minPos) {
1232
- input.setSelectionRange(minPos, minPos);
1233
- return;
1234
- }
1235
- let i = cursor - 1;
1236
- while (i >= minPos && engine.isSeparatorAt(i)) {
1237
- i--;
1238
- }
1239
- while (i >= minPos && !engine.isSeparatorAt(i)) {
1240
- i--;
1241
- }
1242
- const startPos = Math.max(minPos, i + 1);
1243
- const val = input.value;
1244
- const updated = val.slice(0, startPos) + val.slice(cursor);
1245
- this.delegate.applyMask(updated, startPos);
1246
- return;
1247
- }
1248
- const isWordDeleteForward = e.key === "Delete" && (e.ctrlKey || e.altKey || e.metaKey);
1249
- if (isWordDeleteForward) {
1250
- e.preventDefault();
1251
- const val = input.value;
1252
- if (cursor >= val.length) {
1253
- return;
1254
- }
1255
- let i = cursor;
1256
- while (i < val.length && engine.isSeparatorAt(i)) {
1257
- i++;
1258
- }
1259
- while (i < val.length && !engine.isSeparatorAt(i)) {
1260
- i++;
1261
- }
1262
- while (i < val.length && engine.isSeparatorAt(i)) {
1263
- i++;
1264
- }
1265
- const endPos = i;
1266
- const updated = val.slice(0, cursor) + val.slice(endPos);
1267
- this.delegate.applyMask(updated, cursor);
1268
- return;
1269
- }
1270
- if (e.key === "Backspace" && cursor > minPos) {
1271
- if (engine.isSeparatorAt(cursor - 1)) {
1272
- e.preventDefault();
1273
- let targetPos = cursor - 1;
1274
- while (targetPos > minPos && engine.isSeparatorAt(targetPos - 1)) {
1275
- targetPos--;
1276
- }
1277
- if (targetPos > minPos) {
1278
- const val = input.value;
1279
- const updated = val.slice(0, targetPos - 1) + val.slice(cursor);
1280
- this.delegate.applyMask(updated, targetPos - 1);
1281
- } else {
1282
- this.delegate.applyMask("", minPos);
1283
- }
1284
- }
1285
- return;
1286
- }
1287
- if (e.key === "Delete" && cursor < input.value.length) {
1288
- if (engine.isSeparatorAt(cursor)) {
1289
- e.preventDefault();
1290
- let targetPos = cursor;
1291
- while (targetPos < input.value.length && engine.isSeparatorAt(targetPos)) {
1292
- targetPos++;
1293
- }
1294
- if (targetPos < input.value.length) {
1295
- const val = input.value;
1296
- const updated = val.slice(0, targetPos) + val.slice(targetPos + 1);
1297
- this.delegate.applyMask(updated, cursor);
1298
- }
1299
- }
1300
- return;
1301
- }
1302
- }
1303
- /**
1304
- * Analyse et traite l'événement keyup de l'input.
1305
- */
1306
- handleKeyUp(e) {
1307
- const input = this.delegate.getInput();
1308
- const history = this.delegate.getHistory();
1309
- if ((e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "Home") && !e.shiftKey) {
1310
- this.delegate.enforceMinCursor();
1311
- }
1312
- history.updateCurrentCursor(input.selectionStart ?? 0);
1313
- }
1314
- };
1315
-
1316
- // src/mask/InputMask.ts
1317
- var InputMask = class extends BaseInputMask {
1318
- constructor(targetOrWrapper, inputOrOptions, options) {
1319
- const args = resolveMaskConstructorArgs(targetOrWrapper, inputOrOptions, options);
1320
- const wrap = args.wrapper;
1321
- const inp = args.input;
1322
- const opts = args.options;
1323
- const attrMask = wrap?.getAttribute("data-mask") || inp?.getAttribute("data-mask");
1324
- let pattern = opts.mask || attrMask || "";
1325
- if (typeof pattern === "string" && pattern.includes("|")) {
1326
- pattern = pattern.split("|").map((s) => s.trim());
1327
- }
1328
- const placeholderChar = opts.placeholderChar || wrap?.getAttribute("data-mask-placeholder") || inp?.getAttribute("data-mask-placeholder") || "_";
1329
- const dataDisabled = wrap?.hasAttribute("data-disabled") || inp?.hasAttribute("data-disabled");
1330
- const dataStrict = wrap?.getAttribute("data-mask-strict") || inp?.getAttribute("data-mask-strict");
1331
- const dataAutoLower = wrap?.getAttribute("data-mask-auto-lowercase") === "true" || inp?.getAttribute("data-mask-auto-lowercase") === "true";
1332
- const dataInfer = wrap?.getAttribute("data-mask-infer-inputmode") ?? inp?.getAttribute("data-mask-infer-inputmode");
1333
- const inferInputMode = opts.inferInputMode ?? (dataInfer !== null ? dataInfer !== "false" : true);
1334
- const { disabled: optsDisabled, ...otherOpts } = opts;
1335
- const resolvedDisabled = optsDisabled !== void 0 ? optsDisabled : dataDisabled ? true : !pattern || Array.isArray(pattern) && pattern.length === 0;
1336
- const resolvedOptions = {
1337
- ...otherOpts,
1338
- mask: pattern,
1339
- placeholderChar,
1340
- strict: opts.strict ?? (dataStrict !== null ? dataStrict !== "false" : true),
1341
- autoLowercase: opts.autoLowercase ?? dataAutoLower ?? false,
1342
- disabled: resolvedDisabled,
1343
- resetHistoryOnMaskChange: opts.resetHistoryOnMaskChange ?? false,
1344
- inferInputMode,
1345
- onInput: opts.onInput || opts.oninput,
1346
- onChange: opts.onChange || opts.onchange,
1347
- onComplete: opts.onComplete || opts.oncomplete
1348
- };
1349
- super(wrap, inp, resolvedOptions);
1350
- this.isComposing = false;
1351
- this.isUndoingRedoing = false;
1352
- this.isMouseDown = false;
1353
- this.isApplyingMask = false;
1354
- this.lastValue = "";
1355
- this.lastInternalRemainingMask = "";
1356
- this.isNotifying = false;
1357
- this.hasPendingNotification = false;
1358
- this.onChangeNativeHandler = () => {
1359
- };
1360
- this.wasInputModeInferred = false;
1361
- this.cutTimerId = null;
1362
- this.pasteTimerId = null;
1363
- this.resetTimerId = null;
1364
- this.history = new MaskHistory();
1365
- this.engine = new MaskEngine(this.options.mask || "", {
1366
- placeholderChar: this.options.placeholderChar,
1367
- tokens: this.options.tokens,
1368
- strict: this.options.strict,
1369
- autoLowercase: this.options.autoLowercase
1370
- });
1371
- this.syncInferredInputMode();
1372
- this.keyboard = new MaskKeyboard({
1373
- getInput: () => this.input,
1374
- getEngine: () => this.engine,
1375
- getHistory: () => this.history,
1376
- applyMask: (raw, cursor, forceExactCursor) => this.applyMask(raw, cursor, forceExactCursor),
1377
- undo: () => this.undo(),
1378
- redo: () => this.redo(),
1379
- enforceMinCursor: () => this.enforceMinCursor()
1380
- });
1381
- this.bindEvents();
1382
- this.lastValue = this.input.value;
1383
- this.syncInitialValue();
1384
- this.runAuditWarning(this.options.audit);
1385
- }
1386
- getSpecificAuditWarnings() {
1387
- const warnings = [];
1388
- const hasDescribedby = Boolean(this.input.getAttribute("aria-describedby")?.trim());
1389
- const hasPlaceholder = Boolean(this.input.getAttribute("placeholder")?.trim());
1390
- const hasAriaPlaceholder = Boolean(this.input.getAttribute("aria-placeholder")?.trim());
1391
- if (!hasDescribedby && !hasPlaceholder && !hasAriaPlaceholder && !this.options.disabled) {
1392
- warnings.push(
1393
- "Indication du format attendu manquante : d\xE9finissez aria-describedby, placeholder ou aria-placeholder pour informer les technologies d'assistance (WCAG 3.3.2)."
1394
- );
1395
- }
1396
- return warnings;
1397
- }
1398
- extractRawSnippet(snippet) {
1399
- return this.engine.extractRaw(snippet);
1400
- }
1401
- /**
1402
- * Formate statiquement une valeur selon un masque donné sans nécessiter d'élément DOM.
1403
- *
1404
- * @param value Valeur à formater (ex: "0123456789")
1405
- * @param mask Gabarit de masque (ex: "99 99 99 99 99")
1406
- * @param options Options facultatives du masque (tokens, placeholderChar, strict, etc.)
1407
- * @returns Valeur formatée (ex: "01 23 45 67 89")
1408
- */
1409
- static format(value, mask, options = {}) {
1410
- return MaskEngine.format(value, mask, options);
1411
- }
1412
- onNativeValueSet(strVal) {
1413
- if (this.options.disabled) {
1414
- this.checkValueChange();
1415
- } else {
1416
- this.applyMask(strVal, strVal.length);
1417
- }
1418
- }
1419
- onDisabledChange(disabled) {
1420
- if (disabled) {
1421
- this.wrapper.removeAttribute("data-mask");
1422
- this.wrapper.classList.remove("is-complete", "has-selection");
1423
- if (this.ghost) this.ghost.textContent = "";
1424
- this.checkValueChange();
1425
- } else {
1426
- this.applyMask(this.input.value, this.input.selectionStart ?? this.input.value.length);
1427
- }
1428
- }
1429
- /**
1430
- * Associe les écouteurs d'événements nécessaires.
1431
- */
1432
- bindEvents() {
1433
- this.handleInput = this.handleInput.bind(this);
1434
- this.onKeyDown = this.onKeyDown.bind(this);
1435
- this.onPaste = this.onPaste.bind(this);
1436
- this.onFocus = this.onFocus.bind(this);
1437
- this.onBlur = this.onBlur.bind(this);
1438
- this.onClick = this.onClick.bind(this);
1439
- this.onKeyUp = this.onKeyUp.bind(this);
1440
- this.onSelect = this.onSelect.bind(this);
1441
- this.onMouseDown = this.onMouseDown.bind(this);
1442
- this.onMouseUp = this.onMouseUp.bind(this);
1443
- this.onCompositionStart = this.onCompositionStart.bind(this);
1444
- this.onCompositionEnd = this.onCompositionEnd.bind(this);
1445
- this.onScroll = this.onScroll.bind(this);
1446
- this.onBeforeInput = this.onBeforeInput.bind(this);
1447
- this.onCutHandler = () => {
1448
- if (this.cutTimerId !== null) clearTimeout(this.cutTimerId);
1449
- this.cutTimerId = window.setTimeout(() => {
1450
- this.cutTimerId = null;
1451
- if (this.isDestroyed) return;
1452
- if (this.options.disabled) {
1453
- this.checkValueChange();
1454
- } else {
1455
- const cur = this.input.selectionStart ?? this.input.value.length;
1456
- this.applyMask(this.input.value, cur);
1457
- }
1458
- }, 0);
1459
- };
1460
- this.onChangeNativeHandler = () => {
1461
- if (this.isDestroyed) return;
1462
- this.checkValueChange();
1463
- };
1464
- this.input.addEventListener("beforeinput", this.onBeforeInput);
1465
- this.input.addEventListener("input", this.handleInput);
1466
- this.input.addEventListener("keydown", this.onKeyDown);
1467
- this.input.addEventListener("paste", this.onPaste);
1468
- this.input.addEventListener("focus", this.onFocus);
1469
- this.input.addEventListener("blur", this.onBlur);
1470
- this.input.addEventListener("click", this.onClick);
1471
- this.input.addEventListener("keyup", this.onKeyUp);
1472
- this.input.addEventListener("select", this.onSelect);
1473
- this.input.addEventListener("mousedown", this.onMouseDown);
1474
- window.addEventListener("mouseup", this.onMouseUp);
1475
- this.input.addEventListener("compositionstart", this.onCompositionStart);
1476
- this.input.addEventListener("compositionend", this.onCompositionEnd);
1477
- this.input.addEventListener("scroll", this.onScroll);
1478
- this.input.addEventListener("cut", this.onCutHandler);
1479
- this.input.addEventListener("change", this.onChangeNativeHandler);
1480
- if (this.input.form) {
1481
- this.onFormResetHandler = () => {
1482
- if (this.resetTimerId !== null) clearTimeout(this.resetTimerId);
1483
- this.resetTimerId = window.setTimeout(() => {
1484
- this.resetTimerId = null;
1485
- if (this.isDestroyed) return;
1486
- if (this.options.disabled) {
1487
- this.checkValueChange();
1488
- } else {
1489
- this.syncInitialValue();
1490
- }
1491
- }, 0);
1492
- };
1493
- this.input.form.addEventListener("reset", this.onFormResetHandler);
1494
- }
1495
- }
1496
- /**
1497
- * Synchronise dynamiquement l'attribut inputmode="numeric" selon le motif actif
1498
- * sans jamais écraser un inputmode défini explicitement par l'hôte.
1499
- */
1500
- syncInferredInputMode() {
1501
- if (!this.options.inferInputMode) return;
1502
- const isNum = !this.options.disabled && this.engine.isNumericOnly();
1503
- if (isNum) {
1504
- if (!this.input.hasAttribute("inputmode")) {
1505
- this.input.inputMode = "numeric";
1506
- this.wasInputModeInferred = true;
1507
- }
1508
- } else if (this.wasInputModeInferred && this.input.getAttribute("inputmode") === "numeric") {
1509
- this.input.removeAttribute("inputmode");
1510
- this.wasInputModeInferred = false;
1511
- }
1512
- }
1513
- /**
1514
- * Supprime tous les écouteurs et nettoie les attributs associés.
1515
- */
1516
- destroy() {
1517
- if (this.isDestroyed) return;
1518
- if (this.cutTimerId !== null) {
1519
- clearTimeout(this.cutTimerId);
1520
- this.cutTimerId = null;
1521
- }
1522
- if (this.pasteTimerId !== null) {
1523
- clearTimeout(this.pasteTimerId);
1524
- this.pasteTimerId = null;
1525
- }
1526
- if (this.resetTimerId !== null) {
1527
- clearTimeout(this.resetTimerId);
1528
- this.resetTimerId = null;
1529
- }
1530
- this.input.removeEventListener("beforeinput", this.onBeforeInput);
1531
- this.input.removeEventListener("input", this.handleInput);
1532
- this.input.removeEventListener("keydown", this.onKeyDown);
1533
- this.input.removeEventListener("paste", this.onPaste);
1534
- this.input.removeEventListener("focus", this.onFocus);
1535
- this.input.removeEventListener("blur", this.onBlur);
1536
- this.input.removeEventListener("click", this.onClick);
1537
- this.input.removeEventListener("keyup", this.onKeyUp);
1538
- this.input.removeEventListener("select", this.onSelect);
1539
- this.input.removeEventListener("mousedown", this.onMouseDown);
1540
- window.removeEventListener("mouseup", this.onMouseUp);
1541
- this.input.removeEventListener("compositionstart", this.onCompositionStart);
1542
- this.input.removeEventListener("compositionend", this.onCompositionEnd);
1543
- this.input.removeEventListener("scroll", this.onScroll);
1544
- this.input.removeEventListener("cut", this.onCutHandler);
1545
- this.input.removeEventListener("change", this.onChangeNativeHandler);
1546
- if (this.input.form && this.onFormResetHandler) {
1547
- this.input.form.removeEventListener("reset", this.onFormResetHandler);
1548
- }
1549
- if (this.wasInputModeInferred && this.input.getAttribute("inputmode") === "numeric") {
1550
- this.input.removeAttribute("inputmode");
1551
- }
1552
- this.history.clear();
1553
- super.destroy();
1554
- }
1555
- /**
1556
- * Définit si le masque bloque strictement les entrées non conformes.
1557
- */
1558
- setStrict(strict) {
1559
- this.options.strict = strict;
1560
- this.engine.setStrict(strict);
1561
- if (!this.options.disabled) {
1562
- this.applyMask(this.input.value, this.input.selectionStart ?? this.input.value.length);
1563
- }
1564
- }
1565
- /**
1566
- * Indique si le masque est en mode strict.
1567
- */
1568
- isStrict() {
1569
- return this.engine.isStrict();
1570
- }
1571
- /**
1572
- * Modifie dynamiquement le masque actif.
1573
- * Permet de désactiver le masque avec null/vide, ou de spécifier un mode strict/souple.
1574
- */
1575
- setMask(newPattern, options) {
1576
- const newStrict = typeof options === "boolean" ? options : options && typeof options === "object" && options.strict !== void 0 ? options.strict : this.options.strict;
1577
- const shouldResetHistory = options && typeof options === "object" && options.resetHistory !== void 0 ? options.resetHistory : Boolean(this.options.resetHistoryOnMaskChange);
1578
- const isTargetingEmpty = !newPattern || Array.isArray(newPattern) && newPattern.length === 0;
1579
- if (isTargetingEmpty && this.options.disabled && (!this.options.mask || this.options.mask === "")) {
1580
- return;
1581
- }
1582
- if (!newPattern || Array.isArray(newPattern) && newPattern.length === 0) {
1583
- this.options.mask = "";
1584
- this.options.strict = newStrict;
1585
- this.engine.setStrict(newStrict ?? true);
1586
- this.engine.compile("");
1587
- if (shouldResetHistory) {
1588
- this.history.clear();
1589
- }
1590
- this.setDisabled(true);
1591
- this.syncInferredInputMode();
1592
- return;
1593
- }
1594
- this.options.mask = newPattern;
1595
- this.options.strict = newStrict;
1596
- this.engine.setStrict(newStrict ?? true);
1597
- this.engine.compile(newPattern);
1598
- if (shouldResetHistory) {
1599
- this.history.clear();
1600
- }
1601
- this.setDisabled(false);
1602
- this.syncInferredInputMode();
1603
- }
1604
- handleAttributeMutation(attrName) {
1605
- super.handleAttributeMutation(attrName);
1606
- if (attrName === "data-mask") {
1607
- const rawAttr = this.getAttr("data-mask");
1608
- if (rawAttr === this.lastInternalRemainingMask) {
1609
- return;
1610
- }
1611
- const currentMaskStr = Array.isArray(this.options.mask) ? this.options.mask.join("|") : this.options.mask || "";
1612
- if (rawAttr === currentMaskStr) {
1613
- return;
1614
- }
1615
- if (rawAttr) {
1616
- const maskVal = rawAttr.includes("|") ? rawAttr.split("|").map((s) => s.trim()) : rawAttr;
1617
- this.setMask(maskVal);
1618
- } else {
1619
- this.setMask(null);
1620
- }
1621
- } else if (attrName === "data-mask-strict") {
1622
- const strictVal = this.getAttr("data-mask-strict");
1623
- this.setStrict(strictVal !== "false");
1624
- } else if (attrName === "data-mask-auto-lowercase") {
1625
- this.options.autoLowercase = this.getAttr("data-mask-auto-lowercase") === "true";
1626
- this.engine.compile(this.options.mask || "");
1627
- this.applyMask(this.input.value, this.input.selectionStart ?? this.input.value.length);
1628
- } else if (attrName === "placeholder") {
1629
- this.updateGhost(this.input.value);
1630
- }
1631
- }
1632
- /**
1633
- * Affecte une nouvelle valeur manuellement (formatée ou brute).
1634
- */
1635
- setValue(val) {
1636
- const safeVal = val !== null && val !== void 0 ? String(val) : "";
1637
- if (this.options.disabled) {
1638
- this.input.value = safeVal;
1639
- this.checkValueChange();
1640
- return;
1641
- }
1642
- this.applyMask(safeVal, safeVal.length);
1643
- }
1644
- /**
1645
- * Retourne la valeur brute sans séparateurs.
1646
- */
1647
- getRawValue() {
1648
- return this.engine.extractRaw(this.input.value);
1649
- }
1650
- /**
1651
- * Indique si tous les emplacements éditables sont renseignés.
1652
- */
1653
- isComplete() {
1654
- if (this.options.disabled) return true;
1655
- const raw = this.getRawValue();
1656
- return raw.length >= this.engine.getEditableCount();
1657
- }
1658
- /**
1659
- * Callback d'écoute directe ou getter/setter pour onInput.
1660
- */
1661
- get onInput() {
1662
- return this.options.onInput;
1663
- }
1664
- set onInput(callback) {
1665
- this.options.onInput = callback;
1666
- }
1667
- /**
1668
- * Annule la dernière modification (Undo).
1669
- */
1670
- undo() {
1671
- if (this.options.disabled) return;
1672
- const state = this.history.undo();
1673
- if (state) {
1674
- this.isUndoingRedoing = true;
1675
- this.applyMask(state.raw, state.cursor);
1676
- this.isUndoingRedoing = false;
1677
- }
1678
- }
1679
- /**
1680
- * Rétablit la modification annulée (Redo).
1681
- */
1682
- redo() {
1683
- if (this.options.disabled) return;
1684
- const state = this.history.redo();
1685
- if (state) {
1686
- this.isUndoingRedoing = true;
1687
- this.applyMask(state.raw, state.cursor);
1688
- this.isUndoingRedoing = false;
1689
- }
1690
- }
1691
- // ==========================================================================
1692
- // Gestionnaires d'événements DOM
1693
- // ==========================================================================
1694
- checkSelection() {
1695
- if (this.options.disabled) return;
1696
- const start = this.input.selectionStart ?? 0;
1697
- const end = this.input.selectionEnd ?? start;
1698
- const hasSelection = start !== end;
1699
- this.wrapper.classList.toggle("has-selection", hasSelection);
1700
- }
1701
- onBeforeInput(e) {
1702
- if (this.options.disabled) return;
1703
- if (this.isComposing) return;
1704
- if (!this.engine.isStrict()) return;
1705
- if (e.inputType === "insertFromPaste") return;
1706
- if (e.inputType && e.inputType.startsWith("insert")) {
1707
- const totalSlots = this.engine.getEditableCount();
1708
- if (totalSlots > 0) {
1709
- const currentRaw = this.getRawValue();
1710
- const start = this.input.selectionStart ?? 0;
1711
- const end = this.input.selectionEnd ?? start;
1712
- let availableCapacity = Math.max(0, totalSlots - currentRaw.length);
1713
- if (end > start) {
1714
- const selectedRaw = this.engine.extractRaw(this.input.value.slice(start, end));
1715
- availableCapacity = Math.max(0, totalSlots - (currentRaw.length - selectedRaw.length));
1716
- }
1717
- if (availableCapacity <= 0) {
1718
- e.preventDefault();
1719
- }
1720
- }
1721
- }
1722
- }
1723
- handleInput(e) {
1724
- if (this.isDispatchingNativeInput) return;
1725
- if (this.isComposing) return;
1726
- const hasOnInput = Boolean(this.options.onInput || this.options.oninput);
1727
- if (hasOnInput && this.input.value !== this.lastValue) {
1728
- this.checkValueChange();
1729
- }
1730
- if (this.options.disabled) {
1731
- this.checkValueChange();
1732
- return;
1733
- }
1734
- const prevState = this.history.getCurrent();
1735
- const totalSlots = this.engine.getEditableCount();
1736
- if (totalSlots > 0 && this.engine.isStrict() && prevState && prevState.raw.length >= totalSlots) {
1737
- const newRaw = this.engine.extractRaw(this.input.value);
1738
- if (newRaw.length > totalSlots) {
1739
- this.applyMask(prevState.raw, prevState.cursor);
1740
- return;
1741
- }
1742
- }
1743
- const oldCursor = this.input.selectionStart ?? this.input.value.length;
1744
- this.applyMask(this.input.value, oldCursor);
1745
- this.checkSelection();
1746
- }
1747
- onKeyDown(e) {
1748
- if (this.options.disabled) return;
1749
- this.keyboard.handleKeyDown(e);
1750
- }
1751
- onMouseDown() {
1752
- this.isMouseDown = true;
1753
- }
1754
- onMouseUp() {
1755
- this.isMouseDown = false;
1756
- this.checkSelection();
1757
- }
1758
- onPaste(e) {
1759
- if (this.options.disabled) {
1760
- if (this.pasteTimerId !== null) clearTimeout(this.pasteTimerId);
1761
- this.pasteTimerId = window.setTimeout(() => {
1762
- this.pasteTimerId = null;
1763
- if (!this.isDestroyed) this.checkValueChange();
1764
- }, 0);
1765
- return;
1766
- }
1767
- e.preventDefault();
1768
- this.history.updateCurrentCursor(this.input.selectionStart ?? 0);
1769
- const rawPasted = e.clipboardData?.getData("text") || "";
1770
- const pastedText = rawPasted.trim();
1771
- if (!pastedText) return;
1772
- const minPos = this.engine.getPrefixLength();
1773
- const selStart = this.input.selectionStart ?? 0;
1774
- const selEnd = this.input.selectionEnd ?? selStart;
1775
- const currentVal = this.input.value;
1776
- const totalSlots = this.engine.getEditableCount();
1777
- const currentRaw = this.getRawValue();
1778
- const prefix = this.engine.getPrefix();
1779
- const cleanPrefix = prefix.replace(/[\s.-]+/g, "").toUpperCase();
1780
- const cleanPasted = pastedText.replace(/[\s.-]+/g, "").toUpperCase();
1781
- const startsWithStaticPrefix = cleanPrefix.length > 0 && cleanPasted.startsWith(cleanPrefix);
1782
- const prefixInField = currentVal.slice(0, Math.max(minPos, selStart)).replace(/[\s.-]+/g, "").toUpperCase();
1783
- const startsWithFieldStart = prefixInField.length >= 2 && cleanPasted.startsWith(prefixInField);
1784
- let effectiveStart = Math.max(minPos, selStart);
1785
- let effectiveEnd = Math.max(minPos, selEnd);
1786
- if (startsWithStaticPrefix || startsWithFieldStart) {
1787
- effectiveStart = 0;
1788
- effectiveEnd = currentVal.length;
1789
- }
1790
- let availableCapacity = Math.max(0, totalSlots - currentRaw.length);
1791
- if (effectiveStart !== effectiveEnd) {
1792
- const selectedRaw = this.engine.extractRaw(currentVal.slice(effectiveStart, effectiveEnd));
1793
- availableCapacity = Math.max(0, totalSlots - (currentRaw.length - selectedRaw.length));
1794
- }
1795
- if (this.engine.isStrict() && availableCapacity <= 0) {
1796
- return;
1797
- }
1798
- let combined;
1799
- let newCursorPos;
1800
- if (effectiveStart === 0 && effectiveEnd === currentVal.length) {
1801
- combined = pastedText;
1802
- newCursorPos = pastedText.length;
1803
- } else {
1804
- combined = currentVal.slice(0, effectiveStart) + pastedText + currentVal.slice(effectiveEnd);
1805
- newCursorPos = effectiveStart + pastedText.length;
1806
- }
1807
- this.applyMask(combined, newCursorPos);
1808
- this.checkSelection();
1809
- }
1810
- onFocus() {
1811
- this.syncGhostStyles();
1812
- this.wrapper.classList.add("is-focused");
1813
- if (!this.options.disabled && !this.isMouseDown) {
1814
- this.enforceMinCursor();
1815
- }
1816
- this.updateGhost(this.input.value);
1817
- this.checkSelection();
1818
- }
1819
- onBlur() {
1820
- this.wrapper.classList.remove("is-focused", "has-selection");
1821
- if (this.input.type === "password") {
1822
- this.history.clear();
1823
- }
1824
- this.updateGhost(this.input.value);
1825
- }
1826
- onClick() {
1827
- if (!this.options.disabled) {
1828
- this.enforceMinCursor();
1829
- }
1830
- this.history.updateCurrentCursor(this.input.selectionStart ?? 0);
1831
- this.checkSelection();
1832
- }
1833
- onKeyUp(e) {
1834
- if (!this.options.disabled) {
1835
- this.keyboard.handleKeyUp(e);
1836
- }
1837
- this.checkSelection();
1838
- }
1839
- onSelect() {
1840
- this.history.updateCurrentCursor(this.input.selectionStart ?? 0);
1841
- this.checkSelection();
1842
- }
1843
- onCompositionStart() {
1844
- this.isComposing = true;
1845
- }
1846
- onCompositionEnd() {
1847
- this.isComposing = false;
1848
- if (this.options.disabled) return;
1849
- const oldCursor = this.input.selectionStart ?? this.input.value.length;
1850
- this.applyMask(this.input.value, oldCursor);
1851
- this.checkSelection();
1852
- }
1853
- /**
1854
- * Empêche strictement le curseur de se positionner avant la fin du préfixe statique
1855
- * lorsqu'il n'y a PAS de sélection active.
1856
- * Si une sélection est active (ex: pour copier avec Ctrl+C ou écraser avec Ctrl+A),
1857
- * elle est préservée sans restriction.
1858
- */
1859
- enforceMinCursor() {
1860
- const minPos = this.engine.getPrefixLength();
1861
- if (minPos <= 0) return;
1862
- const start = this.input.selectionStart ?? 0;
1863
- const end = this.input.selectionEnd ?? start;
1864
- if (start !== end) {
1865
- return;
1866
- }
1867
- if (start < minPos) {
1868
- this.input.setSelectionRange(minPos, minPos);
1869
- }
1870
- }
1871
- // ==========================================================================
1872
- // Pipeline de calcul et de synchronisation
1873
- // ==========================================================================
1874
- updateGhost(formatted) {
1875
- if (!this.ghost) return;
1876
- if (this.options.disabled) {
1877
- this.ghost.textContent = "";
1878
- return;
1879
- }
1880
- const isCleanEmpty = !formatted || formatted === this.engine.getPrefix();
1881
- if (this.shouldHideGhostForPlaceholder(isCleanEmpty)) {
1882
- this.ghost.textContent = "";
1883
- return;
1884
- }
1885
- const fullTemplate = this.engine.getFullMaskTemplate();
1886
- const rest = fullTemplate.length > formatted.length ? fullTemplate.substring(formatted.length) : "";
1887
- this.ghost.textContent = "";
1888
- const spanTyped = document.createElement("span");
1889
- spanTyped.className = "mask-ghost-typed";
1890
- spanTyped.textContent = formatted;
1891
- const spanRemaining = document.createElement("span");
1892
- spanRemaining.className = "mask-ghost-remaining";
1893
- spanRemaining.textContent = rest;
1894
- this.ghost.appendChild(spanTyped);
1895
- this.ghost.appendChild(spanRemaining);
1896
- this.ghost.scrollLeft = this.input.scrollLeft;
1897
- }
1898
- applyMask(rawOrPartial, cursorPosition, forceExactCursor = false) {
1899
- if (this.options.disabled || this.isApplyingMask) return;
1900
- this.isApplyingMask = true;
1901
- let formatted = "";
1902
- let isCompleted = false;
1903
- try {
1904
- formatted = this.engine.format(rawOrPartial);
1905
- const remainingMask = this.engine.getRemainingMask(formatted);
1906
- this.input.value = formatted;
1907
- this.lastInternalRemainingMask = remainingMask;
1908
- this.wrapper.setAttribute("data-mask", remainingMask);
1909
- this.updateGhost(formatted);
1910
- const minPos = this.engine.getPrefixLength();
1911
- let safeCursor;
1912
- if (forceExactCursor || this.isUndoingRedoing) {
1913
- safeCursor = Math.max(minPos, Math.min(cursorPosition, formatted.length));
1914
- } else {
1915
- const calculatedCursor = this.engine.mapCursorPosition(rawOrPartial, cursorPosition, formatted);
1916
- safeCursor = Math.max(minPos, calculatedCursor);
1917
- }
1918
- this.input.setSelectionRange(safeCursor, safeCursor);
1919
- isCompleted = this.isComplete();
1920
- this.wrapper.classList.toggle("is-complete", isCompleted);
1921
- if (!this.isUndoingRedoing && this.input.type !== "password") {
1922
- this.history.push(this.getRawValue(), safeCursor);
1923
- }
1924
- } finally {
1925
- this.isApplyingMask = false;
1926
- }
1927
- this.checkValueChange();
1928
- }
1929
- syncInitialValue() {
1930
- if (this.options.disabled) {
1931
- this.wrapper.removeAttribute("data-mask");
1932
- if (this.ghost) this.ghost.textContent = "";
1933
- this.lastValue = this.input.value;
1934
- this.checkValueChange();
1935
- return;
1936
- }
1937
- this.syncGhostStyles();
1938
- const initialVal = this.input.value || "";
1939
- if (initialVal) {
1940
- this.applyMask(initialVal, initialVal.length);
1941
- } else {
1942
- const minPos = this.engine.getPrefixLength();
1943
- if (minPos > 0) {
1944
- this.applyMask("", minPos);
1945
- } else {
1946
- if (this.input.type !== "password") {
1947
- this.history.push("", 0);
1948
- }
1949
- const fullTemplate = this.engine.getFullMaskTemplate();
1950
- this.lastInternalRemainingMask = fullTemplate;
1951
- this.wrapper.setAttribute("data-mask", fullTemplate);
1952
- this.updateGhost("");
1953
- this.checkValueChange();
1954
- }
1955
- }
1956
- }
1957
- /**
1958
- * Vérifie si la valeur a changé et notifie les observateurs (onInput, onChange, onComplete).
1959
- * Gère de manière sûre la réentrance pour permettre d'appeler setMask() directement dans le callback.
1960
- */
1961
- checkValueChange(forceNotify = false) {
1962
- const currentVal = this.input.value;
1963
- if (currentVal === this.lastValue && !forceNotify && !this.hasPendingNotification) {
1964
- return;
1965
- }
1966
- if (this.isNotifying) {
1967
- this.hasPendingNotification = true;
1968
- return;
1969
- }
1970
- this.isNotifying = true;
1971
- try {
1972
- while (this.input.value !== this.lastValue || this.hasPendingNotification || forceNotify) {
1973
- this.hasPendingNotification = false;
1974
- forceNotify = false;
1975
- const valToNotify = this.input.value;
1976
- this.lastValue = valToNotify;
1977
- const raw = this.options.disabled ? valToNotify : this.getRawValue();
1978
- const totalSlots = this.options.disabled ? 0 : this.engine.getEditableCount();
1979
- const isComplete = this.isComplete();
1980
- const detail = {
1981
- value: valToNotify,
1982
- rawValue: raw,
1983
- isComplete,
1984
- totalSlots,
1985
- filledSlots: this.options.disabled ? valToNotify.length : raw.length
1986
- };
1987
- const onInputCb = this.options.onInput || this.options.oninput;
1988
- if (onInputCb) {
1989
- onInputCb(valToNotify, detail);
1990
- }
1991
- this.input.dispatchEvent(new CustomEvent("mask:input", { bubbles: true, detail }));
1992
- this.dispatchNativeInput();
1993
- const onChangeCb = this.options.onChange || this.options.onchange;
1994
- if (onChangeCb) {
1995
- onChangeCb(detail);
1996
- }
1997
- this.input.dispatchEvent(new CustomEvent("mask:change", { bubbles: true, detail }));
1998
- const onCompleteCb = this.options.onComplete || this.options.oncomplete;
1999
- if (isComplete) {
2000
- if (onCompleteCb) {
2001
- onCompleteCb(detail);
2002
- }
2003
- this.input.dispatchEvent(new CustomEvent("mask:complete", { bubbles: true, detail }));
2004
- }
2005
- }
2006
- } finally {
2007
- this.isNotifying = false;
2008
- }
2009
- }
2010
- };
2011
-
2012
- // src/mask/AmountEngine.ts
2013
- var AmountEngine = class _AmountEngine {
2014
- constructor(options = {}) {
2015
- let currency = options.currency ?? "";
2016
- if (!currency && options.unit) {
2017
- currency = options.unit;
2018
- }
2019
- const defaultPosition = currency === "$" || currency === "\xA3" || currency === "\xA5" ? "prefix" : "suffix";
2020
- this.options = {
2021
- currency,
2022
- unit: options.unit ?? currency,
2023
- currencyPosition: options.currencyPosition ?? defaultPosition,
2024
- decimals: options.decimals !== void 0 ? Math.max(0, options.decimals) : 2,
2025
- decimalSeparator: options.decimalSeparator ?? ",",
2026
- thousandSeparator: options.thousandSeparator ?? "\xA0",
2027
- // Espace insécable
2028
- allowNegative: options.allowNegative ?? false,
2029
- min: options.min ?? -Infinity,
2030
- max: options.max ?? Infinity
2031
- };
2032
- }
2033
- /**
2034
- * Analyse et nettoie une saisie utilisateur pour extraire ses composantes numériques.
2035
- */
2036
- parse(input) {
2037
- let str = input.trim();
2038
- let isNegative = false;
2039
- if (this.options.allowNegative && str.includes("-")) {
2040
- isNegative = true;
2041
- }
2042
- if (this.options.currency) {
2043
- str = str.replace(new RegExp(this.escapeRegExp(this.options.currency), "g"), "");
2044
- }
2045
- if (this.options.thousandSeparator) {
2046
- str = str.replace(new RegExp(this.escapeRegExp(this.options.thousandSeparator), "g"), "");
2047
- }
2048
- str = str.replace(/[\s\u00A0]/g, "");
2049
- const decSep = this.options.decimalSeparator;
2050
- let firstDecIndex = str.indexOf(decSep);
2051
- if (firstDecIndex === -1) {
2052
- firstDecIndex = str.search(/[,.]/);
2053
- }
2054
- let integerRaw = "";
2055
- let decimalRaw = null;
2056
- let hasDecimal = false;
2057
- if (firstDecIndex !== -1) {
2058
- integerRaw = str.substring(0, firstDecIndex).replace(/\D/g, "");
2059
- if (this.options.decimals > 0) {
2060
- hasDecimal = true;
2061
- decimalRaw = str.substring(firstDecIndex + 1).replace(/\D/g, "").slice(0, this.options.decimals);
2062
- }
2063
- } else {
2064
- integerRaw = str.replace(/\D/g, "");
2065
- }
2066
- if (integerRaw.length > 1) {
2067
- integerRaw = integerRaw.replace(/^0+/, "") || "0";
2068
- }
2069
- return { isNegative, integerPart: integerRaw, decimalPart: decimalRaw, hasDecimal };
2070
- }
2071
- /**
2072
- * Formate une valeur brute ou une saisie courante en préservant la fluidité du curseur.
2073
- *
2074
- * @param input Texte brut ou partiellement formaté
2075
- * @param rawCursor Position actuelle du curseur dans l'input natif
2076
- */
2077
- format(input, rawCursor = input.length, padDecimals = false) {
2078
- if (!input || input.trim() === "" || input === this.options.currency.trim()) {
2079
- return {
2080
- formatted: "",
2081
- rawNumber: null,
2082
- rawValue: "",
2083
- cursor: 0,
2084
- isValid: true
2085
- };
2086
- }
2087
- const prefixBeforeCursor = input.substring(0, rawCursor);
2088
- const digitsBeforeCursor = prefixBeforeCursor.replace(/\D/g, "").length;
2089
- const hadDecimalBeforeCursor = this.options.decimals > 0 && /[,.]/.test(prefixBeforeCursor);
2090
- const { isNegative, integerPart, decimalPart, hasDecimal } = this.parse(input);
2091
- let effectiveDecimal = decimalPart;
2092
- let effectiveHasDecimal = hasDecimal;
2093
- if (padDecimals && this.options.decimals > 0 && (integerPart || decimalPart !== null)) {
2094
- effectiveHasDecimal = true;
2095
- if (effectiveDecimal === null) {
2096
- effectiveDecimal = "0".repeat(this.options.decimals);
2097
- } else if (effectiveDecimal.length < this.options.decimals) {
2098
- effectiveDecimal = effectiveDecimal + "0".repeat(this.options.decimals - effectiveDecimal.length);
2099
- }
2100
- }
2101
- if (isNegative && !integerPart && !effectiveDecimal && !effectiveHasDecimal && this.options.allowNegative) {
2102
- let formatted2 = "-";
2103
- let cursor = 1;
2104
- if (this.options.currency) {
2105
- if (this.options.currencyPosition === "prefix") {
2106
- formatted2 = `${this.options.currency} -`;
2107
- cursor = formatted2.length;
2108
- } else {
2109
- formatted2 = `- ${this.options.currency}`;
2110
- cursor = 1;
2111
- }
2112
- }
2113
- return {
2114
- formatted: formatted2,
2115
- rawNumber: null,
2116
- rawValue: "-",
2117
- cursor,
2118
- isValid: true
2119
- };
2120
- }
2121
- if (!integerPart && !effectiveDecimal && !effectiveHasDecimal) {
2122
- return {
2123
- formatted: "",
2124
- rawNumber: null,
2125
- rawValue: "",
2126
- cursor: 0,
2127
- isValid: true
2128
- };
2129
- }
2130
- const formattedInteger = (integerPart || "0").replace(/\B(?=(\d{3})+(?!\d))/g, this.options.thousandSeparator);
2131
- let numberCore = formattedInteger;
2132
- if (effectiveHasDecimal && this.options.decimals > 0) {
2133
- numberCore += this.options.decimalSeparator + (effectiveDecimal ?? "");
2134
- }
2135
- if (isNegative && numberCore !== "0") {
2136
- numberCore = "-" + numberCore;
2137
- }
2138
- let formatted = numberCore;
2139
- if (this.options.currency) {
2140
- if (this.options.currencyPosition === "prefix") {
2141
- formatted = `${this.options.currency} ${numberCore}`;
2142
- } else {
2143
- formatted = `${numberCore} ${this.options.currency}`;
2144
- }
2145
- }
2146
- const numStr = (isNegative ? "-" : "") + (integerPart || "0") + (decimalPart ? "." + decimalPart : "");
2147
- let num = parseFloat(numStr);
2148
- if (isNaN(num)) num = 0;
2149
- const isValid = num >= this.options.min && num <= this.options.max;
2150
- let newCursor = 0;
2151
- if (this.options.currency && this.options.currencyPosition === "prefix") {
2152
- newCursor = this.options.currency.length + 1;
2153
- }
2154
- let seenDigits = 0;
2155
- let seenDecimal = false;
2156
- let lastValidDigitPosition = newCursor;
2157
- for (let i = newCursor; i < formatted.length; i++) {
2158
- const ch = formatted[i];
2159
- if (ch === this.options.currency.trim()[0] && this.options.currencyPosition === "suffix") {
2160
- break;
2161
- }
2162
- if (/\d/.test(ch)) {
2163
- seenDigits++;
2164
- lastValidDigitPosition = i + 1;
2165
- } else if (ch === this.options.decimalSeparator) {
2166
- seenDecimal = true;
2167
- lastValidDigitPosition = i + 1;
2168
- }
2169
- if (hadDecimalBeforeCursor) {
2170
- if (seenDecimal && seenDigits >= digitsBeforeCursor) {
2171
- newCursor = i + 1;
2172
- break;
2173
- }
2174
- } else {
2175
- if (seenDigits >= digitsBeforeCursor) {
2176
- newCursor = i + 1;
2177
- break;
2178
- }
2179
- }
2180
- }
2181
- if (digitsBeforeCursor > 0 && seenDigits < digitsBeforeCursor && lastValidDigitPosition > newCursor) {
2182
- newCursor = lastValidDigitPosition;
2183
- }
2184
- const minCursor = this.options.currency && this.options.currencyPosition === "prefix" ? this.options.currency.length + 1 : 0;
2185
- const maxCursor = this.options.currency && this.options.currencyPosition === "suffix" ? Math.max(0, formatted.length - this.options.currency.length - 1) : formatted.length;
2186
- newCursor = Math.max(minCursor, Math.min(newCursor, Math.max(minCursor, maxCursor)));
2187
- return {
2188
- formatted,
2189
- rawNumber: num,
2190
- rawValue: numStr,
2191
- cursor: newCursor,
2192
- isValid
2193
- };
2194
- }
2195
- /**
2196
- * Formate statiquement un nombre ou une chaîne numérique.
2197
- */
2198
- static format(value, options = {}) {
2199
- const engine = new _AmountEngine(options);
2200
- const str = typeof value === "number" ? value.toString() : value;
2201
- return engine.format(str).formatted;
2202
- }
2203
- escapeRegExp(string) {
2204
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2205
- }
2206
- };
2207
-
2208
- // src/mask/InputAmountMask.ts
2209
- var InputAmountMask = class extends BaseInputMask {
2210
- constructor(targetOrWrapper, inputOrOptions, options) {
2211
- const args = resolveMaskConstructorArgs(targetOrWrapper, inputOrOptions, options);
2212
- const wrap = args.wrapper;
2213
- const inp = args.input;
2214
- const opts = args.options;
2215
- const dataPad = wrap?.getAttribute("data-mask-pad-decimals") === "true" || inp?.getAttribute("data-mask-pad-decimals") === "true";
2216
- const dataAlign = inp?.getAttribute("data-mask-align") || inp?.getAttribute("data-align") || wrap?.getAttribute("data-mask-align") || wrap?.getAttribute("data-align");
2217
- const resolvedOptions = {
2218
- align: opts.align ?? dataAlign ?? "right",
2219
- padDecimalsOnBlur: opts.padDecimalsOnBlur ?? dataPad ?? false,
2220
- ...opts
2221
- };
2222
- super(wrap, inp, resolvedOptions);
2223
- this.isUndoingRedoing = false;
2224
- this.isApplying = false;
2225
- this.isComposing = false;
2226
- this.lastValue = "";
2227
- this.cutTimerId = null;
2228
- this.resetTimerId = null;
2229
- this.input.inputMode = "decimal";
2230
- this.history = new MaskHistory();
2231
- this.engine = new AmountEngine(this.options);
2232
- this.bindEvents();
2233
- if (this.input.value) {
2234
- if (!this.options.disabled) {
2235
- this.applyAmount(this.input.value, this.input.value.length);
2236
- }
2237
- } else {
2238
- this.updateGhost({
2239
- formatted: "",
2240
- rawNumber: null,
2241
- rawValue: "",
2242
- cursor: 0,
2243
- isValid: true
2244
- });
2245
- }
2246
- this.runAuditWarning(this.options.audit);
2247
- }
2248
- extractRawSnippet(snippet) {
2249
- const p = this.engine.parse(snippet);
2250
- if (!p.integerPart && !p.decimalPart) return "";
2251
- return (p.isNegative ? "-" : "") + (p.integerPart || "0") + (p.decimalPart ? "." + p.decimalPart : "");
2252
- }
2253
- /**
2254
- * Formate statiquement une valeur sans nécessiter d'élément DOM.
2255
- */
2256
- static format(value, options = {}) {
2257
- return AmountEngine.format(value, options);
2258
- }
2259
- onNativeValueSet(strVal) {
2260
- if (this.options.disabled || this.isComposing) {
2261
- this.lastValue = strVal;
2262
- return;
2263
- }
2264
- this.applyAmount(strVal, strVal.length);
2265
- }
2266
- onDisabledChange(disabled) {
2267
- if (!disabled) {
2268
- this.applyAmount(this.input.value, this.input.selectionStart ?? this.input.value.length);
2269
- }
2270
- }
2271
- bindEvents() {
2272
- this.handleInput = this.handleInput.bind(this);
2273
- this.handleKeyDown = this.handleKeyDown.bind(this);
2274
- this.handleBlur = this.handleBlur.bind(this);
2275
- this.handleFocus = this.handleFocus.bind(this);
2276
- this.handleClick = this.handleClick.bind(this);
2277
- this.onCompositionStart = this.onCompositionStart.bind(this);
2278
- this.onCompositionEnd = this.onCompositionEnd.bind(this);
2279
- this.onCutHandler = () => {
2280
- if (this.cutTimerId !== null) {
2281
- clearTimeout(this.cutTimerId);
2282
- }
2283
- this.cutTimerId = window.setTimeout(() => {
2284
- this.cutTimerId = null;
2285
- if (this.isDestroyed || this.options.disabled) return;
2286
- const cur = this.input.selectionStart ?? this.input.value.length;
2287
- this.applyAmount(this.input.value, cur);
2288
- }, 0);
2289
- };
2290
- this.input.addEventListener("input", this.handleInput);
2291
- this.input.addEventListener("keydown", this.handleKeyDown);
2292
- this.input.addEventListener("blur", this.handleBlur);
2293
- this.input.addEventListener("focus", this.handleFocus);
2294
- this.input.addEventListener("click", this.handleClick);
2295
- this.input.addEventListener("scroll", this.onScroll);
2296
- this.input.addEventListener("cut", this.onCutHandler);
2297
- this.input.addEventListener("compositionstart", this.onCompositionStart);
2298
- this.input.addEventListener("compositionend", this.onCompositionEnd);
2299
- if (this.input.form) {
2300
- this.onFormResetHandler = () => {
2301
- if (this.resetTimerId !== null) {
2302
- clearTimeout(this.resetTimerId);
2303
- }
2304
- this.resetTimerId = window.setTimeout(() => {
2305
- this.resetTimerId = null;
2306
- if (this.isDestroyed) return;
2307
- if (this.options.disabled) return;
2308
- this.applyAmount(this.input.value, this.input.value.length);
2309
- }, 0);
2310
- };
2311
- this.input.form.addEventListener("reset", this.onFormResetHandler);
2312
- }
2313
- }
2314
- onCompositionStart() {
2315
- this.isComposing = true;
2316
- }
2317
- onCompositionEnd() {
2318
- this.isComposing = false;
2319
- if (this.options.disabled) return;
2320
- const cur = this.input.selectionStart ?? this.input.value.length;
2321
- this.applyAmount(this.input.value, cur);
2322
- }
2323
- applyAmount(val, cursor) {
2324
- if (this.isApplying || this.options.disabled) return;
2325
- this.isApplying = true;
2326
- try {
2327
- const result = this.engine.format(val, cursor);
2328
- this.setNativeValue(result.formatted);
2329
- this.input.setSelectionRange(result.cursor, result.cursor);
2330
- if (!this.isUndoingRedoing && this.input.type !== "password") {
2331
- this.history.push(result.rawValue, result.cursor);
2332
- }
2333
- this.updateGhost(result);
2334
- if (this.lastValue !== result.formatted) {
2335
- this.lastValue = result.formatted;
2336
- this.notifyChange(result);
2337
- }
2338
- } finally {
2339
- this.isApplying = false;
2340
- }
2341
- }
2342
- updateGhost(result) {
2343
- if (!this.ghost) return;
2344
- if (!result.formatted) {
2345
- if (this.shouldHideGhostForPlaceholder(true)) {
2346
- this.ghost.textContent = "";
2347
- return;
2348
- }
2349
- const hint = this.options.currency ? this.options.currencyPosition === "prefix" ? `${this.options.currency} 0` : `0 ${this.options.currency}` : "0,00";
2350
- this.ghost.textContent = "";
2351
- const span = document.createElement("span");
2352
- span.className = "mask-ghost-remaining";
2353
- span.textContent = hint;
2354
- this.ghost.appendChild(span);
2355
- return;
2356
- }
2357
- this.ghost.textContent = "";
2358
- this.ghost.scrollLeft = this.input.scrollLeft;
2359
- }
2360
- handleInput() {
2361
- if (this.isDispatchingNativeInput) return;
2362
- if (this.options.disabled || this.isComposing) return;
2363
- const rawVal = this.input.value;
2364
- const cur = this.input.selectionStart ?? rawVal.length;
2365
- this.applyAmount(rawVal, cur);
2366
- }
2367
- handleKeyDown(e) {
2368
- if (this.options.disabled) return;
2369
- if ((e.ctrlKey || e.metaKey) && (e.key === "z" || e.key === "Z")) {
2370
- e.preventDefault();
2371
- if (e.shiftKey) this.redo();
2372
- else this.undo();
2373
- return;
2374
- }
2375
- if ((e.ctrlKey || e.metaKey) && (e.key === "y" || e.key === "Y")) {
2376
- e.preventDefault();
2377
- this.redo();
2378
- return;
2379
- }
2380
- if (e.key === "Backspace") {
2381
- const start = this.input.selectionStart ?? 0;
2382
- const end = this.input.selectionEnd ?? 0;
2383
- if (start === end && start > 0) {
2384
- const val = this.input.value;
2385
- const charToDelete = val[start - 1];
2386
- if (charToDelete === this.engine.options.thousandSeparator || charToDelete === " ") {
2387
- e.preventDefault();
2388
- const targetIndex = Math.max(0, start - 2);
2389
- const newVal = val.slice(0, targetIndex) + val.slice(start);
2390
- this.applyAmount(newVal, targetIndex);
2391
- return;
2392
- }
2393
- if (this.options.currency && this.options.currencyPosition === "prefix" && start <= this.options.currency.length + 1) {
2394
- e.preventDefault();
2395
- return;
2396
- }
2397
- }
2398
- }
2399
- if (e.key === "Delete") {
2400
- const start = this.input.selectionStart ?? 0;
2401
- const end = this.input.selectionEnd ?? 0;
2402
- if (start === end && start < this.input.value.length) {
2403
- const val = this.input.value;
2404
- const charAhead = val[start];
2405
- if (charAhead === this.engine.options.thousandSeparator || charAhead === " ") {
2406
- e.preventDefault();
2407
- const newVal = val.slice(0, start) + val.slice(start + 2);
2408
- this.applyAmount(newVal, start);
2409
- return;
2410
- }
2411
- if (this.options.currency && this.options.currencyPosition === "suffix") {
2412
- const suffixStart = val.length - this.options.currency.length - 1;
2413
- if (start >= suffixStart) {
2414
- e.preventDefault();
2415
- return;
2416
- }
2417
- }
2418
- }
2419
- }
2420
- setTimeout(() => this.enforceCursorBounds(), 0);
2421
- }
2422
- enforceCursorBounds() {
2423
- if (!this.input.value || this.options.disabled) return;
2424
- const start = this.input.selectionStart ?? 0;
2425
- const end = this.input.selectionEnd ?? 0;
2426
- if (start !== end) return;
2427
- const val = this.input.value;
2428
- const currency = this.options.currency;
2429
- if (currency) {
2430
- if (this.options.currencyPosition === "prefix") {
2431
- const minPos = currency.length + 1;
2432
- if (start < minPos) {
2433
- this.input.setSelectionRange(minPos, minPos);
2434
- }
2435
- } else if (this.options.currencyPosition === "suffix") {
2436
- const maxPos = Math.max(0, val.length - currency.length - 1);
2437
- if (start > maxPos) {
2438
- this.input.setSelectionRange(maxPos, maxPos);
2439
- }
2440
- }
2441
- }
2442
- }
2443
- handleClick() {
2444
- this.enforceCursorBounds();
2445
- }
2446
- handleFocus() {
2447
- this.wrapper.classList.add("is-focused");
2448
- this.syncGhostStyles();
2449
- this.enforceCursorBounds();
2450
- this.updateGhost(this.engine.format(this.input.value));
2451
- }
2452
- handleBlur() {
2453
- this.wrapper.classList.remove("is-focused");
2454
- if (this.input.type === "password") {
2455
- this.history.clear();
2456
- }
2457
- if (this.options.padDecimalsOnBlur && !this.options.disabled && this.input.value.trim().length > 0) {
2458
- const paddedResult = this.engine.format(this.input.value, this.input.value.length, true);
2459
- if (paddedResult.formatted !== this.input.value) {
2460
- this.setNativeValue(paddedResult.formatted);
2461
- this.lastValue = paddedResult.formatted;
2462
- }
2463
- }
2464
- this.updateGhost(this.engine.format(this.input.value));
2465
- const detail = this.getDetail();
2466
- if (this.options.onChange) {
2467
- this.options.onChange(detail);
2468
- }
2469
- this.input.dispatchEvent(new CustomEvent("mask:change", { bubbles: true, detail }));
2470
- }
2471
- handleAttributeMutation(attrName) {
2472
- super.handleAttributeMutation(attrName);
2473
- if (attrName === "data-mask-pad-decimals") {
2474
- this.options.padDecimalsOnBlur = this.getAttr("data-mask-pad-decimals") === "true";
2475
- } else if (attrName === "placeholder") {
2476
- this.updateGhost(this.engine.format(this.input.value));
2477
- }
2478
- }
2479
- notifyChange(result) {
2480
- const detail = {
2481
- value: result.formatted,
2482
- number: result.rawNumber,
2483
- rawValue: result.rawValue,
2484
- isValid: result.isValid
2485
- };
2486
- if (this.options.onInput) {
2487
- this.options.onInput(detail);
2488
- }
2489
- this.input.dispatchEvent(new CustomEvent("mask:input", { bubbles: true, detail }));
2490
- this.dispatchNativeInput();
2491
- }
2492
- undo() {
2493
- const state = this.history.undo();
2494
- if (state) {
2495
- this.isUndoingRedoing = true;
2496
- try {
2497
- this.applyAmount(state.raw, state.cursor);
2498
- } finally {
2499
- this.isUndoingRedoing = false;
2500
- }
2501
- }
2502
- }
2503
- redo() {
2504
- const state = this.history.redo();
2505
- if (state) {
2506
- this.isUndoingRedoing = true;
2507
- try {
2508
- this.applyAmount(state.raw, state.cursor);
2509
- } finally {
2510
- this.isUndoingRedoing = false;
2511
- }
2512
- }
2513
- }
2514
- getDetail() {
2515
- const parsed = this.engine.format(this.input.value);
2516
- return {
2517
- value: parsed.formatted,
2518
- number: parsed.rawNumber,
2519
- rawValue: parsed.rawValue,
2520
- isValid: parsed.isValid
2521
- };
2522
- }
2523
- getNumber() {
2524
- return this.getDetail().number;
2525
- }
2526
- getRawValue() {
2527
- return this.getDetail().rawValue;
2528
- }
2529
- isValid() {
2530
- return this.getDetail().isValid;
2531
- }
2532
- setValue(val) {
2533
- const str = val !== null && val !== void 0 ? String(val) : "";
2534
- if (this.options.disabled) {
2535
- this.setNativeValue(str);
2536
- this.lastValue = str;
2537
- } else {
2538
- this.applyAmount(str, str.length);
2539
- }
2540
- }
2541
- destroy() {
2542
- if (this.isDestroyed) return;
2543
- if (this.cutTimerId !== null) {
2544
- clearTimeout(this.cutTimerId);
2545
- this.cutTimerId = null;
2546
- }
2547
- if (this.resetTimerId !== null) {
2548
- clearTimeout(this.resetTimerId);
2549
- this.resetTimerId = null;
2550
- }
2551
- this.input.removeEventListener("input", this.handleInput);
2552
- this.input.removeEventListener("keydown", this.handleKeyDown);
2553
- this.input.removeEventListener("blur", this.handleBlur);
2554
- this.input.removeEventListener("focus", this.handleFocus);
2555
- this.input.removeEventListener("click", this.handleClick);
2556
- this.input.removeEventListener("scroll", this.onScroll);
2557
- this.input.removeEventListener("cut", this.onCutHandler);
2558
- this.input.removeEventListener("compositionstart", this.onCompositionStart);
2559
- this.input.removeEventListener("compositionend", this.onCompositionEnd);
2560
- if (this.input.form && this.onFormResetHandler) {
2561
- this.input.form.removeEventListener("reset", this.onFormResetHandler);
2562
- }
2563
- this.history.clear();
2564
- super.destroy();
2565
- }
2566
- };
2567
-
2568
- // src/mask/EmailEngine.ts
2569
- var _EmailEngine = class _EmailEngine {
2570
- constructor(options = {}) {
2571
- this.defaultDomain = null;
2572
- this.defaultTld = "__";
2573
- this.domains = options.domains && options.domains.length > 0 ? options.domains : _EmailEngine.DEFAULT_DOMAINS;
2574
- this.tlds = options.tlds && options.tlds.length > 0 ? options.tlds.map((t) => t.trim().replace(/^\./, "")).filter(Boolean) : [..._EmailEngine.DEFAULT_TLDS];
2575
- this.suggestOnAt = options.suggestOnAt ?? true;
2576
- this.setDefaultDomain(options.defaultDomain ?? null);
2577
- this.setDefaultTld(options.defaultTld !== void 0 ? options.defaultTld : "__");
2578
- }
2579
- /**
2580
- * Définit ou modifie le domaine suggéré par défaut.
2581
- */
2582
- setDefaultDomain(domain) {
2583
- if (domain === true) {
2584
- this.defaultDomain = this.domains.length > 0 ? this.domains[0] : null;
2585
- } else if (typeof domain === "string" && domain.trim().length > 0) {
2586
- this.defaultDomain = domain.trim().replace(/^@/, "");
2587
- } else {
2588
- this.defaultDomain = null;
2589
- }
2590
- }
2591
- /**
2592
- * Définit ou modifie l'extension (TLD) ou gabarit suggéré par défaut sur un domaine inconnu.
2593
- */
2594
- setDefaultTld(tld) {
2595
- if (tld === true) {
2596
- this.defaultTld = this.tlds.length > 0 ? this.tlds[0] : null;
2597
- } else if (typeof tld === "string" && tld.trim().length > 0) {
2598
- this.defaultTld = tld.trim().replace(/^\./, "");
2599
- } else {
2600
- this.defaultTld = null;
2601
- }
2602
- }
2603
- /**
2604
- * Définit ou modifie la liste des extensions (TLD) proposées par ordre de priorité.
2605
- */
2606
- setTlds(tlds) {
2607
- this.tlds = tlds && tlds.length > 0 ? tlds.map((t) => t.trim().replace(/^\./, "")).filter(Boolean) : [..._EmailEngine.DEFAULT_TLDS];
2608
- }
2609
- /**
2610
- * Retourne l'ensemble des extensions (TLD) correspondant au fragment saisi après le dernier point,
2611
- * dans l'ordre exact fourni par l'utilisateur.
2612
- */
2613
- getMatchingTlds(tldInput) {
2614
- const query = (tldInput ?? "").toLowerCase();
2615
- if (query.length === 0) {
2616
- return [...this.tlds];
2617
- }
2618
- return this.tlds.filter((t) => t.toLowerCase().startsWith(query) && t.toLowerCase() !== query);
2619
- }
2620
- /**
2621
- * Retourne l'ensemble des domaines correspondant à la saisie courante.
2622
- */
2623
- getMatchingDomains(input) {
2624
- const val = input ?? "";
2625
- if (!val.includes("@")) {
2626
- return this.defaultDomain ? [this.defaultDomain] : [];
2627
- }
2628
- const atIndex = val.indexOf("@");
2629
- if (val.indexOf("@", atIndex + 1) !== -1) {
2630
- return [];
2631
- }
2632
- const domainPart = val.substring(atIndex + 1);
2633
- if (domainPart.length === 0) {
2634
- return this.suggestOnAt ? [...this.domains] : [];
2635
- }
2636
- const query = domainPart.toLowerCase();
2637
- return this.domains.filter((d) => d.toLowerCase().startsWith(query) && d.toLowerCase() !== query);
2638
- }
2639
- /**
2640
- * Analyse la saisie courante et calcule la suggestion de domaine ou d'extension (TLD) adaptée.
2641
- *
2642
- * @param input Saisie utilisateur
2643
- * @param matchIndex Index de la suggestion à sélectionner si plusieurs domaines/TLD correspondent (permet le cyclage)
2644
- */
2645
- getSuggestion(input, matchIndex = 0) {
2646
- const val = input ?? "";
2647
- if (!val.includes("@")) {
2648
- if (this.defaultDomain) {
2649
- return {
2650
- full: val ? `${val}@${this.defaultDomain}` : `@${this.defaultDomain}`,
2651
- remaining: `@${this.defaultDomain}`,
2652
- matchedDomain: this.defaultDomain,
2653
- isHintOnly: false
2654
- };
2655
- }
2656
- return { full: val, remaining: "", matchedDomain: null, isHintOnly: false };
2657
- }
2658
- const atIndex = val.indexOf("@");
2659
- const localPart = val.substring(0, atIndex);
2660
- const domainPart = val.substring(atIndex + 1);
2661
- if (val.indexOf("@", atIndex + 1) !== -1) {
2662
- return { full: val, remaining: "", matchedDomain: null, isHintOnly: false };
2663
- }
2664
- const matches = this.getMatchingDomains(input);
2665
- if (matches.length > 0) {
2666
- const safeIndex = (matchIndex % matches.length + matches.length) % matches.length;
2667
- const matched = matches[safeIndex];
2668
- const query = domainPart.toLowerCase();
2669
- const remaining = matched.substring(query.length);
2670
- return {
2671
- full: `${localPart}@${matched}`,
2672
- remaining,
2673
- matchedDomain: matched,
2674
- isHintOnly: false
2675
- };
2676
- }
2677
- if (domainPart.length === 0 || domainPart.startsWith(".")) {
2678
- return { full: input, remaining: "", matchedDomain: null, isHintOnly: false };
2679
- }
2680
- const lowerDomain = domainPart.toLowerCase();
2681
- if (this.domains.some((d) => d.toLowerCase() === lowerDomain)) {
2682
- return { full: input, remaining: "", matchedDomain: domainPart, isHintOnly: false };
2683
- }
2684
- const lastDotIndex = domainPart.lastIndexOf(".");
2685
- if (lastDotIndex === -1) {
2686
- if (!this.defaultTld) {
2687
- return { full: input, remaining: "", matchedDomain: null, isHintOnly: false };
2688
- }
2689
- const isHint = this.defaultTld.includes("_");
2690
- const remaining = `.${this.defaultTld}`;
2691
- const fullDomain = `${domainPart}.${this.defaultTld}`;
2692
- return {
2693
- full: isHint ? input : `${localPart}@${fullDomain}`,
2694
- remaining,
2695
- matchedDomain: isHint ? null : fullDomain,
2696
- isHintOnly: isHint
2697
- };
2698
- }
2699
- const hostPart = domainPart.substring(0, lastDotIndex);
2700
- const tldPart = domainPart.substring(lastDotIndex + 1);
2701
- if (!hostPart || hostPart.endsWith(".")) {
2702
- return { full: input, remaining: "", matchedDomain: null, isHintOnly: false };
2703
- }
2704
- if (tldPart.length === 0) {
2705
- if (this.defaultTld && !this.defaultTld.includes("_")) {
2706
- const fullDomain = `${hostPart}.${this.defaultTld}`;
2707
- return {
2708
- full: `${localPart}@${fullDomain}`,
2709
- remaining: this.defaultTld,
2710
- matchedDomain: fullDomain,
2711
- isHintOnly: false
2712
- };
2713
- }
2714
- if (this.defaultTld && this.defaultTld.includes("_")) {
2715
- return {
2716
- full: input,
2717
- remaining: this.defaultTld,
2718
- matchedDomain: null,
2719
- isHintOnly: true
2720
- };
2721
- }
2722
- return { full: input, remaining: "", matchedDomain: null, isHintOnly: false };
2723
- }
2724
- const lowerTld = tldPart.toLowerCase();
2725
- const matchingTlds = this.getMatchingTlds(tldPart);
2726
- if (matchingTlds.length > 0) {
2727
- const safeTldIndex = (matchIndex % matchingTlds.length + matchingTlds.length) % matchingTlds.length;
2728
- const matchedTld = matchingTlds[safeTldIndex];
2729
- const remaining = matchedTld.substring(lowerTld.length);
2730
- const fullDomain = `${hostPart}.${matchedTld}`;
2731
- return {
2732
- full: `${localPart}@${fullDomain}`,
2733
- remaining,
2734
- matchedDomain: fullDomain,
2735
- isHintOnly: false
2736
- };
2737
- }
2738
- if (this.defaultTld && this.defaultTld.includes("_") && tldPart.length < this.defaultTld.length) {
2739
- const remaining = this.defaultTld.substring(tldPart.length);
2740
- if (remaining.includes("_")) {
2741
- return {
2742
- full: input,
2743
- remaining,
2744
- matchedDomain: null,
2745
- isHintOnly: true
2746
- };
2747
- }
2748
- }
2749
- return { full: input, remaining: "", matchedDomain: null, isHintOnly: false };
2750
- }
2751
- };
2752
- _EmailEngine.DEFAULT_DOMAINS = [
2753
- "gmail.com",
2754
- "outlook.com",
2755
- "orange.fr",
2756
- "free.fr",
2757
- "sfr.fr",
2758
- "yahoo.com",
2759
- "hotmail.com",
2760
- "icloud.com",
2761
- "laposte.net",
2762
- "proton.me"
2763
- ];
2764
- _EmailEngine.DEFAULT_TLDS = [
2765
- "com",
2766
- "fr",
2767
- "net",
2768
- "org",
2769
- "eu",
2770
- "io",
2771
- "co",
2772
- "info",
2773
- "biz",
2774
- "me",
2775
- "tv",
2776
- "fi",
2777
- "be",
2778
- "ch",
2779
- "ca",
2780
- "uk",
2781
- "de",
2782
- "es",
2783
- "it"
2784
- ];
2785
- var EmailEngine = _EmailEngine;
2786
-
2787
- // src/mask/InputEmailMask.ts
2788
- var InputEmailMask = class extends BaseInputMask {
2789
- constructor(targetOrWrapper, inputOrOptions, options) {
2790
- const args = resolveMaskConstructorArgs(targetOrWrapper, inputOrOptions, options);
2791
- const wrap = args.wrapper;
2792
- const inp = args.input;
2793
- const opts = args.options;
2794
- const dataCycle = wrap?.getAttribute("data-mask-cycle-suggestions") === "true" || inp?.getAttribute("data-mask-cycle-suggestions") === "true";
2795
- const dataAutoLower = wrap?.getAttribute("data-mask-auto-lowercase") === "true" || inp?.getAttribute("data-mask-auto-lowercase") === "true";
2796
- const dataAriaAuto = wrap?.getAttribute("data-mask-aria-autocomplete") ?? inp?.getAttribute("data-mask-aria-autocomplete");
2797
- const setAriaAutocomplete = opts.setAriaAutocomplete ?? (dataAriaAuto !== null ? dataAriaAuto !== "false" : true);
2798
- const dataTlds = wrap?.getAttribute("data-mask-tlds") ?? inp?.getAttribute("data-mask-tlds");
2799
- const parsedTlds = opts.tlds ?? (dataTlds ? dataTlds.split(",").map((s) => s.trim()).filter(Boolean) : void 0);
2800
- const dataDefaultTld = wrap?.getAttribute("data-mask-default-tld") ?? inp?.getAttribute("data-mask-default-tld");
2801
- const resolvedDefaultTld = opts.defaultTld !== void 0 ? opts.defaultTld : dataDefaultTld !== null ? dataDefaultTld === "false" || dataDefaultTld === "none" ? null : dataDefaultTld === "true" ? true : dataDefaultTld : void 0;
2802
- const resolvedOptions = {
2803
- completeOnTab: true,
2804
- completeOnArrowRight: true,
2805
- completeOnEnter: true,
2806
- cycleSuggestions: opts.cycleSuggestions ?? dataCycle ?? false,
2807
- autoLowercase: opts.autoLowercase ?? dataAutoLower ?? false,
2808
- setAriaAutocomplete,
2809
- ...opts,
2810
- ...parsedTlds !== void 0 ? { tlds: parsedTlds } : {},
2811
- ...resolvedDefaultTld !== void 0 ? { defaultTld: resolvedDefaultTld } : {}
2812
- };
2813
- super(wrap, inp, resolvedOptions);
2814
- this.currentSuggestion = { full: "", remaining: "", matchedDomain: null };
2815
- this.currentSuggestionIndex = 0;
2816
- this.wasAriaAutocompleteSet = false;
2817
- this.cutTimerId = null;
2818
- this.resetTimerId = null;
2819
- this.input.inputMode = "email";
2820
- if (this.options.setAriaAutocomplete && !this.input.hasAttribute("aria-autocomplete")) {
2821
- this.input.setAttribute("aria-autocomplete", "inline");
2822
- this.wasAriaAutocompleteSet = true;
2823
- }
2824
- this.engine = new EmailEngine(this.options);
2825
- this.bindEvents();
2826
- if (!this.options.disabled) {
2827
- this.updateSuggestion();
2828
- }
2829
- this.runAuditWarning(this.options.audit);
2830
- }
2831
- onNativeValueSet(_strVal) {
2832
- if (this.options.disabled) return;
2833
- this.updateSuggestion();
2834
- }
2835
- onDisabledChange(disabled) {
2836
- if (disabled) {
2837
- if (this.ghost) this.ghost.textContent = "";
2838
- } else {
2839
- this.updateSuggestion();
2840
- }
2841
- }
2842
- bindEvents() {
2843
- this.handleInput = this.handleInput.bind(this);
2844
- this.handleKeyDown = this.handleKeyDown.bind(this);
2845
- this.handleBlur = this.handleBlur.bind(this);
2846
- this.handleFocus = this.handleFocus.bind(this);
2847
- this.onCutHandler = () => {
2848
- if (this.cutTimerId !== null) {
2849
- clearTimeout(this.cutTimerId);
2850
- }
2851
- this.cutTimerId = window.setTimeout(() => {
2852
- this.cutTimerId = null;
2853
- if (this.isDestroyed || this.options.disabled) return;
2854
- this.updateSuggestion();
2855
- }, 0);
2856
- };
2857
- this.input.addEventListener("input", this.handleInput);
2858
- this.input.addEventListener("keydown", this.handleKeyDown);
2859
- this.input.addEventListener("blur", this.handleBlur);
2860
- this.input.addEventListener("focus", this.handleFocus);
2861
- this.input.addEventListener("scroll", this.onScroll);
2862
- this.input.addEventListener("cut", this.onCutHandler);
2863
- if (this.input.form) {
2864
- this.onFormResetHandler = () => {
2865
- if (this.resetTimerId !== null) {
2866
- clearTimeout(this.resetTimerId);
2867
- }
2868
- this.resetTimerId = window.setTimeout(() => {
2869
- this.resetTimerId = null;
2870
- if (this.isDestroyed || this.options.disabled) return;
2871
- this.updateSuggestion();
2872
- }, 0);
2873
- };
2874
- this.input.form.addEventListener("reset", this.onFormResetHandler);
2875
- }
2876
- }
2877
- updateSuggestion() {
2878
- if (this.options.disabled) {
2879
- if (this.ghost) this.ghost.textContent = "";
2880
- return;
2881
- }
2882
- const val = this.input.value;
2883
- this.currentSuggestion = this.engine.getSuggestion(val, this.currentSuggestionIndex);
2884
- if (!this.ghost) return;
2885
- if (this.shouldHideGhostForPlaceholder(val.length === 0)) {
2886
- this.ghost.textContent = "";
2887
- } else if (this.currentSuggestion.remaining) {
2888
- this.ghost.textContent = "";
2889
- const spanTyped = document.createElement("span");
2890
- spanTyped.className = "mask-ghost-typed";
2891
- spanTyped.textContent = val;
2892
- const spanRemaining = document.createElement("span");
2893
- spanRemaining.className = "mask-ghost-remaining";
2894
- spanRemaining.textContent = this.currentSuggestion.remaining;
2895
- this.ghost.appendChild(spanTyped);
2896
- this.ghost.appendChild(spanRemaining);
2897
- } else {
2898
- this.ghost.textContent = "";
2899
- }
2900
- this.ghost.scrollLeft = this.input.scrollLeft;
2901
- const detail = this.getDetail();
2902
- if (this.options.onInput) {
2903
- this.options.onInput(detail);
2904
- }
2905
- this.input.dispatchEvent(new CustomEvent("mask:input", { bubbles: true, detail }));
2906
- this.dispatchNativeInput();
2907
- }
2908
- handleInput() {
2909
- if (this.isDispatchingNativeInput) return;
2910
- if (this.options.disabled) return;
2911
- if (this.options.autoLowercase) {
2912
- const start = this.input.selectionStart ?? 0;
2913
- const end = this.input.selectionEnd ?? start;
2914
- const lower = this.input.value.toLowerCase();
2915
- if (lower !== this.input.value) {
2916
- this.setNativeValue(lower);
2917
- this.input.setSelectionRange(start, end);
2918
- }
2919
- }
2920
- this.currentSuggestionIndex = 0;
2921
- this.updateSuggestion();
2922
- }
2923
- handleKeyDown(e) {
2924
- if (this.options.disabled) return;
2925
- const hasSuggestion = Boolean(this.currentSuggestion.remaining) && !this.currentSuggestion.isHintOnly;
2926
- const cursor = this.input.selectionStart ?? 0;
2927
- const isAtEnd = cursor === this.input.value.length;
2928
- const isNotEmpty = this.input.value.length > 0;
2929
- if (this.options.cycleSuggestions && hasSuggestion && isNotEmpty && isAtEnd) {
2930
- if (e.key === "ArrowDown") {
2931
- e.preventDefault();
2932
- this.currentSuggestionIndex++;
2933
- this.updateSuggestion();
2934
- return;
2935
- }
2936
- if (e.key === "ArrowUp") {
2937
- e.preventDefault();
2938
- this.currentSuggestionIndex--;
2939
- this.updateSuggestion();
2940
- return;
2941
- }
2942
- }
2943
- if (e.key === "Tab" && hasSuggestion && isNotEmpty && this.options.completeOnTab) {
2944
- e.preventDefault();
2945
- this.acceptSuggestion();
2946
- return;
2947
- }
2948
- if (e.key === "Enter" && hasSuggestion && isNotEmpty && this.options.completeOnEnter) {
2949
- e.preventDefault();
2950
- this.acceptSuggestion();
2951
- return;
2952
- }
2953
- if (e.key === "ArrowRight" && hasSuggestion && isNotEmpty && isAtEnd && this.options.completeOnArrowRight) {
2954
- e.preventDefault();
2955
- this.acceptSuggestion();
2956
- return;
2957
- }
2958
- }
2959
- /**
2960
- * Valide et applique la suggestion courante dans le champ natif.
2961
- */
2962
- acceptSuggestion() {
2963
- if (!this.currentSuggestion.remaining || this.currentSuggestion.isHintOnly || this.options.disabled || this.input.value.length === 0) return false;
2964
- const completed = this.currentSuggestion.full;
2965
- this.setNativeValue(completed);
2966
- this.input.setSelectionRange(completed.length, completed.length);
2967
- this.currentSuggestionIndex = 0;
2968
- this.updateSuggestion();
2969
- const detail = this.getDetail();
2970
- if (this.options.onChange) {
2971
- this.options.onChange(detail);
2972
- }
2973
- this.input.dispatchEvent(new CustomEvent("mask:change", { bubbles: true, detail }));
2974
- this.input.dispatchEvent(new CustomEvent("mask:complete", { bubbles: true, detail }));
2975
- return true;
2976
- }
2977
- /**
2978
- * Modifie dynamiquement le domaine suggéré par défaut.
2979
- */
2980
- setDefaultDomain(domain) {
2981
- this.engine.setDefaultDomain(domain);
2982
- this.updateSuggestion();
2983
- }
2984
- /**
2985
- * Modifie dynamiquement l'extension (TLD) ou gabarit suggéré par défaut sur un domaine inconnu.
2986
- */
2987
- setDefaultTld(tld) {
2988
- this.engine.setDefaultTld(tld);
2989
- this.updateSuggestion();
2990
- }
2991
- /**
2992
- * Modifie dynamiquement la liste des extensions (TLD) connues.
2993
- */
2994
- setTlds(tlds) {
2995
- this.engine.setTlds(tlds);
2996
- this.currentSuggestionIndex = 0;
2997
- this.updateSuggestion();
2998
- }
2999
- handleFocus() {
3000
- this.wrapper.classList.add("is-focused");
3001
- this.syncGhostStyles();
3002
- this.updateSuggestion();
3003
- }
3004
- handleBlur() {
3005
- this.wrapper.classList.remove("is-focused");
3006
- this.updateSuggestion();
3007
- const detail = this.getDetail();
3008
- if (this.options.onChange) {
3009
- this.options.onChange(detail);
3010
- }
3011
- this.input.dispatchEvent(new CustomEvent("mask:change", { bubbles: true, detail }));
3012
- }
3013
- handleAttributeMutation(attrName) {
3014
- super.handleAttributeMutation(attrName);
3015
- if (attrName === "data-mask-cycle-suggestions") {
3016
- this.options.cycleSuggestions = this.getAttr("data-mask-cycle-suggestions") === "true";
3017
- } else if (attrName === "data-mask-auto-lowercase") {
3018
- this.options.autoLowercase = this.getAttr("data-mask-auto-lowercase") === "true";
3019
- } else if (attrName === "data-mask-default-tld") {
3020
- const val = this.getAttr("data-mask-default-tld");
3021
- this.setDefaultTld(val === null || val === "false" || val === "none" ? null : val === "true" ? true : val);
3022
- } else if (attrName === "data-mask-tlds") {
3023
- const val = this.getAttr("data-mask-tlds");
3024
- this.setTlds(val ? val.split(",").map((s) => s.trim()).filter(Boolean) : null);
3025
- } else if (attrName === "placeholder") {
3026
- this.updateSuggestion();
3027
- }
3028
- }
3029
- getDetail() {
3030
- return {
3031
- value: this.input.value,
3032
- suggestedValue: this.currentSuggestion.isHintOnly ? "" : this.currentSuggestion.full,
3033
- domain: this.currentSuggestion.matchedDomain
3034
- };
3035
- }
3036
- setValue(val) {
3037
- const str = val !== null && val !== void 0 ? String(val) : "";
3038
- this.setNativeValue(str);
3039
- this.updateSuggestion();
3040
- }
3041
- destroy() {
3042
- if (this.isDestroyed) return;
3043
- if (this.cutTimerId !== null) {
3044
- clearTimeout(this.cutTimerId);
3045
- this.cutTimerId = null;
3046
- }
3047
- if (this.resetTimerId !== null) {
3048
- clearTimeout(this.resetTimerId);
3049
- this.resetTimerId = null;
3050
- }
3051
- this.input.removeEventListener("input", this.handleInput);
3052
- this.input.removeEventListener("keydown", this.handleKeyDown);
3053
- this.input.removeEventListener("blur", this.handleBlur);
3054
- this.input.removeEventListener("focus", this.handleFocus);
3055
- this.input.removeEventListener("scroll", this.onScroll);
3056
- this.input.removeEventListener("cut", this.onCutHandler);
3057
- if (this.input.form && this.onFormResetHandler) {
3058
- this.input.form.removeEventListener("reset", this.onFormResetHandler);
3059
- }
3060
- if (this.wasAriaAutocompleteSet && this.input.getAttribute("aria-autocomplete") === "inline") {
3061
- this.input.removeAttribute("aria-autocomplete");
3062
- }
3063
- super.destroy();
3064
- }
3065
- };
3066
-
3067
- // src/mask/index.ts
3068
- var Mask = {
3069
- BaseInputMask,
3070
- InputMask,
3071
- MaskEngine,
3072
- MaskHistory,
3073
- MaskKeyboard,
3074
- AmountEngine,
3075
- InputAmountMask,
3076
- EmailEngine,
3077
- InputEmailMask
3078
- };
3079
- if (typeof window !== "undefined") {
3080
- const win = window;
3081
- const wulfNamespace = win.Wulf || {};
3082
- win.Wulf = wulfNamespace;
3083
- wulfNamespace.Mask = Mask;
3084
- }
3085
- var index_default = InputMask;
3086
- //# sourceMappingURL=mask.cjs.js.map