wulf.js 1.9.0 → 1.9.2

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 (75) hide show
  1. package/README.md +220 -19
  2. package/changelog.md +42 -0
  3. package/dist/focus-trap.esm.js +407 -0
  4. package/dist/focus-trap.esm.js.map +7 -0
  5. package/dist/focus-trap.global.js +433 -0
  6. package/dist/focus-trap.global.js.map +7 -0
  7. package/dist/focus-trap.global.min.js +6 -0
  8. package/dist/focus-trap.global.min.js.map +7 -0
  9. package/dist/index.esm.js +1179 -8
  10. package/dist/index.esm.js.map +4 -4
  11. package/dist/index.global.js +1180 -9
  12. package/dist/index.global.js.map +4 -4
  13. package/dist/index.global.min.js +5 -2
  14. package/dist/index.global.min.js.map +4 -4
  15. package/dist/mask.esm.js +106 -2
  16. package/dist/mask.esm.js.map +3 -3
  17. package/dist/mask.global.js +107 -3
  18. package/dist/mask.global.js.map +3 -3
  19. package/dist/mask.global.min.js +5 -2
  20. package/dist/mask.global.min.js.map +4 -4
  21. package/dist/masonry.esm.js +78 -3
  22. package/dist/masonry.esm.js.map +3 -3
  23. package/dist/masonry.global.js +79 -4
  24. package/dist/masonry.global.js.map +3 -3
  25. package/dist/masonry.global.min.js +5 -2
  26. package/dist/masonry.global.min.js.map +4 -4
  27. package/dist/scroll.esm.js +78 -3
  28. package/dist/scroll.esm.js.map +3 -3
  29. package/dist/scroll.global.js +79 -4
  30. package/dist/scroll.global.js.map +3 -3
  31. package/dist/scroll.global.min.js +5 -2
  32. package/dist/scroll.global.min.js.map +4 -4
  33. package/dist/shortcut.esm.js +584 -0
  34. package/dist/shortcut.esm.js.map +7 -0
  35. package/dist/shortcut.global.js +610 -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.esm.js +91 -2
  40. package/dist/toast.esm.js.map +3 -3
  41. package/dist/toast.global.js +92 -3
  42. package/dist/toast.global.js.map +3 -3
  43. package/dist/toast.global.min.js +5 -2
  44. package/dist/toast.global.min.js.map +4 -4
  45. package/dist/types/common/AuditableComponent.d.ts +45 -0
  46. package/dist/types/common/LocalizedComponent.d.ts +3 -2
  47. package/dist/types/focus-trap/FocusTrap.d.ts +64 -0
  48. package/dist/types/focus-trap/index.d.ts +3 -0
  49. package/dist/types/focus-trap/types.d.ts +45 -0
  50. package/dist/types/index.d.ts +5 -0
  51. package/dist/types/mask/BaseInputMask.d.ts +14 -1
  52. package/dist/types/mask/InputMask.d.ts +1 -0
  53. package/dist/types/mask/types.d.ts +5 -2
  54. package/dist/types/masonry/Masonry.d.ts +7 -0
  55. package/dist/types/masonry/types.d.ts +7 -2
  56. package/dist/types/scroll/ScrollBlock.d.ts +7 -0
  57. package/dist/types/scroll/types.d.ts +3 -2
  58. package/dist/types/shortcut/ShortcutFormatter.d.ts +31 -0
  59. package/dist/types/shortcut/ShortcutManager.d.ts +91 -0
  60. package/dist/types/shortcut/index.d.ts +4 -0
  61. package/dist/types/shortcut/types.d.ts +101 -0
  62. package/dist/types/toast/Toast.d.ts +3 -0
  63. package/dist/types/toast/ToastInstance.d.ts +9 -1
  64. package/dist/types/toast/types.d.ts +3 -2
  65. package/package.json +23 -10
  66. package/dist/index.cjs.js +0 -4783
  67. package/dist/index.cjs.js.map +0 -7
  68. package/dist/mask.cjs.js +0 -2982
  69. package/dist/mask.cjs.js.map +0 -7
  70. package/dist/masonry.cjs.js +0 -783
  71. package/dist/masonry.cjs.js.map +0 -7
  72. package/dist/scroll.cjs.js +0 -748
  73. package/dist/scroll.cjs.js.map +0 -7
  74. package/dist/toast.cjs.js +0 -626
  75. package/dist/toast.cjs.js.map +0 -7
