wulf.js 1.9.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +118 -78
  2. package/changelog.md +60 -0
  3. package/dist/focus-trap.esm.js +202 -136
  4. package/dist/focus-trap.esm.js.map +3 -3
  5. package/dist/focus-trap.global.js +203 -137
  6. package/dist/focus-trap.global.js.map +3 -3
  7. package/dist/focus-trap.global.min.js +4 -4
  8. package/dist/focus-trap.global.min.js.map +4 -4
  9. package/dist/index.esm.js +2130 -858
  10. package/dist/index.esm.js.map +4 -4
  11. package/dist/index.global.js +2124 -852
  12. package/dist/index.global.js.map +4 -4
  13. package/dist/index.global.min.js +4 -4
  14. package/dist/index.global.min.js.map +4 -4
  15. package/dist/mask.css +1 -1
  16. package/dist/mask.css.map +2 -2
  17. package/dist/mask.esm.js +686 -330
  18. package/dist/mask.esm.js.map +3 -3
  19. package/dist/mask.global.js +687 -331
  20. package/dist/mask.global.js.map +3 -3
  21. package/dist/mask.global.min.js +4 -4
  22. package/dist/mask.global.min.js.map +4 -4
  23. package/dist/mask.layered.css +1 -0
  24. package/dist/mask.layered.css.map +7 -0
  25. package/dist/masonry.css +1 -1
  26. package/dist/masonry.css.map +2 -2
  27. package/dist/masonry.esm.js +248 -77
  28. package/dist/masonry.esm.js.map +3 -3
  29. package/dist/masonry.global.js +249 -78
  30. package/dist/masonry.global.js.map +3 -3
  31. package/dist/masonry.global.min.js +4 -4
  32. package/dist/masonry.global.min.js.map +4 -4
  33. package/dist/masonry.layered.css +1 -0
  34. package/dist/masonry.layered.css.map +7 -0
  35. package/dist/scroll.css +1 -1
  36. package/dist/scroll.css.map +2 -2
  37. package/dist/scroll.esm.js +462 -129
  38. package/dist/scroll.esm.js.map +3 -3
  39. package/dist/scroll.global.js +463 -130
  40. package/dist/scroll.global.js.map +3 -3
  41. package/dist/scroll.global.min.js +4 -4
  42. package/dist/scroll.global.min.js.map +4 -4
  43. package/dist/scroll.layered.css +1 -0
  44. package/dist/scroll.layered.css.map +7 -0
  45. package/dist/shortcut.esm.js +164 -48
  46. package/dist/shortcut.esm.js.map +3 -3
  47. package/dist/shortcut.global.js +165 -49
  48. package/dist/shortcut.global.js.map +3 -3
  49. package/dist/shortcut.global.min.js +2 -2
  50. package/dist/shortcut.global.min.js.map +4 -4
  51. package/dist/toast.css +1 -1
  52. package/dist/toast.css.map +2 -2
  53. package/dist/toast.esm.js +489 -124
  54. package/dist/toast.esm.js.map +3 -3
  55. package/dist/toast.global.js +490 -125
  56. package/dist/toast.global.js.map +3 -3
  57. package/dist/toast.global.min.js +3 -3
  58. package/dist/toast.global.min.js.map +4 -4
  59. package/dist/toast.layered.css +1 -0
  60. package/dist/toast.layered.css.map +7 -0
  61. package/dist/types/common/dom.d.ts +38 -0
  62. package/dist/types/focus-trap/FocusTrap.d.ts +14 -6
  63. package/dist/types/focus-trap/types.d.ts +2 -2
  64. package/dist/types/index.d.ts +10 -0
  65. package/dist/types/mask/BaseInputMask.d.ts +20 -0
  66. package/dist/types/mask/InputAmountMask.d.ts +2 -0
  67. package/dist/types/mask/InputEmailMask.d.ts +16 -1
  68. package/dist/types/mask/MaskEngine.d.ts +4 -0
  69. package/dist/types/masonry/Masonry.d.ts +10 -3
  70. package/dist/types/scroll/ScrollBlock.d.ts +31 -3
  71. package/dist/types/scroll/types.d.ts +13 -1
  72. package/dist/types/shortcut/ShortcutFormatter.d.ts +6 -0
  73. package/dist/types/shortcut/ShortcutManager.d.ts +1 -0
  74. package/dist/types/toast/Toast.d.ts +4 -0
  75. package/dist/types/toast/ToastInstance.d.ts +22 -10
  76. package/dist/types/toast/ToastManager.d.ts +37 -4
  77. package/dist/types/toast/i18n/types.d.ts +2 -0
  78. package/dist/types/toast/types.d.ts +9 -2
  79. package/package.json +16 -3
@@ -32,6 +32,53 @@ var __WulfIIFE = (() => {
32
32
  toastI18n: () => toastI18n
33
33
  });
34
34
 
35
+ // src/common/dom.ts
36
+ function getSafeWulfNamespace() {
37
+ if (typeof window === "undefined") return null;
38
+ const win = window;
39
+ const existing = win.Wulf;
40
+ if (!existing || typeof existing !== "object" || typeof Node !== "undefined" && existing instanceof Node || typeof HTMLCollection !== "undefined" && existing instanceof HTMLCollection) {
41
+ const fresh = {};
42
+ win.Wulf = fresh;
43
+ return fresh;
44
+ }
45
+ return existing;
46
+ }
47
+ function prefersReducedMotion() {
48
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
49
+ }
50
+ function waitForAnimations(element, fallbackMs, signal) {
51
+ const safeFallback = Number.isFinite(fallbackMs) ? Math.min(fallbackMs, 6e4) : 300;
52
+ if (signal?.aborted || safeFallback <= 0 || prefersReducedMotion()) {
53
+ return Promise.resolve();
54
+ }
55
+ const animations = typeof element.getAnimations === "function" ? element.getAnimations().filter((a) => {
56
+ if (a.playState !== "running") return false;
57
+ const timing = a.effect?.getComputedTiming?.();
58
+ return timing ? Number.isFinite(timing.endTime) : true;
59
+ }) : [];
60
+ if (animations.length === 0) {
61
+ return Promise.resolve();
62
+ }
63
+ return new Promise((resolve) => {
64
+ let settled = false;
65
+ let timerId = null;
66
+ const finish = () => {
67
+ if (settled) return;
68
+ settled = true;
69
+ if (timerId !== null) {
70
+ clearTimeout(timerId);
71
+ timerId = null;
72
+ }
73
+ signal?.removeEventListener("abort", finish);
74
+ resolve();
75
+ };
76
+ signal?.addEventListener("abort", finish, { once: true });
77
+ timerId = setTimeout(finish, safeFallback);
78
+ Promise.allSettled(animations.map((a) => a.finished)).then(finish);
79
+ });
80
+ }
81
+
35
82
  // src/common/i18n.ts
