wulf.js 2.1.1 → 2.2.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 (146) hide show
  1. package/README.md +217 -11
  2. package/changelog.md +50 -0
  3. package/dist/anchor.esm.js +9 -0
  4. package/dist/anchor.esm.js.map +7 -0
  5. package/dist/anchor.global.js +695 -0
  6. package/dist/anchor.global.js.map +7 -0
  7. package/dist/anchor.global.min.js +6 -0
  8. package/dist/anchor.global.min.js.map +7 -0
  9. package/dist/autosize.css +1 -0
  10. package/dist/autosize.css.map +7 -0
  11. package/dist/autosize.esm.js +10 -0
  12. package/dist/autosize.esm.js.map +7 -0
  13. package/dist/autosize.global.js +657 -0
  14. package/dist/autosize.global.js.map +7 -0
  15. package/dist/autosize.global.min.js +6 -0
  16. package/dist/autosize.global.min.js.map +7 -0
  17. package/dist/autosize.layered.css +1 -0
  18. package/dist/autosize.layered.css.map +7 -0
  19. package/dist/chunks/chunk-22AIMRD5.js +119 -0
  20. package/dist/chunks/chunk-22AIMRD5.js.map +7 -0
  21. package/dist/chunks/chunk-5N2IRGDM.js +766 -0
  22. package/dist/chunks/chunk-5N2IRGDM.js.map +7 -0
  23. package/dist/chunks/chunk-72FVCNNZ.js +863 -0
  24. package/dist/chunks/chunk-72FVCNNZ.js.map +7 -0
  25. package/dist/chunks/chunk-AXZYYW7H.js +865 -0
  26. package/dist/chunks/chunk-AXZYYW7H.js.map +7 -0
  27. package/dist/chunks/chunk-CM3SBIVQ.js +1116 -0
  28. package/dist/chunks/chunk-CM3SBIVQ.js.map +7 -0
  29. package/dist/chunks/chunk-H4GRLGQ3.js +578 -0
  30. package/dist/chunks/chunk-H4GRLGQ3.js.map +7 -0
  31. package/dist/chunks/chunk-ITRU2RFV.js +1195 -0
  32. package/dist/chunks/chunk-ITRU2RFV.js.map +7 -0
  33. package/dist/chunks/chunk-NLUQZEL4.js +1029 -0
  34. package/dist/chunks/chunk-NLUQZEL4.js.map +7 -0
  35. package/dist/chunks/chunk-QV46A7FV.js +197 -0
  36. package/dist/chunks/chunk-QV46A7FV.js.map +7 -0
  37. package/dist/chunks/chunk-SXLUXN6W.js +612 -0
  38. package/dist/chunks/chunk-SXLUXN6W.js.map +7 -0
  39. package/dist/chunks/chunk-T2H4EJCW.js +621 -0
  40. package/dist/chunks/chunk-T2H4EJCW.js.map +7 -0
  41. package/dist/chunks/chunk-TILLYEF2.js +6044 -0
  42. package/dist/chunks/chunk-TILLYEF2.js.map +7 -0
  43. package/dist/chunks/chunk-VJO22BAT.js +72 -0
  44. package/dist/chunks/chunk-VJO22BAT.js.map +7 -0
  45. package/dist/chunks/chunk-ZGUU6DMM.js +77 -0
  46. package/dist/chunks/chunk-ZGUU6DMM.js.map +7 -0
  47. package/dist/focus-trap.esm.js +6 -594
  48. package/dist/focus-trap.esm.js.map +3 -3
  49. package/dist/focus-trap.global.js +176 -61
  50. package/dist/focus-trap.global.js.map +3 -3
  51. package/dist/focus-trap.global.min.js +4 -4
  52. package/dist/focus-trap.global.min.js.map +4 -4
  53. package/dist/index.esm.js +79 -10448
  54. package/dist/index.esm.js.map +4 -4
  55. package/dist/index.global.js +3660 -202
  56. package/dist/index.global.js.map +4 -4
  57. package/dist/index.global.min.js +6 -3
  58. package/dist/index.global.min.js.map +4 -4
  59. package/dist/mask.esm.js +16 -6094
  60. package/dist/mask.esm.js.map +4 -4
  61. package/dist/mask.global.js +44 -55
  62. package/dist/mask.global.js.map +3 -3
  63. package/dist/mask.global.min.js +3 -3
  64. package/dist/mask.global.min.js.map +4 -4
  65. package/dist/masonry.esm.js +15 -1158
  66. package/dist/masonry.esm.js.map +4 -4
  67. package/dist/masonry.global.js +84 -94
  68. package/dist/masonry.global.js.map +3 -3
  69. package/dist/masonry.global.min.js +4 -4
  70. package/dist/masonry.global.min.js.map +4 -4
  71. package/dist/scroll.css +1 -1
  72. package/dist/scroll.css.map +2 -2
  73. package/dist/scroll.esm.js +14 -1252
  74. package/dist/scroll.esm.js.map +3 -3
  75. package/dist/scroll.global.js +64 -58
  76. package/dist/scroll.global.js.map +3 -3
  77. package/dist/scroll.global.min.js +3 -3
  78. package/dist/scroll.global.min.js.map +4 -4
  79. package/dist/scroll.layered.css +1 -1
  80. package/dist/scroll.layered.css.map +2 -2
  81. package/dist/shortcut.esm.js +6 -901
  82. package/dist/shortcut.esm.js.map +4 -4
  83. package/dist/shortcut.global.js +43 -36
  84. package/dist/shortcut.global.js.map +3 -3
  85. package/dist/shortcut.global.min.js +6 -3
  86. package/dist/shortcut.global.min.js.map +4 -4
  87. package/dist/size-report.json +319 -0
  88. package/dist/sortable.css +1 -0
  89. package/dist/sortable.css.map +7 -0
  90. package/dist/sortable.esm.js +22 -0
  91. package/dist/sortable.esm.js.map +7 -0
  92. package/dist/sortable.global.js +1477 -0
  93. package/dist/sortable.global.js.map +7 -0
  94. package/dist/sortable.global.min.js +6 -0
  95. package/dist/sortable.global.min.js.map +7 -0
  96. package/dist/sortable.layered.css +1 -0
  97. package/dist/sortable.layered.css.map +7 -0
  98. package/dist/sri-manifest.json +64 -0
  99. package/dist/toast.css +1 -1
  100. package/dist/toast.css.map +2 -2
  101. package/dist/toast.esm.js +19 -1208
  102. package/dist/toast.esm.js.map +3 -3
  103. package/dist/toast.global.js +314 -111
  104. package/dist/toast.global.js.map +3 -3
  105. package/dist/toast.global.min.js +3 -3
  106. package/dist/toast.global.min.js.map +4 -4
  107. package/dist/toast.layered.css +1 -1
  108. package/dist/toast.layered.css.map +2 -2
  109. package/dist/types/anchor/Anchor.d.ts +41 -0
  110. package/dist/types/anchor/index.d.ts +3 -0
  111. package/dist/types/anchor/types.d.ts +115 -0
  112. package/dist/types/autosize/Autosize.d.ts +71 -0
  113. package/dist/types/autosize/index.d.ts +3 -0
  114. package/dist/types/autosize/types.d.ts +66 -0
  115. package/dist/types/common/AuditableComponent.d.ts +1 -1
  116. package/dist/types/common/registry.d.ts +40 -0
  117. package/dist/types/focus-trap/FocusTrap.d.ts +3 -1
  118. package/dist/types/index.d.ts +13 -1
  119. package/dist/types/scroll/types.d.ts +6 -0
  120. package/dist/types/shortcut/ShortcutManager.d.ts +2 -0
  121. package/dist/types/shortcut/types.d.ts +5 -0
  122. package/dist/types/sortable/Sortable.d.ts +75 -0
  123. package/dist/types/sortable/i18n/en.d.ts +2 -0
  124. package/dist/types/sortable/i18n/fr.d.ts +2 -0
  125. package/dist/types/sortable/i18n/index.d.ts +9 -0
  126. package/dist/types/sortable/i18n/types.d.ts +15 -0
  127. package/dist/types/sortable/index.d.ts +4 -0
  128. package/dist/types/sortable/types.d.ts +112 -0
  129. package/dist/types/toast/Toast.d.ts +6 -1
  130. package/dist/types/toast/ToastInstance.d.ts +7 -0
  131. package/dist/types/toast/ToastManager.d.ts +2 -2
  132. package/dist/types/toast/types.d.ts +27 -1
  133. package/dist/types/undo/UndoManager.d.ts +112 -0
  134. package/dist/types/undo/i18n/en.d.ts +2 -0
  135. package/dist/types/undo/i18n/fr.d.ts +2 -0
  136. package/dist/types/undo/i18n/index.d.ts +9 -0
  137. package/dist/types/undo/i18n/types.d.ts +6 -0
  138. package/dist/types/undo/index.d.ts +5 -0
  139. package/dist/types/undo/types.d.ts +106 -0
  140. package/dist/undo.esm.js +23 -0
  141. package/dist/undo.esm.js.map +7 -0
  142. package/dist/undo.global.js +1029 -0
  143. package/dist/undo.global.js.map +7 -0
  144. package/dist/undo.global.min.js +6 -0
  145. package/dist/undo.global.min.js.map +7 -0
  146. package/package.json +54 -5