package/dist/index.cjs.js DELETED
@@ -1,4783 +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/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
- LocalizedComponent: () => LocalizedComponent,
30
- Mask: () => mask_exports,
31
- MaskEngine: () => MaskEngine,
32
- MaskHistory: () => MaskHistory,
33
- MaskKeyboard: () => MaskKeyboard,
34
- Masonry: () => masonry_exports,
35
- Scroll: () => scroll_exports,
36
- Toast: () => toast_exports,
37
- createI18nManager: () => createI18nManager,
38
- default: () => mask_default,
39
- resolveMaskConstructorArgs: () => resolveMaskConstructorArgs
40
- });
41
- module.exports = __toCommonJS(index_exports);
42
-
43
- // src/mask/index.ts
44
- var mask_exports = {};
45
- __export(mask_exports, {
46
- AmountEngine: () => AmountEngine,
47
- BaseInputMask: () => BaseInputMask,
48
- EmailEngine: () => EmailEngine,
49
- InputAmountMask: () => InputAmountMask,
50
- InputEmailMask: () => InputEmailMask,
51
- InputMask: () => InputMask,
52
- Mask: () => Mask,
53
- MaskEngine: () => MaskEngine,
54
- MaskHistory: () => MaskHistory,
55
- MaskKeyboard: () => MaskKeyboard,
56
- default: () => mask_default,
57
- resolveMaskConstructorArgs: () => resolveMaskConstructorArgs
58
- });
59
-
60
- // src/mask/BaseInputMask.ts
61
- function resolveMaskConstructorArgs(targetOrWrapper, inputOrOptions, maybeOptions) {
62
- const isSecondArgInput = Boolean(
63
- inputOrOptions && typeof inputOrOptions === "object" && "tagName" in inputOrOptions && inputOrOptions.tagName === "INPUT"
64
- );
65
- if (isSecondArgInput) {
66
- return {
67
- wrapper: targetOrWrapper || null,
68
- input: inputOrOptions,
69
- options: maybeOptions || {}
70
- };
71
- }
72
- return {
73
- wrapper: null,
74
- input: targetOrWrapper,
75
- options: inputOrOptions && typeof inputOrOptions === "object" && !("tagName" in inputOrOptions) ? inputOrOptions : {}
76
- };
77
- }
78
- var BaseInputMask = class {
79
- constructor(targetOrWrapper, inputOrOptions, maybeOptions) {
80
- this.ghost = null;
81
- this.isWrapperCreated = false;
82
- this.isDestroyed = false;
83
- this.isFocused = false;
84
- this.isDispatchingNativeInput = false;
85
- this.lastTrackedValue = "";
86
- this.nativeValueDescriptor = null;
87
- this.onCutHandler = () => {
88
- };
89
- this.mutationObserver = null;
90
- this.focusSelectTimerId = null;
91
- this.onBaseCopy = (e) => {
92
- if (!this.options.copyRaw || this.options.disabled || this.input.type === "password") return;
93
- const start = this.input.selectionStart ?? 0;
94
- const end = this.input.selectionEnd ?? start;
95
- let textToCopy = "";
96
- if (start !== end) {
97
- textToCopy = this.extractRawSnippet(this.input.value.slice(start, end));
98
- } else {
99
- textToCopy = this.getRawValue();
100
- }
101
- if (textToCopy && e.clipboardData) {
102
- e.preventDefault();
103
- e.clipboardData.setData("text/plain", textToCopy);
104
- }
105
- };
106
- this.onBaseFocus = () => {
107
- this.isFocused = true;
108
- if (this.options.selectAllOnFocus && this.input.value.length > 0) {
109
- if (this.focusSelectTimerId !== null) {
110
- clearTimeout(this.focusSelectTimerId);
111
- }
112
- this.focusSelectTimerId = window.setTimeout(() => {
113
- this.focusSelectTimerId = null;
114
- if (!this.isDestroyed && document.activeElement === this.input) {
115
- this.input.select();
116
- }
117
- }, 0);
118
- }
119
- };
120
- this.onBaseBlur = () => {
121
- this.isFocused = false;
122
- };
123
- /**
124
- * Synchronise le défilement horizontal du ghost avec celui du champ d'entrée natif.
125
- */
126
- this.onScroll = () => {
127
- if (this.ghost) {
128
- this.ghost.scrollLeft = this.input.scrollLeft;
129
- }
130
- };
131
- const { wrapper: providedWrapper, input, options } = resolveMaskConstructorArgs(targetOrWrapper, inputOrOptions, maybeOptions);
132
- if (!input || typeof input !== "object" || input.nodeType !== 1 || input.tagName !== "INPUT") {
133
- throw new Error(`[${new.target.name || "InputMask"}] input (HTMLInputElement) est requis.`);
134
- }
135
- this.input = input;
136
- const dataCreateWrapper = this.input.getAttribute("data-mask-create-wrapper") === "true";
137
- const shouldCreateWrapper = Boolean(options.createWrapper ?? dataCreateWrapper);
138
- let effectiveWrapper = providedWrapper;
139
- if (!effectiveWrapper && shouldCreateWrapper) {
140
- const span = document.createElement("span");
141
- span.className = "wulf-mask-wrapper";
142
- span.style.display = "inline-grid";
143
- span.style.gridTemplateColumns = "1fr";
144
- span.style.gridTemplateRows = "1fr";
145
- span.style.verticalAlign = "middle";
146
- span.style.boxSizing = "border-box";
147
- span.style.position = "relative";
148
- if (this.input.parentNode) {
149
- this.input.parentNode.insertBefore(span, this.input);
150
- }
151
- span.appendChild(this.input);
152
- this.input.style.gridArea = "1 / 1 / 2 / 2";
153
- this.input.style.boxSizing = "border-box";
154
- effectiveWrapper = span;
155
- this.isWrapperCreated = true;
156
- }
157
- if (!effectiveWrapper) {
158
- throw new Error(`[${new.target.name || "InputMask"}] wrapper (HTMLElement) et input (HTMLInputElement) sont requis, ou activez l'option createWrapper: true.`);
159
- }
160
- this.wrapper = effectiveWrapper;
161
- this.normalizeInputType();
162
- const dataFocusOnly = this.getAttr("data-mask-focus-only") === "true";
163
- const dataDisabled = this.hasAttr("data-disabled");
164
- const dataSelectAll = this.getAttr("data-mask-select-on-focus") === "true";
165
- const dataCopyRaw = this.getAttr("data-mask-copy-raw") === "true";
166
- const dataAlign = this.getAttr("data-mask-align") || this.getAttr("data-align");
167
- const { disabled: optDisabled, align: optAlign, ...otherOptions } = options;
168
- const resolvedDisabled = optDisabled !== void 0 ? optDisabled : dataDisabled ? true : false;
169
- const isPassword = this.input.type === "password";
170
- this.options = {
171
- ...otherOptions,
172
- createWrapper: shouldCreateWrapper,
173
- showMaskOnFocus: options.showMaskOnFocus ?? dataFocusOnly ?? false,
174
- selectAllOnFocus: options.selectAllOnFocus ?? dataSelectAll ?? false,
175
- copyRaw: isPassword ? false : options.copyRaw ?? dataCopyRaw ?? false,
176
- disabled: resolvedDisabled,
177
- align: optAlign ?? (dataAlign || void 0),
178
- emitNativeInput: options.emitNativeInput ?? true
179
- };
180
- if (this.options.showMaskOnFocus) {
181
- this.wrapper.classList.add("mask-focus-only");
182
- }
183
- if (this.options.disabled) {
184
- this.wrapper.setAttribute("data-disabled", "true");
185
- }
186
- if (this.options.align) {
187
- this.setAlign(this.options.align);
188
- }
189
- this.createGhost();
190
- this.hookValueProperty();
191
- this.bindBaseEvents();
192
- this.initMutationObserver();
193
- }
194
- /**
195
- * Récupère un attribut depuis le wrapper ou l'input natif.
196
- */
197
- getAttr(name) {
198
- return this.input.getAttribute(name) || this.wrapper.getAttribute(name);
199
- }
200
- /**
201
- * Vérifie la présence d'un attribut sur le wrapper ou l'input natif.
202
- */
203
- hasAttr(name) {
204
- return this.wrapper.hasAttribute(name) || this.input.hasAttribute(name);
205
- }
206
- /**
207
- * Indique si un placeholder natif non vide est configuré sur l'input.
208
- */
209
- hasNativePlaceholder() {
210
- return Boolean(this.input.placeholder && this.input.placeholder.trim().length > 0);
211
- }
212
- /**
213
- * Détermine si le masque fantôme doit s'effacer pour laisser place au placeholder natif
214
- * lorsque le champ est vide et n'a pas le focus.
215
- */
216
- shouldHideGhostForPlaceholder(isInputEmpty) {
217
- return !this.isFocused && isInputEmpty && this.hasNativePlaceholder();
218
- }
219
- /**
220
- * Attache les écouteurs de base pour focus/blur, copie brute et sélection.
221
- */
222
- bindBaseEvents() {
223
- this.input.addEventListener("copy", this.onBaseCopy);
224
- this.input.addEventListener("focus", this.onBaseFocus);
225
- this.input.addEventListener("blur", this.onBaseBlur);
226
- }
227
- /**
228
- * Extrait la valeur brute d'un extrait de chaîne sélectionné.
229
- */
230
- extractRawSnippet(snippet) {
231
- return snippet;
232
- }
233
- /**
234
- * Initialise l'observation des modifications dynamiques des attributs data-* et placeholder.
235
- */
236
- initMutationObserver() {
237
- if (typeof MutationObserver === "undefined") return;
238
- this.mutationObserver = new MutationObserver((mutations) => {
239
- for (const m of mutations) {
240
- if (m.type === "attributes" && m.attributeName) {
241
- this.handleAttributeMutation(m.attributeName);
242
- }
243
- }
244
- });
245
- const config = {
246
- attributes: true,
247
- attributeFilter: [
248
- "data-mask",
249
- "data-mask-placeholder",
250
- "data-mask-focus-only",
251
- "data-mask-strict",
252
- "data-mask-select-on-focus",
253
- "data-mask-copy-raw",
254
- "data-mask-pad-decimals",
255
- "data-mask-auto-lowercase",
256
- "data-mask-cycle-suggestions",
257
- "data-mask-default-tld",
258
- "data-mask-tlds",
259
- "data-disabled",
260
- "data-mask-align",
261
- "data-align",
262
- "placeholder"
263
- ]
264
- };
265
- this.mutationObserver.observe(this.wrapper, config);
266
- if (this.input !== this.wrapper) {
267
- this.mutationObserver.observe(this.input, config);
268
- }
269
- }
270
- /**
271
- * Modifie dynamiquement l'alignement du champ et du masque fantôme.
272
- */
273
- setAlign(align) {
274
- const targetAlign = align || void 0;
275
- const currentAttr = this.wrapper.getAttribute("data-align");
276
- if (this.options.align === targetAlign && currentAttr === (align || null)) {
277
- return;
278
- }
279
- this.options.align = targetAlign;
280
- this.wrapper.classList.remove("align-left", "align-right", "align-center");
281
- if (align) {
282
- this.wrapper.classList.add(`align-${align}`);
283
- if (this.wrapper.getAttribute("data-align") !== align) {
284
- this.wrapper.setAttribute("data-align", align);
285
- }
286
- } else {
287
- if (this.wrapper.hasAttribute("data-align")) {
288
- this.wrapper.removeAttribute("data-align");
289
- }
290
- }
291
- this.syncGhostStyles();
292
- }
293
- /**
294
- * Crochet appelé lorsqu'un attribut pertinent a été modifié dynamiquement à la volée.
295
- */
296
- handleAttributeMutation(attrName) {
297
- if (attrName === "data-disabled") {
298
- const isDisabled = this.hasAttr("data-disabled");
299
- if (isDisabled !== Boolean(this.options.disabled)) {
300
- this.setDisabled(isDisabled);
301
- }
302
- } else if (attrName === "data-mask-focus-only") {
303
- const focusOnly = this.getAttr("data-mask-focus-only") === "true";
304
- if (focusOnly !== Boolean(this.options.showMaskOnFocus)) {
305
- this.setShowMaskOnFocus(focusOnly);
306
- }
307
- } else if (attrName === "data-mask-select-on-focus") {
308
- this.options.selectAllOnFocus = this.getAttr("data-mask-select-on-focus") === "true";
309
- } else if (attrName === "data-mask-copy-raw") {
310
- this.options.copyRaw = this.getAttr("data-mask-copy-raw") === "true";
311
- } else if (attrName === "data-mask-align" || attrName === "data-align") {
312
- const align = this.getAttr("data-mask-align") || this.getAttr("data-align");
313
- if (align !== (this.options.align ?? null)) {
314
- this.setAlign(align);
315
- }
316
- }
317
- }
318
- /**
319
- * Corrige les types d'input natifs incompatibles avec setSelectionRange (ex: number, email, date).
320
- */
321
- normalizeInputType() {
322
- const incompatibleTypes = ["number", "email", "date", "datetime-local", "month", "week", "time", "color", "file", "range"];
323
- if (this.input.type && incompatibleTypes.includes(this.input.type.toLowerCase())) {
324
- const origType = this.input.type.toLowerCase();
325
- this.input.type = "text";
326
- if (origType === "number") {
327
- this.input.inputMode = "numeric";
328
- }
329
- }
330
- }
331
- /**
332
- * Crée l'élément d'arrière-plan fantôme garantissant un rendu sans superposition
333
- * ni altération de couleur, compatible avec les polices proportionnelles et monospaces.
334
- */
335
- createGhost() {
336
- const existing = this.wrapper.querySelector(".mask-ghost");
337
- if (existing) {
338
- existing.remove();
339
- }
340
- this.ghost = document.createElement("div");
341
- this.ghost.className = "mask-ghost";
342
- this.ghost.setAttribute("aria-hidden", "true");
343
- this.ghost.style.display = "flex";
344
- this.ghost.style.alignItems = "center";
345
- this.wrapper.appendChild(this.ghost);
346
- this.wrapper.classList.add("has-ghost");
347
- this.syncGhostStyles();
348
- }
349
- /**
350
- * Clone fidèlement la géométrie typographique et les espacements de l'input natif
351
- * sur le conteneur fantôme pour garantir un alignement sub-pixel absolu quel que soit
352
- * le style imposé par le framework parent (police, taille, padding, letter-spacing).
353
- */
354
- syncGhostStyles() {
355
- if (!this.ghost || typeof window === "undefined") return;
356
- const style = window.getComputedStyle(this.input);
357
- if (!style) return;
358
- this.ghost.style.fontFamily = style.fontFamily;
359
- this.ghost.style.fontSize = style.fontSize;
360
- this.ghost.style.fontWeight = style.fontWeight;
361
- this.ghost.style.fontStyle = style.fontStyle;
362
- this.ghost.style.letterSpacing = style.letterSpacing;
363
- this.ghost.style.lineHeight = style.lineHeight;
364
- this.ghost.style.paddingTop = style.paddingTop;
365
- this.ghost.style.paddingBottom = style.paddingBottom;
366
- this.ghost.style.paddingLeft = style.paddingLeft;
367
- this.ghost.style.paddingRight = style.paddingRight;
368
- this.ghost.style.borderTopWidth = style.borderTopWidth;
369
- this.ghost.style.borderBottomWidth = style.borderBottomWidth;
370
- this.ghost.style.borderLeftWidth = style.borderLeftWidth;
371
- this.ghost.style.borderRightWidth = style.borderRightWidth;
372
- this.ghost.style.borderTopStyle = style.borderTopStyle === "none" ? "none" : "solid";
373
- this.ghost.style.borderBottomStyle = style.borderBottomStyle === "none" ? "none" : "solid";
374
- this.ghost.style.borderLeftStyle = style.borderLeftStyle === "none" ? "none" : "solid";
375
- this.ghost.style.borderRightStyle = style.borderRightStyle === "none" ? "none" : "solid";
376
- this.ghost.style.borderColor = "transparent";
377
- this.ghost.style.boxSizing = style.boxSizing;
378
- this.ghost.style.textAlign = style.textAlign;
379
- this.ghost.style.direction = style.direction;
380
- const isRtl = style.direction === "rtl" || this.input.getAttribute("dir") === "rtl" || this.wrapper.getAttribute("dir") === "rtl";
381
- if (style.textAlign === "right" || style.textAlign === "end" || isRtl && style.textAlign !== "left" && style.textAlign !== "center") {
382
- this.ghost.style.justifyContent = "flex-end";
383
- } else if (style.textAlign === "center") {
384
- this.ghost.style.justifyContent = "center";
385
- } else {
386
- this.ghost.style.justifyContent = "flex-start";
387
- }
388
- }
389
- /**
390
- * Affecte directement la valeur native sans boucler sur le setter surchargé.
391
- */
392
- setNativeValue(val) {
393
- if (this.nativeValueDescriptor && this.nativeValueDescriptor.set) {
394
- this.nativeValueDescriptor.set.call(this.input, val);
395
- } else {
396
- this.input.value = val;
397
- }
398
- }
399
- /**
400
- * Émet l'événement 'input' natif W3C avec bulles pour synchroniser
401
- * les observateurs standards et les frameworks (React, Vue, Svelte, Angular).
402
- * Synchronise également le tracker de valeur interne de React (_valueTracker).
403
- */
404
- dispatchNativeInput() {
405
- if (this.isDestroyed || typeof window === "undefined") return;
406
- if (this.options.emitNativeInput === false) return;
407
- this.isDispatchingNativeInput = true;
408
- try {
409
- const tracker = this.input._valueTracker;
410
- if (tracker && typeof tracker.setValue === "function") {
411
- tracker.setValue(this.lastTrackedValue);
412
- }
413
- this.lastTrackedValue = this.input.value;
414
- this.input.dispatchEvent(new Event("input", { bubbles: true, cancelable: false }));
415
- } finally {
416
- this.isDispatchingNativeInput = false;
417
- }
418
- }
419
- /**
420
- * Intercepte les modifications directes de la propriété input.value (ex: input.value = '').
421
- */
422
- hookValueProperty() {
423
- try {
424
- const proto = HTMLInputElement.prototype;
425
- const desc = Object.getOwnPropertyDescriptor(proto, "value");
426
- if (!desc || !desc.set || !desc.get) return;
427
- this.nativeValueDescriptor = desc;
428
- const self = this;
429
- Object.defineProperty(this.input, "value", {
430
- get() {
431
- return desc.get.call(this);
432
- },
433
- set(newVal) {
434
- const strVal = String(newVal ?? "");
435
- desc.set.call(this, strVal);
436
- if (self.isDestroyed) return;
437
- self.onNativeValueSet(strVal);
438
- },
439
- configurable: true
440
- });
441
- } catch {
442
- }
443
- }
444
- /**
445
- * Supprime l'interception de input.value et restaure le comportement natif.
446
- */
447
- unhookValueProperty() {
448
- try {
449
- delete this.input.value;
450
- } catch {
451
- }
452
- }
453
- /**
454
- * Active ou désactive l'affichage du masque uniquement au focus.
455
- */
456
- setShowMaskOnFocus(enable) {
457
- this.options.showMaskOnFocus = enable;
458
- this.wrapper.classList.toggle("mask-focus-only", enable);
459
- }
460
- /**
461
- * Active ou désactive le masquage de saisie (getter / setter fluide).
462
- */
463
- disabled(disabledVal) {
464
- if (disabledVal === void 0) {
465
- return Boolean(this.options.disabled);
466
- }
467
- this.setDisabled(disabledVal);
468
- }
469
- /**
470
- * Active ou désactive le masquage / l'assistance de saisie.
471
- */
472
- setDisabled(disabled) {
473
- this.options.disabled = Boolean(disabled);
474
- if (this.options.disabled) {
475
- this.wrapper.setAttribute("data-disabled", "true");
476
- } else {
477
- this.wrapper.removeAttribute("data-disabled");
478
- }
479
- this.onDisabledChange(this.options.disabled);
480
- }
481
- /**
482
- /**
483
- * Retourne l'élément conteneur (wrapper).
484
- */
485
- getWrapper() {
486
- return this.wrapper;
487
- }
488
- /**
489
- * Retourne l'élément input natif sous-jacent.
490
- */
491
- getInput() {
492
- return this.input;
493
- }
494
- /**
495
- * Retourne l'élément fantôme (ghost) affichant le masque en arrière-plan.
496
- */
497
- getGhost() {
498
- return this.ghost;
499
- }
500
- /**
501
- * Retourne l'ensemble des éléments DOM associés au masque (wrapper, input, ghost).
502
- */
503
- getElements() {
504
- return {
505
- wrapper: this.wrapper,
506
- input: this.input,
507
- ghost: this.ghost
508
- };
509
- }
510
- /**
511
- * Retourne la valeur actuelle affichée dans l'input (formatée).
512
- */
513
- getValue() {
514
- return this.input.value;
515
- }
516
- /**
517
- * Retourne la valeur brute sans séparateurs.
518
- * Par défaut retourne la valeur de l'input si non surchargée.
519
- */
520
- getRawValue() {
521
- return this.input.value;
522
- }
523
- /**
524
- * Supprime les éléments fantômes, restaure les propriétés et nettoie les attributs.
525
- */
526
- destroy() {
527
- if (this.isDestroyed) return;
528
- this.isDestroyed = true;
529
- if (this.focusSelectTimerId !== null) {
530
- clearTimeout(this.focusSelectTimerId);
531
- this.focusSelectTimerId = null;
532
- }
533
- if (this.mutationObserver) {
534
- this.mutationObserver.disconnect();
535
- this.mutationObserver = null;
536
- }
537
- this.input.removeEventListener("copy", this.onBaseCopy);
538
- this.input.removeEventListener("focus", this.onBaseFocus);
539
- this.input.removeEventListener("blur", this.onBaseBlur);
540
- this.unhookValueProperty();
541
- if (this.ghost) {
542
- this.ghost.remove();
543
- this.ghost = null;
544
- }
545
- if (this.isWrapperCreated && this.wrapper) {
546
- this.input.style.gridArea = "";
547
- this.input.style.boxSizing = "";
548
- if (this.wrapper.parentNode) {
549
- this.wrapper.parentNode.insertBefore(this.input, this.wrapper);
550
- }
551
- this.wrapper.remove();
552
- } else if (this.wrapper) {
553
- this.wrapper.removeAttribute("data-mask");
554
- this.wrapper.removeAttribute("data-disabled");
555
- this.wrapper.classList.remove("is-complete", "is-focused", "mask-focus-only", "has-selection", "has-ghost");
556
- }
557
- }
558
- };
559
-
560
- // src/mask/MaskEngine.ts
561
- var DEFAULT_TOKENS = {
562
- "9": { pattern: /[0-9]/ },
563
- "a": { pattern: /[a-zA-Z]/ },
564
- "A": { pattern: /[a-zA-Z]/, transform: (c) => c.toUpperCase() },
565
- "*": { pattern: /[a-zA-Z0-9]/ },
566
- "#": { pattern: /[a-zA-Z0-9]/, transform: (c) => c.toUpperCase() }
567
- };
568
- var MaskEngine = class _MaskEngine {
569
- constructor(pattern, options = {}) {
570
- this.patterns = [];
571
- this.subEngines = [];
572
- this.activeEngine = null;
573
- this.slots = [];
574
- this.fullMaskTemplate = "";
575
- this.prefixSlotsCount = 0;
576
- this.prefixString = "";
577
- this.strict = true;
578
- this.autoLowercase = false;
579
- const opts = options || {};
580
- this.placeholderChar = opts.placeholderChar || "_";
581
- this.tokens = { ...DEFAULT_TOKENS, ...opts.tokens || {} };
582
- this.strict = opts.strict !== false;
583
- this.autoLowercase = opts.autoLowercase ?? false;
584
- this.pattern = "";
585
- this.compile(pattern);
586
- }
587
- /**
588
- * Formate une valeur selon un gabarit de masque donné.
589
- * Fonction statique utilitaire permettant un formatage direct sans instanciation manuelle.
590
- *
591
- * @param value Valeur à formater (brute ou partiellement formatée)
592
- * @param pattern Masque à appliquer (ex: "99 99 99 99 99" ou tableau de masques)
593
- * @param options Options facultatives (placeholderChar, tokens, strict, autoLowercase)
594
- * @returns La valeur formatée selon le masque
595
- */
596
- static format(value, pattern, options = {}) {
597
- if (!pattern || Array.isArray(pattern) && pattern.length === 0) return value ?? "";
598
- const engine = new _MaskEngine(pattern, options || {});
599
- return engine.format(value ?? "");
600
- }
601
- /**
602
- * Analyse le ou les gabarits statiques et compile la liste des slots.
603
- */
604
- compile(newPattern) {
605
- if (newPattern !== void 0) {
606
- if (Array.isArray(newPattern)) {
607
- this.patterns = [...newPattern];
608
- this.pattern = this.patterns[0] || "";
609
- } else {
610
- this.patterns = [];
611
- this.pattern = newPattern;
612
- }
613
- }
614
- if (this.patterns.length > 0) {
615
- this.subEngines = this.patterns.map((p) => new _MaskEngine(p, {
616
- placeholderChar: this.placeholderChar,
617
- tokens: this.tokens,
618
- strict: this.strict,
619
- autoLowercase: this.autoLowercase
620
- }));
621
- this.activeEngine = this.subEngines[0];
622
- this.slots = this.activeEngine.slots;
623
- this.fullMaskTemplate = this.activeEngine.fullMaskTemplate;
624
- this.prefixSlotsCount = this.activeEngine.prefixSlotsCount;
625
- this.prefixString = this.activeEngine.prefixString;
626
- return this.slots;
627
- }
628
- this.subEngines = [];
629
- this.activeEngine = null;
630
- this.slots = [];
631
- let templateBuilder = "";
632
- let isPrefixMode = true;
633
- for (let i = 0; i < this.pattern.length; i++) {
634
- let char = this.pattern[i];
635
- let isEscaped = false;
636
- if (char === "\\" && i + 1 < this.pattern.length) {
637
- isEscaped = true;
638
- i++;
639
- char = this.pattern[i];
640
- }
641
- const token = !isEscaped ? this.tokens[char] : void 0;
642
- if (token) {
643
- isPrefixMode = false;
644
- this.slots.push({
645
- char,
646
- isStatic: false,
647
- isPrefix: false,
648
- token,
649
- placeholder: this.placeholderChar
650
- });
651
- templateBuilder += this.placeholderChar;
652
- } else {
653
- this.slots.push({
654
- char,
655
- isStatic: true,
656
- isPrefix: isPrefixMode,
657
- placeholder: char
658
- });
659
- templateBuilder += char;
660
- }
661
- }
662
- this.fullMaskTemplate = templateBuilder;
663
- this.prefixSlotsCount = 0;
664
- this.prefixString = "";
665
- for (const slot of this.slots) {
666
- if (slot.isPrefix) {
667
- this.prefixSlotsCount++;
668
- this.prefixString += slot.char;
669
- } else {
670
- break;
671
- }
672
- }
673
- return this.slots;
674
- }
675
- /**
676
- * Sélectionne dynamiquement le meilleur sous-moteur en fonction de la valeur passée.
677
- */
678
- selectEngine(input) {
679
- if (this.subEngines.length <= 1) {
680
- return this;
681
- }
682
- const trimmed = String(input ?? "");
683
- const withMatchingPrefix = this.subEngines.filter((e) => {
684
- const p = e.getPrefix();
685
- return p.length > 0 && trimmed.toLowerCase().startsWith(p.trim().toLowerCase());
686
- });
687
- const candidates = withMatchingPrefix.length > 0 ? withMatchingPrefix : this.subEngines;
688
- const maxCandidate = [...candidates].sort((a, b) => b.getEditableCount() - a.getEditableCount())[0];
689
- const raw = maxCandidate ? maxCandidate.extractRaw(trimmed) : trimmed;
690
- const rawLen = raw.length;
691
- for (const eng of candidates) {
692
- if (eng.getEditableCount() >= rawLen) {
693
- this.activeEngine = eng;
694
- return eng;
695
- }
696
- }
697
- this.activeEngine = candidates[candidates.length - 1];
698
- return this.activeEngine;
699
- }
700
- /**
701
- * Retourne la chaîne du préfixe statique initial (ex: "+33 ").
702
- */
703
- getPrefix() {
704
- return this.activeEngine ? this.activeEngine.getPrefix() : this.prefixString;
705
- }
706
- /**
707
- * Retourne la longueur en caractères du préfixe statique initial.
708
- */
709
- getPrefixLength() {
710
- return this.activeEngine ? this.activeEngine.getPrefixLength() : this.prefixSlotsCount;
711
- }
712
- /**
713
- * Retourne le gabarit complet du masque avec ses placeholders (ex: "FR76 ____ ____").
714
- */
715
- getFullMaskTemplate() {
716
- return this.activeEngine ? this.activeEngine.getFullMaskTemplate() : this.fullMaskTemplate;
717
- }
718
- /**
719
- * Nombre total de positions éditables dans le masque.
720
- */
721
- getEditableCount() {
722
- if (this.subEngines.length > 0) {
723
- return Math.max(...this.subEngines.map((e) => e.getEditableCount()));
724
- }
725
- return this.activeEngine ? this.activeEngine.getEditableCount() : this.slots.filter((s) => !s.isStatic).length;
726
- }
727
- /**
728
- * Indique si tous les emplacements éditables du masque acceptent exclusivement des chiffres numériques.
729
- */
730
- isNumericOnly() {
731
- if (this.subEngines.length > 0) {
732
- return this.subEngines.every((e) => e.isNumericOnly());
733
- }
734
- const targetSlots = this.activeEngine ? this.activeEngine.slots : this.slots;
735
- const editable = targetSlots.filter((s) => !s.isStatic);
736
- if (editable.length === 0) return false;
737
- return editable.every((s) => s.char === "9" || s.token && s.token.pattern.test("0") && !s.token.pattern.test("a") && !s.token.pattern.test("Z"));
738
- }
739
- /**
740
- * Définit si le masque bloque strictement les entrées non conformes.
741
- */
742
- setStrict(strict) {
743
- this.strict = strict;
744
- }
745
- /**
746
- * Indique si le masque est en mode strict.
747
- */
748
- isStrict() {
749
- return this.strict;
750
- }
751
- /**
752
- * Filtre et extrait uniquement les caractères éditables valides d'une chaîne.
753
- * Gère intelligemment la présence ou l'absence des séparateurs statiques et du préfixe.
754
- */
755
- extractRaw(input) {
756
- if (this.subEngines.length > 0) {
757
- const engine = this.selectEngine(input);
758
- if (engine !== this) {
759
- return engine.extractRaw(input);
760
- }
761
- }
762
- const str = String(input ?? "");
763
- if (!str) return "";
764
- let raw = "";
765
- let inputIdx = 0;
766
- let slotIdx = 0;
767
- if (this.prefixSlotsCount > 0) {
768
- while (inputIdx < str.length && (str[inputIdx] === " " || str[inputIdx] === " ")) {
769
- inputIdx++;
770
- }
771
- let pIdx = 0;
772
- while (inputIdx < str.length && pIdx < this.prefixSlotsCount) {
773
- const pChar = this.slots[pIdx].char;
774
- const inChar = str[inputIdx];
775
- if (inChar.toUpperCase() === pChar.toUpperCase()) {
776
- inputIdx++;
777
- pIdx++;
778
- } else if (pChar === " " && inChar !== " ") {
779
- pIdx++;
780
- } else {
781
- break;
782
- }
783
- }
784
- slotIdx = this.prefixSlotsCount;
785
- }
786
- while (inputIdx < str.length && slotIdx < this.slots.length) {
787
- const slot = this.slots[slotIdx];
788
- const char = str[inputIdx];
789
- if (slot.isStatic) {
790
- if (char.toUpperCase() === slot.char.toUpperCase()) {
791
- inputIdx++;
792
- slotIdx++;
793
- } else {
794
- slotIdx++;
795
- }
796
- } else {
797
- if (slot.token && slot.token.pattern.test(char)) {
798
- let transformed = slot.token.transform ? slot.token.transform(char) : char;
799
- if (this.autoLowercase && !slot.token.transform) {
800
- transformed = transformed.toLowerCase();
801
- }
802
- raw += transformed;
803
- inputIdx++;
804
- slotIdx++;
805
- } else if (!this.strict) {
806
- raw += this.autoLowercase ? char.toLowerCase() : char;
807
- inputIdx++;
808
- slotIdx++;
809
- } else {
810
- inputIdx++;
811
- }
812
- }
813
- }
814
- if (!this.strict && inputIdx < str.length) {
815
- const remaining = str.slice(inputIdx);
816
- raw += this.autoLowercase ? remaining.toLowerCase() : remaining;
817
- }
818
- return raw;
819
- }
820
- /**
821
- * Formate une chaîne brute en appliquant le gabarit avec ses séparateurs statiques.
822
- * Si aucune donnée éditable n'est présente, retourne le préfixe statique fixe s'il existe.
823
- */
824
- format(rawValue) {
825
- if (this.subEngines.length > 0) {
826
- const engine = this.selectEngine(rawValue);
827
- if (engine !== this) {
828
- return engine.format(rawValue);
829
- }
830
- }
831
- const rawStr = String(rawValue ?? "");
832
- if (!this.slots.length) return rawStr;
833
- const cleanRaw = this.extractRaw(rawStr);
834
- if (cleanRaw.length === 0) {
835
- return this.prefixString;
836
- }
837
- let formatted = "";
838
- let rawIdx = 0;
839
- for (let i = 0; i < this.slots.length; i++) {
840
- const slot = this.slots[i];
841
- if (slot.isStatic) {
842
- const hasRemainingRaw = rawIdx < cleanRaw.length;
843
- const isPrefix = rawIdx === 0 && Boolean(slot.isPrefix);
844
- const isCompletedSegmentTrailingSep = rawIdx > 0 && rawIdx === cleanRaw.length;
845
- if (hasRemainingRaw || isPrefix || isCompletedSegmentTrailingSep) {
846
- formatted += slot.char;
847
- } else {
848
- break;
849
- }
850
- } else {
851
- if (rawIdx < cleanRaw.length) {
852
- const char = cleanRaw[rawIdx];
853
- let transformed = slot.token?.transform ? slot.token.transform(char) : char;
854
- if (this.autoLowercase && !slot.token?.transform) {
855
- transformed = transformed.toLowerCase();
856
- }
857
- formatted += transformed;
858
- rawIdx++;
859
- } else {
860
- break;
861
- }
862
- }
863
- }
864
- if (!this.strict && rawIdx < cleanRaw.length) {
865
- const extra = cleanRaw.substring(rawIdx);
866
- formatted += this.autoLowercase ? extra.toLowerCase() : extra;
867
- }
868
- return formatted;
869
- }
870
- /**
871
- * Calcule le gabarit restant aligné au texte formaté (supporte les polices proportionnelles non-monospace).
872
- */
873
- getRemainingMask(formatted) {
874
- if (this.activeEngine && this.activeEngine !== this) {
875
- return this.activeEngine.getRemainingMask(formatted);
876
- }
877
- if (!this.fullMaskTemplate) return "";
878
- if (formatted.length >= this.fullMaskTemplate.length) {
879
- return formatted;
880
- }
881
- return formatted + this.fullMaskTemplate.substring(formatted.length);
882
- }
883
- /**
884
- * Mappe la position du curseur en préservant le nombre exact de caractères éditables
885
- * saisis avant le curseur, et en garantissant que le curseur ne recule jamais dans le préfixe statique.
886
- */
887
- mapCursorPosition(inputValue, inputCursor, formatted) {
888
- if (this.activeEngine && this.activeEngine !== this) {
889
- return this.activeEngine.mapCursorPosition(inputValue, inputCursor, formatted);
890
- }
891
- const minPos = this.prefixSlotsCount;
892
- const safeInput = String(inputValue ?? "");
893
- const safeFormatted = String(formatted ?? "");
894
- if (inputCursor <= 0 || !safeFormatted) return minPos;
895
- const rawBeforeCursor = this.extractRaw(safeInput.slice(0, inputCursor));
896
- const targetRawCount = rawBeforeCursor.length;
897
- if (targetRawCount === 0) {
898
- return Math.max(minPos, Math.min(this.getNextEditablePosition(0), safeFormatted.length));
899
- }
900
- let currentRawCount = 0;
901
- let targetPos = safeFormatted.length;
902
- for (let i = 0; i < safeFormatted.length && i < this.slots.length; i++) {
903
- const slot = this.slots[i];
904
- if (!slot.isStatic) {
905
- currentRawCount++;
906
- if (currentRawCount === targetRawCount) {
907
- targetPos = i + 1;
908
- break;
909
- }
910
- }
911
- }
912
- while (targetPos < safeFormatted.length && this.slots[targetPos] && this.slots[targetPos].isStatic) {
913
- targetPos++;
914
- }
915
- return Math.max(minPos, Math.min(targetPos, safeFormatted.length));
916
- }
917
- /**
918
- * Vérifie si le slot à l'index donné est un séparateur statique.
919
- */
920
- isSeparatorAt(displayIdx) {
921
- if (this.activeEngine && this.activeEngine !== this) {
922
- return this.activeEngine.isSeparatorAt(displayIdx);
923
- }
924
- if (displayIdx >= 0 && displayIdx < this.slots.length) {
925
- return this.slots[displayIdx].isStatic;
926
- }
927
- return false;
928
- }
929
- /**
930
- * Trouve le prochain emplacement éditable après un index donné.
931
- */
932
- getNextEditablePosition(fromIdx) {
933
- if (this.activeEngine && this.activeEngine !== this) {
934
- return this.activeEngine.getNextEditablePosition(fromIdx);
935
- }
936
- const start = Math.max(0, fromIdx);
937
- for (let i = start; i < this.slots.length; i++) {
938
- if (!this.slots[i].isStatic) {
939
- return i;
940
- }
941
- }
942
- return this.slots.length;
943
- }
944
- /**
945
- * Retourne le slot à l'index donné.
946
- */
947
- getSlotAt(displayIdx) {
948
- if (this.activeEngine && this.activeEngine !== this) {
949
- return this.activeEngine.getSlotAt(displayIdx);
950
- }
951
- return this.slots[displayIdx];
952
- }
953
- /**
954
- * Retourne les slots complets.
955
- */
956
- getSlots() {
957
- if (this.activeEngine && this.activeEngine !== this) {
958
- return this.activeEngine.getSlots();
959
- }
960
- return this.slots;
961
- }
962
- };
963
-
964
- // src/mask/MaskHistory.ts
965
- var MaskHistory = class {
966
- constructor(maxDepth = 50) {
967
- this.stack = [];
968
- this.index = -1;
969
- this.maxDepth = maxDepth;
970
- }
971
- /**
972
- * Enregistre un nouvel état si la valeur brute a changé.
973
- * Si la valeur brute est identique, met simplement à jour la position du curseur de l'état courant.
974
- */
975
- push(raw, cursor) {
976
- const current = this.getCurrent();
977
- if (current && current.raw === raw) {
978
- current.cursor = cursor;
979
- return;
980
- }
981
- this.stack = this.stack.slice(0, this.index + 1);
982
- this.stack.push({ raw, cursor });
983
- if (this.stack.length > this.maxDepth) {
984
- this.stack.shift();
985
- }
986
- this.index = this.stack.length - 1;
987
- }
988
- /**
989
- * Met à jour la position du curseur de l'état courant sans modifier la pile.
990
- */
991
- updateCurrentCursor(cursor) {
992
- const current = this.getCurrent();
993
- if (current) {
994
- current.cursor = cursor;
995
- }
996
- }
997
- /**
998
- * Recule d'un cran dans l'historique et retourne l'état restauré.
999
- */
1000
- undo() {
1001
- if (this.canUndo()) {
1002
- this.index--;
1003
- return this.stack[this.index];
1004
- }
1005
- return null;
1006
- }
1007
- /**
1008
- * Avance d'un cran dans l'historique et retourne l'état restauré.
1009
- */
1010
- redo() {
1011
- if (this.canRedo()) {
1012
- this.index++;
1013
- return this.stack[this.index];
1014
- }
1015
- return null;
1016
- }
1017
- /**
1018
- * Indique si une annulation est possible.
1019
- */
1020
- canUndo() {
1021
- return this.index > 0;
1022
- }
1023
- /**
1024
- * Indique si un rétablissement est possible.
1025
- */
1026
- canRedo() {
1027
- return this.index >= 0 && this.index < this.stack.length - 1;
1028
- }
1029
- /**
1030
- * Retourne l'état courant.
1031
- */
1032
- getCurrent() {
1033
- return this.index >= 0 && this.index < this.stack.length ? this.stack[this.index] : null;
1034
- }
1035
- /**
1036
- * Réinitialise entièrement l'historique.
1037
- */
1038
- clear() {
1039
- this.stack = [];
1040
- this.index = -1;
1041
- }
1042
- };
1043
-
1044
- // src/mask/MaskKeyboard.ts
1045
- var MaskKeyboard = class {
1046
- constructor(delegate) {
1047
- this.delegate = delegate;
1048
- }
1049
- /**
1050
- * Analyse et traite l'événement keydown de l'input.
1051
- */
1052
- handleKeyDown(e) {
1053
- const input = this.delegate.getInput();
1054
- const engine = this.delegate.getEngine();
1055
- const history = this.delegate.getHistory();
1056
- const minPos = engine.getPrefixLength();
1057
- const cursor = input.selectionStart ?? 0;
1058
- const selectionEnd = input.selectionEnd ?? cursor;
1059
- if ((e.ctrlKey || e.metaKey) && (e.key === "z" || e.key === "Z") && !e.shiftKey) {
1060
- e.preventDefault();
1061
- this.delegate.undo();
1062
- return;
1063
- }
1064
- if ((e.ctrlKey || e.metaKey) && (e.key === "y" || e.key === "Y") || (e.ctrlKey || e.metaKey) && e.shiftKey && (e.key === "z" || e.key === "Z")) {
1065
- e.preventDefault();
1066
- this.delegate.redo();
1067
- return;
1068
- }
1069
- history.updateCurrentCursor(cursor);
1070
- const isPrintableChar = e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey;
1071
- const hasSelection = selectionEnd > cursor;
1072
- if (isPrintableChar && !hasSelection) {
1073
- const slots = engine.getSlots();
1074
- const isAlreadyOnSep = cursor < slots.length && slots[cursor].isStatic && slots[cursor].char === e.key;
1075
- const isJustAfterSep = cursor > 0 && cursor - 1 < slots.length && slots[cursor - 1].isStatic && slots[cursor - 1].char === e.key;
1076
- if (isAlreadyOnSep || isJustAfterSep) {
1077
- e.preventDefault();
1078
- const baseIdx = isAlreadyOnSep ? cursor : cursor - 1;
1079
- const nextEditable = engine.getNextEditablePosition(baseIdx + 1);
1080
- this.delegate.applyMask(input.value, nextEditable, true);
1081
- return;
1082
- }
1083
- let nextSepIdx = -1;
1084
- for (let i = cursor; i < slots.length; i++) {
1085
- if (slots[i].isStatic) {
1086
- if (slots[i].char === e.key) {
1087
- nextSepIdx = i;
1088
- }
1089
- break;
1090
- }
1091
- }
1092
- if (nextSepIdx !== -1) {
1093
- e.preventDefault();
1094
- let segStart = nextSepIdx - 1;
1095
- while (segStart >= minPos && !slots[segStart].isStatic) {
1096
- segStart--;
1097
- }
1098
- segStart++;
1099
- const segLength = nextSepIdx - segStart;
1100
- const currentSegVal = input.value.slice(segStart, cursor);
1101
- const isNumericSegment = slots.slice(segStart, nextSepIdx).every((s) => !s.token || s.token.pattern.test("0"));
1102
- if (isNumericSegment && segLength > currentSegVal.length && currentSegVal.length > 0) {
1103
- const missingCount = segLength - currentSegVal.length;
1104
- const paddedSeg = "0".repeat(missingCount) + currentSegVal;
1105
- const remainingTail = input.value.slice(nextSepIdx);
1106
- const padded = input.value.slice(0, segStart) + paddedSeg + remainingTail;
1107
- const nextEditable2 = engine.getNextEditablePosition(nextSepIdx + 1);
1108
- this.delegate.applyMask(padded, nextEditable2, true);
1109
- return;
1110
- }
1111
- const nextEditable = engine.getNextEditablePosition(nextSepIdx + 1);
1112
- this.delegate.applyMask(input.value, nextEditable, true);
1113
- return;
1114
- }
1115
- }
1116
- if (isPrintableChar && engine.isStrict()) {
1117
- const totalSlots = engine.getEditableCount();
1118
- if (totalSlots > 0) {
1119
- const currentRaw = engine.extractRaw(input.value);
1120
- let availableCapacity = totalSlots - currentRaw.length;
1121
- if (selectionEnd > cursor) {
1122
- const selectedRaw = engine.extractRaw(input.value.slice(cursor, selectionEnd));
1123
- availableCapacity = totalSlots - (currentRaw.length - selectedRaw.length);
1124
- }
1125
- if (availableCapacity <= 0) {
1126
- e.preventDefault();
1127
- return;
1128
- }
1129
- }
1130
- }
1131
- if (selectionEnd > cursor) {
1132
- if (e.key === "Backspace" || e.key === "Delete") {
1133
- e.preventDefault();
1134
- const val = input.value;
1135
- const updated = val.slice(0, cursor) + val.slice(selectionEnd);
1136
- this.delegate.applyMask(updated, Math.max(minPos, cursor));
1137
- return;
1138
- }
1139
- return;
1140
- }
1141
- if (e.key === "ArrowLeft" && !e.shiftKey && cursor <= minPos) {
1142
- e.preventDefault();
1143
- input.setSelectionRange(minPos, minPos);
1144
- return;
1145
- }
1146
- if (e.key === "Home" && !e.shiftKey) {
1147
- e.preventDefault();
1148
- input.setSelectionRange(minPos, minPos);
1149
- return;
1150
- }
1151
- if (e.key === "Backspace" && cursor <= minPos) {
1152
- e.preventDefault();
1153
- input.setSelectionRange(minPos, minPos);
1154
- return;
1155
- }
1156
- if (e.key === "Delete" && cursor < minPos) {
1157
- e.preventDefault();
1158
- input.setSelectionRange(minPos, minPos);
1159
- return;
1160
- }
1161
- const isWordDeleteBack = e.key === "Backspace" && (e.ctrlKey || e.altKey || e.metaKey);
1162
- if (isWordDeleteBack) {
1163
- e.preventDefault();
1164
- if (cursor <= minPos) {
1165
- input.setSelectionRange(minPos, minPos);
1166
- return;
1167
- }
1168
- let i = cursor - 1;
1169
- while (i >= minPos && engine.isSeparatorAt(i)) {
1170
- i--;
1171
- }
1172
- while (i >= minPos && !engine.isSeparatorAt(i)) {
1173
- i--;
1174
- }
1175
- const startPos = Math.max(minPos, i + 1);
1176
- const val = input.value;
1177
- const updated = val.slice(0, startPos) + val.slice(cursor);
1178
- this.delegate.applyMask(updated, startPos);
1179
- return;
1180
- }
1181
- const isWordDeleteForward = e.key === "Delete" && (e.ctrlKey || e.altKey || e.metaKey);
1182
- if (isWordDeleteForward) {
1183
- e.preventDefault();
1184
- const val = input.value;
1185
- if (cursor >= val.length) {
1186
- return;
1187
- }
1188
- let i = cursor;
1189
- while (i < val.length && engine.isSeparatorAt(i)) {
1190
- i++;
1191
- }
1192
- while (i < val.length && !engine.isSeparatorAt(i)) {
1193
- i++;
1194
- }
1195
- while (i < val.length && engine.isSeparatorAt(i)) {
1196
- i++;
1197
- }
1198
- const endPos = i;
1199
- const updated = val.slice(0, cursor) + val.slice(endPos);
1200
- this.delegate.applyMask(updated, cursor);
1201
- return;
1202
- }
1203
- if (e.key === "Backspace" && cursor > minPos) {
1204
- if (engine.isSeparatorAt(cursor - 1)) {
1205
- e.preventDefault();
1206
- let targetPos = cursor - 1;
1207
- while (targetPos > minPos && engine.isSeparatorAt(targetPos - 1)) {
1208
- targetPos--;
1209
- }
1210
- if (targetPos > minPos) {
1211
- const val = input.value;
1212
- const updated = val.slice(0, targetPos - 1) + val.slice(cursor);
1213
- this.delegate.applyMask(updated, targetPos - 1);
1214
- } else {
1215
- this.delegate.applyMask("", minPos);
1216
- }
1217
- }
1218
- return;
1219
- }
1220
- if (e.key === "Delete" && cursor < input.value.length) {
1221
- if (engine.isSeparatorAt(cursor)) {
1222
- e.preventDefault();
1223
- let targetPos = cursor;
1224
- while (targetPos < input.value.length && engine.isSeparatorAt(targetPos)) {
1225
- targetPos++;
1226
- }
1227
- if (targetPos < input.value.length) {
1228
- const val = input.value;
1229
- const updated = val.slice(0, targetPos) + val.slice(targetPos + 1);
1230
- this.delegate.applyMask(updated, cursor);
1231
- }
1232
- }
1233
- return;
1234
- }
1235
- }
1236
- /**
1237
- * Analyse et traite l'événement keyup de l'input.
1238
- */
1239
- handleKeyUp(e) {
1240
- const input = this.delegate.getInput();
1241
- const history = this.delegate.getHistory();
1242
- if ((e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "Home") && !e.shiftKey) {
1243
- this.delegate.enforceMinCursor();
1244
- }
1245
- history.updateCurrentCursor(input.selectionStart ?? 0);
1246
- }
1247
- };
1248
-
1249
- // src/mask/InputMask.ts
1250
- var InputMask = class extends BaseInputMask {
1251
- constructor(targetOrWrapper, inputOrOptions, options) {
1252
- const args = resolveMaskConstructorArgs(targetOrWrapper, inputOrOptions, options);
1253
- const wrap = args.wrapper;
1254
- const inp = args.input;
1255
- const opts = args.options;
1256
- const attrMask = wrap?.getAttribute("data-mask") || inp?.getAttribute("data-mask");
1257
- let pattern = opts.mask || attrMask || "";
1258
- if (typeof pattern === "string" && pattern.includes("|")) {
1259
- pattern = pattern.split("|").map((s) => s.trim());
1260
- }
1261
- const placeholderChar = opts.placeholderChar || wrap?.getAttribute("data-mask-placeholder") || inp?.getAttribute("data-mask-placeholder") || "_";
1262
- const dataDisabled = wrap?.hasAttribute("data-disabled") || inp?.hasAttribute("data-disabled");
1263
- const dataStrict = wrap?.getAttribute("data-mask-strict") || inp?.getAttribute("data-mask-strict");
1264
- const dataAutoLower = wrap?.getAttribute("data-mask-auto-lowercase") === "true" || inp?.getAttribute("data-mask-auto-lowercase") === "true";
1265
- const dataInfer = wrap?.getAttribute("data-mask-infer-inputmode") ?? inp?.getAttribute("data-mask-infer-inputmode");
1266
- const inferInputMode = opts.inferInputMode ?? (dataInfer !== null ? dataInfer !== "false" : true);
1267
- const { disabled: optsDisabled, ...otherOpts } = opts;
1268
- const resolvedDisabled = optsDisabled !== void 0 ? optsDisabled : dataDisabled ? true : !pattern || Array.isArray(pattern) && pattern.length === 0;
1269
- const resolvedOptions = {
1270
- ...otherOpts,
1271
- mask: pattern,
1272
- placeholderChar,
1273
- strict: opts.strict ?? (dataStrict !== null ? dataStrict !== "false" : true),
1274
- autoLowercase: opts.autoLowercase ?? dataAutoLower ?? false,
1275
- disabled: resolvedDisabled,
1276
- resetHistoryOnMaskChange: opts.resetHistoryOnMaskChange ?? false,
1277
- inferInputMode,
1278
- onInput: opts.onInput || opts.oninput,
1279
- onChange: opts.onChange || opts.onchange,
1280
- onComplete: opts.onComplete || opts.oncomplete
1281
- };
1282
- super(wrap, inp, resolvedOptions);
1283
- this.isComposing = false;
1284
- this.isUndoingRedoing = false;
1285
- this.isMouseDown = false;
1286
- this.isApplyingMask = false;
1287
- this.lastValue = "";
1288
- this.lastInternalRemainingMask = "";
1289
- this.isNotifying = false;
1290
- this.hasPendingNotification = false;
1291
- this.onChangeNativeHandler = () => {
1292
- };
1293
- this.wasInputModeInferred = false;
1294
- this.cutTimerId = null;
1295
- this.pasteTimerId = null;
1296
- this.resetTimerId = null;
1297
- this.history = new MaskHistory();
1298
- this.engine = new MaskEngine(this.options.mask || "", {
1299
- placeholderChar: this.options.placeholderChar,
1300
- tokens: this.options.tokens,
1301
- strict: this.options.strict,
1302
- autoLowercase: this.options.autoLowercase
1303
- });
1304
- this.syncInferredInputMode();
1305
- this.keyboard = new MaskKeyboard({
1306
- getInput: () => this.input,
1307
- getEngine: () => this.engine,
1308
- getHistory: () => this.history,
1309
- applyMask: (raw, cursor, forceExactCursor) => this.applyMask(raw, cursor, forceExactCursor),
1310
- undo: () => this.undo(),
1311
- redo: () => this.redo(),
1312
- enforceMinCursor: () => this.enforceMinCursor()
1313
- });
1314
- this.bindEvents();
1315
- this.lastValue = this.input.value;
1316
- this.syncInitialValue();
1317
- }
1318
- extractRawSnippet(snippet) {
1319
- return this.engine.extractRaw(snippet);
1320
- }
1321
- /**
1322
- * Formate statiquement une valeur selon un masque donné sans nécessiter d'élément DOM.
1323
- *
1324
- * @param value Valeur à formater (ex: "0123456789")
1325
- * @param mask Gabarit de masque (ex: "99 99 99 99 99")
1326
- * @param options Options facultatives du masque (tokens, placeholderChar, strict, etc.)
1327
- * @returns Valeur formatée (ex: "01 23 45 67 89")
1328
- */
1329
- static format(value, mask, options = {}) {
1330
- return MaskEngine.format(value, mask, options);
1331
- }
1332
- onNativeValueSet(strVal) {
1333
- if (this.options.disabled) {
1334
- this.checkValueChange();
1335
- } else {
1336
- this.applyMask(strVal, strVal.length);
1337
- }
1338
- }
1339
- onDisabledChange(disabled) {
1340
- if (disabled) {
1341
- this.wrapper.removeAttribute("data-mask");
1342
- this.wrapper.classList.remove("is-complete", "has-selection");
1343
- if (this.ghost) this.ghost.textContent = "";
1344
- this.checkValueChange();
1345
- } else {
1346
- this.applyMask(this.input.value, this.input.selectionStart ?? this.input.value.length);
1347
- }
1348
- }
1349
- /**
1350
- * Associe les écouteurs d'événements nécessaires.
1351
- */
1352
- bindEvents() {
1353
- this.handleInput = this.handleInput.bind(this);
1354
- this.onKeyDown = this.onKeyDown.bind(this);
1355
- this.onPaste = this.onPaste.bind(this);
1356
- this.onFocus = this.onFocus.bind(this);
1357
- this.onBlur = this.onBlur.bind(this);
1358
- this.onClick = this.onClick.bind(this);
1359
- this.onKeyUp = this.onKeyUp.bind(this);
1360
- this.onSelect = this.onSelect.bind(this);
1361
- this.onMouseDown = this.onMouseDown.bind(this);
1362
- this.onMouseUp = this.onMouseUp.bind(this);
1363
- this.onCompositionStart = this.onCompositionStart.bind(this);
1364
- this.onCompositionEnd = this.onCompositionEnd.bind(this);
1365
- this.onScroll = this.onScroll.bind(this);
1366
- this.onBeforeInput = this.onBeforeInput.bind(this);
1367
- this.onCutHandler = () => {
1368
- if (this.cutTimerId !== null) clearTimeout(this.cutTimerId);
1369
- this.cutTimerId = window.setTimeout(() => {
1370
- this.cutTimerId = null;
1371
- if (this.isDestroyed) return;
1372
- if (this.options.disabled) {
1373
- this.checkValueChange();
1374
- } else {
1375
- const cur = this.input.selectionStart ?? this.input.value.length;
1376
- this.applyMask(this.input.value, cur);
1377
- }
1378
- }, 0);
1379
- };
1380
- this.onChangeNativeHandler = () => {
1381
- if (this.isDestroyed) return;
1382
- this.checkValueChange();
1383
- };
1384
- this.input.addEventListener("beforeinput", this.onBeforeInput);
1385
- this.input.addEventListener("input", this.handleInput);
1386
- this.input.addEventListener("keydown", this.onKeyDown);
1387
- this.input.addEventListener("paste", this.onPaste);
1388
- this.input.addEventListener("focus", this.onFocus);
1389
- this.input.addEventListener("blur", this.onBlur);
1390
- this.input.addEventListener("click", this.onClick);
1391
- this.input.addEventListener("keyup", this.onKeyUp);
1392
- this.input.addEventListener("select", this.onSelect);
1393
- this.input.addEventListener("mousedown", this.onMouseDown);
1394
- window.addEventListener("mouseup", this.onMouseUp);
1395
- this.input.addEventListener("compositionstart", this.onCompositionStart);
1396
- this.input.addEventListener("compositionend", this.onCompositionEnd);
1397
- this.input.addEventListener("scroll", this.onScroll);
1398
- this.input.addEventListener("cut", this.onCutHandler);
1399
- this.input.addEventListener("change", this.onChangeNativeHandler);
1400
- if (this.input.form) {
1401
- this.onFormResetHandler = () => {
1402
- if (this.resetTimerId !== null) clearTimeout(this.resetTimerId);
1403
- this.resetTimerId = window.setTimeout(() => {
1404
- this.resetTimerId = null;
1405
- if (this.isDestroyed) return;
1406
- if (this.options.disabled) {
1407
- this.checkValueChange();
1408
- } else {
1409
- this.syncInitialValue();
1410
- }
1411
- }, 0);
1412
- };
1413
- this.input.form.addEventListener("reset", this.onFormResetHandler);
1414
- }
1415
- }
1416
- /**
1417
- * Synchronise dynamiquement l'attribut inputmode="numeric" selon le motif actif
1418
- * sans jamais écraser un inputmode défini explicitement par l'hôte.
1419
- */
1420
- syncInferredInputMode() {
1421
- if (!this.options.inferInputMode) return;
1422
- const isNum = !this.options.disabled && this.engine.isNumericOnly();
1423
- if (isNum) {
1424
- if (!this.input.hasAttribute("inputmode")) {
1425
- this.input.inputMode = "numeric";
1426
- this.wasInputModeInferred = true;
1427
- }
1428
- } else if (this.wasInputModeInferred && this.input.getAttribute("inputmode") === "numeric") {
1429
- this.input.removeAttribute("inputmode");
1430
- this.wasInputModeInferred = false;
1431
- }
1432
- }
1433
- /**
1434
- * Supprime tous les écouteurs et nettoie les attributs associés.
1435
- */
1436
- destroy() {
1437
- if (this.isDestroyed) return;
1438
- if (this.cutTimerId !== null) {
1439
- clearTimeout(this.cutTimerId);
1440
- this.cutTimerId = null;
1441
- }
1442
- if (this.pasteTimerId !== null) {
1443
- clearTimeout(this.pasteTimerId);
1444
- this.pasteTimerId = null;
1445
- }
1446
- if (this.resetTimerId !== null) {
1447
- clearTimeout(this.resetTimerId);
1448
- this.resetTimerId = null;
1449
- }
1450
- this.input.removeEventListener("beforeinput", this.onBeforeInput);
1451
- this.input.removeEventListener("input", this.handleInput);
1452
- this.input.removeEventListener("keydown", this.onKeyDown);
1453
- this.input.removeEventListener("paste", this.onPaste);
1454
- this.input.removeEventListener("focus", this.onFocus);
1455
- this.input.removeEventListener("blur", this.onBlur);
1456
- this.input.removeEventListener("click", this.onClick);
1457
- this.input.removeEventListener("keyup", this.onKeyUp);
1458
- this.input.removeEventListener("select", this.onSelect);
1459
- this.input.removeEventListener("mousedown", this.onMouseDown);
1460
- window.removeEventListener("mouseup", this.onMouseUp);
1461
- this.input.removeEventListener("compositionstart", this.onCompositionStart);
1462
- this.input.removeEventListener("compositionend", this.onCompositionEnd);
1463
- this.input.removeEventListener("scroll", this.onScroll);
1464
- this.input.removeEventListener("cut", this.onCutHandler);
1465
- this.input.removeEventListener("change", this.onChangeNativeHandler);
1466
- if (this.input.form && this.onFormResetHandler) {
1467
- this.input.form.removeEventListener("reset", this.onFormResetHandler);
1468
- }
1469
- if (this.wasInputModeInferred && this.input.getAttribute("inputmode") === "numeric") {
1470
- this.input.removeAttribute("inputmode");
1471
- }
1472
- this.history.clear();
1473
- super.destroy();
1474
- }
1475
- /**
1476
- * Définit si le masque bloque strictement les entrées non conformes.
1477
- */
1478
- setStrict(strict) {
1479
- this.options.strict = strict;
1480
- this.engine.setStrict(strict);
1481
- if (!this.options.disabled) {
1482
- this.applyMask(this.input.value, this.input.selectionStart ?? this.input.value.length);
1483
- }
1484
- }
1485
- /**
1486
- * Indique si le masque est en mode strict.
1487
- */
1488
- isStrict() {
1489
- return this.engine.isStrict();
1490
- }
1491
- /**
1492
- * Modifie dynamiquement le masque actif.
1493
- * Permet de désactiver le masque avec null/vide, ou de spécifier un mode strict/souple.
1494
- */
1495
- setMask(newPattern, options) {
1496
- const newStrict = typeof options === "boolean" ? options : options && typeof options === "object" && options.strict !== void 0 ? options.strict : this.options.strict;
1497
- const shouldResetHistory = options && typeof options === "object" && options.resetHistory !== void 0 ? options.resetHistory : Boolean(this.options.resetHistoryOnMaskChange);
1498
- const isTargetingEmpty = !newPattern || Array.isArray(newPattern) && newPattern.length === 0;
1499
- if (isTargetingEmpty && this.options.disabled && (!this.options.mask || this.options.mask === "")) {
1500
- return;
1501
- }
1502
- if (!newPattern || Array.isArray(newPattern) && newPattern.length === 0) {
1503
- this.options.mask = "";
1504
- this.options.strict = newStrict;
1505
- this.engine.setStrict(newStrict ?? true);
1506
- this.engine.compile("");
1507
- if (shouldResetHistory) {
1508
- this.history.clear();
1509
- }
1510
- this.setDisabled(true);
1511
- this.syncInferredInputMode();
1512
- return;
1513
- }
1514
- this.options.mask = newPattern;
1515
- this.options.strict = newStrict;
1516
- this.engine.setStrict(newStrict ?? true);
1517
- this.engine.compile(newPattern);
1518
- if (shouldResetHistory) {
1519
- this.history.clear();
1520
- }
1521
- this.setDisabled(false);
1522
- this.syncInferredInputMode();
1523
- }
1524
- handleAttributeMutation(attrName) {
1525
- super.handleAttributeMutation(attrName);
1526
- if (attrName === "data-mask") {
1527
- const rawAttr = this.getAttr("data-mask");
1528
- if (rawAttr === this.lastInternalRemainingMask) {
1529
- return;
1530
- }
1531
- const currentMaskStr = Array.isArray(this.options.mask) ? this.options.mask.join("|") : this.options.mask || "";
1532
- if (rawAttr === currentMaskStr) {
1533
- return;
1534
- }
1535
- if (rawAttr) {
1536
- const maskVal = rawAttr.includes("|") ? rawAttr.split("|").map((s) => s.trim()) : rawAttr;
1537
- this.setMask(maskVal);
1538
- } else {
1539
- this.setMask(null);
1540
- }
1541
- } else if (attrName === "data-mask-strict") {
1542
- const strictVal = this.getAttr("data-mask-strict");
1543
- this.setStrict(strictVal !== "false");
1544
- } else if (attrName === "data-mask-auto-lowercase") {
1545
- this.options.autoLowercase = this.getAttr("data-mask-auto-lowercase") === "true";
1546
- this.engine.compile(this.options.mask || "");
1547
- this.applyMask(this.input.value, this.input.selectionStart ?? this.input.value.length);
1548
- } else if (attrName === "placeholder") {
1549
- this.updateGhost(this.input.value);
1550
- }
1551
- }
1552
- /**
1553
- * Affecte une nouvelle valeur manuellement (formatée ou brute).
1554
- */
1555
- setValue(val) {
1556
- const safeVal = val !== null && val !== void 0 ? String(val) : "";
1557
- if (this.options.disabled) {
1558
- this.input.value = safeVal;
1559
- this.checkValueChange();
1560
- return;
1561
- }
1562
- this.applyMask(safeVal, safeVal.length);
1563
- }
1564
- /**
1565
- * Retourne la valeur brute sans séparateurs.
1566
- */
1567
- getRawValue() {
1568
- return this.engine.extractRaw(this.input.value);
1569
- }
1570
- /**
1571
- * Indique si tous les emplacements éditables sont renseignés.
1572
- */
1573
- isComplete() {
1574
- if (this.options.disabled) return true;
1575
- const raw = this.getRawValue();
1576
- return raw.length >= this.engine.getEditableCount();
1577
- }
1578
- /**
1579
- * Callback d'écoute directe ou getter/setter pour onInput.
1580
- */
1581
- get onInput() {
1582
- return this.options.onInput;
1583
- }
1584
- set onInput(callback) {
1585
- this.options.onInput = callback;
1586
- }
1587
- /**
1588
- * Annule la dernière modification (Undo).
1589
- */
1590
- undo() {
1591
- if (this.options.disabled) return;
1592
- const state = this.history.undo();
1593
- if (state) {
1594
- this.isUndoingRedoing = true;
1595
- this.applyMask(state.raw, state.cursor);
1596
- this.isUndoingRedoing = false;
1597
- }
1598
- }
1599
- /**
1600
- * Rétablit la modification annulée (Redo).
1601
- */
1602
- redo() {
1603
- if (this.options.disabled) return;
1604
- const state = this.history.redo();
1605
- if (state) {
1606
- this.isUndoingRedoing = true;
1607
- this.applyMask(state.raw, state.cursor);
1608
- this.isUndoingRedoing = false;
1609
- }
1610
- }
1611
- // ==========================================================================
1612
- // Gestionnaires d'événements DOM
1613
- // ==========================================================================
1614
- checkSelection() {
1615
- if (this.options.disabled) return;
1616
- const start = this.input.selectionStart ?? 0;
1617
- const end = this.input.selectionEnd ?? start;
1618
- const hasSelection = start !== end;
1619
- this.wrapper.classList.toggle("has-selection", hasSelection);
1620
- }
1621
- onBeforeInput(e) {
1622
- if (this.options.disabled) return;
1623
- if (this.isComposing) return;
1624
- if (!this.engine.isStrict()) return;
1625
- if (e.inputType === "insertFromPaste") return;
1626
- if (e.inputType && e.inputType.startsWith("insert")) {
1627
- const totalSlots = this.engine.getEditableCount();
1628
- if (totalSlots > 0) {
1629
- const currentRaw = this.getRawValue();
1630
- const start = this.input.selectionStart ?? 0;
1631
- const end = this.input.selectionEnd ?? start;
1632
- let availableCapacity = Math.max(0, totalSlots - currentRaw.length);
1633
- if (end > start) {
1634
- const selectedRaw = this.engine.extractRaw(this.input.value.slice(start, end));
1635
- availableCapacity = Math.max(0, totalSlots - (currentRaw.length - selectedRaw.length));
1636
- }
1637
- if (availableCapacity <= 0) {
1638
- e.preventDefault();
1639
- }
1640
- }
1641
- }
1642
- }
1643
- handleInput(e) {
1644
- if (this.isDispatchingNativeInput) return;
1645
- if (this.isComposing) return;
1646
- const hasOnInput = Boolean(this.options.onInput || this.options.oninput);
1647
- if (hasOnInput && this.input.value !== this.lastValue) {
1648
- this.checkValueChange();
1649
- }
1650
- if (this.options.disabled) {
1651
- this.checkValueChange();
1652
- return;
1653
- }
1654
- const prevState = this.history.getCurrent();
1655
- const totalSlots = this.engine.getEditableCount();
1656
- if (totalSlots > 0 && this.engine.isStrict() && prevState && prevState.raw.length >= totalSlots) {
1657
- const newRaw = this.engine.extractRaw(this.input.value);
1658
- if (newRaw.length > totalSlots) {
1659
- this.applyMask(prevState.raw, prevState.cursor);
1660
- return;
1661
- }
1662
- }
1663
- const oldCursor = this.input.selectionStart ?? this.input.value.length;
1664
- this.applyMask(this.input.value, oldCursor);
1665
- this.checkSelection();
1666
- }
1667
- onKeyDown(e) {
1668
- if (this.options.disabled) return;
1669
- this.keyboard.handleKeyDown(e);
1670
- }
1671
- onMouseDown() {
1672
- this.isMouseDown = true;
1673
- }
1674
- onMouseUp() {
1675
- this.isMouseDown = false;
1676
- this.checkSelection();
1677
- }
1678
- onPaste(e) {
1679
- if (this.options.disabled) {
1680
- if (this.pasteTimerId !== null) clearTimeout(this.pasteTimerId);
1681
- this.pasteTimerId = window.setTimeout(() => {
1682
- this.pasteTimerId = null;
1683
- if (!this.isDestroyed) this.checkValueChange();
1684
- }, 0);
1685
- return;
1686
- }
1687
- e.preventDefault();
1688
- this.history.updateCurrentCursor(this.input.selectionStart ?? 0);
1689
- const rawPasted = e.clipboardData?.getData("text") || "";
1690
- const pastedText = rawPasted.trim();
1691
- if (!pastedText) return;
1692
- const minPos = this.engine.getPrefixLength();
1693
- const selStart = this.input.selectionStart ?? 0;
1694
- const selEnd = this.input.selectionEnd ?? selStart;
1695
- const currentVal = this.input.value;
1696
- const totalSlots = this.engine.getEditableCount();
1697
- const currentRaw = this.getRawValue();
1698
- const prefix = this.engine.getPrefix();
1699
- const cleanPrefix = prefix.replace(/[\s.-]+/g, "").toUpperCase();
1700
- const cleanPasted = pastedText.replace(/[\s.-]+/g, "").toUpperCase();
1701
- const startsWithStaticPrefix = cleanPrefix.length > 0 && cleanPasted.startsWith(cleanPrefix);
1702
- const prefixInField = currentVal.slice(0, Math.max(minPos, selStart)).replace(/[\s.-]+/g, "").toUpperCase();
1703
- const startsWithFieldStart = prefixInField.length >= 2 && cleanPasted.startsWith(prefixInField);
1704
- let effectiveStart = Math.max(minPos, selStart);
1705
- let effectiveEnd = Math.max(minPos, selEnd);
1706
- if (startsWithStaticPrefix || startsWithFieldStart) {
1707
- effectiveStart = 0;
1708
- effectiveEnd = currentVal.length;
1709
- }
1710
- let availableCapacity = Math.max(0, totalSlots - currentRaw.length);
1711
- if (effectiveStart !== effectiveEnd) {
1712
- const selectedRaw = this.engine.extractRaw(currentVal.slice(effectiveStart, effectiveEnd));
1713
- availableCapacity = Math.max(0, totalSlots - (currentRaw.length - selectedRaw.length));
1714
- }
1715
- if (this.engine.isStrict() && availableCapacity <= 0) {
1716
- return;
1717
- }
1718
- let combined;
1719
- let newCursorPos;
1720
- if (effectiveStart === 0 && effectiveEnd === currentVal.length) {
1721
- combined = pastedText;
1722
- newCursorPos = pastedText.length;
1723
- } else {
1724
- combined = currentVal.slice(0, effectiveStart) + pastedText + currentVal.slice(effectiveEnd);
1725
- newCursorPos = effectiveStart + pastedText.length;
1726
- }
1727
- this.applyMask(combined, newCursorPos);
1728
- this.checkSelection();
1729
- }
1730
- onFocus() {
1731
- this.syncGhostStyles();
1732
- this.wrapper.classList.add("is-focused");
1733
- if (!this.options.disabled && !this.isMouseDown) {
1734
- this.enforceMinCursor();
1735
- }
1736
- this.updateGhost(this.input.value);
1737
- this.checkSelection();
1738
- }
1739
- onBlur() {
1740
- this.wrapper.classList.remove("is-focused", "has-selection");
1741
- if (this.input.type === "password") {
1742
- this.history.clear();
1743
- }
1744
- this.updateGhost(this.input.value);
1745
- }
1746
- onClick() {
1747
- if (!this.options.disabled) {
1748
- this.enforceMinCursor();
1749
- }
1750
- this.history.updateCurrentCursor(this.input.selectionStart ?? 0);
1751
- this.checkSelection();
1752
- }
1753
- onKeyUp(e) {
1754
- if (!this.options.disabled) {
1755
- this.keyboard.handleKeyUp(e);
1756
- }
1757
- this.checkSelection();
1758
- }
1759
- onSelect() {
1760
- this.history.updateCurrentCursor(this.input.selectionStart ?? 0);
1761
- this.checkSelection();
1762
- }
1763
- onCompositionStart() {
1764
- this.isComposing = true;
1765
- }
1766
- onCompositionEnd() {
1767
- this.isComposing = false;
1768
- if (this.options.disabled) return;
1769
- const oldCursor = this.input.selectionStart ?? this.input.value.length;
1770
- this.applyMask(this.input.value, oldCursor);
1771
- this.checkSelection();
1772
- }
1773
- /**
1774
- * Empêche strictement le curseur de se positionner avant la fin du préfixe statique
1775
- * lorsqu'il n'y a PAS de sélection active.
1776
- * Si une sélection est active (ex: pour copier avec Ctrl+C ou écraser avec Ctrl+A),
1777
- * elle est préservée sans restriction.
1778
- */
1779
- enforceMinCursor() {
1780
- const minPos = this.engine.getPrefixLength();
1781
- if (minPos <= 0) return;
1782
- const start = this.input.selectionStart ?? 0;
1783
- const end = this.input.selectionEnd ?? start;
1784
- if (start !== end) {
1785
- return;
1786
- }
1787
- if (start < minPos) {
1788
- this.input.setSelectionRange(minPos, minPos);
1789
- }
1790
- }
1791
- // ==========================================================================
1792
- // Pipeline de calcul et de synchronisation
1793
- // ==========================================================================
1794
- updateGhost(formatted) {
1795
- if (!this.ghost) return;
1796
- if (this.options.disabled) {
1797
- this.ghost.textContent = "";
1798
- return;
1799
- }
1800
- const isCleanEmpty = !formatted || formatted === this.engine.getPrefix();
1801
- if (this.shouldHideGhostForPlaceholder(isCleanEmpty)) {
1802
- this.ghost.textContent = "";
1803
- return;
1804
- }
1805
- const fullTemplate = this.engine.getFullMaskTemplate();
1806
- const rest = fullTemplate.length > formatted.length ? fullTemplate.substring(formatted.length) : "";
1807
- this.ghost.textContent = "";
1808
- const spanTyped = document.createElement("span");
1809
- spanTyped.className = "mask-ghost-typed";
1810
- spanTyped.textContent = formatted;
1811
- const spanRemaining = document.createElement("span");
1812
- spanRemaining.className = "mask-ghost-remaining";
1813
- spanRemaining.textContent = rest;
1814
- this.ghost.appendChild(spanTyped);
1815
- this.ghost.appendChild(spanRemaining);
1816
- this.ghost.scrollLeft = this.input.scrollLeft;
1817
- }
1818
- applyMask(rawOrPartial, cursorPosition, forceExactCursor = false) {
1819
- if (this.options.disabled || this.isApplyingMask) return;
1820
- this.isApplyingMask = true;
1821
- let formatted = "";
1822
- let isCompleted = false;
1823
- try {
1824
- formatted = this.engine.format(rawOrPartial);
1825
- const remainingMask = this.engine.getRemainingMask(formatted);
1826
- this.input.value = formatted;
1827
- this.lastInternalRemainingMask = remainingMask;
1828
- this.wrapper.setAttribute("data-mask", remainingMask);
1829
- this.updateGhost(formatted);
1830
- const minPos = this.engine.getPrefixLength();
1831
- let safeCursor;
1832
- if (forceExactCursor || this.isUndoingRedoing) {
1833
- safeCursor = Math.max(minPos, Math.min(cursorPosition, formatted.length));
1834
- } else {
1835
- const calculatedCursor = this.engine.mapCursorPosition(rawOrPartial, cursorPosition, formatted);
1836
- safeCursor = Math.max(minPos, calculatedCursor);
1837
- }
1838
- this.input.setSelectionRange(safeCursor, safeCursor);
1839
- isCompleted = this.isComplete();
1840
- this.wrapper.classList.toggle("is-complete", isCompleted);
1841
- if (!this.isUndoingRedoing && this.input.type !== "password") {
1842
- this.history.push(this.getRawValue(), safeCursor);
1843
- }
1844
- } finally {
1845
- this.isApplyingMask = false;
1846
- }
1847
- this.checkValueChange();
1848
- }
1849
- syncInitialValue() {
1850
- if (this.options.disabled) {
1851
- this.wrapper.removeAttribute("data-mask");
1852
- if (this.ghost) this.ghost.textContent = "";
1853
- this.lastValue = this.input.value;
1854
- this.checkValueChange();
1855
- return;
1856
- }
1857
- this.syncGhostStyles();
1858
- const initialVal = this.input.value || "";
1859
- if (initialVal) {
1860
- this.applyMask(initialVal, initialVal.length);
1861
- } else {
1862
- const minPos = this.engine.getPrefixLength();
1863
- if (minPos > 0) {
1864
- this.applyMask("", minPos);
1865
- } else {
1866
- if (this.input.type !== "password") {
1867
- this.history.push("", 0);
1868
- }
1869
- const fullTemplate = this.engine.getFullMaskTemplate();
1870
- this.lastInternalRemainingMask = fullTemplate;
1871
- this.wrapper.setAttribute("data-mask", fullTemplate);
1872
- this.updateGhost("");
1873
- this.checkValueChange();
1874
- }
1875
- }
1876
- }
1877
- /**
1878
- * Vérifie si la valeur a changé et notifie les observateurs (onInput, onChange, onComplete).
1879
- * Gère de manière sûre la réentrance pour permettre d'appeler setMask() directement dans le callback.
1880
- */
1881
- checkValueChange(forceNotify = false) {
1882
- const currentVal = this.input.value;
1883
- if (currentVal === this.lastValue && !forceNotify && !this.hasPendingNotification) {
1884
- return;
1885
- }
1886
- if (this.isNotifying) {
1887
- this.hasPendingNotification = true;
1888
- return;
1889
- }
1890
- this.isNotifying = true;
1891
- try {
1892
- while (this.input.value !== this.lastValue || this.hasPendingNotification || forceNotify) {
1893
- this.hasPendingNotification = false;
1894
- forceNotify = false;
1895
- const valToNotify = this.input.value;
1896
- this.lastValue = valToNotify;
1897
- const raw = this.options.disabled ? valToNotify : this.getRawValue();
1898
- const totalSlots = this.options.disabled ? 0 : this.engine.getEditableCount();
1899
- const isComplete = this.isComplete();
1900
- const detail = {
1901
- value: valToNotify,
1902
- rawValue: raw,
1903
- isComplete,
1904
- totalSlots,
1905
- filledSlots: this.options.disabled ? valToNotify.length : raw.length
1906
- };
1907
- const onInputCb = this.options.onInput || this.options.oninput;
1908
- if (onInputCb) {
1909
- onInputCb(valToNotify, detail);
1910
- }
1911
- this.input.dispatchEvent(new CustomEvent("mask:input", { bubbles: true, detail }));
1912
- this.dispatchNativeInput();
1913
- const onChangeCb = this.options.onChange || this.options.onchange;
1914
- if (onChangeCb) {
1915
- onChangeCb(detail);
1916
- }
1917
- this.input.dispatchEvent(new CustomEvent("mask:change", { bubbles: true, detail }));
1918
- const onCompleteCb = this.options.onComplete || this.options.oncomplete;
1919
- if (isComplete) {
1920
- if (onCompleteCb) {
1921
- onCompleteCb(detail);
1922
- }
1923
- this.input.dispatchEvent(new CustomEvent("mask:complete", { bubbles: true, detail }));
1924
- }
1925
- }
1926
- } finally {
1927
- this.isNotifying = false;
1928
- }
1929
- }
1930
- };
1931
-
1932
- // src/mask/AmountEngine.ts
1933
- var AmountEngine = class _AmountEngine {
1934
- constructor(options = {}) {
1935
- let currency = options.currency ?? "";
1936
- if (!currency && options.unit) {
1937
- currency = options.unit;
1938
- }
1939
- const defaultPosition = currency === "$" || currency === "\xA3" || currency === "\xA5" ? "prefix" : "suffix";
1940
- this.options = {
1941
- currency,
1942
- unit: options.unit ?? currency,
1943
- currencyPosition: options.currencyPosition ?? defaultPosition,
1944
- decimals: options.decimals !== void 0 ? Math.max(0, options.decimals) : 2,
1945
- decimalSeparator: options.decimalSeparator ?? ",",
1946
- thousandSeparator: options.thousandSeparator ?? "\xA0",
1947
- // Espace insécable
1948
- allowNegative: options.allowNegative ?? false,
1949
- min: options.min ?? -Infinity,
1950
- max: options.max ?? Infinity
1951
- };
1952
- }
1953
- /**
1954
- * Analyse et nettoie une saisie utilisateur pour extraire ses composantes numériques.
1955
- */
1956
- parse(input) {
1957
- let str = input.trim();
1958
- let isNegative = false;
1959
- if (this.options.allowNegative && str.includes("-")) {
1960
- isNegative = true;
1961
- }
1962
- if (this.options.currency) {
1963
- str = str.replace(new RegExp(this.escapeRegExp(this.options.currency), "g"), "");
1964
- }
1965
- if (this.options.thousandSeparator) {
1966
- str = str.replace(new RegExp(this.escapeRegExp(this.options.thousandSeparator), "g"), "");
1967
- }
1968
- str = str.replace(/[\s\u00A0]/g, "");
1969
- const decSep = this.options.decimalSeparator;
1970
- let firstDecIndex = str.indexOf(decSep);
1971
- if (firstDecIndex === -1) {
1972
- firstDecIndex = str.search(/[,.]/);
1973
- }
1974
- let integerRaw = "";
1975
- let decimalRaw = null;
1976
- let hasDecimal = false;
1977
- if (firstDecIndex !== -1) {
1978
- integerRaw = str.substring(0, firstDecIndex).replace(/\D/g, "");
1979
- if (this.options.decimals > 0) {
1980
- hasDecimal = true;
1981
- decimalRaw = str.substring(firstDecIndex + 1).replace(/\D/g, "").slice(0, this.options.decimals);
1982
- }
1983
- } else {
1984
- integerRaw = str.replace(/\D/g, "");
1985
- }
1986
- if (integerRaw.length > 1) {
1987
- integerRaw = integerRaw.replace(/^0+/, "") || "0";
1988
- }
1989
- return { isNegative, integerPart: integerRaw, decimalPart: decimalRaw, hasDecimal };
1990
- }
1991
- /**
1992
- * Formate une valeur brute ou une saisie courante en préservant la fluidité du curseur.
1993
- *
1994
- * @param input Texte brut ou partiellement formaté
1995
- * @param rawCursor Position actuelle du curseur dans l'input natif
1996
- */
1997
- format(input, rawCursor = input.length, padDecimals = false) {
1998
- if (!input || input.trim() === "" || input === this.options.currency.trim()) {
1999
- return {
2000
- formatted: "",
2001
- rawNumber: null,
2002
- rawValue: "",
2003
- cursor: 0,
2004
- isValid: true
2005
- };
2006
- }
2007
- const prefixBeforeCursor = input.substring(0, rawCursor);
2008
- const digitsBeforeCursor = prefixBeforeCursor.replace(/\D/g, "").length;
2009
- const hadDecimalBeforeCursor = this.options.decimals > 0 && /[,.]/.test(prefixBeforeCursor);
2010
- const { isNegative, integerPart, decimalPart, hasDecimal } = this.parse(input);
2011
- let effectiveDecimal = decimalPart;
2012
- let effectiveHasDecimal = hasDecimal;
2013
- if (padDecimals && this.options.decimals > 0 && (integerPart || decimalPart !== null)) {
2014
- effectiveHasDecimal = true;
2015
- if (effectiveDecimal === null) {
2016
- effectiveDecimal = "0".repeat(this.options.decimals);
2017
- } else if (effectiveDecimal.length < this.options.decimals) {
2018
- effectiveDecimal = effectiveDecimal + "0".repeat(this.options.decimals - effectiveDecimal.length);
2019
- }
2020
- }
2021
- if (isNegative && !integerPart && !effectiveDecimal && !effectiveHasDecimal && this.options.allowNegative) {
2022
- let formatted2 = "-";
2023
- let cursor = 1;
2024
- if (this.options.currency) {
2025
- if (this.options.currencyPosition === "prefix") {
2026
- formatted2 = `${this.options.currency} -`;
2027
- cursor = formatted2.length;
2028
- } else {
2029
- formatted2 = `- ${this.options.currency}`;
2030
- cursor = 1;
2031
- }
2032
- }
2033
- return {
2034
- formatted: formatted2,
2035
- rawNumber: null,
2036
- rawValue: "-",
2037
- cursor,
2038
- isValid: true
2039
- };
2040
- }
2041
- if (!integerPart && !effectiveDecimal && !effectiveHasDecimal) {
2042
- return {
2043
- formatted: "",
2044
- rawNumber: null,
2045
- rawValue: "",
2046
- cursor: 0,
2047
- isValid: true
2048
- };
2049
- }
2050
- const formattedInteger = (integerPart || "0").replace(/\B(?=(\d{3})+(?!\d))/g, this.options.thousandSeparator);
2051
- let numberCore = formattedInteger;
2052
- if (effectiveHasDecimal && this.options.decimals > 0) {
2053
- numberCore += this.options.decimalSeparator + (effectiveDecimal ?? "");
2054
- }
2055
- if (isNegative && numberCore !== "0") {
2056
- numberCore = "-" + numberCore;
2057
- }
2058
- let formatted = numberCore;
2059
- if (this.options.currency) {
2060
- if (this.options.currencyPosition === "prefix") {
2061
- formatted = `${this.options.currency} ${numberCore}`;
2062
- } else {
2063
- formatted = `${numberCore} ${this.options.currency}`;
2064
- }
2065
- }
2066
- const numStr = (isNegative ? "-" : "") + (integerPart || "0") + (decimalPart ? "." + decimalPart : "");
2067
- let num = parseFloat(numStr);
2068
- if (isNaN(num)) num = 0;
2069
- const isValid = num >= this.options.min && num <= this.options.max;
2070
- let newCursor = 0;
2071
- if (this.options.currency && this.options.currencyPosition === "prefix") {
2072
- newCursor = this.options.currency.length + 1;
2073
- }
2074
- let seenDigits = 0;
2075
- let seenDecimal = false;
2076
- let lastValidDigitPosition = newCursor;
2077
- for (let i = newCursor; i < formatted.length; i++) {
2078
- const ch = formatted[i];
2079
- if (ch === this.options.currency.trim()[0] && this.options.currencyPosition === "suffix") {
2080
- break;
2081
- }
2082
- if (/\d/.test(ch)) {
2083
- seenDigits++;
2084
- lastValidDigitPosition = i + 1;
2085
- } else if (ch === this.options.decimalSeparator) {
2086
- seenDecimal = true;
2087
- lastValidDigitPosition = i + 1;
2088
- }
2089
- if (hadDecimalBeforeCursor) {
2090
- if (seenDecimal && seenDigits >= digitsBeforeCursor) {
2091
- newCursor = i + 1;
2092
- break;
2093
- }
2094
- } else {
2095
- if (seenDigits >= digitsBeforeCursor) {
2096
- newCursor = i + 1;
2097
- break;
2098
- }
2099
- }
2100
- }
2101
- if (digitsBeforeCursor > 0 && seenDigits < digitsBeforeCursor && lastValidDigitPosition > newCursor) {
2102
- newCursor = lastValidDigitPosition;
2103
- }
2104
- const minCursor = this.options.currency && this.options.currencyPosition === "prefix" ? this.options.currency.length + 1 : 0;
2105
- const maxCursor = this.options.currency && this.options.currencyPosition === "suffix" ? Math.max(0, formatted.length - this.options.currency.length - 1) : formatted.length;
2106
- newCursor = Math.max(minCursor, Math.min(newCursor, Math.max(minCursor, maxCursor)));
2107
- return {
2108
- formatted,
2109
- rawNumber: num,
2110
- rawValue: numStr,
2111
- cursor: newCursor,
2112
- isValid
2113
- };
2114
- }
2115
- /**
2116
- * Formate statiquement un nombre ou une chaîne numérique.
2117
- */
2118
- static format(value, options = {}) {
2119
- const engine = new _AmountEngine(options);
2120
- const str = typeof value === "number" ? value.toString() : value;
2121
- return engine.format(str).formatted;
2122
- }
2123
- escapeRegExp(string) {
2124
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2125
- }
2126
- };
2127
-
2128
- // src/mask/InputAmountMask.ts
2129
- var InputAmountMask = class extends BaseInputMask {
2130
- constructor(targetOrWrapper, inputOrOptions, options) {
2131
- const args = resolveMaskConstructorArgs(targetOrWrapper, inputOrOptions, options);
2132
- const wrap = args.wrapper;
2133
- const inp = args.input;
2134
- const opts = args.options;
2135
- const dataPad = wrap?.getAttribute("data-mask-pad-decimals") === "true" || inp?.getAttribute("data-mask-pad-decimals") === "true";
2136
- const dataAlign = inp?.getAttribute("data-mask-align") || inp?.getAttribute("data-align") || wrap?.getAttribute("data-mask-align") || wrap?.getAttribute("data-align");
2137
- const resolvedOptions = {
2138
- align: opts.align ?? dataAlign ?? "right",
2139
- padDecimalsOnBlur: opts.padDecimalsOnBlur ?? dataPad ?? false,
2140
- ...opts
2141
- };
2142
- super(wrap, inp, resolvedOptions);
2143
- this.isUndoingRedoing = false;
2144
- this.isApplying = false;
2145
- this.isComposing = false;
2146
- this.lastValue = "";
2147
- this.cutTimerId = null;
2148
- this.resetTimerId = null;
2149
- this.input.inputMode = "decimal";
2150
- this.history = new MaskHistory();
2151
- this.engine = new AmountEngine(this.options);
2152
- this.bindEvents();
2153
- if (this.input.value) {
2154
- if (!this.options.disabled) {
2155
- this.applyAmount(this.input.value, this.input.value.length);
2156
- }
2157
- } else {
2158
- this.updateGhost({
2159
- formatted: "",
2160
- rawNumber: null,
2161
- rawValue: "",
2162
- cursor: 0,
2163
- isValid: true
2164
- });
2165
- }
2166
- }
2167
- extractRawSnippet(snippet) {
2168
- const p = this.engine.parse(snippet);
2169
- if (!p.integerPart && !p.decimalPart) return "";
2170
- return (p.isNegative ? "-" : "") + (p.integerPart || "0") + (p.decimalPart ? "." + p.decimalPart : "");
2171
- }
2172
- /**
2173
- * Formate statiquement une valeur sans nécessiter d'élément DOM.
2174
- */
2175
- static format(value, options = {}) {
2176
- return AmountEngine.format(value, options);
2177
- }
2178
- onNativeValueSet(strVal) {
2179
- if (this.options.disabled || this.isComposing) {
2180
- this.lastValue = strVal;
2181
- return;
2182
- }
2183
- this.applyAmount(strVal, strVal.length);
2184
- }
2185
- onDisabledChange(disabled) {
2186
- if (!disabled) {
2187
- this.applyAmount(this.input.value, this.input.selectionStart ?? this.input.value.length);
2188
- }
2189
- }
2190
- bindEvents() {
2191
- this.handleInput = this.handleInput.bind(this);
2192
- this.handleKeyDown = this.handleKeyDown.bind(this);
2193
- this.handleBlur = this.handleBlur.bind(this);
2194
- this.handleFocus = this.handleFocus.bind(this);
2195
- this.handleClick = this.handleClick.bind(this);
2196
- this.onCompositionStart = this.onCompositionStart.bind(this);
2197
- this.onCompositionEnd = this.onCompositionEnd.bind(this);
2198
- this.onCutHandler = () => {
2199
- if (this.cutTimerId !== null) {
2200
- clearTimeout(this.cutTimerId);
2201
- }
2202
- this.cutTimerId = window.setTimeout(() => {
2203
- this.cutTimerId = null;
2204
- if (this.isDestroyed || this.options.disabled) return;
2205
- const cur = this.input.selectionStart ?? this.input.value.length;
2206
- this.applyAmount(this.input.value, cur);
2207
- }, 0);
2208
- };
2209
- this.input.addEventListener("input", this.handleInput);
2210
- this.input.addEventListener("keydown", this.handleKeyDown);
2211
- this.input.addEventListener("blur", this.handleBlur);
2212
- this.input.addEventListener("focus", this.handleFocus);
2213
- this.input.addEventListener("click", this.handleClick);
2214
- this.input.addEventListener("scroll", this.onScroll);
2215
- this.input.addEventListener("cut", this.onCutHandler);
2216
- this.input.addEventListener("compositionstart", this.onCompositionStart);
2217
- this.input.addEventListener("compositionend", this.onCompositionEnd);
2218
- if (this.input.form) {
2219
- this.onFormResetHandler = () => {
2220
- if (this.resetTimerId !== null) {
2221
- clearTimeout(this.resetTimerId);
2222
- }
2223
- this.resetTimerId = window.setTimeout(() => {
2224
- this.resetTimerId = null;
2225
- if (this.isDestroyed) return;
2226
- if (this.options.disabled) return;
2227
- this.applyAmount(this.input.value, this.input.value.length);
2228
- }, 0);
2229
- };
2230
- this.input.form.addEventListener("reset", this.onFormResetHandler);
2231
- }
2232
- }
2233
- onCompositionStart() {
2234
- this.isComposing = true;
2235
- }
2236
- onCompositionEnd() {
2237
- this.isComposing = false;
2238
- if (this.options.disabled) return;
2239
- const cur = this.input.selectionStart ?? this.input.value.length;
2240
- this.applyAmount(this.input.value, cur);
2241
- }
2242
- applyAmount(val, cursor) {
2243
- if (this.isApplying || this.options.disabled) return;
2244
- this.isApplying = true;
2245
- try {
2246
- const result = this.engine.format(val, cursor);
2247
- this.setNativeValue(result.formatted);
2248
- this.input.setSelectionRange(result.cursor, result.cursor);
2249
- if (!this.isUndoingRedoing && this.input.type !== "password") {
2250
- this.history.push(result.rawValue, result.cursor);
2251
- }
2252
- this.updateGhost(result);
2253
- if (this.lastValue !== result.formatted) {
2254
- this.lastValue = result.formatted;
2255
- this.notifyChange(result);
2256
- }
2257
- } finally {
2258
- this.isApplying = false;
2259
- }
2260
- }
2261
- updateGhost(result) {
2262
- if (!this.ghost) return;
2263
- if (!result.formatted) {
2264
- if (this.shouldHideGhostForPlaceholder(true)) {
2265
- this.ghost.textContent = "";
2266
- return;
2267
- }
2268
- const hint = this.options.currency ? this.options.currencyPosition === "prefix" ? `${this.options.currency} 0` : `0 ${this.options.currency}` : "0,00";
2269
- this.ghost.textContent = "";
2270
- const span = document.createElement("span");
2271
- span.className = "mask-ghost-remaining";
2272
- span.textContent = hint;
2273
- this.ghost.appendChild(span);
2274
- return;
2275
- }
2276
- this.ghost.textContent = "";
2277
- this.ghost.scrollLeft = this.input.scrollLeft;
2278
- }
2279
- handleInput() {
2280
- if (this.isDispatchingNativeInput) return;
2281
- if (this.options.disabled || this.isComposing) return;
2282
- const rawVal = this.input.value;
2283
- const cur = this.input.selectionStart ?? rawVal.length;
2284
- this.applyAmount(rawVal, cur);
2285
- }
2286
- handleKeyDown(e) {
2287
- if (this.options.disabled) return;
2288
- if ((e.ctrlKey || e.metaKey) && (e.key === "z" || e.key === "Z")) {
2289
- e.preventDefault();
2290
- if (e.shiftKey) this.redo();
2291
- else this.undo();
2292
- return;
2293
- }
2294
- if ((e.ctrlKey || e.metaKey) && (e.key === "y" || e.key === "Y")) {
2295
- e.preventDefault();
2296
- this.redo();
2297
- return;
2298
- }
2299
- if (e.key === "Backspace") {
2300
- const start = this.input.selectionStart ?? 0;
2301
- const end = this.input.selectionEnd ?? 0;
2302
- if (start === end && start > 0) {
2303
- const val = this.input.value;
2304
- const charToDelete = val[start - 1];
2305
- if (charToDelete === this.engine.options.thousandSeparator || charToDelete === " ") {
2306
- e.preventDefault();
2307
- const targetIndex = Math.max(0, start - 2);
2308
- const newVal = val.slice(0, targetIndex) + val.slice(start);
2309
- this.applyAmount(newVal, targetIndex);
2310
- return;
2311
- }
2312
- if (this.options.currency && this.options.currencyPosition === "prefix" && start <= this.options.currency.length + 1) {
2313
- e.preventDefault();
2314
- return;
2315
- }
2316
- }
2317
- }
2318
- if (e.key === "Delete") {
2319
- const start = this.input.selectionStart ?? 0;
2320
- const end = this.input.selectionEnd ?? 0;
2321
- if (start === end && start < this.input.value.length) {
2322
- const val = this.input.value;
2323
- const charAhead = val[start];
2324
- if (charAhead === this.engine.options.thousandSeparator || charAhead === " ") {
2325
- e.preventDefault();
2326
- const newVal = val.slice(0, start) + val.slice(start + 2);
2327
- this.applyAmount(newVal, start);
2328
- return;
2329
- }
2330
- if (this.options.currency && this.options.currencyPosition === "suffix") {
2331
- const suffixStart = val.length - this.options.currency.length - 1;
2332
- if (start >= suffixStart) {
2333
- e.preventDefault();
2334
- return;
2335
- }
2336
- }
2337
- }
2338
- }
2339
- setTimeout(() => this.enforceCursorBounds(), 0);
2340
- }
2341
- enforceCursorBounds() {
2342
- if (!this.input.value || this.options.disabled) return;
2343
- const start = this.input.selectionStart ?? 0;
2344
- const end = this.input.selectionEnd ?? 0;
2345
- if (start !== end) return;
2346
- const val = this.input.value;
2347
- const currency = this.options.currency;
2348
- if (currency) {
2349
- if (this.options.currencyPosition === "prefix") {
2350
- const minPos = currency.length + 1;
2351
- if (start < minPos) {
2352
- this.input.setSelectionRange(minPos, minPos);
2353
- }
2354
- } else if (this.options.currencyPosition === "suffix") {
2355
- const maxPos = Math.max(0, val.length - currency.length - 1);
2356
- if (start > maxPos) {
2357
- this.input.setSelectionRange(maxPos, maxPos);
2358
- }
2359
- }
2360
- }
2361
- }
2362
- handleClick() {
2363
- this.enforceCursorBounds();
2364
- }
2365
- handleFocus() {
2366
- this.wrapper.classList.add("is-focused");
2367
- this.syncGhostStyles();
2368
- this.enforceCursorBounds();
2369
- this.updateGhost(this.engine.format(this.input.value));
2370
- }
2371
- handleBlur() {
2372
- this.wrapper.classList.remove("is-focused");
2373
- if (this.input.type === "password") {
2374
- this.history.clear();
2375
- }
2376
- if (this.options.padDecimalsOnBlur && !this.options.disabled && this.input.value.trim().length > 0) {
2377
- const paddedResult = this.engine.format(this.input.value, this.input.value.length, true);
2378
- if (paddedResult.formatted !== this.input.value) {
2379
- this.setNativeValue(paddedResult.formatted);
2380
- this.lastValue = paddedResult.formatted;
2381
- }
2382
- }
2383
- this.updateGhost(this.engine.format(this.input.value));
2384
- const detail = this.getDetail();
2385
- if (this.options.onChange) {
2386
- this.options.onChange(detail);
2387
- }
2388
- this.input.dispatchEvent(new CustomEvent("mask:change", { bubbles: true, detail }));
2389
- }
2390
- handleAttributeMutation(attrName) {
2391
- super.handleAttributeMutation(attrName);
2392
- if (attrName === "data-mask-pad-decimals") {
2393
- this.options.padDecimalsOnBlur = this.getAttr("data-mask-pad-decimals") === "true";
2394
- } else if (attrName === "placeholder") {
2395
- this.updateGhost(this.engine.format(this.input.value));
2396
- }
2397
- }
2398
- notifyChange(result) {
2399
- const detail = {
2400
- value: result.formatted,
2401
- number: result.rawNumber,
2402
- rawValue: result.rawValue,
2403
- isValid: result.isValid
2404
- };
2405
- if (this.options.onInput) {
2406
- this.options.onInput(detail);
2407
- }
2408
- this.input.dispatchEvent(new CustomEvent("mask:input", { bubbles: true, detail }));
2409
- this.dispatchNativeInput();
2410
- }
2411
- undo() {
2412
- const state = this.history.undo();
2413
- if (state) {
2414
- this.isUndoingRedoing = true;
2415
- try {
2416
- this.applyAmount(state.raw, state.cursor);
2417
- } finally {
2418
- this.isUndoingRedoing = false;
2419
- }
2420
- }
2421
- }
2422
- redo() {
2423
- const state = this.history.redo();
2424
- if (state) {
2425
- this.isUndoingRedoing = true;
2426
- try {
2427
- this.applyAmount(state.raw, state.cursor);
2428
- } finally {
2429
- this.isUndoingRedoing = false;
2430
- }
2431
- }
2432
- }
2433
- getDetail() {
2434
- const parsed = this.engine.format(this.input.value);
2435
- return {
2436
- value: parsed.formatted,
2437
- number: parsed.rawNumber,
2438
- rawValue: parsed.rawValue,
2439
- isValid: parsed.isValid
2440
- };
2441
- }
2442
- getNumber() {
2443
- return this.getDetail().number;
2444
- }
2445
- getRawValue() {
2446
- return this.getDetail().rawValue;
2447
- }
2448
- isValid() {
2449
- return this.getDetail().isValid;
2450
- }
2451
- setValue(val) {
2452
- const str = val !== null && val !== void 0 ? String(val) : "";
2453
- if (this.options.disabled) {
2454
- this.setNativeValue(str);
2455
- this.lastValue = str;
2456
- } else {
2457
- this.applyAmount(str, str.length);
2458
- }
2459
- }
2460
- destroy() {
2461
- if (this.isDestroyed) return;
2462
- if (this.cutTimerId !== null) {
2463
- clearTimeout(this.cutTimerId);
2464
- this.cutTimerId = null;
2465
- }
2466
- if (this.resetTimerId !== null) {
2467
- clearTimeout(this.resetTimerId);
2468
- this.resetTimerId = null;
2469
- }
2470
- this.input.removeEventListener("input", this.handleInput);
2471
- this.input.removeEventListener("keydown", this.handleKeyDown);
2472
- this.input.removeEventListener("blur", this.handleBlur);
2473
- this.input.removeEventListener("focus", this.handleFocus);
2474
- this.input.removeEventListener("click", this.handleClick);
2475
- this.input.removeEventListener("scroll", this.onScroll);
2476
- this.input.removeEventListener("cut", this.onCutHandler);
2477
- this.input.removeEventListener("compositionstart", this.onCompositionStart);
2478
- this.input.removeEventListener("compositionend", this.onCompositionEnd);
2479
- if (this.input.form && this.onFormResetHandler) {
2480
- this.input.form.removeEventListener("reset", this.onFormResetHandler);
2481
- }
2482
- this.history.clear();
2483
- super.destroy();
2484
- }
2485
- };
2486
-
2487
- // src/mask/EmailEngine.ts
2488
- var _EmailEngine = class _EmailEngine {
2489
- constructor(options = {}) {
2490
- this.defaultDomain = null;
2491
- this.defaultTld = "__";
2492
- this.domains = options.domains && options.domains.length > 0 ? options.domains : _EmailEngine.DEFAULT_DOMAINS;
2493
- this.tlds = options.tlds && options.tlds.length > 0 ? options.tlds.map((t) => t.trim().replace(/^\./, "")).filter(Boolean) : [..._EmailEngine.DEFAULT_TLDS];
2494
- this.suggestOnAt = options.suggestOnAt ?? true;
2495
- this.setDefaultDomain(options.defaultDomain ?? null);
2496
- this.setDefaultTld(options.defaultTld !== void 0 ? options.defaultTld : "__");
2497
- }
2498
- /**
2499
- * Définit ou modifie le domaine suggéré par défaut.
2500
- */
2501
- setDefaultDomain(domain) {
2502
- if (domain === true) {
2503
- this.defaultDomain = this.domains.length > 0 ? this.domains[0] : null;
2504
- } else if (typeof domain === "string" && domain.trim().length > 0) {
2505
- this.defaultDomain = domain.trim().replace(/^@/, "");
2506
- } else {
2507
- this.defaultDomain = null;
2508
- }
2509
- }
2510
- /**
2511
- * Définit ou modifie l'extension (TLD) ou gabarit suggéré par défaut sur un domaine inconnu.
2512
- */
2513
- setDefaultTld(tld) {
2514
- if (tld === true) {
2515
- this.defaultTld = this.tlds.length > 0 ? this.tlds[0] : null;
2516
- } else if (typeof tld === "string" && tld.trim().length > 0) {
2517
- this.defaultTld = tld.trim().replace(/^\./, "");
2518
- } else {
2519
- this.defaultTld = null;
2520
- }
2521
- }
2522
- /**
2523
- * Définit ou modifie la liste des extensions (TLD) proposées par ordre de priorité.
2524
- */
2525
- setTlds(tlds) {
2526
- this.tlds = tlds && tlds.length > 0 ? tlds.map((t) => t.trim().replace(/^\./, "")).filter(Boolean) : [..._EmailEngine.DEFAULT_TLDS];
2527
- }
2528
- /**
2529
- * Retourne l'ensemble des extensions (TLD) correspondant au fragment saisi après le dernier point,
2530
- * dans l'ordre exact fourni par l'utilisateur.
2531
- */
2532
- getMatchingTlds(tldInput) {
2533
- const query = (tldInput ?? "").toLowerCase();
2534
- if (query.length === 0) {
2535
- return [...this.tlds];
2536
- }
2537
- return this.tlds.filter((t) => t.toLowerCase().startsWith(query) && t.toLowerCase() !== query);
2538
- }
2539
- /**
2540
- * Retourne l'ensemble des domaines correspondant à la saisie courante.
2541
- */
2542
- getMatchingDomains(input) {
2543
- const val = input ?? "";
2544
- if (!val.includes("@")) {
2545
- return this.defaultDomain ? [this.defaultDomain] : [];
2546
- }
2547
- const atIndex = val.indexOf("@");
2548
- if (val.indexOf("@", atIndex + 1) !== -1) {
2549
- return [];
2550
- }
2551
- const domainPart = val.substring(atIndex + 1);
2552
- if (domainPart.length === 0) {
2553
- return this.suggestOnAt ? [...this.domains] : [];
2554
- }
2555
- const query = domainPart.toLowerCase();
2556
- return this.domains.filter((d) => d.toLowerCase().startsWith(query) && d.toLowerCase() !== query);
2557
- }
2558
- /**
2559
- * Analyse la saisie courante et calcule la suggestion de domaine ou d'extension (TLD) adaptée.
2560
- *
2561
- * @param input Saisie utilisateur
2562
- * @param matchIndex Index de la suggestion à sélectionner si plusieurs domaines/TLD correspondent (permet le cyclage)
2563
- */
2564
- getSuggestion(input, matchIndex = 0) {
2565
- const val = input ?? "";
2566
- if (!val.includes("@")) {
2567
- if (this.defaultDomain) {
2568
- return {
2569
- full: val ? `${val}@${this.defaultDomain}` : `@${this.defaultDomain}`,
2570
- remaining: `@${this.defaultDomain}`,
2571
- matchedDomain: this.defaultDomain,
2572
- isHintOnly: false
2573
- };
2574
- }
2575
- return { full: val, remaining: "", matchedDomain: null, isHintOnly: false };
2576
- }
2577
- const atIndex = val.indexOf("@");
2578
- const localPart = val.substring(0, atIndex);
2579
- const domainPart = val.substring(atIndex + 1);
2580
- if (val.indexOf("@", atIndex + 1) !== -1) {
2581
- return { full: val, remaining: "", matchedDomain: null, isHintOnly: false };
2582
- }
2583
- const matches = this.getMatchingDomains(input);
2584
- if (matches.length > 0) {
2585
- const safeIndex = (matchIndex % matches.length + matches.length) % matches.length;
2586
- const matched = matches[safeIndex];
2587
- const query = domainPart.toLowerCase();
2588
- const remaining = matched.substring(query.length);
2589
- return {
2590
- full: `${localPart}@${matched}`,
2591
- remaining,
2592
- matchedDomain: matched,
2593
- isHintOnly: false
2594
- };
2595
- }
2596
- if (domainPart.length === 0 || domainPart.startsWith(".")) {
2597
- return { full: input, remaining: "", matchedDomain: null, isHintOnly: false };
2598
- }
2599
- const lowerDomain = domainPart.toLowerCase();
2600
- if (this.domains.some((d) => d.toLowerCase() === lowerDomain)) {
2601
- return { full: input, remaining: "", matchedDomain: domainPart, isHintOnly: false };
2602
- }
2603
- const lastDotIndex = domainPart.lastIndexOf(".");
2604
- if (lastDotIndex === -1) {
2605
- if (!this.defaultTld) {
2606
- return { full: input, remaining: "", matchedDomain: null, isHintOnly: false };
2607
- }
2608
- const isHint = this.defaultTld.includes("_");
2609
- const remaining = `.${this.defaultTld}`;
2610
- const fullDomain = `${domainPart}.${this.defaultTld}`;
2611
- return {
2612
- full: isHint ? input : `${localPart}@${fullDomain}`,
2613
- remaining,
2614
- matchedDomain: isHint ? null : fullDomain,
2615
- isHintOnly: isHint
2616
- };
2617
- }
2618
- const hostPart = domainPart.substring(0, lastDotIndex);
2619
- const tldPart = domainPart.substring(lastDotIndex + 1);
2620
- if (!hostPart || hostPart.endsWith(".")) {
2621
- return { full: input, remaining: "", matchedDomain: null, isHintOnly: false };
2622
- }
2623
- if (tldPart.length === 0) {
2624
- if (this.defaultTld && !this.defaultTld.includes("_")) {
2625
- const fullDomain = `${hostPart}.${this.defaultTld}`;
2626
- return {
2627
- full: `${localPart}@${fullDomain}`,
2628
- remaining: this.defaultTld,
2629
- matchedDomain: fullDomain,
2630
- isHintOnly: false
2631
- };
2632
- }
2633
- if (this.defaultTld && this.defaultTld.includes("_")) {
2634
- return {
2635
- full: input,
2636
- remaining: this.defaultTld,
2637
- matchedDomain: null,
2638
- isHintOnly: true
2639
- };
2640
- }
2641
- return { full: input, remaining: "", matchedDomain: null, isHintOnly: false };
2642
- }
2643
- const lowerTld = tldPart.toLowerCase();
2644
- const matchingTlds = this.getMatchingTlds(tldPart);
2645
- if (matchingTlds.length > 0) {
2646
- const safeTldIndex = (matchIndex % matchingTlds.length + matchingTlds.length) % matchingTlds.length;
2647
- const matchedTld = matchingTlds[safeTldIndex];
2648
- const remaining = matchedTld.substring(lowerTld.length);
2649
- const fullDomain = `${hostPart}.${matchedTld}`;
2650
- return {
2651
- full: `${localPart}@${fullDomain}`,
2652
- remaining,
2653
- matchedDomain: fullDomain,
2654
- isHintOnly: false
2655
- };
2656
- }
2657
- if (this.defaultTld && this.defaultTld.includes("_") && tldPart.length < this.defaultTld.length) {
2658
- const remaining = this.defaultTld.substring(tldPart.length);
2659
- if (remaining.includes("_")) {
2660
- return {
2661
- full: input,
2662
- remaining,
2663
- matchedDomain: null,
2664
- isHintOnly: true
2665
- };
2666
- }
2667
- }
2668
- return { full: input, remaining: "", matchedDomain: null, isHintOnly: false };
2669
- }
2670
- };
2671
- _EmailEngine.DEFAULT_DOMAINS = [
2672
- "gmail.com",
2673
- "outlook.com",
2674
- "orange.fr",
2675
- "free.fr",
2676
- "sfr.fr",
2677
- "yahoo.com",
2678
- "hotmail.com",
2679
- "icloud.com",
2680
- "laposte.net",
2681
- "proton.me"
2682
- ];
2683
- _EmailEngine.DEFAULT_TLDS = [
2684
- "com",
2685
- "fr",
2686
- "net",
2687
- "org",
2688
- "eu",
2689
- "io",
2690
- "co",
2691
- "info",
2692
- "biz",
2693
- "me",
2694
- "tv",
2695
- "fi",
2696
- "be",
2697
- "ch",
2698
- "ca",
2699
- "uk",
2700
- "de",
2701
- "es",
2702
- "it"
2703
- ];
2704
- var EmailEngine = _EmailEngine;
2705
-
2706
- // src/mask/InputEmailMask.ts
2707
- var InputEmailMask = class extends BaseInputMask {
2708
- constructor(targetOrWrapper, inputOrOptions, options) {
2709
- const args = resolveMaskConstructorArgs(targetOrWrapper, inputOrOptions, options);
2710
- const wrap = args.wrapper;
2711
- const inp = args.input;
2712
- const opts = args.options;
2713
- const dataCycle = wrap?.getAttribute("data-mask-cycle-suggestions") === "true" || inp?.getAttribute("data-mask-cycle-suggestions") === "true";
2714
- const dataAutoLower = wrap?.getAttribute("data-mask-auto-lowercase") === "true" || inp?.getAttribute("data-mask-auto-lowercase") === "true";
2715
- const dataAriaAuto = wrap?.getAttribute("data-mask-aria-autocomplete") ?? inp?.getAttribute("data-mask-aria-autocomplete");
2716
- const setAriaAutocomplete = opts.setAriaAutocomplete ?? (dataAriaAuto !== null ? dataAriaAuto !== "false" : true);
2717
- const dataTlds = wrap?.getAttribute("data-mask-tlds") ?? inp?.getAttribute("data-mask-tlds");
2718
- const parsedTlds = opts.tlds ?? (dataTlds ? dataTlds.split(",").map((s) => s.trim()).filter(Boolean) : void 0);
2719
- const dataDefaultTld = wrap?.getAttribute("data-mask-default-tld") ?? inp?.getAttribute("data-mask-default-tld");
2720
- const resolvedDefaultTld = opts.defaultTld !== void 0 ? opts.defaultTld : dataDefaultTld !== null ? dataDefaultTld === "false" || dataDefaultTld === "none" ? null : dataDefaultTld === "true" ? true : dataDefaultTld : void 0;
2721
- const resolvedOptions = {
2722
- completeOnTab: true,
2723
- completeOnArrowRight: true,
2724
- completeOnEnter: true,
2725
- cycleSuggestions: opts.cycleSuggestions ?? dataCycle ?? false,
2726
- autoLowercase: opts.autoLowercase ?? dataAutoLower ?? false,
2727
- setAriaAutocomplete,
2728
- ...opts,
2729
- ...parsedTlds !== void 0 ? { tlds: parsedTlds } : {},
2730
- ...resolvedDefaultTld !== void 0 ? { defaultTld: resolvedDefaultTld } : {}
2731
- };
2732
- super(wrap, inp, resolvedOptions);
2733
- this.currentSuggestion = { full: "", remaining: "", matchedDomain: null };
2734
- this.currentSuggestionIndex = 0;
2735
- this.wasAriaAutocompleteSet = false;
2736
- this.cutTimerId = null;
2737
- this.resetTimerId = null;
2738
- this.input.inputMode = "email";
2739
- if (this.options.setAriaAutocomplete && !this.input.hasAttribute("aria-autocomplete")) {
2740
- this.input.setAttribute("aria-autocomplete", "inline");
2741
- this.wasAriaAutocompleteSet = true;
2742
- }
2743
- this.engine = new EmailEngine(this.options);
2744
- this.bindEvents();
2745
- if (!this.options.disabled) {
2746
- this.updateSuggestion();
2747
- }
2748
- }
2749
- onNativeValueSet(_strVal) {
2750
- if (this.options.disabled) return;
2751
- this.updateSuggestion();
2752
- }
2753
- onDisabledChange(disabled) {
2754
- if (disabled) {
2755
- if (this.ghost) this.ghost.textContent = "";
2756
- } else {
2757
- this.updateSuggestion();
2758
- }
2759
- }
2760
- bindEvents() {
2761
- this.handleInput = this.handleInput.bind(this);
2762
- this.handleKeyDown = this.handleKeyDown.bind(this);
2763
- this.handleBlur = this.handleBlur.bind(this);
2764
- this.handleFocus = this.handleFocus.bind(this);
2765
- this.onCutHandler = () => {
2766
- if (this.cutTimerId !== null) {
2767
- clearTimeout(this.cutTimerId);
2768
- }
2769
- this.cutTimerId = window.setTimeout(() => {
2770
- this.cutTimerId = null;
2771
- if (this.isDestroyed || this.options.disabled) return;
2772
- this.updateSuggestion();
2773
- }, 0);
2774
- };
2775
- this.input.addEventListener("input", this.handleInput);
2776
- this.input.addEventListener("keydown", this.handleKeyDown);
2777
- this.input.addEventListener("blur", this.handleBlur);
2778
- this.input.addEventListener("focus", this.handleFocus);
2779
- this.input.addEventListener("scroll", this.onScroll);
2780
- this.input.addEventListener("cut", this.onCutHandler);
2781
- if (this.input.form) {
2782
- this.onFormResetHandler = () => {
2783
- if (this.resetTimerId !== null) {
2784
- clearTimeout(this.resetTimerId);
2785
- }
2786
- this.resetTimerId = window.setTimeout(() => {
2787
- this.resetTimerId = null;
2788
- if (this.isDestroyed || this.options.disabled) return;
2789
- this.updateSuggestion();
2790
- }, 0);
2791
- };
2792
- this.input.form.addEventListener("reset", this.onFormResetHandler);
2793
- }
2794
- }
2795
- updateSuggestion() {
2796
- if (this.options.disabled) {
2797
- if (this.ghost) this.ghost.textContent = "";
2798
- return;
2799
- }
2800
- const val = this.input.value;
2801
- this.currentSuggestion = this.engine.getSuggestion(val, this.currentSuggestionIndex);
2802
- if (!this.ghost) return;
2803
- if (this.shouldHideGhostForPlaceholder(val.length === 0)) {
2804
- this.ghost.textContent = "";
2805
- } else if (this.currentSuggestion.remaining) {
2806
- this.ghost.textContent = "";
2807
- const spanTyped = document.createElement("span");
2808
- spanTyped.className = "mask-ghost-typed";
2809
- spanTyped.textContent = val;
2810
- const spanRemaining = document.createElement("span");
2811
- spanRemaining.className = "mask-ghost-remaining";
2812
- spanRemaining.textContent = this.currentSuggestion.remaining;
2813
- this.ghost.appendChild(spanTyped);
2814
- this.ghost.appendChild(spanRemaining);
2815
- } else {
2816
- this.ghost.textContent = "";
2817
- }
2818
- this.ghost.scrollLeft = this.input.scrollLeft;
2819
- const detail = this.getDetail();
2820
- if (this.options.onInput) {
2821
- this.options.onInput(detail);
2822
- }
2823
- this.input.dispatchEvent(new CustomEvent("mask:input", { bubbles: true, detail }));
2824
- this.dispatchNativeInput();
2825
- }
2826
- handleInput() {
2827
- if (this.isDispatchingNativeInput) return;
2828
- if (this.options.disabled) return;
2829
- if (this.options.autoLowercase) {
2830
- const start = this.input.selectionStart ?? 0;
2831
- const end = this.input.selectionEnd ?? start;
2832
- const lower = this.input.value.toLowerCase();
2833
- if (lower !== this.input.value) {
2834
- this.setNativeValue(lower);
2835
- this.input.setSelectionRange(start, end);
2836
- }
2837
- }
2838
- this.currentSuggestionIndex = 0;
2839
- this.updateSuggestion();
2840
- }
2841
- handleKeyDown(e) {
2842
- if (this.options.disabled) return;
2843
- const hasSuggestion = Boolean(this.currentSuggestion.remaining) && !this.currentSuggestion.isHintOnly;
2844
- const cursor = this.input.selectionStart ?? 0;
2845
- const isAtEnd = cursor === this.input.value.length;
2846
- const isNotEmpty = this.input.value.length > 0;
2847
- if (this.options.cycleSuggestions && hasSuggestion && isNotEmpty && isAtEnd) {
2848
- if (e.key === "ArrowDown") {
2849
- e.preventDefault();
2850
- this.currentSuggestionIndex++;
2851
- this.updateSuggestion();
2852
- return;
2853
- }
2854
- if (e.key === "ArrowUp") {
2855
- e.preventDefault();
2856
- this.currentSuggestionIndex--;
2857
- this.updateSuggestion();
2858
- return;
2859
- }
2860
- }
2861
- if (e.key === "Tab" && hasSuggestion && isNotEmpty && this.options.completeOnTab) {
2862
- e.preventDefault();
2863
- this.acceptSuggestion();
2864
- return;
2865
- }
2866
- if (e.key === "Enter" && hasSuggestion && isNotEmpty && this.options.completeOnEnter) {
2867
- e.preventDefault();
2868
- this.acceptSuggestion();
2869
- return;
2870
- }
2871
- if (e.key === "ArrowRight" && hasSuggestion && isNotEmpty && isAtEnd && this.options.completeOnArrowRight) {
2872
- e.preventDefault();
2873
- this.acceptSuggestion();
2874
- return;
2875
- }
2876
- }
2877
- /**
2878
- * Valide et applique la suggestion courante dans le champ natif.
2879
- */
2880
- acceptSuggestion() {
2881
- if (!this.currentSuggestion.remaining || this.currentSuggestion.isHintOnly || this.options.disabled || this.input.value.length === 0) return false;
2882
- const completed = this.currentSuggestion.full;
2883
- this.setNativeValue(completed);
2884
- this.input.setSelectionRange(completed.length, completed.length);
2885
- this.currentSuggestionIndex = 0;
2886
- this.updateSuggestion();
2887
- const detail = this.getDetail();
2888
- if (this.options.onChange) {
2889
- this.options.onChange(detail);
2890
- }
2891
- this.input.dispatchEvent(new CustomEvent("mask:change", { bubbles: true, detail }));
2892
- this.input.dispatchEvent(new CustomEvent("mask:complete", { bubbles: true, detail }));
2893
- return true;
2894
- }
2895
- /**
2896
- * Modifie dynamiquement le domaine suggéré par défaut.
2897
- */
2898
- setDefaultDomain(domain) {
2899
- this.engine.setDefaultDomain(domain);
2900
- this.updateSuggestion();
2901
- }
2902
- /**
2903
- * Modifie dynamiquement l'extension (TLD) ou gabarit suggéré par défaut sur un domaine inconnu.
2904
- */
2905
- setDefaultTld(tld) {
2906
- this.engine.setDefaultTld(tld);
2907
- this.updateSuggestion();
2908
- }
2909
- /**
2910
- * Modifie dynamiquement la liste des extensions (TLD) connues.
2911
- */
2912
- setTlds(tlds) {
2913
- this.engine.setTlds(tlds);
2914
- this.currentSuggestionIndex = 0;
2915
- this.updateSuggestion();
2916
- }
2917
- handleFocus() {
2918
- this.wrapper.classList.add("is-focused");
2919
- this.syncGhostStyles();
2920
- this.updateSuggestion();
2921
- }
2922
- handleBlur() {
2923
- this.wrapper.classList.remove("is-focused");
2924
- this.updateSuggestion();
2925
- const detail = this.getDetail();
2926
- if (this.options.onChange) {
2927
- this.options.onChange(detail);
2928
- }
2929
- this.input.dispatchEvent(new CustomEvent("mask:change", { bubbles: true, detail }));
2930
- }
2931
- handleAttributeMutation(attrName) {
2932
- super.handleAttributeMutation(attrName);
2933
- if (attrName === "data-mask-cycle-suggestions") {
2934
- this.options.cycleSuggestions = this.getAttr("data-mask-cycle-suggestions") === "true";
2935
- } else if (attrName === "data-mask-auto-lowercase") {
2936
- this.options.autoLowercase = this.getAttr("data-mask-auto-lowercase") === "true";
2937
- } else if (attrName === "data-mask-default-tld") {
2938
- const val = this.getAttr("data-mask-default-tld");
2939
- this.setDefaultTld(val === null || val === "false" || val === "none" ? null : val === "true" ? true : val);
2940
- } else if (attrName === "data-mask-tlds") {
2941
- const val = this.getAttr("data-mask-tlds");
2942
- this.setTlds(val ? val.split(",").map((s) => s.trim()).filter(Boolean) : null);
2943
- } else if (attrName === "placeholder") {
2944
- this.updateSuggestion();
2945
- }
2946
- }
2947
- getDetail() {
2948
- return {
2949
- value: this.input.value,
2950
- suggestedValue: this.currentSuggestion.isHintOnly ? "" : this.currentSuggestion.full,
2951
- domain: this.currentSuggestion.matchedDomain
2952
- };
2953
- }
2954
- setValue(val) {
2955
- const str = val !== null && val !== void 0 ? String(val) : "";
2956
- this.setNativeValue(str);
2957
- this.updateSuggestion();
2958
- }
2959
- destroy() {
2960
- if (this.isDestroyed) return;
2961
- if (this.cutTimerId !== null) {
2962
- clearTimeout(this.cutTimerId);
2963
- this.cutTimerId = null;
2964
- }
2965
- if (this.resetTimerId !== null) {
2966
- clearTimeout(this.resetTimerId);
2967
- this.resetTimerId = null;
2968
- }
2969
- this.input.removeEventListener("input", this.handleInput);
2970
- this.input.removeEventListener("keydown", this.handleKeyDown);
2971
- this.input.removeEventListener("blur", this.handleBlur);
2972
- this.input.removeEventListener("focus", this.handleFocus);
2973
- this.input.removeEventListener("scroll", this.onScroll);
2974
- this.input.removeEventListener("cut", this.onCutHandler);
2975
- if (this.input.form && this.onFormResetHandler) {
2976
- this.input.form.removeEventListener("reset", this.onFormResetHandler);
2977
- }
2978
- if (this.wasAriaAutocompleteSet && this.input.getAttribute("aria-autocomplete") === "inline") {
2979
- this.input.removeAttribute("aria-autocomplete");
2980
- }
2981
- super.destroy();
2982
- }
2983
- };
2984
-
2985
- // src/mask/index.ts
2986
- var Mask = {
2987
- BaseInputMask,
2988
- InputMask,
2989
- MaskEngine,
2990
- MaskHistory,
2991
- MaskKeyboard,
2992
- AmountEngine,
2993
- InputAmountMask,
2994
- EmailEngine,
2995
- InputEmailMask
2996
- };
2997
- if (typeof window !== "undefined") {
2998
- const win = window;
2999
- const wulfNamespace = win.Wulf || {};
3000
- win.Wulf = wulfNamespace;
3001
- wulfNamespace.Mask = Mask;
3002
- }
3003
- var mask_default = InputMask;
3004
-
3005
- // src/scroll/index.ts
3006
- var scroll_exports = {};
3007
- __export(scroll_exports, {
3008
- LocalizedComponent: () => LocalizedComponent,
3009
- Scroll: () => Scroll,
3010
- ScrollBlock: () => ScrollBlock,
3011
- createI18nManager: () => createI18nManager,
3012
- default: () => scroll_default,
3013
- scrollEn: () => scrollEn,
3014
- scrollFr: () => scrollFr,
3015
- scrollI18n: () => scrollI18n
3016
- });
3017
-
3018
- // src/common/LocalizedComponent.ts
3019
- var LocalizedComponent = class {
3020
- /**
3021
- * Définit la langue globale du composant (ex: 'fr', 'en', 'es').
3022
- */
3023
- static setLocale(locale) {
3024
- if (this._i18n) {
3025
- this._i18n.setLocale(locale);
3026
- }
3027
- }
3028
- /**
3029
- * Retourne la langue globale active du composant.
3030
- */
3031
- static getLocale() {
3032
- return this._i18n ? this._i18n.getLocale() : "";
3033
- }
3034
- /**
3035
- * Enregistre un dictionnaire de traduction pour une langue donnée.
3036
- */
3037
- static registerLocale(locale, translations) {
3038
- if (this._i18n) {
3039
- this._i18n.registerLocale(locale, translations);
3040
- }
3041
- }
3042
- /**
3043
- * Surcharge les libellés globalement pour ce composant.
3044
- */
3045
- static setI18n(overrides) {
3046
- if (this._i18n) {
3047
- this._i18n.setI18n(overrides);
3048
- }
3049
- }
3050
- /**
3051
- * Retourne l'ensemble des libellés actifs résolus du composant.
3052
- */
3053
- static getI18n() {
3054
- return this._i18n ? this._i18n.getAll() : {};
3055
- }
3056
- /**
3057
- * Réinitialise les réglages de langue et surcharges globales.
3058
- */
3059
- static resetI18n() {
3060
- if (this._i18n) {
3061
- this._i18n.reset();
3062
- }
3063
- }
3064
- /**
3065
- * Résout une clé au niveau statique de la classe.
3066
- */
3067
- static t(key, instanceOverride) {
3068
- return this._i18n ? this._i18n.t(key, instanceOverride) : String(key);
3069
- }
3070
- constructor(i18nOverrides) {
3071
- this.i18nOverrides = i18nOverrides;
3072
- }
3073
- /**
3074
- * Traduit une clé en tenant compte automatiquement des surcharges de l'instance courante.
3075
- */
3076
- t(key) {
3077
- const ctor = this.constructor;
3078
- return ctor._i18n ? ctor._i18n.t(key, this.i18nOverrides) : String(key);
3079
- }
3080
- };
3081
-
3082
- // src/common/i18n.ts
3083
- function normalizeLocaleCode(locale) {
3084
- return locale.trim().toLowerCase().replace(/_/g, "-");
3085
- }
3086
- function getPrimaryLanguage(normalizedLocale) {
3087
- const dashIndex = normalizedLocale.indexOf("-");
3088
- return dashIndex > 0 ? normalizedLocale.slice(0, dashIndex) : null;
3089
- }
3090
- function assignDefined(target, source) {
3091
- if (!source) return target;
3092
- for (const key of Object.keys(source)) {
3093
- if (source[key] !== void 0) {
3094
- target[key] = source[key];
3095
- }
3096
- }
3097
- return target;
3098
- }
3099
- function createI18nManager(defaultLocale, locales) {
3100
- const fallbackLocale = normalizeLocaleCode(defaultLocale);
3101
- const initialLocales = {};
3102
- for (const [loc, dict] of Object.entries(locales)) {
3103
- initialLocales[normalizeLocaleCode(loc)] = { ...dict };
3104
- }
3105
- let currentLocale = fallbackLocale;
3106
- let activeLocales = { ...initialLocales };
3107
- let globalOverrides = {};
3108
- function resolveActiveDictionaries() {
3109
- const dicts = [];
3110
- const exact = activeLocales[currentLocale];
3111
- if (exact) dicts.push(exact);
3112
- const primary = getPrimaryLanguage(currentLocale);
3113
- if (primary && activeLocales[primary]) {
3114
- dicts.push(activeLocales[primary]);
3115
- }
3116
- return dicts;
3117
- }
3118
- return {
3119
- setLocale(locale) {
3120
- if (locale && locale.trim()) {
3121
- currentLocale = normalizeLocaleCode(locale);
3122
- }
3123
- },
3124
- getLocale() {
3125
- return currentLocale;
3126
- },
3127
- registerLocale(locale, translations) {
3128
- if (!locale || !locale.trim() || !translations) return;
3129
- const norm = normalizeLocaleCode(locale);
3130
- activeLocales[norm] = assignDefined({ ...activeLocales[norm] || {} }, translations);
3131
- },
3132
- setI18n(overrides) {
3133
- if (!overrides) return;
3134
- globalOverrides = assignDefined({ ...globalOverrides }, overrides);
3135
- },
3136
- t(key, instanceOverride) {
3137
- if (instanceOverride && instanceOverride[key] !== void 0) {
3138
- return String(instanceOverride[key]);
3139
- }
3140
- if (globalOverrides[key] !== void 0) {
3141
- return String(globalOverrides[key]);
3142
- }
3143
- for (const dict of resolveActiveDictionaries()) {
3144
- if (dict[key] !== void 0) {
3145
- return String(dict[key]);
3146
- }
3147
- }
3148
- const fallbackDict = activeLocales[fallbackLocale] || initialLocales[fallbackLocale];
3149
- if (fallbackDict && fallbackDict[key] !== void 0) {
3150
- return String(fallbackDict[key]);
3151
- }
3152
- return String(key);
3153
- },
3154
- getAll(instanceOverride) {
3155
- const result = {};
3156
- const fallback = activeLocales[fallbackLocale] || initialLocales[fallbackLocale];
3157
- assignDefined(result, fallback);
3158
- const activeDicts = resolveActiveDictionaries().reverse();
3159
- for (const dict of activeDicts) {
3160
- assignDefined(result, dict);
3161
- }
3162
- assignDefined(result, globalOverrides);
3163
- assignDefined(result, instanceOverride);
3164
- return result;
3165
- },
3166
- reset() {
3167
- currentLocale = fallbackLocale;
3168
- globalOverrides = {};
3169
- activeLocales = {};
3170
- for (const [loc, dict] of Object.entries(initialLocales)) {
3171
- activeLocales[loc] = { ...dict };
3172
- }
3173
- }
3174
- };
3175
- }
3176
-
3177
- // src/scroll/i18n/fr.ts
3178
- var scrollFr = {
3179
- viewport: "Zone de contenu d\xE9filable",
3180
- verticalThumb: "D\xE9filement vertical",
3181
- horizontalThumb: "D\xE9filement horizontal"
3182
- };
3183
-
3184
- // src/scroll/i18n/en.ts
3185
- var scrollEn = {
3186
- viewport: "Scrollable content area",
3187
- verticalThumb: "Vertical scroll",
3188
- horizontalThumb: "Horizontal scroll"
3189
- };
3190
-
3191
- // src/scroll/i18n/index.ts
3192
- var scrollI18n = createI18nManager("fr", {
3193
- fr: scrollFr,
3194
- en: scrollEn
3195
- });
3196
-
3197
- // src/scroll/ScrollBlock.ts
3198
- var idCounter = 0;
3199
- var ScrollBlock = class extends LocalizedComponent {
3200
- constructor(element, options) {
3201
- super(options?.i18n);
3202
- this.createdViewport = false;
3203
- this.wasIdGenerated = false;
3204
- this.wasRoleInferred = false;
3205
- this.wasAriaLabelInferred = false;
3206
- this.hasExplicitAriaLabel = false;
3207
- this.lastInferredAriaLabel = "";
3208
- this.isDragging = false;
3209
- this.dragStartPos = 0;
3210
- this.dragStartScroll = 0;
3211
- this.atBottom = false;
3212
- this.atTop = true;
3213
- this.atRight = false;
3214
- this.atLeft = true;
3215
- const resolvedElement = typeof element === "string" ? document.querySelector(element) : element;
3216
- if (!resolvedElement) {
3217
- throw new Error(`[ScrollBlock] \xC9l\xE9ment introuvable : "${element}".`);
3218
- }
3219
- this.root = resolvedElement;
3220
- this.hasExplicitAriaLabel = Boolean(options?.ariaLabel);
3221
- this.options = {
3222
- axis: options?.axis || "y",
3223
- autoHide: options?.autoHide ?? true,
3224
- autoHideDelay: options?.autoHideDelay ?? 1e3,
3225
- alwaysVisible: options?.alwaysVisible ?? false,
3226
- ariaLabel: options?.ariaLabel || this.t("viewport"),
3227
- i18n: options?.i18n || {},
3228
- minThumbSize: options?.minThumbSize ?? 24,
3229
- edgeThreshold: options?.edgeThreshold ?? 10,
3230
- onScroll: options?.onScroll || (() => {
3231
- }),
3232
- onTotalScroll: options?.onTotalScroll || (() => {
3233
- }),
3234
- onTotalScrollBack: options?.onTotalScrollBack || (() => {
3235
- })
3236
- };
3237
- this.boundOnScroll = this.handleScroll.bind(this);
3238
- this.boundOnMouseEnter = this.handleMouseEnter.bind(this);
3239
- this.boundOnMouseLeave = this.handleMouseLeave.bind(this);
3240
- this.boundOnFocusIn = this.handleFocusIn.bind(this);
3241
- this.boundOnFocusOut = this.handleFocusOut.bind(this);
3242
- this.boundPointerMove = this.handlePointerMove.bind(this);
3243
- this.boundPointerUp = this.handlePointerUp.bind(this);
3244
- this.viewport = this.setupViewport();
3245
- this.setupAccessibility();
3246
- this.setupScrollbars();
3247
- this.setupEventListeners();
3248
- this.setupObserver();
3249
- this.update();
3250
- }
3251
- /**
3252
- * Prépare le viewport défilant sans altérer les éléments enfants.
3253
- */
3254
- setupViewport() {
3255
- this.root.classList.add("wulf-scrollblock");
3256
- if (this.options.alwaysVisible) {
3257
- this.root.classList.add("is-always-visible");
3258
- }
3259
- if (this.options.axis === "both") {
3260
- this.root.classList.add("has-both-axes");
3261
- }
3262
- const existingViewport = this.root.querySelector(":scope > .wulf-scrollblock-viewport");
3263
- if (existingViewport) {
3264
- return existingViewport;
3265
- }
3266
- const viewport = document.createElement("div");
3267
- viewport.className = "wulf-scrollblock-viewport";
3268
- while (this.root.firstChild) {
3269
- viewport.appendChild(this.root.firstChild);
3270
- }
3271
- this.root.appendChild(viewport);
3272
- this.createdViewport = true;
3273
- return viewport;
3274
- }
3275
- /**
3276
- * Configure les attributs WAI-ARIA pour une accessibilité maximale.
3277
- */
3278
- setupAccessibility() {
3279
- if (!this.viewport.id) {
3280
- idCounter += 1;
3281
- this.viewport.id = `wulf-scrollblock-vp-${idCounter}`;
3282
- this.wasIdGenerated = true;
3283
- }
3284
- if (!this.viewport.hasAttribute("role")) {
3285
- this.viewport.setAttribute("role", "region");
3286
- this.wasRoleInferred = true;
3287
- }
3288
- if (!this.viewport.hasAttribute("aria-label")) {
3289
- const label = this.hasExplicitAriaLabel ? this.options.ariaLabel : this.t("viewport");
3290
- this.viewport.setAttribute("aria-label", label);
3291
- this.lastInferredAriaLabel = label;
3292
- this.wasAriaLabelInferred = true;
3293
- }
3294
- }
3295
- /**
3296
- * Synchronise dynamiquement les libellés ARIA si la langue globale change après montage.
3297
- */
3298
- syncAccessibilityLabels() {
3299
- if (this.wasAriaLabelInferred && !this.hasExplicitAriaLabel) {
3300
- const currentAttr = this.viewport.getAttribute("aria-label");
3301
- if (currentAttr === this.lastInferredAriaLabel) {
3302
- const nextLabel = this.t("viewport");
3303
- this.viewport.setAttribute("aria-label", nextLabel);
3304
- this.lastInferredAriaLabel = nextLabel;
3305
- this.options.ariaLabel = nextLabel;
3306
- }
3307
- }
3308
- if (this.thumbY) {
3309
- this.thumbY.setAttribute("aria-label", this.t("verticalThumb"));
3310
- }
3311
- if (this.thumbX) {
3312
- this.thumbX.setAttribute("aria-label", this.t("horizontalThumb"));
3313
- }
3314
- }
3315
- /**
3316
- * Crée les rails et curseurs selon l'axe sélectionné.
3317
- */
3318
- setupScrollbars() {
3319
- if (this.options.axis === "y" || this.options.axis === "both") {
3320
- this.trackY = document.createElement("div");
3321
- this.trackY.className = "wulf-scrollblock-track wulf-scrollblock-vertical";
3322
- this.trackY.setAttribute("aria-hidden", "true");
3323
- this.thumbY = document.createElement("div");
3324
- this.thumbY.className = "wulf-scrollblock-thumb";
3325
- this.thumbY.setAttribute("role", "scrollbar");
3326
- this.thumbY.setAttribute("aria-orientation", "vertical");
3327
- this.thumbY.setAttribute("aria-controls", this.viewport.id);
3328
- this.thumbY.setAttribute("aria-valuenow", "0");
3329
- this.thumbY.setAttribute("aria-valuemin", "0");
3330
- this.thumbY.setAttribute("aria-valuemax", "100");
3331
- this.thumbY.setAttribute("aria-label", this.t("verticalThumb"));
3332
- this.trackY.appendChild(this.thumbY);
3333
- this.root.appendChild(this.trackY);
3334
- this.attachTrackListeners(this.trackY, this.thumbY, "y");
3335
- }
3336
- if (this.options.axis === "x" || this.options.axis === "both") {
3337
- this.trackX = document.createElement("div");
3338
- this.trackX.className = "wulf-scrollblock-track wulf-scrollblock-horizontal";
3339
- this.trackX.setAttribute("aria-hidden", "true");
3340
- this.thumbX = document.createElement("div");
3341
- this.thumbX.className = "wulf-scrollblock-thumb";
3342
- this.thumbX.setAttribute("role", "scrollbar");
3343
- this.thumbX.setAttribute("aria-orientation", "horizontal");
3344
- this.thumbX.setAttribute("aria-controls", this.viewport.id);
3345
- this.thumbX.setAttribute("aria-valuenow", "0");
3346
- this.thumbX.setAttribute("aria-valuemin", "0");
3347
- this.thumbX.setAttribute("aria-valuemax", "100");
3348
- this.thumbX.setAttribute("aria-label", this.t("horizontalThumb"));
3349
- this.trackX.appendChild(this.thumbX);
3350
- this.root.appendChild(this.trackX);
3351
- this.attachTrackListeners(this.trackX, this.thumbX, "x");
3352
- }
3353
- }
3354
- /**
3355
- * Attache les écouteurs sur un rail et son curseur.
3356
- */
3357
- attachTrackListeners(track, thumb, axis) {
3358
- thumb.addEventListener("pointerdown", (e) => {
3359
- e.preventDefault();
3360
- e.stopPropagation();
3361
- this.isDragging = true;
3362
- this.dragAxis = axis;
3363
- this.dragPointerId = e.pointerId;
3364
- this.dragStartPos = axis === "y" ? e.clientY : e.clientX;
3365
- this.dragStartScroll = axis === "y" ? this.viewport.scrollTop : this.viewport.scrollLeft;
3366
- thumb.setPointerCapture(e.pointerId);
3367
- thumb.classList.add("is-active");
3368
- this.root.classList.add("is-dragging");
3369
- window.addEventListener("pointermove", this.boundPointerMove);
3370
- window.addEventListener("pointerup", this.boundPointerUp);
3371
- window.addEventListener("pointercancel", this.boundPointerUp);
3372
- });
3373
- track.addEventListener("pointerdown", (e) => {
3374
- if (e.target === thumb) return;
3375
- e.preventDefault();
3376
- const rect = track.getBoundingClientRect();
3377
- const clickPos = axis === "y" ? e.clientY - rect.top : e.clientX - rect.left;
3378
- const trackSize = axis === "y" ? rect.height : rect.width;
3379
- const clientSize = axis === "y" ? this.viewport.clientHeight : this.viewport.clientWidth;
3380
- const scrollSize = axis === "y" ? this.viewport.scrollHeight : this.viewport.scrollWidth;
3381
- const ratio = clickPos / trackSize;
3382
- const targetScroll = ratio * (scrollSize - clientSize);
3383
- this.scrollTo(axis === "y" ? { top: targetScroll } : { left: targetScroll }, { smooth: true });
3384
- });
3385
- }
3386
- /**
3387
- * Écouteurs globaux sur le viewport et les interactions.
3388
- */
3389
- setupEventListeners() {
3390
- this.viewport.addEventListener("scroll", this.boundOnScroll, { passive: true });
3391
- if (this.options.autoHide && !this.options.alwaysVisible) {
3392
- this.root.addEventListener("mouseenter", this.boundOnMouseEnter);
3393
- this.root.addEventListener("mouseleave", this.boundOnMouseLeave);
3394
- this.root.addEventListener("focusin", this.boundOnFocusIn);
3395
- this.root.addEventListener("focusout", this.boundOnFocusOut);
3396
- }
3397
- }
3398
- /**
3399
- * Initialise le ResizeObserver réactif.
3400
- */
3401
- setupObserver() {
3402
- if (typeof ResizeObserver !== "undefined") {
3403
- this.resizeObserver = new ResizeObserver(() => {
3404
- window.requestAnimationFrame(() => this.update());
3405
- });
3406
- this.resizeObserver.observe(this.root);
3407
- this.resizeObserver.observe(this.viewport);
3408
- if (this.viewport.firstElementChild) {
3409
- this.resizeObserver.observe(this.viewport.firstElementChild);
3410
- }
3411
- }
3412
- }
3413
- /**
3414
- * Déplacement lors du glissement du curseur.
3415
- */
3416
- handlePointerMove(e) {
3417
- if (!this.isDragging || !this.dragAxis) return;
3418
- const isY = this.dragAxis === "y";
3419
- const delta = (isY ? e.clientY : e.clientX) - this.dragStartPos;
3420
- const track = isY ? this.trackY : this.trackX;
3421
- const thumb = isY ? this.thumbY : this.thumbX;
3422
- if (!track || !thumb) return;
3423
- const trackSize = isY ? track.clientHeight : track.clientWidth;
3424
- const thumbSize = isY ? thumb.clientHeight : thumb.clientWidth;
3425
- const clientSize = isY ? this.viewport.clientHeight : this.viewport.clientWidth;
3426
- const scrollSize = isY ? this.viewport.scrollHeight : this.viewport.scrollWidth;
3427
- const maxScroll = scrollSize - clientSize;
3428
- const maxThumbTravel = trackSize - thumbSize;
3429
- if (maxThumbTravel <= 0 || maxScroll <= 0) return;
3430
- const ratio = maxScroll / maxThumbTravel;
3431
- const nextScroll = this.dragStartScroll + delta * ratio;
3432
- if (isY) {
3433
- this.viewport.scrollTop = Math.max(0, Math.min(maxScroll, nextScroll));
3434
- } else {
3435
- this.viewport.scrollLeft = Math.max(0, Math.min(maxScroll, nextScroll));
3436
- }
3437
- }
3438
- /**
3439
- * Relâchement de la capture du pointeur.
3440
- */
3441
- handlePointerUp(e) {
3442
- if (!this.isDragging) return;
3443
- if (this.dragPointerId !== void 0) {
3444
- const activeThumb = this.dragAxis === "y" ? this.thumbY : this.thumbX;
3445
- if (activeThumb && activeThumb.hasPointerCapture(this.dragPointerId)) {
3446
- activeThumb.releasePointerCapture(this.dragPointerId);
3447
- }
3448
- }
3449
- window.removeEventListener("pointermove", this.boundPointerMove);
3450
- window.removeEventListener("pointerup", this.boundPointerUp);
3451
- window.removeEventListener("pointercancel", this.boundPointerUp);
3452
- this.isDragging = false;
3453
- this.dragAxis = void 0;
3454
- this.dragPointerId = void 0;
3455
- this.thumbY?.classList.remove("is-active");
3456
- this.thumbX?.classList.remove("is-active");
3457
- this.root.classList.remove("is-dragging");
3458
- this.scheduleAutoHide();
3459
- }
3460
- /**
3461
- * Gestionnaire d'événement de défilement natif.
3462
- */
3463
- handleScroll() {
3464
- this.syncThumbs();
3465
- const { scrollTop, scrollLeft, scrollHeight, scrollWidth, clientHeight, clientWidth } = this.viewport;
3466
- const maxTop = Math.max(0, scrollHeight - clientHeight);
3467
- const maxLeft = Math.max(0, scrollWidth - clientWidth);
3468
- const progressY = maxTop > 0 ? scrollTop / maxTop : 0;
3469
- const progressX = maxLeft > 0 ? scrollLeft / maxLeft : 0;
3470
- this.options.onScroll({
3471
- top: scrollTop,
3472
- left: scrollLeft,
3473
- maxTop,
3474
- maxLeft,
3475
- progressY: Math.round(progressY * 100),
3476
- progressX: Math.round(progressX * 100)
3477
- });
3478
- const threshold = this.options.edgeThreshold;
3479
- if (maxTop > 0) {
3480
- const nowBottom = scrollTop >= maxTop - threshold;
3481
- const nowTop = scrollTop <= threshold;
3482
- if (nowBottom && !this.atBottom) {
3483
- this.options.onTotalScroll("bottom");
3484
- }
3485
- if (nowTop && !this.atTop) {
3486
- this.options.onTotalScrollBack("top");
3487
- }
3488
- this.atBottom = nowBottom;
3489
- this.atTop = nowTop;
3490
- }
3491
- if (maxLeft > 0) {
3492
- const nowRight = scrollLeft >= maxLeft - threshold;
3493
- const nowLeft = scrollLeft <= threshold;
3494
- if (nowRight && !this.atRight) {
3495
- this.options.onTotalScroll("right");
3496
- }
3497
- if (nowLeft && !this.atLeft) {
3498
- this.options.onTotalScrollBack("left");
3499
- }
3500
- this.atRight = nowRight;
3501
- this.atLeft = nowLeft;
3502
- }
3503
- if (this.options.autoHide && !this.options.alwaysVisible) {
3504
- this.root.classList.add("is-scrolling");
3505
- this.scheduleAutoHide();
3506
- }
3507
- }
3508
- /**
3509
- * Synchronise la position physique et ARIA des curseurs.
3510
- */
3511
- syncThumbs() {
3512
- const { scrollTop, scrollLeft, scrollHeight, scrollWidth, clientHeight, clientWidth } = this.viewport;
3513
- if (this.thumbY && this.trackY) {
3514
- const maxScrollY = scrollHeight - clientHeight;
3515
- const trackHeight = this.trackY.clientHeight;
3516
- const thumbHeight = this.thumbY.clientHeight;
3517
- const maxTravelY = trackHeight - thumbHeight;
3518
- if (maxScrollY > 0 && maxTravelY > 0) {
3519
- const ratioY = scrollTop / maxScrollY;
3520
- const posY = Math.max(0, Math.min(maxTravelY, ratioY * maxTravelY));
3521
- this.thumbY.style.transform = `translate3d(0, ${posY}px, 0)`;
3522
- this.thumbY.setAttribute("aria-valuenow", String(Math.round(ratioY * 100)));
3523
- }
3524
- }
3525
- if (this.thumbX && this.trackX) {
3526
- const maxScrollX = scrollWidth - clientWidth;
3527
- const trackWidth = this.trackX.clientWidth;
3528
- const thumbWidth = this.thumbX.clientWidth;
3529
- const maxTravelX = trackWidth - thumbWidth;
3530
- if (maxScrollX > 0 && maxTravelX > 0) {
3531
- const ratioX = scrollLeft / maxScrollX;
3532
- const posX = Math.max(0, Math.min(maxTravelX, ratioX * maxTravelX));
3533
- this.thumbX.style.transform = `translate3d(${posX}px, 0, 0)`;
3534
- this.thumbX.setAttribute("aria-valuenow", String(Math.round(ratioX * 100)));
3535
- }
3536
- }
3537
- }
3538
- handleMouseEnter() {
3539
- this.root.classList.add("is-visible");
3540
- this.clearAutoHideTimer();
3541
- }
3542
- handleMouseLeave() {
3543
- this.scheduleAutoHide();
3544
- }
3545
- handleFocusIn() {
3546
- this.root.classList.add("is-visible");
3547
- this.clearAutoHideTimer();
3548
- }
3549
- handleFocusOut() {
3550
- this.scheduleAutoHide();
3551
- }
3552
- clearAutoHideTimer() {
3553
- if (this.hideTimer) {
3554
- window.clearTimeout(this.hideTimer);
3555
- this.hideTimer = void 0;
3556
- }
3557
- }
3558
- scheduleAutoHide() {
3559
- if (this.options.alwaysVisible || !this.options.autoHide || this.isDragging) return;
3560
- this.clearAutoHideTimer();
3561
- this.hideTimer = window.setTimeout(() => {
3562
- this.root.classList.remove("is-scrolling");
3563
- this.root.classList.remove("is-visible");
3564
- }, this.options.autoHideDelay);
3565
- }
3566
- /**
3567
- * Recalcule les dimensions et la visibilité des barres.
3568
- */
3569
- update() {
3570
- this.syncAccessibilityLabels();
3571
- const { scrollHeight, clientHeight, scrollWidth, clientWidth } = this.viewport;
3572
- const canScrollY = scrollHeight > clientHeight;
3573
- const canScrollX = scrollWidth > clientWidth;
3574
- this.root.classList.toggle("has-scroll-y", canScrollY);
3575
- this.root.classList.toggle("has-scroll-x", canScrollX);
3576
- if (canScrollY || canScrollX) {
3577
- this.viewport.setAttribute("tabindex", "0");
3578
- } else {
3579
- this.viewport.removeAttribute("tabindex");
3580
- }
3581
- if (this.trackY && this.thumbY) {
3582
- if (canScrollY) {
3583
- const trackHeight = this.trackY.clientHeight;
3584
- const calculatedHeight = Math.max(
3585
- this.options.minThumbSize,
3586
- trackHeight * (clientHeight / scrollHeight)
3587
- );
3588
- this.thumbY.style.height = `${calculatedHeight}px`;
3589
- }
3590
- }
3591
- if (this.trackX && this.thumbX) {
3592
- if (canScrollX) {
3593
- const trackWidth = this.trackX.clientWidth;
3594
- const calculatedWidth = Math.max(
3595
- this.options.minThumbSize,
3596
- trackWidth * (clientWidth / scrollWidth)
3597
- );
3598
- this.thumbX.style.width = `${calculatedWidth}px`;
3599
- }
3600
- }
3601
- this.syncThumbs();
3602
- }
3603
- /**
3604
- * Défilement programmatique direct ou lissé.
3605
- */
3606
- scrollTo(target, options) {
3607
- const prefersReducedMotion = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
3608
- const targetSmooth = typeof target === "object" && target !== null && !(target instanceof HTMLElement) ? target.smooth : void 0;
3609
- const shouldSmooth = (options?.smooth ?? targetSmooth ?? true) && !prefersReducedMotion;
3610
- const behavior = shouldSmooth ? "smooth" : "auto";
3611
- const maxTop = Math.max(0, this.viewport.scrollHeight - this.viewport.clientHeight);
3612
- const maxLeft = Math.max(0, this.viewport.scrollWidth - this.viewport.clientWidth);
3613
- let targetTop;
3614
- let targetLeft;
3615
- if (typeof target === "number") {
3616
- targetTop = target;
3617
- } else if (typeof target === "string") {
3618
- switch (target) {
3619
- case "top":
3620
- targetTop = 0;
3621
- break;
3622
- case "bottom":
3623
- targetTop = maxTop;
3624
- break;
3625
- case "left":
3626
- targetLeft = 0;
3627
- break;
3628
- case "right":
3629
- targetLeft = maxLeft;
3630
- break;
3631
- default: {
3632
- if (/^-?\d+(\.\d+)?%$/.test(target.trim())) {
3633
- const pct = Math.max(0, Math.min(100, parseFloat(target.trim()))) / 100;
3634
- if (this.options.axis === "x") {
3635
- targetLeft = maxLeft * pct;
3636
- } else if (this.options.axis === "both") {
3637
- targetTop = maxTop * pct;
3638
- targetLeft = maxLeft * pct;
3639
- } else {
3640
- targetTop = maxTop * pct;
3641
- }
3642
- break;
3643
- }
3644
- let el = null;
3645
- try {
3646
- el = this.viewport.querySelector(target);
3647
- } catch {
3648
- el = null;
3649
- }
3650
- if (el) {
3651
- targetTop = el.offsetTop;
3652
- targetLeft = el.offsetLeft;
3653
- }
3654
- break;
3655
- }
3656
- }
3657
- } else if (target instanceof HTMLElement) {
3658
- targetTop = target.offsetTop;
3659
- targetLeft = target.offsetLeft;
3660
- } else if (typeof target === "object") {
3661
- targetTop = target.top;
3662
- targetLeft = target.left;
3663
- }
3664
- this.viewport.scrollTo({
3665
- top: targetTop !== void 0 ? Math.max(0, Math.min(maxTop, targetTop)) : void 0,
3666
- left: targetLeft !== void 0 ? Math.max(0, Math.min(maxLeft, targetLeft)) : void 0,
3667
- behavior
3668
- });
3669
- }
3670
- /**
3671
- * Détruit le composant et libère toutes les ressources.
3672
- */
3673
- destroy() {
3674
- this.clearAutoHideTimer();
3675
- if (this.resizeObserver) {
3676
- this.resizeObserver.disconnect();
3677
- }
3678
- this.viewport.removeEventListener("scroll", this.boundOnScroll);
3679
- this.root.removeEventListener("mouseenter", this.boundOnMouseEnter);
3680
- this.root.removeEventListener("mouseleave", this.boundOnMouseLeave);
3681
- this.root.removeEventListener("focusin", this.boundOnFocusIn);
3682
- this.root.removeEventListener("focusout", this.boundOnFocusOut);
3683
- window.removeEventListener("pointermove", this.boundPointerMove);
3684
- window.removeEventListener("pointerup", this.boundPointerUp);
3685
- window.removeEventListener("pointercancel", this.boundPointerUp);
3686
- this.trackY?.remove();
3687
- this.trackX?.remove();
3688
- this.root.classList.remove(
3689
- "wulf-scrollblock",
3690
- "has-scroll-y",
3691
- "has-scroll-x",
3692
- "has-both-axes",
3693
- "is-visible",
3694
- "is-scrolling",
3695
- "is-dragging",
3696
- "is-always-visible"
3697
- );
3698
- if (this.createdViewport && this.viewport.parentElement === this.root) {
3699
- while (this.viewport.firstChild) {
3700
- this.root.insertBefore(this.viewport.firstChild, this.viewport);
3701
- }
3702
- this.viewport.remove();
3703
- } else {
3704
- this.viewport.removeAttribute("tabindex");
3705
- if (this.wasIdGenerated) {
3706
- this.viewport.removeAttribute("id");
3707
- }
3708
- if (this.wasRoleInferred && this.viewport.getAttribute("role") === "region") {
3709
- this.viewport.removeAttribute("role");
3710
- }
3711
- if (this.wasAriaLabelInferred && this.viewport.getAttribute("aria-label") === this.lastInferredAriaLabel) {
3712
- this.viewport.removeAttribute("aria-label");
3713
- }
3714
- }
3715
- }
3716
- };
3717
- ScrollBlock._i18n = scrollI18n;
3718
- ScrollBlock.i18n = scrollI18n;
3719
-
3720
- // src/scroll/index.ts
3721
- var Scroll = {
3722
- ScrollBlock,
3723
- i18n: scrollI18n
3724
- };
3725
- var scroll_default = ScrollBlock;
3726
- if (typeof window !== "undefined") {
3727
- const win = window;
3728
- const wulfNamespace = win.Wulf || {};
3729
- win.Wulf = wulfNamespace;
3730
- wulfNamespace.Scroll = Scroll;
3731
- }
3732
-
3733
- // src/masonry/index.ts
3734
- var masonry_exports = {};
3735
- __export(masonry_exports, {
3736
- LayoutEngine: () => LayoutEngine,
3737
- LocalizedComponent: () => LocalizedComponent,
3738
- Masonry: () => Masonry,
3739
- createI18nManager: () => createI18nManager,
3740
- default: () => masonry_default,
3741
- masonryEn: () => masonryEn,
3742
- masonryFr: () => masonryFr,
3743
- masonryI18n: () => masonryI18n
3744
- });
3745
-
3746
- // src/masonry/LayoutEngine.ts
3747
- var LayoutEngine = class {
3748
- /**
3749
- * Normalise les gouttières horizontales et verticales.
3750
- */
3751
- static parseGutter(gutterOption) {
3752
- if (typeof gutterOption === "number") {
3753
- return { x: Math.max(0, gutterOption), y: Math.max(0, gutterOption) };
3754
- }
3755
- if (gutterOption && typeof gutterOption === "object") {
3756
- return {
3757
- x: Math.max(0, Number(gutterOption.x) || 0),
3758
- y: Math.max(0, Number(gutterOption.y) || 0)
3759
- };
3760
- }
3761
- return { x: 0, y: 0 };
3762
- }
3763
- /**
3764
- * Résout la largeur effective d'une colonne en pixels.
3765
- */
3766
- static resolveColumnWidth(container, firstItem, columnWidthOption) {
3767
- if (typeof columnWidthOption === "number" && columnWidthOption > 0) {
3768
- return columnWidthOption;
3769
- }
3770
- if (typeof columnWidthOption === "string") {
3771
- const el = container.querySelector(columnWidthOption);
3772
- if (el) {
3773
- const w = el.getBoundingClientRect().width;
3774
- if (w > 0) return w;
3775
- }
3776
- const parsed = parseFloat(columnWidthOption);
3777
- if (!isNaN(parsed) && parsed > 0) {
3778
- if (columnWidthOption.endsWith("%")) {
3779
- const containerW2 = container.getBoundingClientRect().width;
3780
- return containerW2 * parsed / 100;
3781
- }
3782
- return parsed;
3783
- }
3784
- }
3785
- if (columnWidthOption instanceof HTMLElement) {
3786
- const w = columnWidthOption.getBoundingClientRect().width;
3787
- if (w > 0) return w;
3788
- }
3789
- if (firstItem) {
3790
- const w = firstItem.getBoundingClientRect().width;
3791
- if (w > 0) return w;
3792
- }
3793
- const containerW = container.getBoundingClientRect().width;
3794
- return containerW > 0 ? containerW : 200;
3795
- }
3796
- /**
3797
- * Extrait le facteur d'étalement (span) d'un item sur plusieurs colonnes.
3798
- */
3799
- static getItemSpan(item, colWidth, gutterX, maxCols) {
3800
- const dataSpan = item.getAttribute("data-masonry-span") || item.dataset.masonrySpan;
3801
- if (dataSpan) {
3802
- const parsed = parseInt(dataSpan, 10);
3803
- if (!isNaN(parsed) && parsed > 0) {
3804
- return Math.min(maxCols, parsed);
3805
- }
3806
- }
3807
- const match = item.className.match(/(?:^|\s)(?:span|col-span)-(\d+)(?:\s|$)/);
3808
- if (match && match[1]) {
3809
- const parsed = parseInt(match[1], 10);
3810
- if (!isNaN(parsed) && parsed > 0) {
3811
- return Math.min(maxCols, parsed);
3812
- }
3813
- }
3814
- return 1;
3815
- }
3816
- /**
3817
- * Calcule les positions optimales de tous les items.
3818
- */
3819
- static calculate(container, items, options) {
3820
- const containerRect = container.getBoundingClientRect();
3821
- const containerWidth = containerRect.width;
3822
- const { x: gutterX, y: gutterY } = this.parseGutter(options.gutter);
3823
- if (containerWidth <= 0 || items.length === 0) {
3824
- return {
3825
- cols: 1,
3826
- colWidth: containerWidth,
3827
- gutterX,
3828
- gutterY,
3829
- containerHeight: 0,
3830
- containerWidth,
3831
- positions: []
3832
- };
3833
- }
3834
- const firstItem = items[0] || null;
3835
- let colWidth = this.resolveColumnWidth(container, firstItem, options.columnWidth);
3836
- let cols = Math.floor((containerWidth + gutterX) / (colWidth + gutterX));
3837
- cols = Math.max(1, cols);
3838
- if (!options.columnWidth && cols > 1) {
3839
- colWidth = (containerWidth - (cols - 1) * gutterX) / cols;
3840
- }
3841
- const fittedWidth = options.fitWidth ? cols * colWidth + (cols - 1) * gutterX : void 0;
3842
- const colHeights = new Array(cols).fill(0);
3843
- const positions = [];
3844
- const itemHeights = items.map((item) => {
3845
- const h = item.getBoundingClientRect().height;
3846
- return h > 0 ? h : 50;
3847
- });
3848
- let currentHCol = 0;
3849
- for (let i = 0; i < items.length; i++) {
3850
- const item = items[i];
3851
- const itemH = itemHeights[i];
3852
- const span = this.getItemSpan(item, colWidth, gutterX, cols);
3853
- let targetCol = 0;
3854
- let targetY = 0;
3855
- if (options.horizontalOrder) {
3856
- if (currentHCol + span > cols) {
3857
- currentHCol = 0;
3858
- }
3859
- targetCol = currentHCol;
3860
- let maxY = 0;
3861
- for (let s = 0; s < span; s++) {
3862
- if (colHeights[targetCol + s] > maxY) {
3863
- maxY = colHeights[targetCol + s];
3864
- }
3865
- }
3866
- targetY = maxY;
3867
- currentHCol = (targetCol + span) % cols;
3868
- } else {
3869
- if (span === 1) {
3870
- let minH = colHeights[0];
3871
- targetCol = 0;
3872
- for (let c = 1; c < cols; c++) {
3873
- if (colHeights[c] < minH) {
3874
- minH = colHeights[c];
3875
- targetCol = c;
3876
- }
3877
- }
3878
- targetY = minH;
3879
- } else {
3880
- let bestMax = Infinity;
3881
- targetCol = 0;
3882
- for (let c = 0; c <= cols - span; c++) {
3883
- let maxInSpan = 0;
3884
- for (let s = 0; s < span; s++) {
3885
- if (colHeights[c + s] > maxInSpan) {
3886
- maxInSpan = colHeights[c + s];
3887
- }
3888
- }
3889
- if (maxInSpan < bestMax) {
3890
- bestMax = maxInSpan;
3891
- targetCol = c;
3892
- }
3893
- }
3894
- targetY = bestMax;
3895
- }
3896
- }
3897
- const itemW = span * colWidth + (span - 1) * gutterX;
3898
- const targetX = targetCol * (colWidth + gutterX);
3899
- positions.push({
3900
- element: item,
3901
- x: targetX,
3902
- y: targetY,
3903
- width: itemW,
3904
- height: itemH,
3905
- column: targetCol,
3906
- span
3907
- });
3908
- const nextY = targetY + itemH + gutterY;
3909
- for (let s = 0; s < span; s++) {
3910
- colHeights[targetCol + s] = nextY;
3911
- }
3912
- }
3913
- let maxColH = 0;
3914
- for (let c = 0; c < cols; c++) {
3915
- if (colHeights[c] > maxColH) {
3916
- maxColH = colHeights[c];
3917
- }
3918
- }
3919
- const containerHeight = Math.max(0, maxColH > 0 ? maxColH - gutterY : 0);
3920
- return {
3921
- cols,
3922
- colWidth,
3923
- gutterX,
3924
- gutterY,
3925
- containerHeight,
3926
- containerWidth,
3927
- fittedWidth,
3928
- positions
3929
- };
3930
- }
3931
- };
3932
-
3933
- // src/masonry/i18n/fr.ts
3934
- var masonryFr = {
3935
- gallery: "Galerie en grille asym\xE9trique"
3936
- };
3937
-
3938
- // src/masonry/i18n/en.ts
3939
- var masonryEn = {
3940
- gallery: "Masonry grid gallery"
3941
- };
3942
-
3943
- // src/masonry/i18n/index.ts
3944
- var masonryI18n = createI18nManager("fr", {
3945
- fr: masonryFr,
3946
- en: masonryEn
3947
- });
3948
-
3949
- // src/masonry/Masonry.ts
3950
- var Masonry = class extends LocalizedComponent {
3951
- constructor(target, options = {}) {
3952
- super(options.i18n);
3953
- this.isNativeCSSGrid = false;
3954
- this._items = [];
3955
- this.resizeObserver = null;
3956
- this.itemResizeObserver = null;
3957
- this.layoutRafId = null;
3958
- this.isDestroyed = false;
3959
- this.wasRoleInferred = false;
3960
- this.wasAriaLabelInferred = false;
3961
- this.hasExplicitAriaLabel = false;
3962
- this.lastInferredAriaLabel = "";
3963
- this.removeTimers = /* @__PURE__ */ new Set();
3964
- this.pendingImageListeners = [];
3965
- if (typeof target === "string") {
3966
- const el = document.querySelector(target);
3967
- if (!el) {
3968
- throw new Error(`[Wulf.Masonry] Conteneur introuvable pour le s\xE9lecteur : "${target}"`);
3969
- }
3970
- this.root = el;
3971
- } else if (target instanceof HTMLElement) {
3972
- this.root = target;
3973
- } else {
3974
- throw new Error("[Wulf.Masonry] Cible invalide : fournissez un \xE9l\xE9ment HTMLElement ou un s\xE9lecteur valide.");
3975
- }
3976
- this.originalContainerStyles = {
3977
- height: this.root.style.height,
3978
- width: this.root.style.width
3979
- };
3980
- this.hasExplicitAriaLabel = Boolean(options.ariaLabel);
3981
- this.options = {
3982
- itemSelector: options.itemSelector || "> *",
3983
- columnWidth: options.columnWidth ?? 0,
3984
- gutter: options.gutter ?? 0,
3985
- percentPosition: Boolean(options.percentPosition),
3986
- fitWidth: Boolean(options.fitWidth),
3987
- horizontalOrder: Boolean(options.horizontalOrder),
3988
- transitionDuration: options.transitionDuration !== void 0 ? options.transitionDuration : 300,
3989
- stagger: options.stagger || 0,
3990
- resize: options.resize !== false,
3991
- autoImages: options.autoImages !== false,
3992
- useNativeCSSGrid: options.useNativeCSSGrid !== false,
3993
- ariaRole: options.ariaRole || "region",
3994
- ariaLabel: options.ariaLabel || this.t("gallery"),
3995
- i18n: options.i18n || {},
3996
- onLayout: options.onLayout || (() => {
3997
- }),
3998
- onItemPlaced: options.onItemPlaced || (() => {
3999
- })
4000
- };
4001
- const supportsNativeCSS = typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("grid-template-rows", "masonry");
4002
- if (this.options.useNativeCSSGrid && supportsNativeCSS) {
4003
- this.isNativeCSSGrid = true;
4004
- this.root.classList.add("wulf-masonry", "wulf-masonry--native");
4005
- } else {
4006
- this.root.classList.add("wulf-masonry");
4007
- }
4008
- this.initAccessibility();
4009
- this.applyTransitionDuration();
4010
- this.reloadItems();
4011
- this.initObservers();
4012
- this.initImages();
4013
- this.layout();
4014
- }
4015
- get items() {
4016
- return [...this._items];
4017
- }
4018
- /**
4019
- * Initialise les attributs WAI-ARIA du conteneur.
4020
- */
4021
- initAccessibility() {
4022
- if (this.options.ariaRole && !this.root.hasAttribute("role")) {
4023
- this.root.setAttribute("role", this.options.ariaRole);
4024
- this.wasRoleInferred = true;
4025
- }
4026
- const label = this.hasExplicitAriaLabel ? this.options.ariaLabel : this.t("gallery");
4027
- if (label && !this.root.hasAttribute("aria-label")) {
4028
- this.root.setAttribute("aria-label", label);
4029
- this.lastInferredAriaLabel = label;
4030
- this.wasAriaLabelInferred = true;
4031
- }
4032
- }
4033
- /**
4034
- * Synchronise dynamiquement le libellé ARIA si la langue globale change après montage.
4035
- */
4036
- syncAccessibilityLabels() {
4037
- if (this.wasAriaLabelInferred && !this.hasExplicitAriaLabel) {
4038
- const currentAttr = this.root.getAttribute("aria-label");
4039
- if (currentAttr === this.lastInferredAriaLabel) {
4040
- const nextLabel = this.t("gallery");
4041
- this.root.setAttribute("aria-label", nextLabel);
4042
- this.lastInferredAriaLabel = nextLabel;
4043
- this.options.ariaLabel = nextLabel;
4044
- }
4045
- }
4046
- }
4047
- /**
4048
- * Configure les variables CSS de transition sur le conteneur.
4049
- */
4050
- applyTransitionDuration() {
4051
- const dur = this.options.transitionDuration;
4052
- const durValue = typeof dur === "number" ? `${dur}ms` : dur;
4053
- this.root.style.setProperty("--wulf-masonry-duration", durValue);
4054
- }
4055
- /**
4056
- * Réindexe les éléments enfants ciblés par la disposition.
4057
- */
4058
- reloadItems() {
4059
- if (this.isDestroyed) return;
4060
- let matched = [];
4061
- if (this.options.itemSelector === "> *") {
4062
- matched = Array.from(this.root.children).filter(
4063
- (el) => el instanceof HTMLElement && !el.hasAttribute("data-masonry-ignore")
4064
- );
4065
- } else {
4066
- try {
4067
- matched = Array.from(this.root.querySelectorAll(this.options.itemSelector)).filter(
4068
- (el) => el.parentElement === this.root && !el.hasAttribute("data-masonry-ignore")
4069
- );
4070
- } catch {
4071
- matched = Array.from(this.root.children).filter(
4072
- (el) => el instanceof HTMLElement && !el.hasAttribute("data-masonry-ignore")
4073
- );
4074
- }
4075
- }
4076
- this._items = matched;
4077
- for (const item of this._items) {
4078
- item.classList.add("wulf-masonry-item");
4079
- if (this.itemResizeObserver) {
4080
- this.itemResizeObserver.observe(item);
4081
- }
4082
- }
4083
- }
4084
- /**
4085
- * Active ResizeObserver sur le conteneur et les éléments individuels.
4086
- */
4087
- initObservers() {
4088
- if (!this.options.resize || typeof ResizeObserver === "undefined") return;
4089
- let prevWidth = this.root.getBoundingClientRect().width;
4090
- this.resizeObserver = new ResizeObserver((entries) => {
4091
- for (const entry of entries) {
4092
- const currentWidth = entry.contentRect.width;
4093
- if (Math.abs(currentWidth - prevWidth) >= 1) {
4094
- prevWidth = currentWidth;
4095
- this.scheduleLayout();
4096
- }
4097
- }
4098
- });
4099
- this.resizeObserver.observe(this.root);
4100
- this.itemResizeObserver = new ResizeObserver(() => {
4101
- this.scheduleLayout();
4102
- });
4103
- for (const item of this._items) {
4104
- this.itemResizeObserver.observe(item);
4105
- }
4106
- }
4107
- /**
4108
- * Détecte les balises <img> sans dimensions prédéfinies et attend leur décodage/chargement.
4109
- */
4110
- initImages() {
4111
- if (!this.options.autoImages) return;
4112
- const images = Array.from(this.root.querySelectorAll("img"));
4113
- for (const img of images) {
4114
- if (!img.complete) {
4115
- const attachLoadListener = () => {
4116
- const onLoad = () => {
4117
- this.pendingImageListeners = this.pendingImageListeners.filter((l) => l.handler !== onLoad);
4118
- if (!this.isDestroyed) this.scheduleLayout();
4119
- };
4120
- this.pendingImageListeners.push({ img, handler: onLoad });
4121
- img.addEventListener("load", onLoad, { once: true });
4122
- };
4123
- if (typeof img.decode === "function") {
4124
- img.decode().then(() => {
4125
- if (!this.isDestroyed) this.scheduleLayout();
4126
- }).catch(() => {
4127
- attachLoadListener();
4128
- });
4129
- } else {
4130
- attachLoadListener();
4131
- }
4132
- }
4133
- }
4134
- }
4135
- /**
4136
- * Planifie un recalcul au prochain tick d'animation via requestAnimationFrame.
4137
- */
4138
- scheduleLayout() {
4139
- if (this.isDestroyed) return;
4140
- if (this.layoutRafId !== null) {
4141
- cancelAnimationFrame(this.layoutRafId);
4142
- }
4143
- this.layoutRafId = requestAnimationFrame(() => {
4144
- this.layoutRafId = null;
4145
- this.layout();
4146
- });
4147
- }
4148
- /**
4149
- * Calcule et applique les nouvelles coordonnées GPU de chaque item.
4150
- */
4151
- layout() {
4152
- if (this.isDestroyed) return;
4153
- this.syncAccessibilityLabels();
4154
- if (this.isNativeCSSGrid) {
4155
- this.options.onLayout([]);
4156
- return;
4157
- }
4158
- this.root.setAttribute("aria-busy", "true");
4159
- const result = LayoutEngine.calculate(this.root, this._items, this.options);
4160
- this.root.style.height = `${result.containerHeight}px`;
4161
- if (this.options.fitWidth && result.fittedWidth !== void 0) {
4162
- this.root.style.width = `${result.fittedWidth}px`;
4163
- this.root.classList.add("wulf-masonry--fit-width");
4164
- } else {
4165
- this.root.classList.remove("wulf-masonry--fit-width");
4166
- }
4167
- const stagger = this.options.stagger;
4168
- const usePercent = this.options.percentPosition && result.containerWidth > 0;
4169
- for (let i = 0; i < result.positions.length; i++) {
4170
- const pos = result.positions[i];
4171
- const item = pos.element;
4172
- if (usePercent) {
4173
- const wPct = Number((pos.width / result.containerWidth * 100).toFixed(4));
4174
- item.style.setProperty("--wulf-masonry-w", `${wPct}%`);
4175
- } else {
4176
- item.style.setProperty("--wulf-masonry-w", `${pos.width}px`);
4177
- }
4178
- item.style.setProperty("--wulf-masonry-x", `${pos.x}px`);
4179
- item.style.setProperty("--wulf-masonry-y", `${pos.y}px`);
4180
- if (stagger > 0) {
4181
- item.style.transitionDelay = `${i * stagger}ms`;
4182
- } else {
4183
- item.style.removeProperty("transition-delay");
4184
- }
4185
- item.classList.remove("wulf-masonry-item--hidden");
4186
- this.options.onItemPlaced(item, pos);
4187
- }
4188
- this.root.setAttribute("aria-busy", "false");
4189
- this.options.onLayout(result.positions);
4190
- }
4191
- /**
4192
- * Ajoute de nouveaux éléments à la fin du conteneur.
4193
- */
4194
- append(elements) {
4195
- if (this.isDestroyed) return;
4196
- const list = Array.isArray(elements) ? elements : [elements];
4197
- if (list.length === 0) return;
4198
- const frag = document.createDocumentFragment();
4199
- for (const el of list) {
4200
- el.classList.add("wulf-masonry-item", "wulf-masonry-item--hidden");
4201
- frag.appendChild(el);
4202
- }
4203
- this.root.appendChild(frag);
4204
- this.reloadItems();
4205
- this.initImages();
4206
- this.layout();
4207
- }
4208
- /**
4209
- * Ajoute de nouveaux éléments au début du conteneur.
4210
- */
4211
- prepend(elements) {
4212
- if (this.isDestroyed) return;
4213
- const list = Array.isArray(elements) ? elements : [elements];
4214
- if (list.length === 0) return;
4215
- const first = this.root.firstChild;
4216
- const frag = document.createDocumentFragment();
4217
- for (const el of list) {
4218
- el.classList.add("wulf-masonry-item", "wulf-masonry-item--hidden");
4219
- frag.appendChild(el);
4220
- }
4221
- this.root.insertBefore(frag, first);
4222
- this.reloadItems();
4223
- this.initImages();
4224
- this.layout();
4225
- }
4226
- /**
4227
- * Supprime des éléments avec animation de fondu/sortie.
4228
- */
4229
- remove(elements) {
4230
- if (this.isDestroyed) return;
4231
- const list = Array.isArray(elements) ? elements : [elements];
4232
- if (list.length === 0) return;
4233
- for (const el of list) {
4234
- el.classList.add("wulf-masonry-item--hidden");
4235
- }
4236
- const dur = typeof this.options.transitionDuration === "number" ? this.options.transitionDuration : 300;
4237
- if (dur <= 0) {
4238
- for (const el of list) {
4239
- if (el.parentElement === this.root) {
4240
- if (this.itemResizeObserver) {
4241
- this.itemResizeObserver.unobserve(el);
4242
- }
4243
- this.root.removeChild(el);
4244
- }
4245
- }
4246
- this.reloadItems();
4247
- this.layout();
4248
- return;
4249
- }
4250
- const timerId = window.setTimeout(() => {
4251
- this.removeTimers.delete(timerId);
4252
- if (this.isDestroyed) return;
4253
- for (const el of list) {
4254
- if (el.parentElement === this.root) {
4255
- if (this.itemResizeObserver) {
4256
- this.itemResizeObserver.unobserve(el);
4257
- }
4258
- this.root.removeChild(el);
4259
- }
4260
- }
4261
- this.reloadItems();
4262
- this.layout();
4263
- }, dur);
4264
- this.removeTimers.add(timerId);
4265
- }
4266
- /**
4267
- * Libère les ressources, déconnecte les observateurs et nettoie les styles injectés.
4268
- */
4269
- destroy() {
4270
- if (this.isDestroyed) return;
4271
- this.isDestroyed = true;
4272
- for (const timerId of this.removeTimers) {
4273
- clearTimeout(timerId);
4274
- }
4275
- this.removeTimers.clear();
4276
- for (const { img, handler } of this.pendingImageListeners) {
4277
- img.removeEventListener("load", handler);
4278
- }
4279
- this.pendingImageListeners = [];
4280
- if (this.layoutRafId !== null) {
4281
- cancelAnimationFrame(this.layoutRafId);
4282
- this.layoutRafId = null;
4283
- }
4284
- if (this.resizeObserver) {
4285
- this.resizeObserver.disconnect();
4286
- this.resizeObserver = null;
4287
- }
4288
- if (this.itemResizeObserver) {
4289
- this.itemResizeObserver.disconnect();
4290
- this.itemResizeObserver = null;
4291
- }
4292
- this.root.classList.remove("wulf-masonry", "wulf-masonry--native", "wulf-masonry--fit-width");
4293
- this.root.removeAttribute("aria-busy");
4294
- if (this.wasRoleInferred && this.root.getAttribute("role") === this.options.ariaRole) {
4295
- this.root.removeAttribute("role");
4296
- }
4297
- if (this.wasAriaLabelInferred && this.root.getAttribute("aria-label") === this.lastInferredAriaLabel) {
4298
- this.root.removeAttribute("aria-label");
4299
- }
4300
- this.root.style.removeProperty("--wulf-masonry-duration");
4301
- if (this.originalContainerStyles.height) {
4302
- this.root.style.height = this.originalContainerStyles.height;
4303
- } else {
4304
- this.root.style.removeProperty("height");
4305
- }
4306
- if (this.originalContainerStyles.width) {
4307
- this.root.style.width = this.originalContainerStyles.width;
4308
- } else {
4309
- this.root.style.removeProperty("width");
4310
- }
4311
- for (const item of this._items) {
4312
- item.classList.remove("wulf-masonry-item", "wulf-masonry-item--hidden");
4313
- item.style.removeProperty("--wulf-masonry-w");
4314
- item.style.removeProperty("--wulf-masonry-x");
4315
- item.style.removeProperty("--wulf-masonry-y");
4316
- item.style.removeProperty("transition-delay");
4317
- }
4318
- this._items = [];
4319
- }
4320
- };
4321
- Masonry._i18n = masonryI18n;
4322
- Masonry.i18n = masonryI18n;
4323
-
4324
- // src/masonry/index.ts
4325
- var masonry_default = Masonry;
4326
- if (typeof window !== "undefined") {
4327
- const win = window;
4328
- const wulfNamespace = win.Wulf || {};
4329
- win.Wulf = wulfNamespace;
4330
- wulfNamespace.Masonry = Object.assign(Masonry, {
4331
- Masonry,
4332
- LayoutEngine,
4333
- i18n: masonryI18n
4334
- });
4335
- }
4336
-
4337
- // src/toast/index.ts
4338
- var toast_exports = {};
4339
- __export(toast_exports, {
4340
- LocalizedComponent: () => LocalizedComponent,
4341
- Toast: () => Toast,
4342
- ToastInstance: () => ToastInstance,
4343
- ToastManager: () => ToastManager,
4344
- createI18nManager: () => createI18nManager,
4345
- default: () => toast_default,
4346
- toastEn: () => toastEn,
4347
- toastFr: () => toastFr,
4348
- toastI18n: () => toastI18n
4349
- });
4350
-
4351
- // src/toast/i18n/fr.ts
4352
- var toastFr = {
4353
- closeButton: "Fermer la notification"
4354
- };
4355
-
4356
- // src/toast/i18n/en.ts
4357
- var toastEn = {
4358
- closeButton: "Close notification"
4359
- };
4360
-
4361
- // src/toast/i18n/index.ts
4362
- var toastI18n = createI18nManager("fr", {
4363
- fr: toastFr,
4364
- en: toastEn
4365
- });
4366
-
4367
- // src/toast/ToastInstance.ts
4368
- var nextToastId = 1;
4369
- var ToastInstance = class {
4370
- constructor(options, onDismiss) {
4371
- this._isClosed = false;
4372
- this.timerId = null;
4373
- this.remainingTime = 0;
4374
- this.timerStartTime = 0;
4375
- this.isPaused = false;
4376
- this.id = `wulf-toast-${nextToastId++}`;
4377
- this.options = Object.freeze({ ...options });
4378
- this.onDismissCallback = onDismiss;
4379
- const duration = options.duration === void 0 ? 4e3 : options.duration;
4380
- if (typeof duration === "number" && duration > 0) {
4381
- this.remainingTime = duration;
4382
- } else {
4383
- this.remainingTime = 0;
4384
- }
4385
- this.element = this.createDOM();
4386
- this.bindEvents();
4387
- }
4388
- get isClosed() {
4389
- return this._isClosed;
4390
- }
4391
- /**
4392
- * Construction du DOM de manière 100% sécurisée sans aucun `innerHTML`.
4393
- */
4394
- createDOM() {
4395
- const el = document.createElement("div");
4396
- el.id = this.id;
4397
- el.className = "wulf-toast";
4398
- const role = this.options.role === "alert" ? "alert" : "status";
4399
- el.setAttribute("role", role);
4400
- el.setAttribute("aria-live", role === "alert" ? "assertive" : "polite");
4401
- el.setAttribute("aria-atomic", "true");
4402
- if (this.options.backgroundColor) {
4403
- el.style.setProperty("--wulf-toast-bg", this.options.backgroundColor);
4404
- }
4405
- if (this.options.titleColor) {
4406
- el.style.setProperty("--wulf-toast-title-color", this.options.titleColor);
4407
- }
4408
- if (this.options.textColor) {
4409
- el.style.setProperty("--wulf-toast-text-color", this.options.textColor);
4410
- }
4411
- if (this.options.iconColor) {
4412
- el.style.setProperty("--wulf-toast-icon-color", this.options.iconColor);
4413
- }
4414
- if (this.options.closeButtonColor) {
4415
- el.style.setProperty("--wulf-toast-close-color", this.options.closeButtonColor);
4416
- }
4417
- if (this.options.icon && this.options.icon.trim() !== "") {
4418
- const iconContainer = document.createElement("span");
4419
- iconContainer.className = `wulf-toast-icon ${this.options.icon.trim()}`;
4420
- iconContainer.setAttribute("aria-hidden", "true");
4421
- el.appendChild(iconContainer);
4422
- }
4423
- const content = document.createElement("div");
4424
- content.className = "wulf-toast-content";
4425
- if (this.options.title && this.options.title.trim() !== "") {
4426
- const titleEl = document.createElement("div");
4427
- titleEl.className = "wulf-toast-title";
4428
- this.appendTextWithLineBreaks(titleEl, this.options.title);
4429
- content.appendChild(titleEl);
4430
- }
4431
- if (this.options.message && this.options.message.trim() !== "") {
4432
- const messageEl = document.createElement("div");
4433
- messageEl.className = "wulf-toast-message";
4434
- this.appendTextWithLineBreaks(messageEl, this.options.message);
4435
- content.appendChild(messageEl);
4436
- }
4437
- el.appendChild(content);
4438
- const closable = this.options.closable ?? true;
4439
- if (closable) {
4440
- const closeBtn = document.createElement("button");
4441
- closeBtn.type = "button";
4442
- closeBtn.className = "wulf-toast-close";
4443
- closeBtn.setAttribute("aria-label", toastI18n.t("closeButton", this.options.i18n));
4444
- closeBtn.setAttribute("tabindex", "0");
4445
- const closeIcon = document.createElement("span");
4446
- closeIcon.className = "wulf-toast-close-icon";
4447
- closeIcon.setAttribute("aria-hidden", "true");
4448
- closeIcon.textContent = "\xD7";
4449
- closeBtn.appendChild(closeIcon);
4450
- closeBtn.addEventListener("click", (e) => {
4451
- e.stopPropagation();
4452
- this.close("close-button");
4453
- });
4454
- el.appendChild(closeBtn);
4455
- }
4456
- return el;
4457
- }
4458
- /**
4459
- * Injection de texte sécurisée gérant nativement les retours à la ligne (\n et \r\n).
4460
- * Utilise document.createTextNode et des éléments <br> créés proprement.
4461
- */
4462
- appendTextWithLineBreaks(container, text) {
4463
- const lines = text.split(/\r\n|\r|\n/);
4464
- lines.forEach((line, index) => {
4465
- if (index > 0) {
4466
- container.appendChild(document.createElement("br"));
4467
- }
4468
- container.appendChild(document.createTextNode(line));
4469
- });
4470
- }
4471
- /**
4472
- * Liaison des événements clavier, souris, et pause au survol / focus (WCAG 2.2)
4473
- */
4474
- bindEvents() {
4475
- this.element.addEventListener("click", (e) => {
4476
- if (this.options.onClick) {
4477
- this.options.onClick(this, e);
4478
- }
4479
- if (this.options.closeOnClick) {
4480
- this.close("toast-click");
4481
- }
4482
- });
4483
- this.element.addEventListener("mouseenter", () => this.pauseTimer());
4484
- this.element.addEventListener("mouseleave", () => this.resumeTimer());
4485
- this.element.addEventListener("focusin", () => this.pauseTimer());
4486
- this.element.addEventListener("focusout", () => this.resumeTimer());
4487
- }
4488
- /**
4489
- * Démarrage du compte à rebours de disparition automatique
4490
- */
4491
- startTimer() {
4492
- if (this._isClosed || this.remainingTime <= 0) return;
4493
- this.timerStartTime = Date.now();
4494
- this.timerId = window.setTimeout(() => {
4495
- this.close("timeout");
4496
- }, this.remainingTime);
4497
- }
4498
- /**
4499
- * Met en pause le compte à rebours (au survol ou prise de focus)
4500
- */
4501
- pauseTimer() {
4502
- if (this._isClosed || this.remainingTime <= 0 || this.isPaused) return;
4503
- if (this.timerId !== null) {
4504
- window.clearTimeout(this.timerId);
4505
- this.timerId = null;
4506
- }
4507
- const elapsed = Date.now() - this.timerStartTime;
4508
- this.remainingTime = Math.max(0, this.remainingTime - elapsed);
4509
- this.isPaused = true;
4510
- }
4511
- /**
4512
- * Reprend le compte à rebours
4513
- */
4514
- resumeTimer() {
4515
- if (this._isClosed || this.remainingTime <= 0 || !this.isPaused) return;
4516
- this.isPaused = false;
4517
- this.startTimer();
4518
- }
4519
- /**
4520
- * Déclenche la destruction immédiate sans animation (utile pour purger lors d'une rafale)
4521
- */
4522
- destroyImmediate(reason = "replace") {
4523
- if (this._isClosed) return;
4524
- this._isClosed = true;
4525
- if (this.timerId !== null) {
4526
- window.clearTimeout(this.timerId);
4527
- this.timerId = null;
4528
- }
4529
- if (this.element.parentNode) {
4530
- this.element.parentNode.removeChild(this.element);
4531
- }
4532
- if (this.onDismissCallback) {
4533
- this.onDismissCallback(this, reason);
4534
- }
4535
- if (this.options.onClose) {
4536
- this.options.onClose(this, reason);
4537
- }
4538
- }
4539
- /**
4540
- * Déclenche la fermeture propre et l'animation de sortie du toast.
4541
- * Si fast = true, utilise une disparition accélérée (90ms) pour le remplacement séquentiel.
4542
- */
4543
- close(reason = "programmatic", fast = false) {
4544
- if (this._isClosed) return Promise.resolve();
4545
- this._isClosed = true;
4546
- if (this.timerId !== null) {
4547
- window.clearTimeout(this.timerId);
4548
- this.timerId = null;
4549
- }
4550
- return new Promise((resolve) => {
4551
- this.element.classList.add(fast ? "wulf-toast-hiding-fast" : "wulf-toast-hiding");
4552
- const handleAnimationEnd = () => {
4553
- if (this.element.parentNode) {
4554
- this.element.parentNode.removeChild(this.element);
4555
- }
4556
- if (this.onDismissCallback) {
4557
- this.onDismissCallback(this, reason);
4558
- }
4559
- if (this.options.onClose) {
4560
- this.options.onClose(this, reason);
4561
- }
4562
- resolve();
4563
- };
4564
- const isReducedMotion = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
4565
- if (isReducedMotion) {
4566
- handleAnimationEnd();
4567
- } else if (fast) {
4568
- window.setTimeout(handleAnimationEnd, 90);
4569
- } else {
4570
- let transitioned = false;
4571
- let fallbackTimerId = null;
4572
- const onEnd = () => {
4573
- if (!transitioned) {
4574
- transitioned = true;
4575
- if (fallbackTimerId !== null) {
4576
- window.clearTimeout(fallbackTimerId);
4577
- fallbackTimerId = null;
4578
- }
4579
- this.element.removeEventListener("animationend", onEnd);
4580
- this.element.removeEventListener("transitionend", onEnd);
4581
- handleAnimationEnd();
4582
- }
4583
- };
4584
- this.element.addEventListener("animationend", onEnd, { once: true });
4585
- this.element.addEventListener("transitionend", onEnd, { once: true });
4586
- fallbackTimerId = window.setTimeout(onEnd, 300);
4587
- }
4588
- });
4589
- }
4590
- };
4591
-
4592
- // src/toast/ToastManager.ts
4593
- var _ToastManager = class _ToastManager {
4594
- constructor() {
4595
- this.containers = /* @__PURE__ */ new Map();
4596
- this.activeToasts = /* @__PURE__ */ new Map();
4597
- this.replaceTokens = /* @__PURE__ */ new Map();
4598
- this.pendingReplacements = /* @__PURE__ */ new Set();
4599
- }
4600
- static getInstance() {
4601
- if (!_ToastManager.instance) {
4602
- _ToastManager.instance = new _ToastManager();
4603
- }
4604
- return _ToastManager.instance;
4605
- }
4606
- /**
4607
- * Ajoute et affiche une notification Toast.
4608
- */
4609
- add(toast) {
4610
- const position = toast.options.position || "top-right";
4611
- let list = this.activeToasts.get(position);
4612
- if (!list) {
4613
- list = [];
4614
- this.activeToasts.set(position, list);
4615
- }
4616
- if (toast.options.replace && list.length > 0) {
4617
- const existing = [...list];
4618
- const token = (this.replaceTokens.get(position) || 0) + 1;
4619
- this.replaceTokens.set(position, token);
4620
- this.pendingReplacements.add(position);
4621
- const promises = existing.map((t) => t.close("replace", true));
4622
- Promise.all(promises).then(() => {
4623
- this.pendingReplacements.delete(position);
4624
- if (this.replaceTokens.get(position) !== token) {
4625
- return;
4626
- }
4627
- this.mountToast(toast, position);
4628
- });
4629
- return;
4630
- }
4631
- const maxToasts = typeof toast.options.maxToasts === "number" && toast.options.maxToasts > 0 ? toast.options.maxToasts : 5;
4632
- if (list.length >= maxToasts) {
4633
- const countToRemove = list.length - maxToasts + 1;
4634
- const oldestItems = list.splice(0, countToRemove);
4635
- for (const item of oldestItems) {
4636
- item.close("max-limit", true);
4637
- }
4638
- }
4639
- this.mountToast(toast, position);
4640
- }
4641
- /**
4642
- * Insère l'élément toast dans le DOM et déclenche les callbacks et compteurs.
4643
- */
4644
- mountToast(toast, position) {
4645
- const container = this.getOrCreateContainer(position);
4646
- let list = this.activeToasts.get(position);
4647
- if (!list) {
4648
- list = [];
4649
- this.activeToasts.set(position, list);
4650
- }
4651
- container.appendChild(toast.element);
4652
- list.push(toast);
4653
- if (toast.options.onOpen) {
4654
- try {
4655
- toast.options.onOpen(toast);
4656
- } catch (err) {
4657
- console.error("[Wulf.Toast] Erreur dans le callback onOpen:", err);
4658
- }
4659
- }
4660
- toast.startTimer();
4661
- }
4662
- /**
4663
- * Retire une notification de la pile et nettoie le conteneur s'il est vide.
4664
- */
4665
- remove(toast, _reason) {
4666
- const position = toast.options.position || "top-right";
4667
- const list = this.activeToasts.get(position);
4668
- if (list) {
4669
- const index = list.indexOf(toast);
4670
- if (index !== -1) {
4671
- list.splice(index, 1);
4672
- }
4673
- if (list.length === 0 && !this.pendingReplacements.has(position)) {
4674
- const container = this.containers.get(position);
4675
- if (container && (!container.firstChild || container.children.length === 0)) {
4676
- if (container.parentNode) {
4677
- container.parentNode.removeChild(container);
4678
- }
4679
- this.containers.delete(position);
4680
- this.activeToasts.delete(position);
4681
- }
4682
- }
4683
- }
4684
- }
4685
- /**
4686
- * Ferme l'ensemble des toasts actifs (sur une position ou partout) et attend leur retrait complet.
4687
- */
4688
- clearAll(position) {
4689
- const promises = [];
4690
- if (position) {
4691
- const list = this.activeToasts.get(position);
4692
- if (list && list.length > 0) {
4693
- const copy = [...list];
4694
- for (const t of copy) {
4695
- promises.push(t.close("programmatic"));
4696
- }
4697
- } else {
4698
- const container = this.containers.get(position);
4699
- if (container && (!container.firstChild || container.children.length === 0)) {
4700
- if (container.parentNode) {
4701
- container.parentNode.removeChild(container);
4702
- }
4703
- this.containers.delete(position);
4704
- this.activeToasts.delete(position);
4705
- }
4706
- }
4707
- } else {
4708
- const allPositions = /* @__PURE__ */ new Set([
4709
- ...Array.from(this.containers.keys()),
4710
- ...Array.from(this.activeToasts.keys())
4711
- ]);
4712
- for (const pos of allPositions) {
4713
- promises.push(this.clearAll(pos));
4714
- }
4715
- }
4716
- return Promise.all(promises).then(() => {
4717
- if (!position) {
4718
- for (const [pos, container] of Array.from(this.containers.entries())) {
4719
- if (!container.firstChild || container.children.length === 0) {
4720
- if (container.parentNode) {
4721
- container.parentNode.removeChild(container);
4722
- }
4723
- this.containers.delete(pos);
4724
- this.activeToasts.delete(pos);
4725
- }
4726
- }
4727
- }
4728
- });
4729
- }
4730
- /**
4731
- * Récupère ou crée le conteneur DOM pour une position d'affichage.
4732
- */
4733
- getOrCreateContainer(position) {
4734
- let container = this.containers.get(position);
4735
- if (!container || !document.body.contains(container)) {
4736
- container = document.createElement("div");
4737
- container.className = `wulf-toast-container wulf-toast-${position}`;
4738
- container.setAttribute("aria-live", "polite");
4739
- container.setAttribute("aria-relevant", "additions removals");
4740
- document.body.appendChild(container);
4741
- this.containers.set(position, container);
4742
- }
4743
- return container;
4744
- }
4745
- };
4746
- _ToastManager.instance = null;
4747
- var ToastManager = _ToastManager;
4748
-
4749
- // src/toast/Toast.ts
4750
- var Toast = class extends LocalizedComponent {
4751
- /**
4752
- * Affiche une nouvelle notification Toast avec les options spécifiées.
4753
- */
4754
- static show(options = {}) {
4755
- const manager = ToastManager.getInstance();
4756
- const instance = new ToastInstance(options, (t, reason) => {
4757
- manager.remove(t, reason);
4758
- });
4759
- manager.add(instance);
4760
- return instance;
4761
- }
4762
- /**
4763
- * Ferme immédiatement l'ensemble des toasts actifs (globalement ou par position) et attend leur retrait complet.
4764
- */
4765
- static clearAll(position) {
4766
- return ToastManager.getInstance().clearAll(position);
4767
- }
4768
- };
4769
- Toast._i18n = toastI18n;
4770
- Toast.i18n = toastI18n;
4771
-
4772
- // src/toast/index.ts
4773
- var toast_default = Toast;
4774
- if (typeof window !== "undefined") {
4775
- const win = window;
4776
- const wulfNamespace = win.Wulf || {};
4777
- win.Wulf = wulfNamespace;
4778
- wulfNamespace.Toast = Object.assign(Toast, {
4779
- Toast,
4780
- i18n: toastI18n
4781
- });
4782
- }
4783
- //# sourceMappingURL=index.cjs.js.map