36
83
  var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
37
84
  function isSafeKey(key) {
@@ -49,7 +96,7 @@ var __WulfIIFE = (() => {
49
96
  function assignDefined(target, source) {
50
97
  if (!source || typeof source !== "object") return target;
51
98
  for (const key of Object.keys(source)) {
52
- if (isSafeKey(String(key)) && Object.prototype.hasOwnProperty.call(source, key) && source[key] !== void 0) {
99
+ if (isSafeKey(String(key)) && Object.hasOwn(source, key) && source[key] !== void 0) {
53
100
  target[key] = source[key];
54
101
  }
55
102
  }
@@ -110,7 +157,7 @@ var __WulfIIFE = (() => {
110
157
  if (!isSafeKey(String(key))) {
111
158
  return "";
112
159
  }
113
- if (instanceOverride && typeof instanceOverride === "object" && Object.prototype.hasOwnProperty.call(instanceOverride, key) && instanceOverride[key] !== void 0) {
160
+ if (instanceOverride && typeof instanceOverride === "object" && Object.hasOwn(instanceOverride, key) && instanceOverride[key] !== void 0) {
114
161
  return String(instanceOverride[key]);
115
162
  }
116
163
  if (globalOverrides[key] !== void 0) {
@@ -182,8 +229,11 @@ var __WulfIIFE = (() => {
182
229
  const rawValue = element.getAttribute(attrName)?.trim();
183
230
  if (!rawValue) return false;
184
231
  const doc = element.ownerDocument || document;
232
+ const root = typeof element.getRootNode === "function" ? element.getRootNode() : doc;
185
233
  const ids = rawValue.split(/\s+/).filter(Boolean);
186
- const isValid = ids.length > 0 && ids.every((id) => Boolean(doc.getElementById(id)));
234
+ const isValid = ids.length > 0 && ids.every(
235
+ (id) => Boolean(typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot ? root.getElementById(id) : doc.getElementById(id))
236
+ );
187
237
  if (!isValid) {
188
238
  warnings.push(
189
239
  `Attribut ${attrName}="${rawValue}" invalide : l'\xE9l\xE9ment cible est introuvable dans le DOM.`
@@ -195,6 +245,7 @@ var __WulfIIFE = (() => {
195
245
 
196
246
  // src/common/LocalizedComponent.ts
197
247
  var LocalizedComponent = class extends AuditableComponent {
248
+ static _i18n;
198
249
  /**
199
250
  * Définit la langue globale du composant (ex: 'fr', 'en', 'es').
200
251
  */
@@ -245,6 +296,10 @@ var __WulfIIFE = (() => {
245
296
  static t(key, instanceOverride) {
246
297
  return this._i18n ? this._i18n.t(key, instanceOverride) : String(key);
247
298
  }
299
+ /**
300
+ * Surcharges de localisation spécifiques à cette instance.
301
+ */
302
+ i18nOverrides;
248
303
  constructor(i18nOverrides) {
249
304
  super();
250
305
  this.i18nOverrides = i18nOverrides;
@@ -260,12 +315,14 @@ var __WulfIIFE = (() => {
260
315
 
261
316
  // src/toast/i18n/fr.ts
262
317
  var toastFr = {
263
- closeButton: "Fermer la notification"
318
+ closeButton: "Fermer la notification",
319
+ notificationsRegion: "Notifications"
264
320
  };
265
321
 
266
322
  // src/toast/i18n/en.ts
267
323
  var toastEn = {
268
- closeButton: "Close notification"
324
+ closeButton: "Close notification",
325
+ notificationsRegion: "Notifications"
269
326
  };
270
327
 
271
328
  // src/toast/i18n/index.ts
@@ -276,29 +333,54 @@ var __WulfIIFE = (() => {
276
333
 
277
334
  // src/toast/ToastInstance.ts
278
335
  var nextToastId = 1;
336
+ var DEFAULT_TOAST_DURATION = 5e3;
279
337
  function isSafeCssValue(val) {
280
338
  if (!val || typeof val !== "string" || val.length > 128) return false;
281
- return !/[;{}<>\\]|url\s*\(/i.test(val);
339
+ const trimmed = val.trim();
340
+ if (!trimmed) return false;
341
+ if (/[\u0000-\u001F\u007F;{}<>\\]|(?:url|image-set|-webkit-image-set|image|src|expression|attr|env)\s*\(/i.test(trimmed)) {
342
+ return false;
343
+ }
344
+ if (typeof CSS !== "undefined" && typeof CSS.supports === "function") {
345
+ return CSS.supports("color", trimmed) || CSS.supports("background-color", trimmed);
346
+ }
347
+ return true;
282
348
  }
283
349
  function sanitizeIconClasses(icon) {
284
- return icon.trim().split(/\s+/).filter((token) => /^[a-zA-Z0-9_-]+$/.test(token) && !token.startsWith("wulf-toast")).slice(0, 8).join(" ");
350
+ return icon.slice(0, 128).trim().split(/\s+/).filter((token) => /^[a-zA-Z0-9_-]+$/.test(token) && !token.startsWith("wulf-toast")).slice(0, 8).join(" ");
285
351
  }
286
352
  var ToastInstance = class extends AuditableComponent {
353
+ id;
354
+ options;
355
+ element;
356
+ _isClosed = false;
357
+ _isFinalized = false;
358
+ closePromise = null;
359
+ timerId = null;
360
+ remainingTime = 0;
361
+ hasDuration = false;
362
+ timerStartTime = 0;
363
+ isPausedByHover = false;
364
+ isPausedByFocus = false;
365
+ isPausedByVisibility = false;
366
+ isPendingFocusDismiss = false;
367
+ previousActiveElement = null;
368
+ eventsAbortController = new AbortController();
369
+ disposeAbortController = new AbortController();
370
+ onDismissCallback;
287
371
  constructor(options, onDismiss) {
288
372
  super();
289
- this._isClosed = false;
290
- this.timerId = null;
291
- this.remainingTime = 0;
292
- this.timerStartTime = 0;
293
- this.isPaused = false;
294
373
  this.id = `wulf-toast-${nextToastId++}`;
295
374
  this.options = Object.freeze({ ...options });
296
375
  this.onDismissCallback = onDismiss;
297
- const duration = options.duration === void 0 ? 4e3 : options.duration;
298
- if (typeof duration === "number" && duration > 0) {
299
- this.remainingTime = duration;
376
+ this.previousActiveElement = typeof document !== "undefined" && document.activeElement instanceof HTMLElement ? document.activeElement : null;
377
+ const duration = options.duration === void 0 ? DEFAULT_TOAST_DURATION : options.duration;
378
+ if (typeof duration === "number" && Number.isFinite(duration) && duration > 0) {
379
+ this.remainingTime = Math.min(duration, 2147483647);
380
+ this.hasDuration = true;
300
381
  } else {
301
382
  this.remainingTime = 0;
383
+ this.hasDuration = false;
302
384
  }
303
385
  this.element = this.createDOM();
304
386
  this.bindEvents();
@@ -307,6 +389,9 @@ var __WulfIIFE = (() => {
307
389
  get isClosed() {
308
390
  return this._isClosed;
309
391
  }
392
+ getPreviousActiveElement() {
393
+ return this.previousActiveElement;
394
+ }
310
395
  /**
311
396
  * Vérifie la conformité d'accessibilité WAI-ARIA de la notification Toast
312
397
  * et retourne la liste des contraintes manquantes.
@@ -320,7 +405,7 @@ var __WulfIIFE = (() => {
320
405
  "Contenu textuel vide : d\xE9finissez au moins un title ou un message pour que le lecteur d'\xE9cran puisse annoncer la notification (WCAG 4.1.3)."
321
406
  );
322
407
  }
323
- const duration = this.options.duration === void 0 ? 4e3 : this.options.duration;
408
+ const duration = this.options.duration === void 0 ? DEFAULT_TOAST_DURATION : this.options.duration;
324
409
  if (typeof duration === "number" && duration > 0 && duration < 5e3) {
325
410
  warnings.push(
326
411
  `Dur\xE9e d'affichage trop courte (duration: ${duration}ms) : pr\xE9voyez au moins 5000ms ou duration: false pour laisser le temps de lecture aux utilisateurs (WCAG 2.2.1).`
@@ -328,9 +413,9 @@ var __WulfIIFE = (() => {
328
413
  }
329
414
  const closable = this.options.closable ?? true;
330
415
  const isPersistent = duration === false || typeof duration === "number" && duration <= 0;
331
- if (isPersistent && !closable && !this.options.closeOnClick) {
416
+ if (isPersistent && !closable) {
332
417
  warnings.push(
333
- "Notification persistante impossible \xE0 fermer : activez closable: true ou closeOnClick: true lorsque duration est d\xE9sactiv\xE9 (WCAG 2.1.1)."
418
+ "Notification persistante impossible \xE0 fermer au clavier : activez closable: true lorsque duration est d\xE9sactiv\xE9 (WCAG 2.1.1)."
334
419
  );
335
420
  }
336
421
  return warnings;
@@ -343,15 +428,13 @@ var __WulfIIFE = (() => {
343
428
  }
344
429
  /**
345
430
  * Construction du DOM de manière 100% sécurisée sans aucun `innerHTML`.
431
+ * Les annonces sont gérées sur un canal unique dans `ToastManager` pour éviter tout doublon AT.
346
432
  */
347
433
  createDOM() {
348
434
  const el = document.createElement("div");
349
435
  el.id = this.id;
350
436
  el.className = "wulf-toast";
351
- const role = this.options.role === "alert" ? "alert" : "status";
352
- el.setAttribute("role", role);
353
- el.setAttribute("aria-live", role === "alert" ? "assertive" : "polite");
354
- el.setAttribute("aria-atomic", "true");
437
+ el.setAttribute("data-toast-role", this.options.role === "alert" ? "alert" : "status");
355
438
  if (this.options.backgroundColor && isSafeCssValue(this.options.backgroundColor)) {
356
439
  el.style.setProperty("--wulf-toast-bg", this.options.backgroundColor.trim());
357
440
  }
@@ -397,7 +480,6 @@ var __WulfIIFE = (() => {
397
480
  closeBtn.type = "button";
398
481
  closeBtn.className = "wulf-toast-close";
399
482
  closeBtn.setAttribute("aria-label", toastI18n.t("closeButton", this.options.i18n));
400
- closeBtn.setAttribute("tabindex", "0");
401
483
  const closeIcon = document.createElement("span");
402
484
  closeIcon.className = "wulf-toast-close-icon";
403
485
  closeIcon.setAttribute("aria-hidden", "true");
@@ -406,7 +488,7 @@ var __WulfIIFE = (() => {
406
488
  closeBtn.addEventListener("click", (e) => {
407
489
  e.stopPropagation();
408
490
  this.close("close-button");
409
- });
491
+ }, { signal: this.eventsAbortController.signal });
410
492
  el.appendChild(closeBtn);
411
493
  }
412
494
  if (this.options.progressBar && this.remainingTime > 0) {
@@ -420,7 +502,6 @@ var __WulfIIFE = (() => {
420
502
  }
421
503
  /**
422
504
  * Injection de texte sécurisée gérant nativement les retours à la ligne (\n et \r\n).
423
- * Utilise document.createTextNode et des éléments <br> créés proprement (plafonné contre le DoS DOM).
424
505
  */
425
506
  appendTextWithLineBreaks(container, text) {
426
507
  const safeText = String(text ?? "").slice(0, 4096);
@@ -433,9 +514,10 @@ var __WulfIIFE = (() => {
433
514
  });
434
515
  }
435
516
  /**
436
- * Liaison des événements clavier, souris, et pause au survol / focus (WCAG 2.2)
517
+ * Liaison des événements clavier, souris, visibilité d'onglet et pause au survol/focus (WCAG 2.2).
437
518
  */
438
519
  bindEvents() {
520
+ const { signal } = this.eventsAbortController;
439
521
  this.element.addEventListener("click", (e) => {
440
522
  if (this.options.onClick) {
441
523
  this.options.onClick(this, e);
@@ -443,115 +525,162 @@ var __WulfIIFE = (() => {
443
525
  if (this.options.closeOnClick) {
444
526
  this.close("toast-click");
445
527
  }
446
- });
447
- this.element.addEventListener("mouseenter", () => this.pauseTimer());
448
- this.element.addEventListener("mouseleave", () => this.resumeTimer());
449
- this.element.addEventListener("focusin", () => this.pauseTimer());
450
- this.element.addEventListener("focusout", () => this.resumeTimer());
528
+ }, { signal });
529
+ this.element.addEventListener("mouseenter", () => this.pauseTimer("hover"), { signal });
530
+ this.element.addEventListener("mouseleave", () => this.resumeTimer("hover"), { signal });
531
+ this.element.addEventListener("focusin", () => this.pauseTimer("focus"), { signal });
532
+ this.element.addEventListener("focusout", (e) => {
533
+ const nextFocused = e.relatedTarget;
534
+ if (nextFocused && this.element.contains(nextFocused)) {
535
+ return;
536
+ }
537
+ if (this.isPendingFocusDismiss && !this._isClosed) {
538
+ this.isPendingFocusDismiss = false;
539
+ this.close("timeout");
540
+ return;
541
+ }
542
+ this.resumeTimer("focus");
543
+ }, { signal });
544
+ this.element.addEventListener("keydown", (e) => {
545
+ if (e.key === "Escape" && (this.options.closable ?? true)) {
546
+ e.stopPropagation();
547
+ this.close("close-button");
548
+ }
549
+ }, { signal });
550
+ if (typeof document !== "undefined") {
551
+ document.addEventListener("visibilitychange", () => {
552
+ if (document.visibilityState === "hidden") {
553
+ this.pauseTimer("visibility");
554
+ } else {
555
+ this.resumeTimer("visibility");
556
+ }
557
+ }, { signal });
558
+ }
559
+ }
560
+ get isPaused() {
561
+ return this.isPausedByHover || this.isPausedByFocus || this.isPausedByVisibility;
451
562
  }
452
563
  /**
453
- * Démarrage du compte à rebours de disparition automatique
564
+ * Démarrage du compte à rebours de disparition automatique (horloge monotone).
454
565
  */
455
566
  startTimer() {
456
- if (this._isClosed || this.remainingTime <= 0) return;
457
- this.timerStartTime = Date.now();
567
+ if (this._isClosed || this.remainingTime <= 0 || this.isPaused) return;
568
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
569
+ this.isPausedByVisibility = true;
570
+ this.element.classList.add("is-paused");
571
+ return;
572
+ }
573
+ if (this.timerId !== null) {
574
+ window.clearTimeout(this.timerId);
575
+ this.timerId = null;
576
+ }
577
+ this.timerStartTime = performance.now();
458
578
  this.timerId = window.setTimeout(() => {
579
+ this.timerId = null;
580
+ if (typeof document !== "undefined" && this.element.contains(document.activeElement)) {
581
+ this.isPendingFocusDismiss = true;
582
+ return;
583
+ }
459
584
  this.close("timeout");
460
585
  }, this.remainingTime);
461
586
  }
462
587
  /**
463
- * Met en pause le compte à rebours (au survol ou prise de focus)
588
+ * Met en pause le compte à rebours (au survol, au focus ou à la perte de visibilité d'onglet).
464
589
  */
465
- pauseTimer() {
466
- if (this._isClosed || this.remainingTime <= 0 || this.isPaused) return;
590
+ pauseTimer(source = "interaction") {
591
+ if (this._isClosed || !this.hasDuration || this.remainingTime <= 0) return;
592
+ const wasPaused = this.isPaused;
593
+ if (source === "visibility") {
594
+ this.isPausedByVisibility = true;
595
+ } else if (source === "focus") {
596
+ this.isPausedByFocus = true;
597
+ } else {
598
+ this.isPausedByHover = true;
599
+ }
600
+ if (wasPaused) return;
467
601
  if (this.timerId !== null) {
468
602
  window.clearTimeout(this.timerId);
469
603
  this.timerId = null;
604
+ const elapsed = performance.now() - this.timerStartTime;
605
+ this.remainingTime = Math.max(0, this.remainingTime - elapsed);
470
606
  }
471
- const elapsed = Date.now() - this.timerStartTime;
472
- this.remainingTime = Math.max(0, this.remainingTime - elapsed);
473
- this.isPaused = true;
474
607
  this.element.classList.add("is-paused");
475
608
  }
476
609
  /**
477
- * Reprend le compte à rebours
610
+ * Reprend le compte à rebours si aucune autre cause de pause n'est active.
478
611
  */
479
- resumeTimer() {
480
- if (this._isClosed || this.remainingTime <= 0 || !this.isPaused) return;
481
- this.isPaused = false;
612
+ resumeTimer(source = "interaction") {
613
+ if (this._isClosed || !this.hasDuration) return;
614
+ if (source === "visibility") {
615
+ this.isPausedByVisibility = false;
616
+ } else if (source === "focus") {
617
+ this.isPausedByFocus = false;
618
+ } else if (source === "hover") {
619
+ this.isPausedByHover = false;
620
+ } else {
621
+ this.isPausedByHover = false;
622
+ this.isPausedByFocus = false;
623
+ }
624
+ if (this.isPaused) return;
482
625
  this.element.classList.remove("is-paused");
626
+ if (this.remainingTime <= 0) {
627
+ this.close("timeout");
628
+ return;
629
+ }
483
630
  this.startTimer();
484
631
  }
632
+ finalizeDismiss(reason) {
633
+ if (this._isFinalized) return;
634
+ this._isFinalized = true;
635
+ this.eventsAbortController.abort();
636
+ if (this.onDismissCallback) {
637
+ this.onDismissCallback(this, reason);
638
+ }
639
+ if (this.element.parentNode) {
640
+ this.element.parentNode.removeChild(this.element);
641
+ }
642
+ if (this.options.onClose) {
643
+ this.options.onClose(this, reason);
644
+ }
645
+ }
485
646
  /**
486
- * Déclenche la destruction immédiate sans animation (utile pour purger lors d'une rafale)
647
+ * Déclenche la destruction immédiate sans animation.
487
648
  */
488
649
  destroyImmediate(reason = "replace") {
489
- if (this._isClosed) return;
490
650
  this._isClosed = true;
491
651
  if (this.timerId !== null) {
492
652
  window.clearTimeout(this.timerId);
493
653
  this.timerId = null;
494
654
  }
495
- if (this.element.parentNode) {
496
- this.element.parentNode.removeChild(this.element);
497
- }
498
- if (this.onDismissCallback) {
499
- this.onDismissCallback(this, reason);
500
- }
501
- if (this.options.onClose) {
502
- this.options.onClose(this, reason);
503
- }
655
+ this.disposeAbortController.abort();
656
+ this.finalizeDismiss(reason);
504
657
  }
505
658
  /**
506
659
  * Déclenche la fermeture propre et l'animation de sortie du toast.
507
- * Si fast = true, utilise une disparition accélérée (90ms) pour le remplacement séquentiel.
660
+ * Si fast = true, utilise une disparition accélérée pour le remplacement séquentiel.
508
661
  */
509
662
  close(reason = "programmatic", fast = false) {
510
- if (this._isClosed) return Promise.resolve();
663
+ if (this._isClosed) {
664
+ return this.closePromise ?? Promise.resolve();
665
+ }
511
666
  this._isClosed = true;
512
667
  if (this.timerId !== null) {
513
668
  window.clearTimeout(this.timerId);
514
669
  this.timerId = null;
515
670
  }
516
- return new Promise((resolve) => {
517
- this.element.classList.add(fast ? "wulf-toast-hiding-fast" : "wulf-toast-hiding");
518
- const handleAnimationEnd = () => {
519
- if (this.element.parentNode) {
520
- this.element.parentNode.removeChild(this.element);
521
- }
522
- if (this.onDismissCallback) {
523
- this.onDismissCallback(this, reason);
524
- }
525
- if (this.options.onClose) {
526
- this.options.onClose(this, reason);
527
- }
528
- resolve();
529
- };
530
- const isReducedMotion = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
531
- if (isReducedMotion) {
532
- handleAnimationEnd();
533
- } else if (fast) {
534
- window.setTimeout(handleAnimationEnd, 90);
535
- } else {
536
- let transitioned = false;
537
- let fallbackTimerId = null;
538
- const onEnd = () => {
539
- if (!transitioned) {
540
- transitioned = true;
541
- if (fallbackTimerId !== null) {
542
- window.clearTimeout(fallbackTimerId);
543
- fallbackTimerId = null;
544
- }
545
- this.element.removeEventListener("animationend", onEnd);
546
- this.element.removeEventListener("transitionend", onEnd);
547
- handleAnimationEnd();
548
- }
549
- };
550
- this.element.addEventListener("animationend", onEnd, { once: true });
551
- this.element.addEventListener("transitionend", onEnd, { once: true });
552
- fallbackTimerId = window.setTimeout(onEnd, 300);
671
+ this.eventsAbortController.abort();
672
+ this.element.classList.add(fast ? "wulf-toast-hiding-fast" : "wulf-toast-hiding");
673
+ if (prefersReducedMotion()) {
674
+ this.finalizeDismiss(reason);
675
+ this.closePromise = Promise.resolve();
676
+ return this.closePromise;
677
+ }
678
+ this.closePromise = waitForAnimations(this.element, fast ? 90 : 300, this.disposeAbortController.signal).then(() => {
679
+ if (!this.disposeAbortController.signal.aborted) {
680
+ this.finalizeDismiss(reason);
553
681
  }
554
682
  });
683
+ return this.closePromise;
555
684
  }
556
685
  };
557
686
 
@@ -567,12 +696,35 @@ var __WulfIIFE = (() => {
567
696
  function normalizePosition(pos) {
568
697
  return pos && VALID_POSITIONS.has(pos) ? pos : "top-right";
569
698
  }
570
- var _ToastManager = class _ToastManager {
699
+ var FOCUSABLE_IN_TOAST = 'button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])';
700
+ var ToastManager = class _ToastManager {
701
+ static instance = null;
702
+ containers = /* @__PURE__ */ new Map();
703
+ activeToasts = /* @__PURE__ */ new Map();
704
+ announcerEl = null;
705
+ politeRegion = null;
706
+ assertiveRegion = null;
707
+ announceTimers = [];
708
+ politeAnnounceTimerId = null;
709
+ assertiveAnnounceTimerId = null;
710
+ politeClearTimerId = null;
711
+ assertiveClearTimerId = null;
712
+ lastPoliteText = "";
713
+ lastAssertiveText = "";
714
+ announcerToggle = false;
715
+ /**
716
+ * Vérifie si un conteneur Popover est ouvert (compatible natif et polyfill OddBird).
717
+ */
718
+ isPopoverOpen(container) {
719
+ try {
720
+ if (container.matches(":popover-open")) return true;
721
+ } catch {
722
+ }
723
+ return container.classList.contains(":popover-open");
724
+ }
725
+ replaceTokens = /* @__PURE__ */ new Map();
726
+ pendingReplacements = /* @__PURE__ */ new Set();
571
727
  constructor() {
572
- this.containers = /* @__PURE__ */ new Map();
573
- this.activeToasts = /* @__PURE__ */ new Map();
574
- this.replaceTokens = /* @__PURE__ */ new Map();
575
- this.pendingReplacements = /* @__PURE__ */ new Set();
576
728
  }
577
729
  static getInstance() {
578
730
  if (!_ToastManager.instance) {
@@ -590,6 +742,8 @@ var __WulfIIFE = (() => {
590
742
  list = [];
591
743
  this.activeToasts.set(position, list);
592
744
  }
745
+ const rawMax = toast.options.maxToasts;
746
+ const maxToasts = typeof rawMax === "number" && Number.isFinite(rawMax) && rawMax > 0 ? Math.min(50, Math.max(1, Math.floor(rawMax))) : 5;
593
747
  if (toast.options.replace && list.length > 0) {
594
748
  const existing = [...list];
595
749
  const token = (this.replaceTokens.get(position) || 0) + 1;
@@ -599,14 +753,17 @@ var __WulfIIFE = (() => {
599
753
  Promise.all(promises).then(() => {
600
754
  this.pendingReplacements.delete(position);
601
755
  if (this.replaceTokens.get(position) !== token) {
756
+ toast.destroyImmediate("replace");
602
757
  return;
603
758
  }
604
- this.mountToast(toast, position, 5);
759
+ this.mountToast(toast, position, maxToasts);
605
760
  });
606
761
  return;
607
762
  }
608
- const rawMax = toast.options.maxToasts;
609
- const maxToasts = typeof rawMax === "number" && Number.isFinite(rawMax) && rawMax > 0 ? Math.min(50, Math.max(1, Math.floor(rawMax))) : 5;
763
+ if (this.pendingReplacements.has(position)) {
764
+ this.replaceTokens.set(position, (this.replaceTokens.get(position) || 0) + 1);
765
+ this.pendingReplacements.delete(position);
766
+ }
610
767
  if (list.length >= maxToasts) {
611
768
  const countToRemove = list.length - maxToasts + 1;
612
769
  const oldestItems = list.splice(0, countToRemove);
@@ -617,10 +774,12 @@ var __WulfIIFE = (() => {
617
774
  this.mountToast(toast, position, maxToasts);
618
775
  }
619
776
  /**
620
- * Insère l'élément toast dans le DOM et déclenche les callbacks et compteurs.
777
+ * Insère l'élément toast dans le conteneur Top Layer, annonce le message et démarre le minuteur.
621
778
  */
622
779
  mountToast(toast, position, maxToasts = 5) {
623
- const container = this.getOrCreateContainer(position);
780
+ if (toast.isClosed) return;
781
+ const useTopLayer = toast.options.useTopLayer ?? true;
782
+ const container = this.getOrCreateContainer(position, toast, useTopLayer);
624
783
  let list = this.activeToasts.get(position);
625
784
  if (!list) {
626
785
  list = [];
@@ -636,8 +795,19 @@ var __WulfIIFE = (() => {
636
795
  }
637
796
  }
638
797
  }
798
+ if (useTopLayer && typeof container.showPopover === "function" && container.getAttribute("popover") === "manual") {
799
+ try {
800
+ const popoverEl = container;
801
+ if (!this.isPopoverOpen(container)) {
802
+ popoverEl.showPopover();
803
+ }
804
+ } catch {
805
+ container.removeAttribute("popover");
806
+ }
807
+ }
639
808
  container.appendChild(toast.element);
640
809
  list.push(toast);
810
+ this.announce(toast);
641
811
  if (toast.options.onOpen) {
642
812
  try {
643
813
  toast.options.onOpen(toast);
@@ -647,6 +817,142 @@ var __WulfIIFE = (() => {
647
817
  }
648
818
  toast.startTimer();
649
819
  }
820
+ /**
821
+ * Annonce la notification sur un canal unique pour éviter les doubles lectures AT.
822
+ */
823
+ announce(toast) {
824
+ const parts = [toast.options.title, toast.options.message].filter((val) => typeof val === "string" && val.trim().length > 0).map((val) => val.trim());
825
+ if (parts.length === 0) return;
826
+ const rawText = parts.join(". ");
827
+ const text = rawText.length > 512 ? `${rawText.slice(0, 509)}...` : rawText;
828
+ const isAlert = toast.options.role === "alert";
829
+ const docWithAriaNotify = document;
830
+ if (typeof docWithAriaNotify.ariaNotify === "function") {
831
+ try {
832
+ docWithAriaNotify.ariaNotify(text, { priority: isAlert ? "high" : "normal" });
833
+ return;
834
+ } catch {
835
+ }
836
+ }
837
+ const wasCreated = !this.announcerEl || !this.announcerEl.isConnected;
838
+ this.ensureAnnouncer();
839
+ const region = isAlert ? this.assertiveRegion : this.politeRegion;
840
+ if (!region) return;
841
+ if (isAlert) {
842
+ if (this.assertiveAnnounceTimerId !== null) {
843
+ window.clearTimeout(this.assertiveAnnounceTimerId);
844
+ this.assertiveAnnounceTimerId = null;
845
+ }
846
+ if (this.assertiveClearTimerId !== null) {
847
+ window.clearTimeout(this.assertiveClearTimerId);
848
+ this.assertiveClearTimerId = null;
849
+ }
850
+ } else {
851
+ if (this.politeAnnounceTimerId !== null) {
852
+ window.clearTimeout(this.politeAnnounceTimerId);
853
+ this.politeAnnounceTimerId = null;
854
+ }
855
+ if (this.politeClearTimerId !== null) {
856
+ window.clearTimeout(this.politeClearTimerId);
857
+ this.politeClearTimerId = null;
858
+ }
859
+ }
860
+ region.textContent = "";
861
+ const lastText = isAlert ? this.lastAssertiveText : this.lastPoliteText;
862
+ let finalMessage = text;
863
+ if (text === lastText) {
864
+ this.announcerToggle = !this.announcerToggle;
865
+ finalMessage = this.announcerToggle ? `${text}\xA0` : text;
866
+ } else {
867
+ this.announcerToggle = false;
868
+ }
869
+ if (isAlert) {
870
+ this.lastAssertiveText = text;
871
+ } else {
872
+ this.lastPoliteText = text;
873
+ }
874
+ const delay = wasCreated ? 120 : 50;
875
+ const timerId = window.setTimeout(() => {
876
+ const idx = this.announceTimers.indexOf(timerId);
877
+ if (idx !== -1) this.announceTimers.splice(idx, 1);
878
+ if (isAlert) {
879
+ this.assertiveAnnounceTimerId = null;
880
+ } else {
881
+ this.politeAnnounceTimerId = null;
882
+ }
883
+ if (region.isConnected) {
884
+ region.textContent = finalMessage;
885
+ const clearId = window.setTimeout(() => {
886
+ const cIdx = this.announceTimers.indexOf(clearId);
887
+ if (cIdx !== -1) this.announceTimers.splice(cIdx, 1);
888
+ if (region.isConnected && region.textContent === finalMessage) {
889
+ region.textContent = "";
890
+ }
891
+ }, 4e3);
892
+ this.announceTimers.push(clearId);
893
+ if (isAlert) {
894
+ this.assertiveClearTimerId = clearId;
895
+ } else {
896
+ this.politeClearTimerId = clearId;
897
+ }
898
+ }
899
+ }, delay);
900
+ this.announceTimers.push(timerId);
901
+ if (isAlert) {
902
+ this.assertiveAnnounceTimerId = timerId;
903
+ } else {
904
+ this.politeAnnounceTimerId = timerId;
905
+ }
906
+ }
907
+ /**
908
+ * Crée ou reconnecte le conteneur persistant des annonces ARIA hors du popover.
909
+ */
910
+ ensureAnnouncer() {
911
+ if (this.announcerEl && document.body.contains(this.announcerEl)) {
912
+ return;
913
+ }
914
+ const wrapper = document.createElement("div");
915
+ wrapper.className = "wulf-toast-announcer";
916
+ wrapper.setAttribute("data-wulf-toast-announcer", "true");
917
+ const polite = document.createElement("div");
918
+ polite.setAttribute("role", "status");
919
+ polite.setAttribute("aria-live", "polite");
920
+ polite.setAttribute("aria-atomic", "true");
921
+ const assertive = document.createElement("div");
922
+ assertive.setAttribute("role", "alert");
923
+ assertive.setAttribute("aria-live", "assertive");
924
+ assertive.setAttribute("aria-atomic", "true");
925
+ wrapper.appendChild(polite);
926
+ wrapper.appendChild(assertive);
927
+ document.body.appendChild(wrapper);
928
+ this.announcerEl = wrapper;
929
+ this.politeRegion = polite;
930
+ this.assertiveRegion = assertive;
931
+ }
932
+ /**
933
+ * Transfère le focus avant de retirer un toast focalisé pour éviter que le focus ne retombe sur <body>.
934
+ */
935
+ handleFocusHandoff(toast, list) {
936
+ if (!toast.element.contains(document.activeElement)) {
937
+ return;
938
+ }
939
+ for (let i = list.length - 1; i >= 0; i--) {
940
+ const sibling = list[i];
941
+ if (sibling === toast || sibling.isClosed || !sibling.element.isConnected) continue;
942
+ const target = sibling.element.querySelector(FOCUSABLE_IN_TOAST);
943
+ if (target) {
944
+ target.focus({ preventScroll: true });
945
+ return;
946
+ }
947
+ }
948
+ const prev = toast.getPreviousActiveElement();
949
+ if (prev && prev.isConnected && typeof prev.focus === "function" && !prev.disabled && !prev.closest("[inert]") && prev.getAttribute("aria-hidden") !== "true") {
950
+ try {
951
+ prev.focus();
952
+ } catch {
953
+ }
954
+ }
955
+ }
650
956
  /**
651
957
  * Retire une notification de la pile et nettoie le conteneur s'il est vide.
652
958
  */
@@ -658,16 +964,32 @@ var __WulfIIFE = (() => {
658
964
  if (index !== -1) {
659
965
  list.splice(index, 1);
660
966
  }
967
+ this.handleFocusHandoff(toast, list);
968
+ if (toast.element.parentNode) {
969
+ toast.element.parentNode.removeChild(toast.element);
970
+ }
661
971
  if (list.length === 0 && !this.pendingReplacements.has(position)) {
662
972
  const container = this.containers.get(position);
663
973
  if (container && (!container.firstChild || container.children.length === 0)) {
664
- if (container.parentNode) {
665
- container.parentNode.removeChild(container);
666
- }
974
+ this.disposeContainer(container);
667
975
  this.containers.delete(position);
668
976
  this.activeToasts.delete(position);
669
977
  }
670
978
  }
979
+ } else if (toast.element.parentNode) {
980
+ toast.element.parentNode.removeChild(toast.element);
981
+ }
982
+ }
983
+ disposeContainer(container) {
984
+ try {
985
+ const popoverEl = container;
986
+ if (typeof popoverEl.hidePopover === "function" && this.isPopoverOpen(container)) {
987
+ popoverEl.hidePopover();
988
+ }
989
+ } catch {
990
+ }
991
+ if (container.parentNode) {
992
+ container.parentNode.removeChild(container);
671
993
  }
672
994
  }
673
995
  /**
@@ -676,6 +998,8 @@ var __WulfIIFE = (() => {
676
998
  clearAll(position) {
677
999
  const promises = [];
678
1000
  if (position) {
1001
+ this.replaceTokens.set(position, (this.replaceTokens.get(position) || 0) + 1);
1002
+ this.pendingReplacements.delete(position);
679
1003
  const list = this.activeToasts.get(position);
680
1004
  if (list && list.length > 0) {
681
1005
  const copy = [...list];
@@ -685,14 +1009,24 @@ var __WulfIIFE = (() => {
685
1009
  } else {
686
1010
  const container = this.containers.get(position);
687
1011
  if (container && (!container.firstChild || container.children.length === 0)) {
688
- if (container.parentNode) {
689
- container.parentNode.removeChild(container);
690
- }
1012
+ this.disposeContainer(container);
691
1013
  this.containers.delete(position);
692
1014
  this.activeToasts.delete(position);
693
1015
  }
694
1016
  }
695
1017
  } else {
1018
+ for (const pos of this.replaceTokens.keys()) {
1019
+ this.replaceTokens.set(pos, (this.replaceTokens.get(pos) || 0) + 1);
1020
+ }
1021
+ this.pendingReplacements.clear();
1022
+ for (const timerId of this.announceTimers) {
1023
+ window.clearTimeout(timerId);
1024
+ }
1025
+ this.announceTimers = [];
1026
+ this.politeAnnounceTimerId = null;
1027
+ this.assertiveAnnounceTimerId = null;
1028
+ this.politeClearTimerId = null;
1029
+ this.assertiveClearTimerId = null;
696
1030
  const allPositions = /* @__PURE__ */ new Set([
697
1031
  ...Array.from(this.containers.keys()),
698
1032
  ...Array.from(this.activeToasts.keys())
@@ -705,9 +1039,7 @@ var __WulfIIFE = (() => {
705
1039
  if (!position) {
706
1040
  for (const [pos, container] of Array.from(this.containers.entries())) {
707
1041
  if (!container.firstChild || container.children.length === 0) {
708
- if (container.parentNode) {
709
- container.parentNode.removeChild(container);
710
- }
1042
+ this.disposeContainer(container);
711
1043
  this.containers.delete(pos);
712
1044
  this.activeToasts.delete(pos);
713
1045
  }
@@ -715,27 +1047,58 @@ var __WulfIIFE = (() => {
715
1047
  }
716
1048
  });
717
1049
  }
1050
+ /**
1051
+ * Détruit immédiatement tous les toasts, conteneurs, annonceurs ARIA et temporisations en cours.
1052
+ */
1053
+ destroy() {
1054
+ for (const timerId of this.announceTimers) {
1055
+ window.clearTimeout(timerId);
1056
+ }
1057
+ this.announceTimers = [];
1058
+ for (const list of Array.from(this.activeToasts.values())) {
1059
+ for (const toast of [...list]) {
1060
+ toast.destroyImmediate("programmatic");
1061
+ }
1062
+ }
1063
+ for (const container of Array.from(this.containers.values())) {
1064
+ this.disposeContainer(container);
1065
+ }
1066
+ this.containers.clear();
1067
+ this.activeToasts.clear();
1068
+ this.replaceTokens.clear();
1069
+ this.pendingReplacements.clear();
1070
+ if (this.announcerEl) {
1071
+ this.announcerEl.remove();
1072
+ this.announcerEl = null;
1073
+ this.politeRegion = null;
1074
+ this.assertiveRegion = null;
1075
+ }
1076
+ _ToastManager.instance = null;
1077
+ }
718
1078
  /**
719
1079
  * Récupère ou crée le conteneur DOM pour une position d'affichage.
720
1080
  */
721
- getOrCreateContainer(position) {
1081
+ getOrCreateContainer(position, toast, useTopLayer) {
722
1082
  let container = this.containers.get(position);
723
1083
  if (!container || !document.body.contains(container)) {
724
1084
  container = document.createElement("div");
725
1085
  container.className = `wulf-toast-container wulf-toast-${position}`;
726
- container.setAttribute("aria-live", "polite");
727
- container.setAttribute("aria-relevant", "additions removals");
1086
+ container.setAttribute("role", "region");
1087
+ container.setAttribute("aria-label", toastI18n.t("notificationsRegion", toast.options.i18n));
1088
+ if (useTopLayer && typeof container.showPopover === "function") {
1089
+ container.setAttribute("popover", "manual");
1090
+ }
728
1091
  document.body.appendChild(container);
729
1092
  this.containers.set(position, container);
730
1093
  }
731
1094
  return container;
732
1095
  }
733
1096
  };
734
- _ToastManager.instance = null;
735
- var ToastManager = _ToastManager;
736
1097
 
737
1098
  // src/toast/Toast.ts
738
1099
  var Toast = class extends LocalizedComponent {
1100
+ static _i18n = toastI18n;
1101
+ static i18n = toastI18n;
739
1102
  audit() {
740
1103
  return [];
741
1104
  }
@@ -762,16 +1125,18 @@ var __WulfIIFE = (() => {
762
1125
  static clearAll(position) {
763
1126
  return ToastManager.getInstance().clearAll(position);
764
1127
  }
1128
+ /**
1129
+ * Détruit le gestionnaire de notifications (conteneurs, annonceurs ARIA et timers).
1130
+ */
1131
+ static destroy() {
1132
+ ToastManager.getInstance().destroy();
1133
+ }
765
1134
  };
766
- Toast._i18n = toastI18n;
767
- Toast.i18n = toastI18n;
768
1135
 
769
1136
  // src/toast/index.ts
770
1137
  var index_default = Toast;
771
- if (typeof window !== "undefined") {
772
- const win = window;
773
- const wulfNamespace = win.Wulf || {};
774
- win.Wulf = wulfNamespace;
1138
+ var wulfNamespace = getSafeWulfNamespace();
1139
+ if (wulfNamespace) {
775
1140
  wulfNamespace.Toast = Object.assign(Toast, {
776
1141
  Toast,
777
1142
  i18n: toastI18n
@@ -779,5 +1144,5 @@ var __WulfIIFE = (() => {
779
1144
  }
780
1145
  return __toCommonJS(index_exports);
781
1146
  })();
782
- if (typeof window !== "undefined") { window.Wulf = window.Wulf || {}; if (typeof __WulfIIFE !== "undefined" && __WulfIIFE) { for (var k in __WulfIIFE) { if (Object.prototype.hasOwnProperty.call(__WulfIIFE, k) && k !== "__proto__" && k !== "constructor" && k !== "prototype" && window.Wulf[k] === undefined) { try { Object.defineProperty(window.Wulf, k, { value: __WulfIIFE[k], writable: true, configurable: true, enumerable: true }); } catch (_) { try { window.Wulf[k] = __WulfIIFE[k]; } catch (__) {} } } } } }
1147
+ if (typeof window !== "undefined") { var __w = window.Wulf; if (!__w || typeof __w !== "object" || (typeof Node !== "undefined" && __w instanceof Node) || (typeof HTMLCollection !== "undefined" && __w instanceof HTMLCollection)) { __w = {}; window.Wulf = __w; } if (typeof __WulfIIFE !== "undefined" && __WulfIIFE) { for (var k in __WulfIIFE) { if (Object.hasOwn(__WulfIIFE, k) && k !== "__proto__" && k !== "constructor" && k !== "prototype" && __w[k] === undefined) { try { Object.defineProperty(__w, k, { value: __WulfIIFE[k], writable: true, configurable: true, enumerable: true }); } catch (_) { try { __w[k] = __WulfIIFE[k]; } catch (__) {} } } } } }
783
1148
  //# sourceMappingURL=toast.global.js.map