package/dist/toast.esm.js CHANGED
@@ -1,1217 +1,28 @@
1
- // src/common/dom.ts
2
- function getSafeWulfNamespace() {
3
- if (typeof window === "undefined") return null;
4
- const win = window;
5
- const existing = win.Wulf;
6
- if (!existing || typeof existing !== "object" || typeof Node !== "undefined" && existing instanceof Node || typeof HTMLCollection !== "undefined" && existing instanceof HTMLCollection) {
7
- const fresh = {};
8
- win.Wulf = fresh;
9
- return fresh;
10
- }
11
- return existing;
12
- }
13
- function stripBidiAndInvisibles(raw, maxLength = 4096) {
14
- const safeLimit = Math.max(0, maxLength);
15
- return String(raw ?? "").slice(0, safeLimit).replace(/[\u061C\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g, "");
16
- }
17
- function getDeepActiveElement(root) {
18
- if (typeof document === "undefined") return null;
19
- let active = (root ?? document).activeElement;
20
- while (active && active.shadowRoot && active.shadowRoot.activeElement) {
21
- active = active.shadowRoot.activeElement;
22
- }
23
- return active && typeof active.focus === "function" ? active : null;
24
- }
25
- function isImeComposing(event) {
26
- return Boolean(
27
- event.isComposing || event.key === "Process" || event.key === "Enter" && event.keyCode === 229
28
- );
29
- }
30
- function prefersReducedMotion() {
31
- return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
32
- }
33
- function waitForAnimations(element, fallbackMs, signal) {
34
- const safeFallback = Number.isFinite(fallbackMs) ? Math.min(fallbackMs, 6e4) : 300;
35
- if (signal?.aborted || safeFallback <= 0 || prefersReducedMotion()) {
36
- return Promise.resolve();
37
- }
38
- const animations = typeof element.getAnimations === "function" ? element.getAnimations().filter((a) => {
39
- if (a.playState !== "running") return false;
40
- const timing = a.effect?.getComputedTiming?.();
41
- return timing ? Number.isFinite(timing.endTime) : true;
42
- }) : [];
43
- if (animations.length === 0) {
44
- return Promise.resolve();
45
- }
46
- return new Promise((resolve) => {
47
- let settled = false;
48
- let timerId = null;
49
- const finish = () => {
50
- if (settled) return;
51
- settled = true;
52
- if (timerId !== null) {
53
- clearTimeout(timerId);
54
- timerId = null;
55
- }
56
- signal?.removeEventListener("abort", finish);
57
- resolve();
58
- };
59
- signal?.addEventListener("abort", finish, { once: true });
60
- timerId = setTimeout(finish, safeFallback);
61
- Promise.allSettled(animations.map((a) => a.finished)).then(finish);
62
- });
63
- }
64
-
65
- // src/common/i18n.ts
66
- var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
67
- function isSafeKey(key) {
68
- return Boolean(key) && !FORBIDDEN_KEYS.has(key);
69
- }
70
- function normalizeLocaleCode(locale) {
71
- const norm = String(locale ?? "").trim().toLowerCase().replace(/_/g, "-");
72
- return isSafeKey(norm) ? norm : "";
73
- }
74
- function getPrimaryLanguage(normalizedLocale) {
75
- const dashIndex = normalizedLocale.indexOf("-");
76
- const primary = dashIndex > 0 ? normalizedLocale.slice(0, dashIndex) : null;
77
- return primary && isSafeKey(primary) ? primary : null;
78
- }
79
- function assignDefined(target, source) {
80
- if (!source || typeof source !== "object") return target;
81
- for (const key of Object.keys(source)) {
82
- if (isSafeKey(String(key)) && Object.hasOwn(source, key) && source[key] !== void 0) {
83
- target[key] = source[key];
84
- }
85
- }
86
- return target;
87
- }
88
- function createI18nManager(defaultLocale, locales) {
89
- const fallbackLocale = normalizeLocaleCode(defaultLocale) || "fr";
90
- const initialLocales = /* @__PURE__ */ Object.create(null);
91
- for (const [loc, dict] of Object.entries(locales)) {
92
- const norm = normalizeLocaleCode(loc);
93
- if (norm) {
94
- initialLocales[norm] = assignDefined(/* @__PURE__ */ Object.create(null), dict);
95
- }
96
- }
97
- let currentLocale = fallbackLocale;
98
- let activeLocales = /* @__PURE__ */ Object.create(null);
99
- for (const [loc, dict] of Object.entries(initialLocales)) {
100
- activeLocales[loc] = assignDefined(/* @__PURE__ */ Object.create(null), dict);
101
- }
102
- let globalOverrides = /* @__PURE__ */ Object.create(null);
103
- function resolveActiveDictionaries() {
104
- const dicts = [];
105
- if (isSafeKey(currentLocale)) {
106
- const exact = activeLocales[currentLocale];
107
- if (exact) dicts.push(exact);
108
- }
109
- const primary = getPrimaryLanguage(currentLocale);
110
- if (primary && activeLocales[primary]) {
111
- dicts.push(activeLocales[primary]);
112
- }
113
- return dicts;
114
- }
115
- return {
116
- setLocale(locale) {
117
- if (locale && typeof locale === "string" && locale.trim()) {
118
- const norm = normalizeLocaleCode(locale);
119
- if (norm) {
120
- currentLocale = norm;
121
- }
122
- }
123
- },
124
- getLocale() {
125
- return currentLocale;
126
- },
127
- registerLocale(locale, translations) {
128
- if (!locale || typeof locale !== "string" || !locale.trim() || !translations) return;
129
- const norm = normalizeLocaleCode(locale);
130
- if (!norm) return;
131
- const base = assignDefined(/* @__PURE__ */ Object.create(null), activeLocales[norm]);
132
- activeLocales[norm] = assignDefined(base, translations);
133
- },
134
- setI18n(overrides) {
135
- if (!overrides || typeof overrides !== "object") return;
136
- const base = assignDefined(/* @__PURE__ */ Object.create(null), globalOverrides);
137
- globalOverrides = assignDefined(base, overrides);
138
- },
139
- t(key, instanceOverride) {
140
- if (!isSafeKey(String(key))) {
141
- return "";
142
- }
143
- if (instanceOverride && typeof instanceOverride === "object" && Object.hasOwn(instanceOverride, key) && instanceOverride[key] !== void 0) {
144
- return String(instanceOverride[key]);
145
- }
146
- if (globalOverrides[key] !== void 0) {
147
- return String(globalOverrides[key]);
148
- }
149
- for (const dict of resolveActiveDictionaries()) {
150
- if (dict[key] !== void 0) {
151
- return String(dict[key]);
152
- }
153
- }
154
- const fallbackDict = activeLocales[fallbackLocale] || initialLocales[fallbackLocale];
155
- if (fallbackDict && fallbackDict[key] !== void 0) {
156
- return String(fallbackDict[key]);
157
- }
158
- return String(key);
159
- },
160
- getAll(instanceOverride) {
161
- const result = {};
162
- const fallback = activeLocales[fallbackLocale] || initialLocales[fallbackLocale];
163
- assignDefined(result, fallback);
164
- const activeDicts = resolveActiveDictionaries().reverse();
165
- for (const dict of activeDicts) {
166
- assignDefined(result, dict);
167
- }
168
- assignDefined(result, globalOverrides);
169
- assignDefined(result, instanceOverride);
170
- return result;
171
- },
172
- reset() {
173
- currentLocale = fallbackLocale;
174
- globalOverrides = /* @__PURE__ */ Object.create(null);
175
- activeLocales = /* @__PURE__ */ Object.create(null);
176
- for (const [loc, dict] of Object.entries(initialLocales)) {
177
- activeLocales[loc] = assignDefined(/* @__PURE__ */ Object.create(null), dict);
178
- }
179
- }
180
- };
181
- }
182
-
183
- // src/common/AuditableComponent.ts
184
- var AuditableComponent = class {
185
- /**
186
- * Indication affichée en pied de warning pour expliquer comment désactiver l'audit.
187
- */
188
- getAuditDisableHint() {
189
- return "Passez { audit: false } dans les options pour d\xE9sactiver cet avertissement";
190
- }
191
- /**
192
- * Exécute l'audit d'accessibilité et émet un avertissement standardisé dans la console
193
- * si l'audit est activé et que des contraintes manquent.
194
- */
195
- runAuditWarning(enabled = true) {
196
- if (!enabled) return [];
197
- const warnings = this.audit();
198
- if (warnings.length > 0 && typeof console !== "undefined" && typeof console.warn === "function") {
199
- console.warn(
200
- `[${this.getAuditPrefix()}] Audit d'accessibilit\xE9 \u2014 ${warnings.length} contrainte(s) manquante(s) sur ${this.getAuditTargetLabel()} :
201
- ` + warnings.map((w) => ` - ${w}`).join("\n") + `
202
- (${this.getAuditDisableHint()})`
203
- );
204
- }
205
- return warnings;
206
- }
207
- /**
208
- * Vérifie si un attribut de référence d'IDs ARIA (ex: aria-labelledby, aria-describedby, aria-errormessage)
209
- * pointe vers des éléments réellement présents dans le document (et optionnellement non vides).
210
- */
211
- checkAriaIdReferences(element, attrName, warnings, requireNonEmptyText = false) {
212
- const rawValue = element.getAttribute(attrName)?.trim();
213
- if (!rawValue) return false;
214
- const doc = element.ownerDocument || document;
215
- const root = typeof element.getRootNode === "function" ? element.getRootNode() : doc;
216
- const ids = rawValue.split(/\s+/).filter(Boolean);
217
- const targets = ids.map(
218
- (id) => typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot ? root.getElementById(id) : doc.getElementById(id)
219
- );
220
- const allFound = ids.length > 0 && targets.every((el) => Boolean(el));
221
- if (!allFound) {
222
- warnings.push(
223
- `Attribut ${attrName}="${rawValue}" invalide : l'\xE9l\xE9ment cible est introuvable dans le DOM.`
224
- );
225
- return false;
226
- }
227
- if (requireNonEmptyText) {
228
- const hasNonEmptyText = targets.some((el) => {
229
- if (!el) return false;
230
- const text = el.textContent?.trim() || el.getAttribute("aria-label")?.trim() || "";
231
- return text.length > 0;
232
- });
233
- if (!hasNonEmptyText) {
234
- warnings.push(
235
- `Attribut ${attrName}="${rawValue}" invalide : l'\xE9l\xE9ment cible ne contient aucun texte accessible.`
236
- );
237
- return false;
238
- }
239
- }
240
- return true;
241
- }
242
- };
243
-
244
- // src/common/LocalizedComponent.ts
245
- var LocalizedComponent = class extends AuditableComponent {
246
- static _i18n;
247
- /**
248
- * Définit la langue globale du composant (ex: 'fr', 'en', 'es').
249
- */
250
- static setLocale(locale) {
251
- if (this._i18n) {
252
- this._i18n.setLocale(locale);
253
- }
254
- }
255
- /**
256
- * Retourne la langue globale active du composant.
257
- */
258
- static getLocale() {
259
- return this._i18n ? this._i18n.getLocale() : "";
260
- }
261
- /**
262
- * Enregistre un dictionnaire de traduction pour une langue donnée.
263
- */
264
- static registerLocale(locale, translations) {
265
- if (this._i18n) {
266
- this._i18n.registerLocale(locale, translations);
267
- }
268
- }
269
- /**
270
- * Surcharge les libellés globalement pour ce composant.
271
- */
272
- static setI18n(overrides) {
273
- if (this._i18n) {
274
- this._i18n.setI18n(overrides);
275
- }
276
- }
277
- /**
278
- * Retourne l'ensemble des libellés actifs résolus du composant.
279
- */
280
- static getI18n() {
281
- return this._i18n ? this._i18n.getAll() : {};
282
- }
283
- /**
284
- * Réinitialise les réglages de langue et surcharges globales.
285
- */
286
- static resetI18n() {
287
- if (this._i18n) {
288
- this._i18n.reset();
289
- }
290
- }
291
- /**
292
- * Résout une clé au niveau statique de la classe.
293
- */
294
- static t(key, instanceOverride) {
295
- return this._i18n ? this._i18n.t(key, instanceOverride) : String(key);
296
- }
297
- /**
298
- * Surcharges de localisation spécifiques à cette instance.
299
- */
300
- i18nOverrides;
301
- constructor(i18nOverrides) {
302
- super();
303
- this.i18nOverrides = i18nOverrides;
304
- }
305
- /**
306
- * Traduit une clé en tenant compte automatiquement des surcharges de l'instance courante.
307
- */
308
- t(key) {
309
- const ctor = this.constructor;
310
- return ctor._i18n ? ctor._i18n.t(key, this.i18nOverrides) : String(key);
311
- }
312
- };
313
-
314
- // src/toast/i18n/fr.ts
315
- var toastFr = {
316
- closeButton: "Fermer la notification",
317
- notificationsRegion: "Notifications"
318
- };
319
-
320
- // src/toast/i18n/en.ts
321
- var toastEn = {
322
- closeButton: "Close notification",
323
- notificationsRegion: "Notifications"
324
- };
325
-
326
- // src/toast/i18n/index.ts
327
- var toastI18n = createI18nManager("fr", {
328
- fr: toastFr,
329
- en: toastEn
330
- });
331
-
332
- // src/toast/ToastInstance.ts
333
- var nextToastId = 1;
334
- var DEFAULT_TOAST_DURATION = 5e3;
335
- var SAFE_COLOR_FALLBACK_RE = /^(?:#[0-9a-f]{3,8}|(?:rgb|rgba|hsl|hsla|oklch|oklab|lch|lab)\([^;{}<>\\]+\)|[a-z]{3,20})$/i;
336
- function isSafeCssValue(val) {
337
- if (!val || typeof val !== "string" || val.length > 128) return false;
338
- const trimmed = val.trim();
339
- if (!trimmed) return false;
340
- if (/[\u0000-\u001F\u007F;{}<>\\]|(?:url|image-set|-webkit-image-set|image|src|expression|attr|env|var)\s*\(/i.test(trimmed)) {
341
- return false;
342
- }
343
- if (typeof CSS !== "undefined" && typeof CSS.supports === "function") {
344
- return CSS.supports("color", trimmed) || CSS.supports("background-color", trimmed);
345
- }
346
- return SAFE_COLOR_FALLBACK_RE.test(trimmed);
347
- }
348
- function sanitizeIconClasses(icon) {
349
- return icon.slice(0, 128).trim().split(/\s+/).filter((token) => /^[a-zA-Z0-9_-]+$/.test(token) && !token.startsWith("wulf-toast")).slice(0, 8).join(" ");
350
- }
351
- var ToastInstance = class extends AuditableComponent {
352
- id;
353
- options;
354
- element;
355
- _isClosed = false;
356
- _isFinalized = false;
357
- closePromise = null;
358
- timerId = null;
359
- remainingTime = 0;
360
- hasDuration = false;
361
- timerStartTime = 0;
362
- isPausedByHover = false;
363
- isPausedByFocus = false;
364
- isPausedByVisibility = false;
365
- isPendingFocusDismiss = false;
366
- previousActiveElement = null;
367
- eventsAbortController = new AbortController();
368
- disposeAbortController = new AbortController();
369
- onDismissCallback;
370
- constructor(options, onDismiss) {
371
- super();
372
- this.id = `wulf-toast-${nextToastId++}`;
373
- this.options = Object.freeze({ ...options });
374
- this.onDismissCallback = onDismiss;
375
- this.previousActiveElement = getDeepActiveElement();
376
- const duration = options.duration === void 0 ? DEFAULT_TOAST_DURATION : options.duration;
377
- if (typeof duration === "number" && Number.isFinite(duration) && duration > 0) {
378
- this.remainingTime = Math.min(duration, 2147483647);
379
- this.hasDuration = true;
380
- } else {
381
- this.remainingTime = 0;
382
- this.hasDuration = false;
383
- }
384
- this.element = this.createDOM();
385
- this.bindEvents();
386
- this.runAuditWarning(options.audit !== false);
387
- }
388
- get isClosed() {
389
- return this._isClosed;
390
- }
391
- getPreviousActiveElement() {
392
- return this.previousActiveElement;
393
- }
394
- /**
395
- * Vérifie la conformité d'accessibilité WAI-ARIA de la notification Toast
396
- * et retourne la liste des contraintes manquantes.
397
- */
398
- audit() {
399
- const warnings = [];
400
- const hasTitle = Boolean(this.options.title && this.options.title.trim().length > 0);
401
- const hasMessage = Boolean(this.options.message && this.options.message.trim().length > 0);
402
- if (!hasTitle && !hasMessage) {
403
- warnings.push(
404
- "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)."
405
- );
406
- }
407
- const duration = this.options.duration === void 0 ? DEFAULT_TOAST_DURATION : this.options.duration;
408
- if (typeof duration === "number" && duration > 0 && duration < 5e3) {
409
- warnings.push(
410
- `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).`
411
- );
412
- }
413
- const closable = this.options.closable ?? true;
414
- const isPersistent = duration === false || typeof duration === "number" && duration <= 0;
415
- if (isPersistent && !closable) {
416
- warnings.push(
417
- "Notification persistante impossible \xE0 fermer au clavier : activez closable: true lorsque duration est d\xE9sactiv\xE9 (WCAG 2.1.1)."
418
- );
419
- }
420
- return warnings;
421
- }
422
- getAuditPrefix() {
423
- return "Wulf.Toast";
424
- }
425
- getAuditTargetLabel() {
426
- return `#${this.id}`;
427
- }
428
- /**
429
- * Construction du DOM de manière 100% sécurisée sans aucun `innerHTML`.
430
- * Les annonces sont gérées sur un canal unique dans `ToastManager` pour éviter tout doublon AT.
431
- */
432
- createDOM() {
433
- const el = document.createElement("div");
434
- el.id = this.id;
435
- el.className = "wulf-toast";
436
- el.setAttribute("data-toast-role", this.options.role === "alert" ? "alert" : "status");
437
- if (this.options.backgroundColor && isSafeCssValue(this.options.backgroundColor)) {
438
- el.style.setProperty("--wulf-toast-bg", this.options.backgroundColor.trim());
439
- }
440
- if (this.options.titleColor && isSafeCssValue(this.options.titleColor)) {
441
- el.style.setProperty("--wulf-toast-title-color", this.options.titleColor.trim());
442
- }
443
- if (this.options.textColor && isSafeCssValue(this.options.textColor)) {
444
- el.style.setProperty("--wulf-toast-text-color", this.options.textColor.trim());
445
- }
446
- if (this.options.iconColor && isSafeCssValue(this.options.iconColor)) {
447
- el.style.setProperty("--wulf-toast-icon-color", this.options.iconColor.trim());
448
- }
449
- if (this.options.closeButtonColor && isSafeCssValue(this.options.closeButtonColor)) {
450
- el.style.setProperty("--wulf-toast-close-color", this.options.closeButtonColor.trim());
451
- }
452
- if (this.options.icon && typeof this.options.icon === "string" && this.options.icon.trim() !== "") {
453
- const safeIcon = sanitizeIconClasses(this.options.icon);
454
- if (safeIcon) {
455
- const iconContainer = document.createElement("span");
456
- iconContainer.className = `wulf-toast-icon ${safeIcon}`;
457
- iconContainer.setAttribute("aria-hidden", "true");
458
- el.appendChild(iconContainer);
459
- }
460
- }
461
- const content = document.createElement("div");
462
- const isInteractiveContent = Boolean(this.options.onClick || this.options.closeOnClick);
463
- content.className = isInteractiveContent ? "wulf-toast-content wulf-toast-content--interactive" : "wulf-toast-content";
464
- if (isInteractiveContent) {
465
- content.setAttribute("role", "button");
466
- content.setAttribute("tabindex", "0");
467
- content.addEventListener("keydown", (e) => {
468
- if (isImeComposing(e)) return;
469
- if (e.key === "Enter") {
470
- e.preventDefault();
471
- e.stopPropagation();
472
- content.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
473
- } else if (e.key === " ") {
474
- e.preventDefault();
475
- e.stopPropagation();
476
- }
477
- }, { signal: this.eventsAbortController.signal });
478
- content.addEventListener("keyup", (e) => {
479
- if (e.key === " ") {
480
- e.preventDefault();
481
- e.stopPropagation();
482
- content.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
483
- }
484
- }, { signal: this.eventsAbortController.signal });
485
- }
486
- if (this.options.title && this.options.title.trim() !== "") {
487
- const titleEl = document.createElement("div");
488
- titleEl.className = "wulf-toast-title";
489
- this.appendTextWithLineBreaks(titleEl, this.options.title);
490
- content.appendChild(titleEl);
491
- }
492
- if (this.options.message && this.options.message.trim() !== "") {
493
- const messageEl = document.createElement("div");
494
- messageEl.className = "wulf-toast-message";
495
- this.appendTextWithLineBreaks(messageEl, this.options.message);
496
- content.appendChild(messageEl);
497
- }
498
- el.appendChild(content);
499
- const closable = this.options.closable ?? true;
500
- if (closable) {
501
- const closeBtn = document.createElement("button");
502
- closeBtn.type = "button";
503
- closeBtn.className = "wulf-toast-close";
504
- closeBtn.setAttribute("aria-label", toastI18n.t("closeButton", this.options.i18n));
505
- const closeIcon = document.createElement("span");
506
- closeIcon.className = "wulf-toast-close-icon";
507
- closeIcon.setAttribute("aria-hidden", "true");
508
- closeIcon.textContent = "\xD7";
509
- closeBtn.appendChild(closeIcon);
510
- closeBtn.addEventListener("click", (e) => {
511
- e.stopPropagation();
512
- this.close("close-button");
513
- }, { signal: this.eventsAbortController.signal });
514
- el.appendChild(closeBtn);
515
- }
516
- if (this.options.progressBar && this.remainingTime > 0) {
517
- el.style.setProperty("--wulf-toast-duration", `${this.remainingTime}ms`);
518
- const progressBar = document.createElement("div");
519
- progressBar.className = "wulf-toast-progress";
520
- progressBar.setAttribute("aria-hidden", "true");
521
- el.appendChild(progressBar);
522
- }
523
- return el;
524
- }
525
- /**
526
- * Injection de texte sécurisée gérant nativement les retours à la ligne (\n et \r\n).
527
- */
528
- appendTextWithLineBreaks(container, text) {
529
- const safeText = stripBidiAndInvisibles(String(text ?? ""), 4096);
530
- const lines = safeText.split(/\r\n|\r|\n/).slice(0, 100);
531
- lines.forEach((line, index) => {
532
- if (index > 0) {
533
- container.appendChild(document.createElement("br"));
534
- }
535
- container.appendChild(document.createTextNode(line));
536
- });
537
- }
538
- /**
539
- * Liaison des événements clavier, souris, visibilité d'onglet et pause au survol/focus (WCAG 2.2).
540
- */
541
- bindEvents() {
542
- const { signal } = this.eventsAbortController;
543
- this.element.addEventListener("click", (e) => {
544
- if (this.options.onClick) {
545
- try {
546
- this.options.onClick(this, e);
547
- } catch (err) {
548
- console.error("[Wulf.Toast] Erreur dans le callback onClick:", err);
549
- }
550
- }
551
- if (this.options.closeOnClick) {
552
- this.close("toast-click");
553
- }
554
- }, { signal });
555
- this.element.addEventListener("mouseenter", () => this.pauseTimer("hover"), { signal });
556
- this.element.addEventListener("mouseleave", () => this.resumeTimer("hover"), { signal });
557
- this.element.addEventListener("focusin", () => this.pauseTimer("focus"), { signal });
558
- this.element.addEventListener("focusout", (e) => {
559
- const nextFocused = e.relatedTarget;
560
- if (nextFocused && this.element.contains(nextFocused)) {
561
- return;
562
- }
563
- if (this.isPendingFocusDismiss && !this._isClosed) {
564
- this.isPendingFocusDismiss = false;
565
- this.close("timeout");
566
- return;
567
- }
568
- this.resumeTimer("focus");
569
- }, { signal });
570
- this.element.addEventListener("keydown", (e) => {
571
- if (e.key === "Escape" && (this.options.closable ?? true)) {
572
- if (isImeComposing(e)) return;
573
- e.stopPropagation();
574
- this.close("close-button");
575
- }
576
- }, { signal });
577
- if (typeof document !== "undefined") {
578
- document.addEventListener("visibilitychange", () => {
579
- if (document.visibilityState === "hidden") {
580
- this.pauseTimer("visibility");
581
- } else {
582
- this.resumeTimer("visibility");
583
- }
584
- }, { signal });
585
- }
586
- }
587
- get isPaused() {
588
- return this.isPausedByHover || this.isPausedByFocus || this.isPausedByVisibility;
589
- }
590
- /**
591
- * Démarrage du compte à rebours de disparition automatique (horloge monotone).
592
- */
593
- startTimer() {
594
- if (this._isClosed || this.remainingTime <= 0 || this.isPaused) return;
595
- if (typeof document !== "undefined" && document.visibilityState === "hidden") {
596
- this.isPausedByVisibility = true;
597
- this.element.classList.add("is-paused");
598
- return;
599
- }
600
- if (this.timerId !== null) {
601
- window.clearTimeout(this.timerId);
602
- this.timerId = null;
603
- }
604
- this.timerStartTime = performance.now();
605
- this.timerId = window.setTimeout(() => {
606
- this.timerId = null;
607
- const active = getDeepActiveElement();
608
- if (active && this.element.contains(active)) {
609
- this.isPendingFocusDismiss = true;
610
- return;
611
- }
612
- this.close("timeout");
613
- }, this.remainingTime);
614
- }
615
- /**
616
- * Met en pause le compte à rebours (au survol, au focus ou à la perte de visibilité d'onglet).
617
- */
618
- pauseTimer(source = "interaction") {
619
- if (this._isClosed || !this.hasDuration || this.remainingTime <= 0) return;
620
- const wasPaused = this.isPaused;
621
- if (source === "visibility") {
622
- this.isPausedByVisibility = true;
623
- } else if (source === "focus") {
624
- this.isPausedByFocus = true;
625
- } else {
626
- this.isPausedByHover = true;
627
- }
628
- if (wasPaused) return;
629
- if (this.timerId !== null) {
630
- window.clearTimeout(this.timerId);
631
- this.timerId = null;
632
- const elapsed = performance.now() - this.timerStartTime;
633
- this.remainingTime = Math.max(0, this.remainingTime - elapsed);
634
- }
635
- this.element.classList.add("is-paused");
636
- }
637
- /**
638
- * Reprend le compte à rebours si aucune autre cause de pause n'est active.
639
- */
640
- resumeTimer(source = "interaction") {
641
- if (this._isClosed || !this.hasDuration) return;
642
- if (source === "visibility") {
643
- this.isPausedByVisibility = false;
644
- } else if (source === "focus") {
645
- this.isPausedByFocus = false;
646
- } else if (source === "hover") {
647
- this.isPausedByHover = false;
648
- const active = getDeepActiveElement();
649
- if (active && this.element.contains(active)) {
650
- this.isPausedByFocus = true;
651
- }
652
- } else {
653
- this.isPausedByHover = false;
654
- this.isPausedByFocus = false;
655
- }
656
- if (this.isPaused) return;
657
- this.element.classList.remove("is-paused");
658
- if (this.remainingTime <= 0) {
659
- this.close("timeout");
660
- return;
661
- }
662
- this.startTimer();
663
- }
664
- finalizeDismiss(reason) {
665
- if (this._isFinalized) return;
666
- this._isFinalized = true;
667
- this.eventsAbortController.abort();
668
- if (this.onDismissCallback) {
669
- this.onDismissCallback(this, reason);
670
- }
671
- if (this.element.parentNode) {
672
- this.element.parentNode.removeChild(this.element);
673
- }
674
- if (this.options.onClose) {
675
- try {
676
- this.options.onClose(this, reason);
677
- } catch (err) {
678
- console.error("[Wulf.Toast] Erreur dans le callback onClose:", err);
679
- }
680
- }
681
- }
682
- /**
683
- * Déclenche la destruction immédiate sans animation.
684
- */
685
- destroyImmediate(reason = "replace") {
686
- this._isClosed = true;
687
- if (this.timerId !== null) {
688
- window.clearTimeout(this.timerId);
689
- this.timerId = null;
690
- }
691
- this.disposeAbortController.abort();
692
- this.finalizeDismiss(reason);
693
- }
694
- /**
695
- * Déclenche la fermeture propre et l'animation de sortie du toast.
696
- * Si fast = true, utilise une disparition accélérée pour le remplacement séquentiel.
697
- */
698
- close(reason = "programmatic", fast = false) {
699
- if (this._isClosed) {
700
- return this.closePromise ?? Promise.resolve();
701
- }
702
- this._isClosed = true;
703
- if (this.timerId !== null) {
704
- window.clearTimeout(this.timerId);
705
- this.timerId = null;
706
- }
707
- this.eventsAbortController.abort();
708
- this.element.classList.add(fast ? "wulf-toast-hiding-fast" : "wulf-toast-hiding");
709
- if (prefersReducedMotion()) {
710
- this.finalizeDismiss(reason);
711
- this.closePromise = Promise.resolve();
712
- return this.closePromise;
713
- }
714
- this.closePromise = waitForAnimations(this.element, fast ? 90 : 300, this.disposeAbortController.signal).then(() => {
715
- if (!this.disposeAbortController.signal.aborted) {
716
- this.finalizeDismiss(reason);
717
- }
718
- });
719
- return this.closePromise;
720
- }
721
- };
722
-
723
- // src/toast/ToastManager.ts
724
- var VALID_POSITIONS = /* @__PURE__ */ new Set([
725
- "top-left",
726
- "top-center",
727
- "top-right",
728
- "bottom-left",
729
- "bottom-center",
730
- "bottom-right"
731
- ]);
732
- function normalizePosition(pos) {
733
- return pos && VALID_POSITIONS.has(pos) ? pos : "top-right";
734
- }
735
- var FOCUSABLE_IN_TOAST = 'button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])';
736
- var ToastManager = class _ToastManager {
737
- static instance = null;
738
- containers = /* @__PURE__ */ new Map();
739
- containerBaseLabels = /* @__PURE__ */ new WeakMap();
740
- activeToasts = /* @__PURE__ */ new Map();
741
- announcerEl = null;
742
- politeRegion = null;
743
- assertiveRegion = null;
744
- announceTimers = [];
745
- politeAnnounceTimerId = null;
746
- assertiveAnnounceTimerId = null;
747
- politeClearTimerId = null;
748
- assertiveClearTimerId = null;
749
- lastPoliteText = "";
750
- lastAssertiveText = "";
751
- announcerToggle = false;
752
- /**
753
- * Vérifie si un conteneur Popover est ouvert (compatible natif et polyfill OddBird).
754
- */
755
- isPopoverOpen(container) {
756
- try {
757
- if (container.matches(":popover-open")) return true;
758
- } catch {
759
- }
760
- return container.classList.contains(":popover-open");
761
- }
762
- replaceTokens = /* @__PURE__ */ new Map();
763
- pendingReplacements = /* @__PURE__ */ new Set();
764
- constructor() {
765
- }
766
- static getInstance() {
767
- if (!_ToastManager.instance) {
768
- _ToastManager.instance = new _ToastManager();
769
- }
770
- return _ToastManager.instance;
771
- }
772
- /**
773
- * Ajoute et affiche une notification Toast.
774
- */
775
- add(toast) {
776
- const position = normalizePosition(toast.options.position);
777
- let list = this.activeToasts.get(position);
778
- if (!list) {
779
- list = [];
780
- this.activeToasts.set(position, list);
781
- }
782
- const rawMax = toast.options.maxToasts;
783
- const maxToasts = typeof rawMax === "number" && Number.isFinite(rawMax) && rawMax > 0 ? Math.min(50, Math.max(1, Math.floor(rawMax))) : 5;
784
- if (toast.options.replace && list.length > 0) {
785
- const existing = [...list];
786
- const token = (this.replaceTokens.get(position) || 0) + 1;
787
- this.replaceTokens.set(position, token);
788
- this.pendingReplacements.add(position);
789
- const promises = existing.map((t) => t.close("replace", true));
790
- Promise.all(promises).then(() => {
791
- this.pendingReplacements.delete(position);
792
- if (this.replaceTokens.get(position) !== token) {
793
- toast.destroyImmediate("replace");
794
- return;
795
- }
796
- this.mountToast(toast, position, maxToasts);
797
- });
798
- return;
799
- }
800
- if (this.pendingReplacements.has(position)) {
801
- this.replaceTokens.set(position, (this.replaceTokens.get(position) || 0) + 1);
802
- this.pendingReplacements.delete(position);
803
- }
804
- if (list.length >= maxToasts) {
805
- const countToRemove = list.length - maxToasts + 1;
806
- const oldestItems = list.splice(0, countToRemove);
807
- for (const item of oldestItems) {
808
- item.close("max-limit", true);
809
- }
810
- }
811
- this.mountToast(toast, position, maxToasts);
812
- }
813
- /**
814
- * Insère l'élément toast dans le conteneur Top Layer, annonce le message et démarre le minuteur.
815
- */
816
- mountToast(toast, position, maxToasts = 5) {
817
- if (toast.isClosed) return;
818
- const useTopLayer = toast.options.useTopLayer ?? true;
819
- const container = this.getOrCreateContainer(position, toast, useTopLayer);
820
- let list = this.activeToasts.get(position);
821
- if (!list) {
822
- list = [];
823
- this.activeToasts.set(position, list);
824
- }
825
- const maxDomNodes = maxToasts + 10;
826
- if (container.children.length >= maxDomNodes) {
827
- const children = Array.from(container.children);
828
- for (const child of children) {
829
- if (container.children.length < maxDomNodes) break;
830
- if (child.classList.contains("wulf-toast-hiding") || child.classList.contains("wulf-toast-hiding-fast")) {
831
- child.remove();
832
- }
833
- }
834
- }
835
- if (useTopLayer && typeof container.showPopover === "function" && container.getAttribute("popover") === "manual") {
836
- try {
837
- const popoverEl = container;
838
- if (!this.isPopoverOpen(container)) {
839
- popoverEl.showPopover();
840
- }
841
- } catch {
842
- container.removeAttribute("popover");
843
- }
844
- }
845
- container.appendChild(toast.element);
846
- list.push(toast);
847
- this.announce(toast);
848
- if (toast.options.onOpen) {
849
- try {
850
- toast.options.onOpen(toast);
851
- } catch (err) {
852
- console.error("[Wulf.Toast] Erreur dans le callback onOpen:", err);
853
- }
854
- }
855
- toast.startTimer();
856
- }
857
- /**
858
- * Annonce la notification sur un canal unique pour éviter les doubles lectures AT.
859
- */
860
- announce(toast) {
861
- const parts = [toast.options.title, toast.options.message].filter((val) => typeof val === "string" && val.trim().length > 0).map((val) => stripBidiAndInvisibles(val, 512).trim()).filter(Boolean);
862
- if (parts.length === 0) return;
863
- const rawText = parts.join(". ");
864
- const text = rawText.length > 512 ? `${rawText.slice(0, 509)}...` : rawText;
865
- const isAlert = toast.options.role === "alert";
866
- const docWithAriaNotify = document;
867
- if (typeof docWithAriaNotify.ariaNotify === "function") {
868
- try {
869
- docWithAriaNotify.ariaNotify(text, { priority: isAlert ? "high" : "normal" });
870
- return;
871
- } catch {
872
- }
873
- }
874
- const wasCreated = !this.announcerEl || !this.announcerEl.isConnected;
875
- this.ensureAnnouncer();
876
- const region = isAlert ? this.assertiveRegion : this.politeRegion;
877
- if (!region) return;
878
- if (isAlert) {
879
- if (this.assertiveAnnounceTimerId !== null) {
880
- window.clearTimeout(this.assertiveAnnounceTimerId);
881
- this.assertiveAnnounceTimerId = null;
882
- }
883
- if (this.assertiveClearTimerId !== null) {
884
- window.clearTimeout(this.assertiveClearTimerId);
885
- this.assertiveClearTimerId = null;
886
- }
887
- } else {
888
- if (this.politeAnnounceTimerId !== null) {
889
- window.clearTimeout(this.politeAnnounceTimerId);
890
- this.politeAnnounceTimerId = null;
891
- }
892
- if (this.politeClearTimerId !== null) {
893
- window.clearTimeout(this.politeClearTimerId);
894
- this.politeClearTimerId = null;
895
- }
896
- }
897
- region.textContent = "";
898
- const lastText = isAlert ? this.lastAssertiveText : this.lastPoliteText;
899
- let finalMessage = text;
900
- if (text === lastText) {
901
- this.announcerToggle = !this.announcerToggle;
902
- finalMessage = this.announcerToggle ? `${text}\xA0` : text;
903
- } else {
904
- this.announcerToggle = false;
905
- }
906
- if (isAlert) {
907
- this.lastAssertiveText = text;
908
- } else {
909
- this.lastPoliteText = text;
910
- }
911
- const delay = wasCreated ? 120 : 50;
912
- const timerId = window.setTimeout(() => {
913
- const idx = this.announceTimers.indexOf(timerId);
914
- if (idx !== -1) this.announceTimers.splice(idx, 1);
915
- if (isAlert) {
916
- this.assertiveAnnounceTimerId = null;
917
- } else {
918
- this.politeAnnounceTimerId = null;
919
- }
920
- if (region.isConnected) {
921
- region.textContent = finalMessage;
922
- const clearId = window.setTimeout(() => {
923
- const cIdx = this.announceTimers.indexOf(clearId);
924
- if (cIdx !== -1) this.announceTimers.splice(cIdx, 1);
925
- if (region.isConnected && region.textContent === finalMessage) {
926
- region.textContent = "";
927
- }
928
- }, 4e3);
929
- this.announceTimers.push(clearId);
930
- if (isAlert) {
931
- this.assertiveClearTimerId = clearId;
932
- } else {
933
- this.politeClearTimerId = clearId;
934
- }
935
- }
936
- }, delay);
937
- this.announceTimers.push(timerId);
938
- if (isAlert) {
939
- this.assertiveAnnounceTimerId = timerId;
940
- } else {
941
- this.politeAnnounceTimerId = timerId;
942
- }
943
- }
944
- /**
945
- * Crée ou reconnecte le conteneur persistant des annonces ARIA hors du popover.
946
- */
947
- ensureAnnouncer() {
948
- if (this.announcerEl && document.body.contains(this.announcerEl)) {
949
- return;
950
- }
951
- const wrapper = document.createElement("div");
952
- wrapper.className = "wulf-toast-announcer";
953
- wrapper.setAttribute("data-wulf-toast-announcer", "true");
954
- const polite = document.createElement("div");
955
- polite.setAttribute("role", "status");
956
- polite.setAttribute("aria-live", "polite");
957
- polite.setAttribute("aria-atomic", "true");
958
- const assertive = document.createElement("div");
959
- assertive.setAttribute("role", "alert");
960
- assertive.setAttribute("aria-live", "assertive");
961
- assertive.setAttribute("aria-atomic", "true");
962
- wrapper.appendChild(polite);
963
- wrapper.appendChild(assertive);
964
- document.body.appendChild(wrapper);
965
- this.announcerEl = wrapper;
966
- this.politeRegion = polite;
967
- this.assertiveRegion = assertive;
968
- }
969
- /**
970
- * Transfère le focus avant de retirer un toast focalisé pour éviter que le focus ne retombe sur <body>.
971
- */
972
- handleFocusHandoff(toast, list) {
973
- const active = getDeepActiveElement();
974
- if (!active || !toast.element.contains(active)) {
975
- return;
976
- }
977
- for (let i = list.length - 1; i >= 0; i--) {
978
- const sibling = list[i];
979
- if (sibling === toast || sibling.isClosed || !sibling.element.isConnected) continue;
980
- const target = sibling.element.querySelector(FOCUSABLE_IN_TOAST);
981
- if (target) {
982
- target.focus({ preventScroll: true });
983
- return;
984
- }
985
- }
986
- const prev = toast.getPreviousActiveElement();
987
- if (prev && prev.isConnected && typeof prev.focus === "function" && !prev.disabled && !prev.hidden && !prev.closest("[hidden]") && !prev.closest("[inert]") && prev.getAttribute("aria-hidden") !== "true" && (prev.tabIndex >= 0 || prev.getAttribute("tabindex") !== null)) {
988
- const prevWithCheck = prev;
989
- if (typeof prevWithCheck.checkVisibility === "function" && !prevWithCheck.checkVisibility({
990
- checkOpacity: false,
991
- checkVisibilityCSS: true,
992
- visibilityProperty: true
993
- })) {
994
- return;
995
- }
996
- try {
997
- prev.focus();
998
- } catch {
999
- }
1000
- }
1001
- }
1002
- /**
1003
- * Retire une notification de la pile et nettoie le conteneur s'il est vide.
1004
- */
1005
- remove(toast, _reason) {
1006
- const position = normalizePosition(toast.options.position);
1007
- const list = this.activeToasts.get(position);
1008
- if (list) {
1009
- const index = list.indexOf(toast);
1010
- if (index !== -1) {
1011
- list.splice(index, 1);
1012
- }
1013
- this.handleFocusHandoff(toast, list);
1014
- if (toast.element.parentNode) {
1015
- toast.element.parentNode.removeChild(toast.element);
1016
- }
1017
- if (list.length === 0 && !this.pendingReplacements.has(position)) {
1018
- const container = this.containers.get(position);
1019
- if (container && (!container.firstChild || container.children.length === 0)) {
1020
- this.disposeContainer(container);
1021
- this.containers.delete(position);
1022
- this.activeToasts.delete(position);
1023
- this.syncContainerRegionLabels();
1024
- }
1025
- }
1026
- } else if (toast.element.parentNode) {
1027
- toast.element.parentNode.removeChild(toast.element);
1028
- }
1029
- }
1030
- disposeContainer(container) {
1031
- try {
1032
- const popoverEl = container;
1033
- if (typeof popoverEl.hidePopover === "function" && this.isPopoverOpen(container)) {
1034
- popoverEl.hidePopover();
1035
- }
1036
- } catch {
1037
- }
1038
- if (container.parentNode) {
1039
- container.parentNode.removeChild(container);
1040
- }
1041
- }
1042
- /**
1043
- * Ferme l'ensemble des toasts actifs (sur une position ou partout) et attend leur retrait complet.
1044
- */
1045
- clearAll(position) {
1046
- const promises = [];
1047
- if (position) {
1048
- this.replaceTokens.set(position, (this.replaceTokens.get(position) || 0) + 1);
1049
- this.pendingReplacements.delete(position);
1050
- const list = this.activeToasts.get(position);
1051
- if (list && list.length > 0) {
1052
- const copy = [...list];
1053
- for (const t of copy) {
1054
- promises.push(t.close("programmatic"));
1055
- }
1056
- } else {
1057
- const container = this.containers.get(position);
1058
- if (container && (!container.firstChild || container.children.length === 0)) {
1059
- this.disposeContainer(container);
1060
- this.containers.delete(position);
1061
- this.activeToasts.delete(position);
1062
- this.syncContainerRegionLabels();
1063
- }
1064
- }
1065
- } else {
1066
- for (const pos of this.replaceTokens.keys()) {
1067
- this.replaceTokens.set(pos, (this.replaceTokens.get(pos) || 0) + 1);
1068
- }
1069
- this.pendingReplacements.clear();
1070
- for (const timerId of this.announceTimers) {
1071
- window.clearTimeout(timerId);
1072
- }
1073
- this.announceTimers = [];
1074
- this.politeAnnounceTimerId = null;
1075
- this.assertiveAnnounceTimerId = null;
1076
- this.politeClearTimerId = null;
1077
- this.assertiveClearTimerId = null;
1078
- const allPositions = /* @__PURE__ */ new Set([
1079
- ...Array.from(this.containers.keys()),
1080
- ...Array.from(this.activeToasts.keys())
1081
- ]);
1082
- for (const pos of allPositions) {
1083
- promises.push(this.clearAll(pos));
1084
- }
1085
- }
1086
- return Promise.all(promises).then(() => {
1087
- if (!position) {
1088
- for (const [pos, container] of Array.from(this.containers.entries())) {
1089
- if (!container.firstChild || container.children.length === 0) {
1090
- this.disposeContainer(container);
1091
- this.containers.delete(pos);
1092
- this.activeToasts.delete(pos);
1093
- }
1094
- }
1095
- this.syncContainerRegionLabels();
1096
- }
1097
- });
1098
- }
1099
- /**
1100
- * Détruit immédiatement tous les toasts, conteneurs, annonceurs ARIA et temporisations en cours.
1101
- */
1102
- destroy() {
1103
- for (const timerId of this.announceTimers) {
1104
- window.clearTimeout(timerId);
1105
- }
1106
- this.announceTimers = [];
1107
- this.politeAnnounceTimerId = null;
1108
- this.assertiveAnnounceTimerId = null;
1109
- this.politeClearTimerId = null;
1110
- this.assertiveClearTimerId = null;
1111
- for (const list of Array.from(this.activeToasts.values())) {
1112
- for (const toast of [...list]) {
1113
- toast.destroyImmediate("programmatic");
1114
- }
1115
- }
1116
- for (const container of Array.from(this.containers.values())) {
1117
- this.disposeContainer(container);
1118
- }
1119
- this.containers.clear();
1120
- this.activeToasts.clear();
1121
- this.replaceTokens.clear();
1122
- this.pendingReplacements.clear();
1123
- if (this.announcerEl) {
1124
- this.announcerEl.remove();
1125
- this.announcerEl = null;
1126
- this.politeRegion = null;
1127
- this.assertiveRegion = null;
1128
- }
1129
- _ToastManager.instance = null;
1130
- }
1131
- syncContainerRegionLabels() {
1132
- const useSuffix = this.containers.size > 1;
1133
- for (const [pos, container] of this.containers.entries()) {
1134
- const baseLabel = this.containerBaseLabels.get(container) || toastI18n.t("notificationsRegion");
1135
- container.setAttribute("aria-label", useSuffix ? `${baseLabel} (${pos})` : baseLabel);
1136
- }
1137
- }
1138
- /**
1139
- * Récupère ou crée le conteneur DOM pour une position d'affichage.
1140
- */
1141
- getOrCreateContainer(position, toast, useTopLayer) {
1142
- let container = this.containers.get(position);
1143
- if (!container || !document.body.contains(container)) {
1144
- container = document.createElement("div");
1145
- container.className = `wulf-toast-container wulf-toast-${position}`;
1146
- container.setAttribute("role", "region");
1147
- const baseLabel = toastI18n.t("notificationsRegion", toast.options.i18n);
1148
- this.containerBaseLabels.set(container, baseLabel);
1149
- container.setAttribute("aria-label", baseLabel);
1150
- if (useTopLayer && typeof container.showPopover === "function") {
1151
- container.setAttribute("popover", "manual");
1152
- }
1153
- document.body.appendChild(container);
1154
- this.containers.set(position, container);
1155
- this.syncContainerRegionLabels();
1156
- }
1157
- return container;
1158
- }
1159
- };
1160
-
1161
- // src/toast/Toast.ts
1162
- var Toast = class extends LocalizedComponent {
1163
- static _i18n = toastI18n;
1164
- static i18n = toastI18n;
1165
- audit() {
1166
- return [];
1167
- }
1168
- getAuditPrefix() {
1169
- return "Wulf.Toast";
1170
- }
1171
- getAuditTargetLabel() {
1172
- return "Toast";
1173
- }
1174
- /**
1175
- * Affiche une nouvelle notification Toast avec les options spécifiées.
1176
- */
1177
- static show(options = {}) {
1178
- const manager = ToastManager.getInstance();
1179
- const instance = new ToastInstance(options, (t, reason) => {
1180
- manager.remove(t, reason);
1181
- });
1182
- manager.add(instance);
1183
- return instance;
1184
- }
1185
- /**
1186
- * Ferme immédiatement l'ensemble des toasts actifs (globalement ou par position) et attend leur retrait complet.
1187
- */
1188
- static clearAll(position) {
1189
- return ToastManager.getInstance().clearAll(position);
1190
- }
1191
- /**
1192
- * Détruit le gestionnaire de notifications (conteneurs, annonceurs ARIA et timers).
1193
- */
1194
- static destroy() {
1195
- ToastManager.getInstance().destroy();
1196
- }
1197
- };
1198
-
1199
- // src/toast/index.ts
1200
- var index_default = Toast;
1201
- var wulfNamespace = getSafeWulfNamespace();
1202
- if (wulfNamespace) {
1203
- wulfNamespace.Toast = Object.assign(Toast, {
1204
- Toast,
1205
- i18n: toastI18n
1206
- });
1207
- }
1
+ import {
2
+ Toast,
3
+ ToastInstance,
4
+ ToastManager,
5
+ isSafeCssValue,
6
+ toastEn,
7
+ toastFr,
8
+ toastI18n,
9
+ toast_default
10
+ } from "./chunks/chunk-CM3SBIVQ.js";
11
+ import {
12
+ LocalizedComponent,
13
+ createI18nManager
14
+ } from "./chunks/chunk-QV46A7FV.js";
15
+ import "./chunks/chunk-ZGUU6DMM.js";
16
+ import "./chunks/chunk-22AIMRD5.js";
17
+ import "./chunks/chunk-VJO22BAT.js";
1208
18
  export {
1209
19
  LocalizedComponent,
1210
20
  Toast,
1211
21
  ToastInstance,
1212
22
  ToastManager,
1213
23
  createI18nManager,
1214
- index_default as default,
24
+ toast_default as default,
25
+ isSafeCssValue,
1215
26
  toastEn,
1216
27
  toastFr,
1217
28
  toastI18n