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
@@ -22,7 +22,9 @@ var __WulfIIFE = (() => {
22
22
  var index_exports = {};
23
23
  __export(index_exports, {
24
24
  AmountEngine: () => AmountEngine,
25
+ Anchor: () => anchor_exports,
25
26
  AuditableComponent: () => AuditableComponent,
27
+ Autosize: () => autosize_exports,
26
28
  BaseInputMask: () => BaseInputMask,
27
29
  DATE_UTC_PRESETS: () => DATE_UTC_PRESETS,
28
30
  DateUTCEngine: () => DateUTCEngine,
@@ -44,13 +46,20 @@ var __WulfIIFE = (() => {
44
46
  Shortcut: () => shortcut_exports,
45
47
  ShortcutFormatter: () => ShortcutFormatter,
46
48
  ShortcutManager: () => ShortcutManager,
49
+ Sortable: () => sortable_exports,
47
50
  Toast: () => toast_exports,
48
51
  ToastInstance: () => ToastInstance,
49
52
  ToastManager: () => ToastManager,
53
+ Undo: () => undo_exports,
54
+ UndoManager: () => UndoManager,
55
+ WulfAnchor: () => Anchor,
56
+ WulfAutosize: () => Autosize,
50
57
  WulfFocusTrap: () => FocusTrap,
51
58
  WulfMasonry: () => Masonry,
52
59
  WulfShortcut: () => ShortcutManager,
60
+ WulfSortable: () => Sortable,
53
61
  WulfToast: () => Toast,
62
+ WulfUndo: () => UndoManager,
54
63
  createI18nManager: () => createI18nManager,
55
64
  default: () => mask_default,
56
65
  getDeepActiveElement: () => getDeepActiveElement,
@@ -86,6 +95,67 @@ var __WulfIIFE = (() => {
86
95
  stripBidiAndInvisibles: () => stripBidiAndInvisibles
87
96
  });
88
97
 
98
+ // src/common/AuditableComponent.ts
99
+ var AuditableComponent = class {
100
+ /**
101
+ * Indication affichée en pied de warning pour expliquer comment désactiver l'audit.
102
+ */
103
+ getAuditDisableHint() {
104
+ return "Passez { audit: false } dans les options pour d\xE9sactiver cet avertissement";
105
+ }
106
+ /**
107
+ * Exécute l'audit d'accessibilité et émet un avertissement standardisé dans la console
108
+ * si l'audit est activé et que des contraintes manquent.
109
+ */
110
+ runAuditWarning(enabled = true) {
111
+ if (!enabled) return [];
112
+ const warnings = this.audit();
113
+ if (warnings.length > 0 && typeof console !== "undefined" && typeof console.warn === "function") {
114
+ console.warn(
115
+ `[${this.getAuditPrefix()}] Audit d'accessibilit\xE9 \u2014 ${warnings.length} contrainte(s) manquante(s) sur ${this.getAuditTargetLabel()} :
116
+ ` + warnings.map((w) => ` - ${w}`).join("\n") + `
117
+ (${this.getAuditDisableHint()})`
118
+ );
119
+ }
120
+ return warnings;
121
+ }
122
+ /**
123
+ * Vérifie si un attribut de référence d'IDs ARIA (ex: aria-labelledby, aria-describedby, aria-errormessage)
124
+ * pointe vers des éléments réellement présents dans le document (et optionnellement non vides).
125
+ */
126
+ checkAriaIdReferences(element, attrName, warnings, requireNonEmptyText = false) {
127
+ const rawValue = element.getAttribute(attrName)?.trim();
128
+ if (!rawValue) return false;
129
+ const doc = element.ownerDocument || document;
130
+ const root = typeof element.getRootNode === "function" ? element.getRootNode() : doc;
131
+ const ids = rawValue.split(/\s+/).filter(Boolean);
132
+ const targets = ids.map(
133
+ (id) => typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot ? root.getElementById(id) : doc.getElementById(id)
134
+ );
135
+ const allFound = ids.length > 0 && targets.every((el) => Boolean(el));
136
+ if (!allFound) {
137
+ warnings.push(
138
+ `Attribut ${attrName}="${rawValue}" invalide : l'\xE9l\xE9ment cible est introuvable dans le DOM.`
139
+ );
140
+ return false;
141
+ }
142
+ if (requireNonEmptyText) {
143
+ const hasNonEmptyText = targets.some((el) => {
144
+ if (!el) return false;
145
+ const text = el.textContent?.trim() || el.getAttribute("aria-label")?.trim() || "";
146
+ return text.length > 0;
147
+ });
148
+ if (!hasNonEmptyText) {
149
+ warnings.push(
150
+ `Attribut ${attrName}="${rawValue}" invalide : l'\xE9l\xE9ment cible ne contient aucun texte accessible.`
151
+ );
152
+ return false;
153
+ }
154
+ }
155
+ return true;
156
+ }
157
+ };
158
+
89
159
  // src/common/dom.ts
90
160
  function getSafeWulfNamespace() {
91
161
  if (typeof window === "undefined") return null;
@@ -193,67 +263,6 @@ var __WulfIIFE = (() => {
193
263
  });
194
264
  }
195
265
 
196
- // src/common/AuditableComponent.ts
197
- var AuditableComponent = class {
198
- /**
199
- * Indication affichée en pied de warning pour expliquer comment désactiver l'audit.
200
- */
201
- getAuditDisableHint() {
202
- return "Passez { audit: false } dans les options pour d\xE9sactiver cet avertissement";
203
- }
204
- /**
205
- * Exécute l'audit d'accessibilité et émet un avertissement standardisé dans la console
206
- * si l'audit est activé et que des contraintes manquent.
207
- */
208
- runAuditWarning(enabled = true) {
209
- if (!enabled) return [];
210
- const warnings = this.audit();
211
- if (warnings.length > 0 && typeof console !== "undefined" && typeof console.warn === "function") {
212
- console.warn(
213
- `[${this.getAuditPrefix()}] Audit d'accessibilit\xE9 \u2014 ${warnings.length} contrainte(s) manquante(s) sur ${this.getAuditTargetLabel()} :
214
- ` + warnings.map((w) => ` - ${w}`).join("\n") + `
215
- (${this.getAuditDisableHint()})`
216
- );
217
- }
218
- return warnings;
219
- }
220
- /**
221
- * Vérifie si un attribut de référence d'IDs ARIA (ex: aria-labelledby, aria-describedby, aria-errormessage)
222
- * pointe vers des éléments réellement présents dans le document (et optionnellement non vides).
223
- */
224
- checkAriaIdReferences(element, attrName, warnings, requireNonEmptyText = false) {
225
- const rawValue = element.getAttribute(attrName)?.trim();
226
- if (!rawValue) return false;
227
- const doc = element.ownerDocument || document;
228
- const root = typeof element.getRootNode === "function" ? element.getRootNode() : doc;
229
- const ids = rawValue.split(/\s+/).filter(Boolean);
230
- const targets = ids.map(
231
- (id) => typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot ? root.getElementById(id) : doc.getElementById(id)
232
- );
233
- const allFound = ids.length > 0 && targets.every((el) => Boolean(el));
234
- if (!allFound) {
235
- warnings.push(
236
- `Attribut ${attrName}="${rawValue}" invalide : l'\xE9l\xE9ment cible est introuvable dans le DOM.`
237
- );
238
- return false;
239
- }
240
- if (requireNonEmptyText) {
241
- const hasNonEmptyText = targets.some((el) => {
242
- if (!el) return false;
243
- const text = el.textContent?.trim() || el.getAttribute("aria-label")?.trim() || "";
244
- return text.length > 0;
245
- });
246
- if (!hasNonEmptyText) {
247
- warnings.push(
248
- `Attribut ${attrName}="${rawValue}" invalide : l'\xE9l\xE9ment cible ne contient aucun texte accessible.`
249
- );
250
- return false;
251
- }
252
- }
253
- return true;
254
- }
255
- };
256
-
257
266
  // src/mask/paste.ts
258
267
  var MAX_PASTE_LENGTH = 4096;
259
268
  function sanitizePastedText(raw, maxLength = MAX_PASTE_LENGTH) {
@@ -311,7 +320,10 @@ var __WulfIIFE = (() => {
311
320
  const shouldCreateWrapper = Boolean(options.createWrapper ?? dataCreateWrapper);
312
321
  let effectiveWrapper = providedWrapper;
313
322
  if (!effectiveWrapper && shouldCreateWrapper) {
314
- const doc = this.input.ownerDocument || document;
323
+ const doc = this.input.ownerDocument || (typeof document !== "undefined" ? document : null);
324
+ if (!doc) {
325
+ throw new Error("[InputMask] Document DOM introuvable pour createWrapper.");
326
+ }
315
327
  const span = doc.createElement("span");
316
328
  span.className = "wulf-mask-wrapper wulf-mask-wrapper--auto";
317
329
  if (this.input.parentNode) {
@@ -461,7 +473,7 @@ var __WulfIIFE = (() => {
461
473
  }
462
474
  onBaseFocus = () => {
463
475
  this.isFocused = true;
464
- if (this.options.selectAllOnFocus && this.input.value.length > 0) {
476
+ if (this.options.selectAllOnFocus && this.input.value.length > 0 && typeof window !== "undefined") {
465
477
  if (this.focusSelectTimerId !== null) {
466
478
  clearTimeout(this.focusSelectTimerId);
467
479
  }
@@ -678,9 +690,10 @@ var __WulfIIFE = (() => {
678
690
  if (typeof this.ghost.replaceChildren === "function") {
679
691
  this.ghost.replaceChildren(...nodes);
680
692
  } else {
693
+ const doc = this.ghost.ownerDocument || (typeof document !== "undefined" ? document : null);
681
694
  this.ghost.textContent = "";
682
695
  for (const n of nodes) {
683
- this.ghost.appendChild(typeof n === "string" ? document.createTextNode(n) : n);
696
+ this.ghost.appendChild(typeof n === "string" ? doc ? doc.createTextNode(n) : new Text(n) : n);
684
697
  }
685
698
  }
686
699
  this.wrapper.classList.toggle("has-visible-ghost", nodes.length > 0);
@@ -6240,10 +6253,6 @@ var __WulfIIFE = (() => {
6240
6253
  sanitizePastedText,
6241
6254
  stripBidiAndInvisibles
6242
6255
  };
6243
- var wulfNamespace = getSafeWulfNamespace();
6244
- if (wulfNamespace) {
6245
- wulfNamespace.Mask = Mask;
6246
- }
6247
6256
  var mask_default = InputMask;
6248
6257
 
6249
6258
  // src/scroll/index.ts
@@ -6528,6 +6537,9 @@ var __WulfIIFE = (() => {
6528
6537
  super(options?.i18n);
6529
6538
  let resolvedElement = null;
6530
6539
  if (typeof element === "string") {
6540
+ if (typeof document === "undefined") {
6541
+ throw new Error("[ScrollBlock] Impossible de r\xE9soudre un s\xE9lecteur CSS sans environnement DOM (document).");
6542
+ }
6531
6543
  try {
6532
6544
  resolvedElement = document.querySelector(element);
6533
6545
  } catch {
@@ -6536,7 +6548,7 @@ var __WulfIIFE = (() => {
6536
6548
  } else {
6537
6549
  resolvedElement = element;
6538
6550
  }
6539
- if (!resolvedElement || !(resolvedElement instanceof HTMLElement)) {
6551
+ if (!resolvedElement || typeof HTMLElement === "undefined" || !(resolvedElement instanceof HTMLElement)) {
6540
6552
  throw new Error(`[ScrollBlock] \xC9l\xE9ment introuvable : "${element}".`);
6541
6553
  }
6542
6554
  this.root = resolvedElement;
@@ -6553,6 +6565,7 @@ var __WulfIIFE = (() => {
6553
6565
  autoHide: options?.autoHide ?? true,
6554
6566
  autoHideDelay: safeAutoHideDelay,
6555
6567
  alwaysVisible: options?.alwaysVisible ?? false,
6568
+ scrollShadows: options?.scrollShadows ?? false,
6556
6569
  ariaLabel: options?.ariaLabel || this.t("viewport"),
6557
6570
  i18n: options?.i18n || {},
6558
6571
  minThumbSize: safeMinThumbSize,
@@ -6587,7 +6600,10 @@ var __WulfIIFE = (() => {
6587
6600
  * Prépare le viewport défilant sans altérer les éléments enfants.
6588
6601
  */
6589
6602
  setupViewport() {
6590
- this.root.classList.add("wulf-scrollblock");
6603
+ this.root.classList.add("wulf-scrollblock", `wulf-scrollblock--axis-${this.options.axis}`);
6604
+ if (this.options.scrollShadows) {
6605
+ this.root.classList.add("wulf-scrollblock--shadows");
6606
+ }
6591
6607
  if (this.options.mode === "native") {
6592
6608
  this.root.classList.add("wulf-scrollblock--native");
6593
6609
  }
@@ -6736,9 +6752,11 @@ var __WulfIIFE = (() => {
6736
6752
  }
6737
6753
  thumb.classList.add("is-active");
6738
6754
  this.root.classList.add("is-dragging");
6739
- window.addEventListener("pointermove", this.boundPointerMove, { signal: dragSignal });
6740
- window.addEventListener("pointerup", this.boundPointerUp, { signal: dragSignal });
6741
- window.addEventListener("pointercancel", this.boundPointerUp, { signal: dragSignal });
6755
+ if (typeof window !== "undefined") {
6756
+ window.addEventListener("pointermove", this.boundPointerMove, { signal: dragSignal });
6757
+ window.addEventListener("pointerup", this.boundPointerUp, { signal: dragSignal });
6758
+ window.addEventListener("pointercancel", this.boundPointerUp, { signal: dragSignal });
6759
+ }
6742
6760
  thumb.addEventListener("lostpointercapture", this.boundPointerUp, { signal: dragSignal });
6743
6761
  }, { signal });
6744
6762
  thumb.addEventListener("keydown", (e) => {
@@ -6840,7 +6858,7 @@ var __WulfIIFE = (() => {
6840
6858
  */
6841
6859
  setupObserver() {
6842
6860
  const scheduleUpdate = () => {
6843
- if (this.isDestroyed || this.resizeRafId !== null) return;
6861
+ if (this.isDestroyed || this.resizeRafId !== null || typeof window === "undefined") return;
6844
6862
  this.resizeRafId = window.requestAnimationFrame(() => {
6845
6863
  this.resizeRafId = null;
6846
6864
  if (!this.isDestroyed) {
@@ -6990,7 +7008,7 @@ var __WulfIIFE = (() => {
6990
7008
  this.scheduleAutoHide();
6991
7009
  }
6992
7010
  }
6993
- if (!this.supportsScrollEnd) {
7011
+ if (!this.supportsScrollEnd && typeof window !== "undefined") {
6994
7012
  if (this.scrollEndFallbackTimer !== void 0) {
6995
7013
  window.clearTimeout(this.scrollEndFallbackTimer);
6996
7014
  }
@@ -7017,7 +7035,7 @@ var __WulfIIFE = (() => {
7017
7035
  * Planifie une synchronisation des curseurs calée sur la prochaine trame d'affichage.
7018
7036
  */
7019
7037
  scheduleSyncThumbs() {
7020
- if (this.options.mode === "native" || this.isDestroyed) return;
7038
+ if (this.options.mode === "native" || this.isDestroyed || typeof window === "undefined") return;
7021
7039
  if (this.rafId !== null) return;
7022
7040
  this.rafId = window.requestAnimationFrame(() => {
7023
7041
  this.rafId = null;
@@ -7081,13 +7099,13 @@ var __WulfIIFE = (() => {
7081
7099
  this.scheduleAutoHide();
7082
7100
  }
7083
7101
  clearAutoHideTimer() {
7084
- if (this.hideTimer) {
7102
+ if (this.hideTimer && typeof window !== "undefined") {
7085
7103
  window.clearTimeout(this.hideTimer);
7086
- this.hideTimer = void 0;
7087
7104
  }
7105
+ this.hideTimer = void 0;
7088
7106
  }
7089
7107
  scheduleAutoHide() {
7090
- if (this.options.alwaysVisible || !this.options.autoHide || this.isDragging) return;
7108
+ if (this.options.alwaysVisible || !this.options.autoHide || this.isDragging || typeof window === "undefined") return;
7091
7109
  this.clearAutoHideTimer();
7092
7110
  this.hideTimer = window.setTimeout(() => {
7093
7111
  this.root.classList.remove("is-scrolling");
@@ -7280,8 +7298,10 @@ var __WulfIIFE = (() => {
7280
7298
  const finish = () => {
7281
7299
  if (settled) return;
7282
7300
  settled = true;
7283
- if (idleTimerId !== void 0) window.clearTimeout(idleTimerId);
7284
- if (maxTimerId !== void 0) window.clearTimeout(maxTimerId);
7301
+ if (typeof window !== "undefined") {
7302
+ if (idleTimerId !== void 0) window.clearTimeout(idleTimerId);
7303
+ if (maxTimerId !== void 0) window.clearTimeout(maxTimerId);
7304
+ }
7285
7305
  if (this.activeScrollToController === waitController) {
7286
7306
  this.activeScrollToController = void 0;
7287
7307
  }
@@ -7292,7 +7312,7 @@ var __WulfIIFE = (() => {
7292
7312
  this.abortController.signal.addEventListener("abort", finish, { once: true, signal: waitController.signal });
7293
7313
  if (this.supportsScrollEnd) {
7294
7314
  this.viewport.addEventListener("scrollend", finish, { once: true, signal: waitController.signal });
7295
- } else {
7315
+ } else if (typeof window !== "undefined") {
7296
7316
  const bumpIdle = () => {
7297
7317
  if (idleTimerId !== void 0) window.clearTimeout(idleTimerId);
7298
7318
  idleTimerId = window.setTimeout(finish, 150);
@@ -7300,7 +7320,11 @@ var __WulfIIFE = (() => {
7300
7320
  this.viewport.addEventListener("scroll", bumpIdle, { passive: true, signal: waitController.signal });
7301
7321
  bumpIdle();
7302
7322
  }
7303
- maxTimerId = window.setTimeout(finish, 2500);
7323
+ if (typeof window !== "undefined") {
7324
+ maxTimerId = window.setTimeout(finish, 2500);
7325
+ } else {
7326
+ finish();
7327
+ }
7304
7328
  });
7305
7329
  }
7306
7330
  /**
@@ -7352,18 +7376,20 @@ var __WulfIIFE = (() => {
7352
7376
  }
7353
7377
  this.isDestroyed = true;
7354
7378
  this.clearAutoHideTimer();
7355
- if (this.scrollEndFallbackTimer !== void 0) {
7356
- window.clearTimeout(this.scrollEndFallbackTimer);
7357
- this.scrollEndFallbackTimer = void 0;
7358
- }
7359
- if (this.rafId !== null) {
7360
- window.cancelAnimationFrame(this.rafId);
7361
- this.rafId = null;
7362
- }
7363
- if (this.resizeRafId !== null) {
7364
- window.cancelAnimationFrame(this.resizeRafId);
7365
- this.resizeRafId = null;
7379
+ if (typeof window !== "undefined") {
7380
+ if (this.scrollEndFallbackTimer !== void 0) {
7381
+ window.clearTimeout(this.scrollEndFallbackTimer);
7382
+ }
7383
+ if (this.rafId !== null) {
7384
+ window.cancelAnimationFrame(this.rafId);
7385
+ }
7386
+ if (this.resizeRafId !== null) {
7387
+ window.cancelAnimationFrame(this.resizeRafId);
7388
+ }
7366
7389
  }
7390
+ this.scrollEndFallbackTimer = void 0;
7391
+ this.rafId = null;
7392
+ this.resizeRafId = null;
7367
7393
  this.activeScrollToController?.abort();
7368
7394
  this.activeScrollToController = void 0;
7369
7395
  this.dragAbortController?.abort();
@@ -7382,6 +7408,10 @@ var __WulfIIFE = (() => {
7382
7408
  this.root.classList.remove(
7383
7409
  "wulf-scrollblock",
7384
7410
  "wulf-scrollblock--native",
7411
+ "wulf-scrollblock--shadows",
7412
+ "wulf-scrollblock--axis-y",
7413
+ "wulf-scrollblock--axis-x",
7414
+ "wulf-scrollblock--axis-both",
7385
7415
  "has-scroll-y",
7386
7416
  "has-scroll-x",
7387
7417
  "has-both-axes",
@@ -7419,10 +7449,6 @@ var __WulfIIFE = (() => {
7419
7449
  i18n: scrollI18n
7420
7450
  };
7421
7451
  var scroll_default = ScrollBlock;
7422
- var wulfNamespace2 = getSafeWulfNamespace();
7423
- if (wulfNamespace2) {
7424
- wulfNamespace2.Scroll = Scroll;
7425
- }
7426
7452
 
7427
7453
  // src/masonry/index.ts
7428
7454
  var masonry_exports = {};
@@ -7696,6 +7722,9 @@ var __WulfIIFE = (() => {
7696
7722
  constructor(target, options = {}) {
7697
7723
  super(options.i18n);
7698
7724
  if (typeof target === "string") {
7725
+ if (typeof document === "undefined") {
7726
+ throw new Error("[Wulf.Masonry] Impossible de r\xE9soudre un s\xE9lecteur CSS sans environnement DOM (document).");
7727
+ }
7699
7728
  let el = null;
7700
7729
  try {
7701
7730
  el = document.querySelector(target);
@@ -7706,7 +7735,7 @@ var __WulfIIFE = (() => {
7706
7735
  throw new Error(`[Wulf.Masonry] Conteneur introuvable pour le s\xE9lecteur : "${target}"`);
7707
7736
  }
7708
7737
  this.root = el;
7709
- } else if (target instanceof HTMLElement) {
7738
+ } else if (typeof HTMLElement !== "undefined" && target instanceof HTMLElement) {
7710
7739
  this.root = target;
7711
7740
  } else {
7712
7741
  throw new Error("[Wulf.Masonry] Cible invalide : fournissez un \xE9l\xE9ment HTMLElement ou un s\xE9lecteur valide.");
@@ -7945,10 +7974,14 @@ var __WulfIIFE = (() => {
7945
7974
  */
7946
7975
  scheduleLayout() {
7947
7976
  if (this.isDestroyed) return;
7977
+ if (typeof window === "undefined" || typeof window.requestAnimationFrame !== "function") {
7978
+ this.layout();
7979
+ return;
7980
+ }
7948
7981
  if (this.layoutRafId !== null) {
7949
- cancelAnimationFrame(this.layoutRafId);
7982
+ window.cancelAnimationFrame(this.layoutRafId);
7950
7983
  }
7951
- this.layoutRafId = requestAnimationFrame(() => {
7984
+ this.layoutRafId = window.requestAnimationFrame(() => {
7952
7985
  this.layoutRafId = null;
7953
7986
  this.layout();
7954
7987
  });
@@ -8199,7 +8232,9 @@ var __WulfIIFE = (() => {
8199
8232
  this.isDestroyed = true;
8200
8233
  this.abortController.abort();
8201
8234
  if (this.layoutRafId !== null) {
8202
- cancelAnimationFrame(this.layoutRafId);
8235
+ if (typeof window !== "undefined" && typeof window.cancelAnimationFrame === "function") {
8236
+ window.cancelAnimationFrame(this.layoutRafId);
8237
+ }
8203
8238
  this.layoutRafId = null;
8204
8239
  }
8205
8240
  if (this.resizeObserver) {
@@ -8256,14 +8291,6 @@ var __WulfIIFE = (() => {
8256
8291
 
8257
8292
  // src/masonry/index.ts
8258
8293
  var masonry_default = Masonry;
8259
- var wulfNamespace3 = getSafeWulfNamespace();
8260
- if (wulfNamespace3) {
8261
- wulfNamespace3.Masonry = Object.assign(Masonry, {
8262
- Masonry,
8263
- LayoutEngine,
8264
- i18n: masonryI18n
8265
- });
8266
- }
8267
8294
 
8268
8295
  // src/toast/index.ts
8269
8296
  var toast_exports = {};
@@ -8274,6 +8301,7 @@ var __WulfIIFE = (() => {
8274
8301
  ToastManager: () => ToastManager,
8275
8302
  createI18nManager: () => createI18nManager,
8276
8303
  default: () => toast_default,
8304
+ isSafeCssValue: () => isSafeCssValue,
8277
8305
  toastEn: () => toastEn,
8278
8306
  toastFr: () => toastFr,
8279
8307
  toastI18n: () => toastI18n
@@ -8300,7 +8328,7 @@ var __WulfIIFE = (() => {
8300
8328
  // src/toast/ToastInstance.ts
8301
8329
  var nextToastId = 1;
8302
8330
  var DEFAULT_TOAST_DURATION = 5e3;
8303
- var SAFE_COLOR_FALLBACK_RE = /^(?:#[0-9a-f]{3,8}|(?:rgb|rgba|hsl|hsla|oklch|oklab|lch|lab)\([^;{}<>\\]+\)|[a-z]{3,20})$/i;
8331
+ var SAFE_COLOR_FALLBACK_RE = /^(?:#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})|(?:rgb|rgba|hsl|hsla|oklch|oklab|lch|lab)\(\s*(?:[+-]?(?:\d+\.?\d*|\.\d+)(?:%|deg|rad|grad|turn)?|none)(?:\s*[,/\s]\s*(?:[+-]?(?:\d+\.?\d*|\.\d+)(?:%|deg|rad|grad|turn)?|none)){2,3}\s*\)|[a-z]{3,20})$/i;
8304
8332
  function isSafeCssValue(val) {
8305
8333
  if (!val || typeof val !== "string" || val.length > 128) return false;
8306
8334
  const trimmed = val.trim();
@@ -8331,12 +8359,16 @@ var __WulfIIFE = (() => {
8331
8359
  isPausedByFocus = false;
8332
8360
  isPausedByVisibility = false;
8333
8361
  isPendingFocusDismiss = false;
8362
+ actionPending = false;
8334
8363
  previousActiveElement = null;
8335
8364
  eventsAbortController = new AbortController();
8336
8365
  disposeAbortController = new AbortController();
8337
8366
  onDismissCallback;
8338
8367
  constructor(options, onDismiss) {
8339
8368
  super();
8369
+ if (typeof document === "undefined") {
8370
+ throw new Error("[Wulf.Toast] Impossible d'instancier une notification Toast sans environnement DOM (document).");
8371
+ }
8340
8372
  this.id = `wulf-toast-${nextToastId++}`;
8341
8373
  this.options = Object.freeze({ ...options });
8342
8374
  this.onDismissCallback = onDismiss;
@@ -8385,6 +8417,14 @@ var __WulfIIFE = (() => {
8385
8417
  "Notification persistante impossible \xE0 fermer au clavier : activez closable: true lorsque duration est d\xE9sactiv\xE9 (WCAG 2.1.1)."
8386
8418
  );
8387
8419
  }
8420
+ if (this.options.action) {
8421
+ const safeActionLabel = stripBidiAndInvisibles(String(this.options.action.label ?? ""), 128).trim();
8422
+ if (!safeActionLabel) {
8423
+ warnings.push(
8424
+ "Bouton d'action invalide : action.label doit contenir un texte non vide (WCAG 4.1.2)."
8425
+ );
8426
+ }
8427
+ }
8388
8428
  return warnings;
8389
8429
  }
8390
8430
  getAuditPrefix() {
@@ -8464,6 +8504,63 @@ var __WulfIIFE = (() => {
8464
8504
  content.appendChild(messageEl);
8465
8505
  }
8466
8506
  el.appendChild(content);
8507
+ const actionDef = this.options.action;
8508
+ if (actionDef && typeof actionDef.onClick === "function") {
8509
+ const safeLabel = stripBidiAndInvisibles(String(actionDef.label ?? ""), 128).trim();
8510
+ if (safeLabel) {
8511
+ const actionBtn = document.createElement("button");
8512
+ actionBtn.type = "button";
8513
+ actionBtn.className = "wulf-toast-action";
8514
+ actionBtn.textContent = safeLabel;
8515
+ if (typeof actionDef.ariaLabel === "string") {
8516
+ const safeAriaLabel = stripBidiAndInvisibles(actionDef.ariaLabel, 256).trim();
8517
+ if (safeAriaLabel) {
8518
+ actionBtn.setAttribute("aria-label", safeAriaLabel);
8519
+ }
8520
+ }
8521
+ const resetActionState = () => {
8522
+ this.actionPending = false;
8523
+ if (!this._isClosed) {
8524
+ actionBtn.disabled = false;
8525
+ actionBtn.removeAttribute("aria-busy");
8526
+ }
8527
+ };
8528
+ actionBtn.addEventListener("click", (e) => {
8529
+ e.stopPropagation();
8530
+ if (this._isClosed || this.actionPending) return;
8531
+ this.actionPending = true;
8532
+ actionBtn.disabled = true;
8533
+ actionBtn.setAttribute("aria-busy", "true");
8534
+ const shouldClose = actionDef.closeOnClick !== false;
8535
+ try {
8536
+ const result = actionDef.onClick(this, e);
8537
+ if (result && typeof result.then === "function") {
8538
+ result.then(
8539
+ () => {
8540
+ if (shouldClose && !this._isClosed) {
8541
+ this.close("action");
8542
+ } else {
8543
+ resetActionState();
8544
+ }
8545
+ },
8546
+ (err) => {
8547
+ console.error("[Wulf.Toast] Erreur dans action.onClick:", err);
8548
+ resetActionState();
8549
+ }
8550
+ );
8551
+ } else if (shouldClose && !this._isClosed) {
8552
+ this.close("action");
8553
+ } else {
8554
+ resetActionState();
8555
+ }
8556
+ } catch (err) {
8557
+ console.error("[Wulf.Toast] Erreur dans action.onClick:", err);
8558
+ resetActionState();
8559
+ }
8560
+ }, { signal: this.eventsAbortController.signal });
8561
+ el.appendChild(actionBtn);
8562
+ }
8563
+ }
8467
8564
  const closable = this.options.closable ?? true;
8468
8565
  if (closable) {
8469
8566
  const closeBtn = document.createElement("button");
@@ -8566,10 +8663,11 @@ var __WulfIIFE = (() => {
8566
8663
  return;
8567
8664
  }
8568
8665
  if (this.timerId !== null) {
8569
- window.clearTimeout(this.timerId);
8666
+ if (typeof window !== "undefined") window.clearTimeout(this.timerId);
8570
8667
  this.timerId = null;
8571
8668
  }
8572
- this.timerStartTime = performance.now();
8669
+ if (typeof window === "undefined") return;
8670
+ this.timerStartTime = typeof performance !== "undefined" ? performance.now() : Date.now();
8573
8671
  this.timerId = window.setTimeout(() => {
8574
8672
  this.timerId = null;
8575
8673
  const active = getDeepActiveElement();
@@ -8595,9 +8693,10 @@ var __WulfIIFE = (() => {
8595
8693
  }
8596
8694
  if (wasPaused) return;
8597
8695
  if (this.timerId !== null) {
8598
- window.clearTimeout(this.timerId);
8696
+ if (typeof window !== "undefined") window.clearTimeout(this.timerId);
8599
8697
  this.timerId = null;
8600
- const elapsed = performance.now() - this.timerStartTime;
8698
+ const now = typeof performance !== "undefined" ? performance.now() : Date.now();
8699
+ const elapsed = now - this.timerStartTime;
8601
8700
  this.remainingTime = Math.max(0, this.remainingTime - elapsed);
8602
8701
  }
8603
8702
  this.element.classList.add("is-paused");
@@ -8653,7 +8752,7 @@ var __WulfIIFE = (() => {
8653
8752
  destroyImmediate(reason = "replace") {
8654
8753
  this._isClosed = true;
8655
8754
  if (this.timerId !== null) {
8656
- window.clearTimeout(this.timerId);
8755
+ if (typeof window !== "undefined") window.clearTimeout(this.timerId);
8657
8756
  this.timerId = null;
8658
8757
  }
8659
8758
  this.disposeAbortController.abort();
@@ -8669,7 +8768,7 @@ var __WulfIIFE = (() => {
8669
8768
  }
8670
8769
  this._isClosed = true;
8671
8770
  if (this.timerId !== null) {
8672
- window.clearTimeout(this.timerId);
8771
+ if (typeof window !== "undefined") window.clearTimeout(this.timerId);
8673
8772
  this.timerId = null;
8674
8773
  }
8675
8774
  this.eventsAbortController.abort();
@@ -8688,6 +8787,71 @@ var __WulfIIFE = (() => {
8688
8787
  }
8689
8788
  };
8690
8789
 
8790
+ // src/common/registry.ts
8791
+ var WULF_TRAP_STACK_SYMBOL = Symbol.for("wulf.focusTrap.stack.v1");
8792
+ var WULF_TOAST_MANAGER_SYMBOL = Symbol.for("wulf.toast.manager.v1");
8793
+ var WULF_TOAST_CONTAINERS_SYMBOL = Symbol.for("wulf.toast.containers.v1");
8794
+ var WULF_TOAST_ANNOUNCERS_SYMBOL = Symbol.for("wulf.toast.announcers.v1");
8795
+ function getGlobalRegistry() {
8796
+ if (typeof globalThis === "undefined") return null;
8797
+ return globalThis;
8798
+ }
8799
+ function getSharedTrapStack() {
8800
+ const reg = getGlobalRegistry();
8801
+ if (!reg) return [];
8802
+ let stack = reg[WULF_TRAP_STACK_SYMBOL];
8803
+ if (!Array.isArray(stack)) {
8804
+ stack = [];
8805
+ reg[WULF_TRAP_STACK_SYMBOL] = stack;
8806
+ }
8807
+ return stack;
8808
+ }
8809
+ function getSharedToastManager() {
8810
+ const reg = getGlobalRegistry();
8811
+ if (!reg) return null;
8812
+ return reg[WULF_TOAST_MANAGER_SYMBOL] ?? null;
8813
+ }
8814
+ function setSharedToastManager(instance) {
8815
+ const reg = getGlobalRegistry();
8816
+ if (!reg) return;
8817
+ reg[WULF_TOAST_MANAGER_SYMBOL] = instance;
8818
+ }
8819
+ function getWeakSetRegistry(sym) {
8820
+ if (typeof WeakSet === "undefined") return null;
8821
+ const reg = getGlobalRegistry();
8822
+ if (!reg) return null;
8823
+ let set = reg[sym];
8824
+ if (!(set instanceof WeakSet)) {
8825
+ set = /* @__PURE__ */ new WeakSet();
8826
+ reg[sym] = set;
8827
+ }
8828
+ return set;
8829
+ }
8830
+ function registerToastContainer(el) {
8831
+ getWeakSetRegistry(WULF_TOAST_CONTAINERS_SYMBOL)?.add(el);
8832
+ }
8833
+ function unregisterToastContainer(el) {
8834
+ getWeakSetRegistry(WULF_TOAST_CONTAINERS_SYMBOL)?.delete(el);
8835
+ }
8836
+ function isRegisteredToastContainer(el) {
8837
+ if (!el || typeof HTMLElement === "undefined" || !(el instanceof HTMLElement)) {
8838
+ return false;
8839
+ }
8840
+ return getWeakSetRegistry(WULF_TOAST_CONTAINERS_SYMBOL)?.has(el) ?? false;
8841
+ }
8842
+ function registerToastAnnouncer(el) {
8843
+ getWeakSetRegistry(WULF_TOAST_ANNOUNCERS_SYMBOL)?.add(el);
8844
+ }
8845
+ function unregisterToastAnnouncer(el) {
8846
+ getWeakSetRegistry(WULF_TOAST_ANNOUNCERS_SYMBOL)?.delete(el);
8847
+ }
8848
+ function isRegisteredToastAnnouncer(el) {
8849
+ if (!el || typeof HTMLElement === "undefined" || !(el instanceof HTMLElement)) {
8850
+ return false;
8851
+ }
8852
+ return getWeakSetRegistry(WULF_TOAST_ANNOUNCERS_SYMBOL)?.has(el) ?? false;
8853
+ }
8854
+
8691
8855
  // src/toast/ToastManager.ts
8692
8856
  var VALID_POSITIONS = /* @__PURE__ */ new Set([
8693
8857
  "top-left",
@@ -8702,7 +8866,6 @@ var __WulfIIFE = (() => {
8702
8866
  }
8703
8867
  var FOCUSABLE_IN_TOAST = 'button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])';
8704
8868
  var ToastManager = class _ToastManager {
8705
- static instance = null;
8706
8869
  containers = /* @__PURE__ */ new Map();
8707
8870
  containerBaseLabels = /* @__PURE__ */ new WeakMap();
8708
8871
  activeToasts = /* @__PURE__ */ new Map();
@@ -8732,15 +8895,21 @@ var __WulfIIFE = (() => {
8732
8895
  constructor() {
8733
8896
  }
8734
8897
  static getInstance() {
8735
- if (!_ToastManager.instance) {
8736
- _ToastManager.instance = new _ToastManager();
8898
+ let instance = getSharedToastManager();
8899
+ if (!instance) {
8900
+ instance = new _ToastManager();
8901
+ setSharedToastManager(instance);
8737
8902
  }
8738
- return _ToastManager.instance;
8903
+ return instance;
8904
+ }
8905
+ getContainerKey(position, useTopLayer) {
8906
+ return `${position}:${useTopLayer ? "top" : "fixed"}`;
8739
8907
  }
8740
8908
  /**
8741
8909
  * Ajoute et affiche une notification Toast.
8742
8910
  */
8743
8911
  add(toast) {
8912
+ if (typeof document === "undefined" || typeof window === "undefined") return;
8744
8913
  const position = normalizePosition(toast.options.position);
8745
8914
  let list = this.activeToasts.get(position);
8746
8915
  if (!list) {
@@ -8782,7 +8951,7 @@ var __WulfIIFE = (() => {
8782
8951
  * Insère l'élément toast dans le conteneur Top Layer, annonce le message et démarre le minuteur.
8783
8952
  */
8784
8953
  mountToast(toast, position, maxToasts = 5) {
8785
- if (toast.isClosed) return;
8954
+ if (toast.isClosed || typeof document === "undefined") return;
8786
8955
  const useTopLayer = toast.options.useTopLayer ?? true;
8787
8956
  const container = this.getOrCreateContainer(position, toast, useTopLayer);
8788
8957
  let list = this.activeToasts.get(position);
@@ -8826,6 +8995,7 @@ var __WulfIIFE = (() => {
8826
8995
  * Annonce la notification sur un canal unique pour éviter les doubles lectures AT.
8827
8996
  */
8828
8997
  announce(toast) {
8998
+ if (typeof document === "undefined" || typeof window === "undefined") return;
8829
8999
  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);
8830
9000
  if (parts.length === 0) return;
8831
9001
  const rawText = parts.join(". ");
@@ -8913,12 +9083,14 @@ var __WulfIIFE = (() => {
8913
9083
  * Crée ou reconnecte le conteneur persistant des annonces ARIA hors du popover.
8914
9084
  */
8915
9085
  ensureAnnouncer() {
9086
+ if (typeof document === "undefined" || !document.body) return;
8916
9087
  if (this.announcerEl && document.body.contains(this.announcerEl)) {
8917
9088
  return;
8918
9089
  }
8919
9090
  const wrapper = document.createElement("div");
8920
9091
  wrapper.className = "wulf-toast-announcer";
8921
9092
  wrapper.setAttribute("data-wulf-toast-announcer", "true");
9093
+ registerToastAnnouncer(wrapper);
8922
9094
  const polite = document.createElement("div");
8923
9095
  polite.setAttribute("role", "status");
8924
9096
  polite.setAttribute("aria-live", "polite");
@@ -8973,6 +9145,9 @@ var __WulfIIFE = (() => {
8973
9145
  remove(toast, _reason) {
8974
9146
  const position = normalizePosition(toast.options.position);
8975
9147
  const list = this.activeToasts.get(position);
9148
+ const useTopLayer = toast.options.useTopLayer ?? true;
9149
+ const containerKey = this.getContainerKey(position, useTopLayer);
9150
+ const parentContainer = toast.element.parentElement;
8976
9151
  if (list) {
8977
9152
  const index = list.indexOf(toast);
8978
9153
  if (index !== -1) {
@@ -8982,20 +9157,34 @@ var __WulfIIFE = (() => {
8982
9157
  if (toast.element.parentNode) {
8983
9158
  toast.element.parentNode.removeChild(toast.element);
8984
9159
  }
9160
+ const targetContainer = this.containers.get(containerKey) || (parentContainer instanceof HTMLElement ? parentContainer : void 0);
9161
+ if (targetContainer && (!targetContainer.firstChild || targetContainer.children.length === 0)) {
9162
+ for (const [k, c] of Array.from(this.containers.entries())) {
9163
+ if (c === targetContainer) {
9164
+ this.containers.delete(k);
9165
+ }
9166
+ }
9167
+ this.disposeContainer(targetContainer);
9168
+ this.syncContainerRegionLabels();
9169
+ }
8985
9170
  if (list.length === 0 && !this.pendingReplacements.has(position)) {
8986
- const container = this.containers.get(position);
8987
- if (container && (!container.firstChild || container.children.length === 0)) {
8988
- this.disposeContainer(container);
8989
- this.containers.delete(position);
8990
- this.activeToasts.delete(position);
8991
- this.syncContainerRegionLabels();
9171
+ for (const mode of [true, false]) {
9172
+ const k = this.getContainerKey(position, mode);
9173
+ const container = this.containers.get(k);
9174
+ if (container && (!container.firstChild || container.children.length === 0)) {
9175
+ this.disposeContainer(container);
9176
+ this.containers.delete(k);
9177
+ }
8992
9178
  }
9179
+ this.activeToasts.delete(position);
9180
+ this.syncContainerRegionLabels();
8993
9181
  }
8994
9182
  } else if (toast.element.parentNode) {
8995
9183
  toast.element.parentNode.removeChild(toast.element);
8996
9184
  }
8997
9185
  }
8998
9186
  disposeContainer(container) {
9187
+ unregisterToastContainer(container);
8999
9188
  try {
9000
9189
  const popoverEl = container;
9001
9190
  if (typeof popoverEl.hidePopover === "function" && this.isPopoverOpen(container)) {
@@ -9011,6 +9200,9 @@ var __WulfIIFE = (() => {
9011
9200
  * Ferme l'ensemble des toasts actifs (sur une position ou partout) et attend leur retrait complet.
9012
9201
  */
9013
9202
  clearAll(position) {
9203
+ if (typeof document === "undefined" || typeof window === "undefined") {
9204
+ return Promise.resolve();
9205
+ }
9014
9206
  const promises = [];
9015
9207
  if (position) {
9016
9208
  this.replaceTokens.set(position, (this.replaceTokens.get(position) || 0) + 1);
@@ -9022,11 +9214,18 @@ var __WulfIIFE = (() => {
9022
9214
  promises.push(t.close("programmatic"));
9023
9215
  }
9024
9216
  } else {
9025
- const container = this.containers.get(position);
9026
- if (container && (!container.firstChild || container.children.length === 0)) {
9027
- this.disposeContainer(container);
9028
- this.containers.delete(position);
9029
- this.activeToasts.delete(position);
9217
+ let removedAny = false;
9218
+ for (const mode of [true, false]) {
9219
+ const k = this.getContainerKey(position, mode);
9220
+ const container = this.containers.get(k);
9221
+ if (container && (!container.firstChild || container.children.length === 0)) {
9222
+ this.disposeContainer(container);
9223
+ this.containers.delete(k);
9224
+ removedAny = true;
9225
+ }
9226
+ }
9227
+ this.activeToasts.delete(position);
9228
+ if (removedAny) {
9030
9229
  this.syncContainerRegionLabels();
9031
9230
  }
9032
9231
  }
@@ -9043,23 +9242,26 @@ var __WulfIIFE = (() => {
9043
9242
  this.assertiveAnnounceTimerId = null;
9044
9243
  this.politeClearTimerId = null;
9045
9244
  this.assertiveClearTimerId = null;
9046
- const allPositions = /* @__PURE__ */ new Set([
9047
- ...Array.from(this.containers.keys()),
9048
- ...Array.from(this.activeToasts.keys())
9049
- ]);
9050
- for (const pos of allPositions) {
9245
+ const positionSet = new Set(Array.from(this.activeToasts.keys()));
9246
+ for (const key of this.containers.keys()) {
9247
+ const pos = key.slice(0, key.lastIndexOf(":"));
9248
+ if (VALID_POSITIONS.has(pos)) {
9249
+ positionSet.add(pos);
9250
+ }
9251
+ }
9252
+ for (const pos of positionSet) {
9051
9253
  promises.push(this.clearAll(pos));
9052
9254
  }
9053
9255
  }
9054
9256
  return Promise.all(promises).then(() => {
9055
9257
  if (!position) {
9056
- for (const [pos, container] of Array.from(this.containers.entries())) {
9258
+ for (const [key, container] of Array.from(this.containers.entries())) {
9057
9259
  if (!container.firstChild || container.children.length === 0) {
9058
9260
  this.disposeContainer(container);
9059
- this.containers.delete(pos);
9060
- this.activeToasts.delete(pos);
9261
+ this.containers.delete(key);
9061
9262
  }
9062
9263
  }
9264
+ this.activeToasts.clear();
9063
9265
  this.syncContainerRegionLabels();
9064
9266
  }
9065
9267
  });
@@ -9068,8 +9270,10 @@ var __WulfIIFE = (() => {
9068
9270
  * Détruit immédiatement tous les toasts, conteneurs, annonceurs ARIA et temporisations en cours.
9069
9271
  */
9070
9272
  destroy() {
9071
- for (const timerId of this.announceTimers) {
9072
- window.clearTimeout(timerId);
9273
+ if (typeof window !== "undefined") {
9274
+ for (const timerId of this.announceTimers) {
9275
+ window.clearTimeout(timerId);
9276
+ }
9073
9277
  }
9074
9278
  this.announceTimers = [];
9075
9279
  this.politeAnnounceTimerId = null;
@@ -9089,26 +9293,32 @@ var __WulfIIFE = (() => {
9089
9293
  this.replaceTokens.clear();
9090
9294
  this.pendingReplacements.clear();
9091
9295
  if (this.announcerEl) {
9296
+ unregisterToastAnnouncer(this.announcerEl);
9092
9297
  this.announcerEl.remove();
9093
9298
  this.announcerEl = null;
9094
9299
  this.politeRegion = null;
9095
9300
  this.assertiveRegion = null;
9096
9301
  }
9097
- _ToastManager.instance = null;
9302
+ setSharedToastManager(null);
9098
9303
  }
9099
9304
  syncContainerRegionLabels() {
9100
9305
  const useSuffix = this.containers.size > 1;
9101
- for (const [pos, container] of this.containers.entries()) {
9306
+ for (const [key, container] of this.containers.entries()) {
9102
9307
  const baseLabel = this.containerBaseLabels.get(container) || toastI18n.t("notificationsRegion");
9308
+ const pos = key.slice(0, key.lastIndexOf(":"));
9103
9309
  container.setAttribute("aria-label", useSuffix ? `${baseLabel} (${pos})` : baseLabel);
9104
9310
  }
9105
9311
  }
9106
9312
  /**
9107
- * Récupère ou crée le conteneur DOM pour une position d'affichage.
9313
+ * Récupère ou crée le conteneur DOM pour une position et un mode Top Layer donnés.
9108
9314
  */
9109
9315
  getOrCreateContainer(position, toast, useTopLayer) {
9110
- let container = this.containers.get(position);
9316
+ const key = this.getContainerKey(position, useTopLayer);
9317
+ let container = this.containers.get(key);
9111
9318
  if (!container || !document.body.contains(container)) {
9319
+ if (container) {
9320
+ unregisterToastContainer(container);
9321
+ }
9112
9322
  container = document.createElement("div");
9113
9323
  container.className = `wulf-toast-container wulf-toast-${position}`;
9114
9324
  container.setAttribute("role", "region");
@@ -9118,8 +9328,9 @@ var __WulfIIFE = (() => {
9118
9328
  if (useTopLayer && typeof container.showPopover === "function") {
9119
9329
  container.setAttribute("popover", "manual");
9120
9330
  }
9331
+ registerToastContainer(container);
9121
9332
  document.body.appendChild(container);
9122
- this.containers.set(position, container);
9333
+ this.containers.set(key, container);
9123
9334
  this.syncContainerRegionLabels();
9124
9335
  }
9125
9336
  return container;
@@ -9127,7 +9338,7 @@ var __WulfIIFE = (() => {
9127
9338
  };
9128
9339
 
9129
9340
  // src/toast/Toast.ts
9130
- var Toast = class extends LocalizedComponent {
9341
+ var Toast = class _Toast extends LocalizedComponent {
9131
9342
  static _i18n = toastI18n;
9132
9343
  static i18n = toastI18n;
9133
9344
  audit() {
@@ -9150,6 +9361,65 @@ var __WulfIIFE = (() => {
9150
9361
  manager.add(instance);
9151
9362
  return instance;
9152
9363
  }
9364
+ /**
9365
+ * Accompagne une promesse asynchrone avec une notification de chargement puis un résultat succès ou erreur.
9366
+ * Seul le toast de chargement est fermé à la résolution/rejet ; tout rejet est toujours repropagé.
9367
+ */
9368
+ static async promise(promiseOrFactory, options) {
9369
+ const resolveMessage = (spec, arg) => {
9370
+ let resolved;
9371
+ if (typeof spec === "function") {
9372
+ try {
9373
+ resolved = spec(arg);
9374
+ } catch (err) {
9375
+ console.error("[Wulf.Toast] Erreur lors de la r\xE9solution du message Toast.promise:", err);
9376
+ return {};
9377
+ }
9378
+ } else {
9379
+ resolved = spec;
9380
+ }
9381
+ if (typeof resolved === "string") {
9382
+ return { message: resolved };
9383
+ }
9384
+ if (resolved && typeof resolved === "object") {
9385
+ return { ...resolved };
9386
+ }
9387
+ return {};
9388
+ };
9389
+ const baseOpts = options.baseOptions ? { ...options.baseOptions } : {};
9390
+ const loadingOpts = resolveMessage(options.loading, void 0);
9391
+ const loadingToast = _Toast.show({
9392
+ ...baseOpts,
9393
+ duration: false,
9394
+ closable: true,
9395
+ role: "status",
9396
+ ...loadingOpts,
9397
+ replace: false
9398
+ });
9399
+ const targetPromise = typeof promiseOrFactory === "function" ? Promise.resolve().then(() => promiseOrFactory()) : Promise.resolve(promiseOrFactory);
9400
+ try {
9401
+ const data = await targetPromise;
9402
+ await loadingToast.close("replace", true);
9403
+ const successOpts = resolveMessage(options.success, data);
9404
+ _Toast.show({
9405
+ ...baseOpts,
9406
+ role: "status",
9407
+ ...successOpts,
9408
+ replace: false
9409
+ });
9410
+ return data;
9411
+ } catch (err) {
9412
+ await loadingToast.close("replace", true);
9413
+ const errorOpts = resolveMessage(options.error, err);
9414
+ _Toast.show({
9415
+ ...baseOpts,
9416
+ role: "alert",
9417
+ ...errorOpts,
9418
+ replace: false
9419
+ });
9420
+ throw err;
9421
+ }
9422
+ }
9153
9423
  /**
9154
9424
  * Ferme immédiatement l'ensemble des toasts actifs (globalement ou par position) et attend leur retrait complet.
9155
9425
  */
@@ -9166,13 +9436,6 @@ var __WulfIIFE = (() => {
9166
9436
 
9167
9437
  // src/toast/index.ts
9168
9438
  var toast_default = Toast;
9169
- var wulfNamespace4 = getSafeWulfNamespace();
9170
- if (wulfNamespace4) {
9171
- wulfNamespace4.Toast = Object.assign(Toast, {
9172
- Toast,
9173
- i18n: toastI18n
9174
- });
9175
- }
9176
9439
 
9177
9440
  // src/focus-trap/index.ts
9178
9441
  var focus_trap_exports = {};
@@ -9206,7 +9469,9 @@ var __WulfIIFE = (() => {
9206
9469
  return null;
9207
9470
  }
9208
9471
  }
9209
- var trapStack = [];
9472
+ function getTrapStack() {
9473
+ return getSharedTrapStack();
9474
+ }
9210
9475
  var FocusTrap = class extends AuditableComponent {
9211
9476
  element;
9212
9477
  options;
@@ -9223,8 +9488,11 @@ var __WulfIIFE = (() => {
9223
9488
  handleFocusInBound;
9224
9489
  constructor(target, options = {}) {
9225
9490
  super();
9491
+ if (typeof target === "string" && typeof document === "undefined") {
9492
+ throw new Error("[Wulf.FocusTrap] Impossible de r\xE9soudre un s\xE9lecteur CSS sans environnement DOM (document).");
9493
+ }
9226
9494
  const el = typeof target === "string" ? safeQuerySelector(document, target) : target;
9227
- if (!el || !(el instanceof HTMLElement)) {
9495
+ if (!el || typeof HTMLElement === "undefined" || !(el instanceof HTMLElement)) {
9228
9496
  throw new Error(`[Wulf.FocusTrap] Conteneur introuvable ou invalide : "${target}"`);
9229
9497
  }
9230
9498
  this.element = el;
@@ -9279,10 +9547,12 @@ var __WulfIIFE = (() => {
9279
9547
  }
9280
9548
  } else {
9281
9549
  if (el.style.display === "none" || el.style.visibility === "hidden") return false;
9282
- const style = window.getComputedStyle(el);
9283
- if (style.display === "none" || style.visibility === "hidden") return false;
9284
- if (el.offsetWidth === 0 && el.offsetHeight === 0 && style.position !== "fixed") {
9285
- return false;
9550
+ if (typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
9551
+ const style = window.getComputedStyle(el);
9552
+ if (style.display === "none" || style.visibility === "hidden") return false;
9553
+ if (el.offsetWidth === 0 && el.offsetHeight === 0 && style.position !== "fixed") {
9554
+ return false;
9555
+ }
9286
9556
  }
9287
9557
  }
9288
9558
  return true;
@@ -9301,9 +9571,11 @@ var __WulfIIFE = (() => {
9301
9571
  isFocusable(el) {
9302
9572
  if (!this.isElementFocusableBase(el)) return false;
9303
9573
  if (el instanceof HTMLInputElement && el.type === "radio" && el.name) {
9574
+ const rootNode = typeof el.getRootNode === "function" ? el.getRootNode() : this.element;
9575
+ const scopeRoot = el.form && this.isNodeInsideContainer(el.form) ? el.form : rootNode && (rootNode instanceof Document || typeof ShadowRoot !== "undefined" && rootNode instanceof ShadowRoot) ? rootNode : this.element;
9304
9576
  const group = Array.from(
9305
- this.element.querySelectorAll(`input[type="radio"][name="${safeCssEscape(el.name)}"]`)
9306
- ).filter((r) => r.form === el.form && this.isElementFocusableBase(r));
9577
+ scopeRoot.querySelectorAll(`input[type="radio"][name="${safeCssEscape(el.name)}"]`)
9578
+ ).filter((r) => r.form === el.form && this.isNodeInsideContainer(r) && this.isElementFocusableBase(r));
9307
9579
  if (group.length === 0) return false;
9308
9580
  const checked = group.find((r) => r.checked);
9309
9581
  if (checked) {
@@ -9313,18 +9585,68 @@ var __WulfIIFE = (() => {
9313
9585
  }
9314
9586
  return true;
9315
9587
  }
9588
+ collectFocusables(root, out, seen) {
9589
+ const children = root.children;
9590
+ for (let i = 0; i < children.length; i++) {
9591
+ const child = children[i];
9592
+ if (!(child instanceof HTMLElement)) continue;
9593
+ if (child.hasAttribute("inert") || child.hidden) continue;
9594
+ let matchesSelector = false;
9595
+ try {
9596
+ matchesSelector = child.matches(FOCUSABLE_SELECTOR);
9597
+ } catch {
9598
+ matchesSelector = false;
9599
+ }
9600
+ if (matchesSelector && !seen.has(child) && this.isFocusable(child)) {
9601
+ seen.add(child);
9602
+ out.push(child);
9603
+ }
9604
+ if (child.shadowRoot) {
9605
+ this.collectFocusables(child.shadowRoot, out, seen);
9606
+ }
9607
+ if (child.tagName === "SLOT") {
9608
+ const assigned = child.assignedElements({ flatten: true });
9609
+ for (const slotted of assigned) {
9610
+ if (!(slotted instanceof HTMLElement)) continue;
9611
+ if (slotted.hasAttribute("inert") || slotted.hidden) continue;
9612
+ let slottedMatches = false;
9613
+ try {
9614
+ slottedMatches = slotted.matches(FOCUSABLE_SELECTOR);
9615
+ } catch {
9616
+ slottedMatches = false;
9617
+ }
9618
+ if (slottedMatches && !seen.has(slotted) && this.isFocusable(slotted)) {
9619
+ seen.add(slotted);
9620
+ out.push(slotted);
9621
+ }
9622
+ if (slotted.shadowRoot) {
9623
+ this.collectFocusables(slotted.shadowRoot, out, seen);
9624
+ }
9625
+ this.collectFocusables(slotted, out, seen);
9626
+ }
9627
+ } else {
9628
+ this.collectFocusables(child, out, seen);
9629
+ }
9630
+ }
9631
+ }
9316
9632
  /**
9317
- * Retourne tous les éléments focusables réels ordonnés dans le conteneur.
9633
+ * Retourne tous les éléments focusables réels ordonnés dans le conteneur (Light DOM + Shadow DOM ouverts).
9318
9634
  */
9319
9635
  getFocusableElements() {
9320
- const rawElements = Array.from(this.element.querySelectorAll(FOCUSABLE_SELECTOR));
9321
- return rawElements.filter((el) => this.isFocusable(el));
9636
+ const out = [];
9637
+ const seen = /* @__PURE__ */ new Set();
9638
+ if (this.element.shadowRoot) {
9639
+ this.collectFocusables(this.element.shadowRoot, out, seen);
9640
+ }
9641
+ this.collectFocusables(this.element, out, seen);
9642
+ return out;
9322
9643
  }
9323
9644
  /**
9324
9645
  * Active le trap.
9325
9646
  */
9326
9647
  activate() {
9327
- if (this.active) return this;
9648
+ if (this.active || typeof document === "undefined") return this;
9649
+ const trapStack = getTrapStack();
9328
9650
  const currentTop = trapStack[trapStack.length - 1];
9329
9651
  if (currentTop) {
9330
9652
  currentTop.pause();
@@ -9365,6 +9687,7 @@ var __WulfIIFE = (() => {
9365
9687
  */
9366
9688
  deactivate() {
9367
9689
  if (!this.active) return this;
9690
+ const trapStack = getTrapStack();
9368
9691
  const wasTop = trapStack[trapStack.length - 1] === this;
9369
9692
  this.active = false;
9370
9693
  this.paused = false;
@@ -9409,6 +9732,7 @@ var __WulfIIFE = (() => {
9409
9732
  */
9410
9733
  unpause() {
9411
9734
  if (!this.active) return;
9735
+ const trapStack = getTrapStack();
9412
9736
  if (trapStack[trapStack.length - 1] !== this) return;
9413
9737
  this.paused = false;
9414
9738
  if (this.options.setInert && !this.isNativeModalDialog()) {
@@ -9491,8 +9815,23 @@ var __WulfIIFE = (() => {
9491
9815
  this.deactivate();
9492
9816
  }
9493
9817
  // --- Implémentation interne ---
9818
+ isNodeInsideContainer(node) {
9819
+ let current = node;
9820
+ while (current) {
9821
+ if (current === this.element || this.element.contains(current)) {
9822
+ return true;
9823
+ }
9824
+ const root = typeof current.getRootNode === "function" ? current.getRootNode() : null;
9825
+ if (typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot && root.host) {
9826
+ current = root.host;
9827
+ } else {
9828
+ break;
9829
+ }
9830
+ }
9831
+ return false;
9832
+ }
9494
9833
  isEventInside(e, target) {
9495
- if (target && this.element.contains(target)) {
9834
+ if (this.isNodeInsideContainer(target)) {
9496
9835
  return true;
9497
9836
  }
9498
9837
  if (typeof e.composedPath === "function") {
@@ -9504,11 +9843,25 @@ var __WulfIIFE = (() => {
9504
9843
  return false;
9505
9844
  }
9506
9845
  isInsideToastContainer(target) {
9507
- if (!target || !(target instanceof Element)) return false;
9508
- const container = target.closest(".wulf-toast-container");
9509
- return Boolean(container && container.parentElement === document.body && !this.element.contains(container));
9510
- }
9511
- ensureContainerTabIndex() {
9846
+ if (typeof document === "undefined" || !target) return false;
9847
+ let current = target;
9848
+ while (current) {
9849
+ if (current instanceof Element) {
9850
+ const container = current.closest(".wulf-toast-container");
9851
+ if (container && isRegisteredToastContainer(container) && container.parentElement === document.body && !this.isNodeInsideContainer(container)) {
9852
+ return true;
9853
+ }
9854
+ }
9855
+ const root = typeof current.getRootNode === "function" ? current.getRootNode() : null;
9856
+ if (typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot && root.host) {
9857
+ current = root.host;
9858
+ } else {
9859
+ break;
9860
+ }
9861
+ }
9862
+ return false;
9863
+ }
9864
+ ensureContainerTabIndex() {
9512
9865
  if (this.element.getAttribute("tabindex") === null) {
9513
9866
  this.element.setAttribute("tabindex", "-1");
9514
9867
  this.addedContainerTabIndex = true;
@@ -9546,7 +9899,7 @@ var __WulfIIFE = (() => {
9546
9899
  const last = focusables[focusables.length - 1];
9547
9900
  const deepCurrent = getDeepActiveElement(document);
9548
9901
  const current = deepCurrent instanceof HTMLElement ? deepCurrent : document.activeElement;
9549
- const isInside = current ? this.element.contains(current) || this.isEventInside(e, current) : false;
9902
+ const isInside = current ? this.isNodeInsideContainer(current) || this.isEventInside(e, current) : false;
9550
9903
  if (!e.shiftKey && (current === last || !isInside)) {
9551
9904
  e.preventDefault();
9552
9905
  first.focus();
@@ -9605,13 +9958,14 @@ var __WulfIIFE = (() => {
9605
9958
  */
9606
9959
  applyInert() {
9607
9960
  this.removeInert();
9961
+ if (typeof document === "undefined") return;
9608
9962
  let current = this.element;
9609
9963
  const ignoredTags = /* @__PURE__ */ new Set(["SCRIPT", "STYLE", "TEMPLATE", "LINK", "META", "NOSCRIPT"]);
9610
9964
  while (current && current !== document.body) {
9611
9965
  const parent = current.parentElement;
9612
9966
  if (parent) {
9613
9967
  for (const sibling of Array.from(parent.children)) {
9614
- if (sibling instanceof HTMLElement && sibling !== current && !ignoredTags.has(sibling.tagName) && !sibling.hasAttribute("inert") && !(parent === document.body && sibling.matches(".wulf-toast-container, .wulf-toast-announcer"))) {
9968
+ if (sibling instanceof HTMLElement && sibling !== current && !ignoredTags.has(sibling.tagName) && !sibling.hasAttribute("inert") && !(parent === document.body && (isRegisteredToastContainer(sibling) || isRegisteredToastAnnouncer(sibling)))) {
9615
9969
  sibling.setAttribute("inert", "");
9616
9970
  this.inertSiblings.push(sibling);
9617
9971
  }
@@ -9643,7 +9997,7 @@ var __WulfIIFE = (() => {
9643
9997
  if (typeof this.options.initialFocus === "string") {
9644
9998
  targetEl = safeQuerySelector(this.element, this.options.initialFocus);
9645
9999
  } else if (this.options.initialFocus instanceof HTMLElement) {
9646
- targetEl = this.element.contains(this.options.initialFocus) ? this.options.initialFocus : null;
10000
+ targetEl = this.isNodeInsideContainer(this.options.initialFocus) ? this.options.initialFocus : null;
9647
10001
  }
9648
10002
  if (targetEl) {
9649
10003
  const isRadio = targetEl instanceof HTMLInputElement && targetEl.type === "radio" && Boolean(targetEl.name);
@@ -9666,7 +10020,7 @@ var __WulfIIFE = (() => {
9666
10020
  this.previousActiveElement.focus();
9667
10021
  return;
9668
10022
  }
9669
- if (this.options.fallbackReturnFocus) {
10023
+ if (this.options.fallbackReturnFocus && typeof document !== "undefined") {
9670
10024
  const fallback = typeof this.options.fallbackReturnFocus === "string" ? safeQuerySelector(document, this.options.fallbackReturnFocus) : this.options.fallbackReturnFocus;
9671
10025
  if (fallback && fallback.isConnected && this.isProgrammaticallyFocusable(fallback)) {
9672
10026
  fallback.focus();
@@ -9675,14 +10029,6 @@ var __WulfIIFE = (() => {
9675
10029
  }
9676
10030
  };
9677
10031
 
9678
- // src/focus-trap/index.ts
9679
- var wulfNamespace5 = getSafeWulfNamespace();
9680
- if (wulfNamespace5) {
9681
- wulfNamespace5.FocusTrap = Object.assign(FocusTrap, {
9682
- FocusTrap
9683
- });
9684
- }
9685
-
9686
10032
  // src/shortcut/index.ts
9687
10033
  var shortcut_exports = {};
9688
10034
  __export(shortcut_exports, {
@@ -9979,6 +10325,8 @@ var __WulfIIFE = (() => {
9979
10325
  sequenceBuffer = [];
9980
10326
  sequenceTimer = null;
9981
10327
  isListening = true;
10328
+ isDestroyed = false;
10329
+ emittedAuditWarnings = /* @__PURE__ */ new Set();
9982
10330
  boundListener = null;
9983
10331
  abortController = null;
9984
10332
  idCounter = 0;
@@ -9990,7 +10338,8 @@ var __WulfIIFE = (() => {
9990
10338
  defaultScope: options?.defaultScope || "global",
9991
10339
  sequenceTimeout,
9992
10340
  target: options?.target || (typeof window !== "undefined" ? window : {}),
9993
- onError: options?.onError
10341
+ onError: options?.onError,
10342
+ audit: options?.audit ?? true
9994
10343
  };
9995
10344
  this.scopeStack = [this.options.defaultScope];
9996
10345
  this.initListener();
@@ -10077,6 +10426,10 @@ var __WulfIIFE = (() => {
10077
10426
  * Retourne une fonction de nettoyage pour désenregistrer immédiatement.
10078
10427
  */
10079
10428
  bind(definition) {
10429
+ if (this.isDestroyed) {
10430
+ return () => {
10431
+ };
10432
+ }
10080
10433
  const list = Array.isArray(definition) ? definition : [definition];
10081
10434
  const registeredIds = [];
10082
10435
  for (const def of list) {
@@ -10106,6 +10459,20 @@ var __WulfIIFE = (() => {
10106
10459
  this.shortcuts.set(id, registered);
10107
10460
  registeredIds.push(id);
10108
10461
  }
10462
+ if (registeredIds.length > 0 && this.options.audit) {
10463
+ const warnings = this.audit();
10464
+ const newWarnings = warnings.filter((w) => !this.emittedAuditWarnings.has(w));
10465
+ if (newWarnings.length > 0) {
10466
+ newWarnings.forEach((w) => this.emittedAuditWarnings.add(w));
10467
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
10468
+ console.warn(
10469
+ `[${this.getAuditPrefix()}] Audit d'accessibilit\xE9 \u2014 ${newWarnings.length} contrainte(s) manquante(s) sur ${this.getAuditTargetLabel()} :
10470
+ ` + newWarnings.map((w) => ` - ${w}`).join("\n") + `
10471
+ (${this.getAuditDisableHint()})`
10472
+ );
10473
+ }
10474
+ }
10475
+ }
10109
10476
  return () => {
10110
10477
  for (const id of registeredIds) {
10111
10478
  this.shortcuts.delete(id);
@@ -10191,6 +10558,7 @@ var __WulfIIFE = (() => {
10191
10558
  * Réactive l'écoute des raccourcis.
10192
10559
  */
10193
10560
  resume() {
10561
+ if (this.isDestroyed) return;
10194
10562
  this.isListening = true;
10195
10563
  }
10196
10564
  /**
@@ -10270,9 +10638,12 @@ var __WulfIIFE = (() => {
10270
10638
  * Détruit le gestionnaire : supprime les écouteurs du DOM et vide toute la mémoire.
10271
10639
  */
10272
10640
  destroy() {
10641
+ if (this.isDestroyed) return;
10642
+ this.isDestroyed = true;
10273
10643
  this.pause();
10274
10644
  this.removeListener();
10275
10645
  this.shortcuts.clear();
10646
+ this.emittedAuditWarnings.clear();
10276
10647
  this.scopeStack = [];
10277
10648
  this.clearSequenceBuffer();
10278
10649
  }
@@ -10304,7 +10675,7 @@ var __WulfIIFE = (() => {
10304
10675
  this.boundListener = null;
10305
10676
  }
10306
10677
  handleKeyDown(event) {
10307
- if (!this.isListening || isImeComposing(event)) {
10678
+ if (this.isDestroyed || !this.isListening || isImeComposing(event)) {
10308
10679
  return;
10309
10680
  }
10310
10681
  const k = (event.key || "").toLowerCase();
@@ -10338,13 +10709,13 @@ var __WulfIIFE = (() => {
10338
10709
  }
10339
10710
  const activeCandidates = this.getActiveShortcuts(currentScope, isEditable, isSensitiveInput, isTypeahead);
10340
10711
  const proposedSequence = [...this.sequenceBuffer.map((b) => b.step), currentStep];
10341
- const matchingSequence = this.findMatchingSequence(activeCandidates, proposedSequence);
10712
+ const matchingSequence = this.findMatchingSequence(activeCandidates, proposedSequence, event);
10342
10713
  if (matchingSequence) {
10343
10714
  this.clearSequenceBuffer();
10344
10715
  this.executeShortcut(matchingSequence, event, currentScope, true);
10345
10716
  return;
10346
10717
  }
10347
- if (this.isPrefixOfAnySequence(activeCandidates, proposedSequence)) {
10718
+ if (this.isPrefixOfAnySequence(activeCandidates, proposedSequence, event)) {
10348
10719
  this.sequenceBuffer.push({ step: currentStep, timestamp: now });
10349
10720
  this.resetSequenceTimer();
10350
10721
  if (event.key.length === 1 && !event.ctrlKey && !event.altKey && !event.metaKey && !isEditable && !isTypeahead) {
@@ -10424,14 +10795,15 @@ var __WulfIIFE = (() => {
10424
10795
  }
10425
10796
  return null;
10426
10797
  }
10427
- findMatchingSequence(candidates, proposed) {
10798
+ findMatchingSequence(candidates, proposed, rawEvent) {
10428
10799
  for (const candidate of candidates) {
10429
10800
  if (!candidate.isSequence || candidate.normalizedSteps.length !== proposed.length) {
10430
10801
  continue;
10431
10802
  }
10432
10803
  let allMatch = true;
10433
10804
  for (let i = 0; i < proposed.length; i++) {
10434
- if (!this.stepMatches(candidate.normalizedSteps[i], proposed[i])) {
10805
+ const stepEvent = i === proposed.length - 1 ? rawEvent : void 0;
10806
+ if (!this.stepMatches(candidate.normalizedSteps[i], proposed[i], stepEvent)) {
10435
10807
  allMatch = false;
10436
10808
  break;
10437
10809
  }
@@ -10442,14 +10814,15 @@ var __WulfIIFE = (() => {
10442
10814
  }
10443
10815
  return null;
10444
10816
  }
10445
- isPrefixOfAnySequence(candidates, proposed) {
10817
+ isPrefixOfAnySequence(candidates, proposed, rawEvent) {
10446
10818
  for (const candidate of candidates) {
10447
10819
  if (!candidate.isSequence || candidate.normalizedSteps.length <= proposed.length) {
10448
10820
  continue;
10449
10821
  }
10450
10822
  let prefixMatches = true;
10451
10823
  for (let i = 0; i < proposed.length; i++) {
10452
- if (!this.stepMatches(candidate.normalizedSteps[i], proposed[i])) {
10824
+ const stepEvent = i === proposed.length - 1 ? rawEvent : void 0;
10825
+ if (!this.stepMatches(candidate.normalizedSteps[i], proposed[i], stepEvent)) {
10453
10826
  prefixMatches = false;
10454
10827
  break;
10455
10828
  }
@@ -10505,15 +10878,3100 @@ var __WulfIIFE = (() => {
10505
10878
  }
10506
10879
  };
10507
10880
 
10508
- // src/shortcut/index.ts
10509
- var wulfNamespace6 = getSafeWulfNamespace();
10510
- if (wulfNamespace6) {
10511
- wulfNamespace6.Shortcut = Object.assign(ShortcutManager, {
10512
- ShortcutManager,
10513
- ShortcutFormatter
10514
- });
10881
+ // src/anchor/index.ts
10882
+ var anchor_exports = {};
10883
+ __export(anchor_exports, {
10884
+ Anchor: () => Anchor,
10885
+ default: () => Anchor
10886
+ });
10887
+
10888
+ // src/anchor/Anchor.ts
10889
+ var anchorIdCounter = 0;
10890
+ var ALL_PLACEMENTS = [
10891
+ "bottom-start",
10892
+ "bottom",
10893
+ "bottom-end",
10894
+ "top-start",
10895
+ "top",
10896
+ "top-end",
10897
+ "right-start",
10898
+ "right",
10899
+ "right-end",
10900
+ "left-start",
10901
+ "left",
10902
+ "left-end"
10903
+ ];
10904
+ var PLACEMENT_SET = new Set(ALL_PLACEMENTS);
10905
+ function resolveCandidatePlacements(preferred) {
10906
+ const seen = /* @__PURE__ */ new Set();
10907
+ const out = [];
10908
+ if (Array.isArray(preferred)) {
10909
+ for (const p of preferred) {
10910
+ if (typeof p === "string" && PLACEMENT_SET.has(p) && !seen.has(p)) {
10911
+ seen.add(p);
10912
+ out.push(p);
10913
+ }
10914
+ }
10915
+ }
10916
+ for (const p of ALL_PLACEMENTS) {
10917
+ if (!seen.has(p)) out.push(p);
10918
+ }
10919
+ return out;
10920
+ }
10921
+ var OPPOSITE_SIDE = {
10922
+ top: "bottom",
10923
+ bottom: "top",
10924
+ left: "right",
10925
+ right: "left"
10926
+ };
10927
+ var ROLE_BY_HASPOPUP = {
10928
+ menu: "menu",
10929
+ listbox: "listbox",
10930
+ tree: "tree",
10931
+ grid: "grid",
10932
+ dialog: "dialog"
10933
+ };
10934
+ function resolveEl(target, root) {
10935
+ if (typeof target !== "string") {
10936
+ return typeof HTMLElement !== "undefined" && target instanceof HTMLElement ? target : null;
10937
+ }
10938
+ if (!target || typeof document === "undefined") return null;
10939
+ try {
10940
+ return (root ?? document).querySelector(target);
10941
+ } catch {
10942
+ return null;
10943
+ }
10944
+ }
10945
+ function getParentCrossingShadow(el) {
10946
+ if (el.parentElement) return el.parentElement;
10947
+ const root = typeof el.getRootNode === "function" ? el.getRootNode() : null;
10948
+ if (typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot && root.host instanceof HTMLElement) {
10949
+ return root.host;
10950
+ }
10951
+ return null;
10952
+ }
10953
+ function isTopLayerElement(el) {
10954
+ try {
10955
+ return el.matches(":popover-open") || el.matches(":modal");
10956
+ } catch {
10957
+ return el.classList.contains(":popover-open");
10958
+ }
10959
+ }
10960
+ function isRtlElement(el) {
10961
+ if (typeof window === "undefined" || typeof window.getComputedStyle !== "function") return false;
10962
+ return window.getComputedStyle(el).direction === "rtl";
10963
+ }
10964
+ function parsePlacement(placement) {
10965
+ const idx = placement.indexOf("-");
10966
+ if (idx === -1) return [placement, null];
10967
+ return [placement.slice(0, idx), placement.slice(idx + 1)];
10968
+ }
10969
+ function toLogicalPositionArea(side, alignment, rtl) {
10970
+ const inlineStart = rtl ? "right" : "left";
10971
+ const blockPos = side === "top" ? "block-start" : side === "bottom" ? "block-end" : null;
10972
+ if (blockPos) {
10973
+ if (!alignment) return blockPos;
10974
+ return `${blockPos} ${alignment === "start" ? "span-inline-end" : "span-inline-start"}`;
10975
+ }
10976
+ const inlinePos = side === inlineStart ? "inline-start" : "inline-end";
10977
+ if (!alignment) return inlinePos;
10978
+ return `${inlinePos} ${alignment === "start" ? "span-block-end" : "span-block-start"}`;
10979
+ }
10980
+ function intersectRects(a, b) {
10981
+ const x = Math.max(a.x, b.x);
10982
+ const y = Math.max(a.y, b.y);
10983
+ const right = Math.min(a.x + a.width, b.x + b.width);
10984
+ const bottom = Math.min(a.y + a.height, b.y + b.height);
10985
+ return { x, y, width: Math.max(0, right - x), height: Math.max(0, bottom - y) };
10986
+ }
10987
+ function getViewportRect() {
10988
+ if (typeof window === "undefined" || typeof document === "undefined") {
10989
+ return { x: 0, y: 0, width: 0, height: 0 };
10990
+ }
10991
+ const vv = window.visualViewport;
10992
+ if (vv) {
10993
+ return { x: vv.offsetLeft, y: vv.offsetTop, width: vv.width, height: vv.height };
10994
+ }
10995
+ return {
10996
+ x: 0,
10997
+ y: 0,
10998
+ width: document.documentElement.clientWidth || window.innerWidth,
10999
+ height: document.documentElement.clientHeight || window.innerHeight
11000
+ };
11001
+ }
11002
+ function getBoundaryRect(floating, boundary) {
11003
+ if (boundary && typeof boundary === "object" && !("nodeType" in boundary)) {
11004
+ return { ...boundary };
11005
+ }
11006
+ if (typeof HTMLElement !== "undefined" && boundary instanceof HTMLElement) {
11007
+ const r = boundary.getBoundingClientRect();
11008
+ return { x: r.left, y: r.top, width: r.width, height: r.height };
11009
+ }
11010
+ let rect = getViewportRect();
11011
+ if (boundary === "viewport" || isTopLayerElement(floating) || typeof window === "undefined") {
11012
+ return rect;
11013
+ }
11014
+ const clipRe = /(hidden|clip|auto|scroll)/;
11015
+ let cur = getParentCrossingShadow(floating);
11016
+ while (cur && cur !== document.body && cur !== document.documentElement) {
11017
+ const cs = window.getComputedStyle(cur);
11018
+ if (clipRe.test(cs.overflow + cs.overflowX + cs.overflowY)) {
11019
+ const cr = cur.getBoundingClientRect();
11020
+ rect = intersectRects(rect, {
11021
+ x: cr.left + cur.clientLeft,
11022
+ y: cr.top + cur.clientTop,
11023
+ width: cur.clientWidth || cr.width,
11024
+ height: cur.clientHeight || cr.height
11025
+ });
11026
+ }
11027
+ cur = getParentCrossingShadow(cur);
11028
+ }
11029
+ return rect;
11030
+ }
11031
+ function getContainingBlockOffset(floating, strategy) {
11032
+ if (typeof window === "undefined") return { x: 0, y: 0 };
11033
+ if (strategy === "absolute") {
11034
+ const op = floating.offsetParent;
11035
+ if (op instanceof HTMLElement && op !== document.body && op !== document.documentElement) {
11036
+ const r = op.getBoundingClientRect();
11037
+ return { x: r.left + op.clientLeft - op.scrollLeft, y: r.top + op.clientTop - op.scrollTop };
11038
+ }
11039
+ return { x: -window.scrollX, y: -window.scrollY };
11040
+ }
11041
+ if (isTopLayerElement(floating)) return { x: 0, y: 0 };
11042
+ let cur = getParentCrossingShadow(floating);
11043
+ while (cur && cur !== document.documentElement) {
11044
+ const cs = window.getComputedStyle(cur);
11045
+ if (cs.transform !== "none" || cs.perspective !== "none" || cs.filter !== "none" || cs.backdropFilter && cs.backdropFilter !== "none" || /layout|paint|strict|content/.test(cs.contain) || /transform|perspective|filter/.test(cs.willChange)) {
11046
+ const r = cur.getBoundingClientRect();
11047
+ return {
11048
+ x: r.left + cur.clientLeft - cur.scrollLeft,
11049
+ y: r.top + cur.clientTop - cur.scrollTop
11050
+ };
11051
+ }
11052
+ cur = getParentCrossingShadow(cur);
11053
+ }
11054
+ return { x: 0, y: 0 };
11055
+ }
11056
+ var Anchor = class _Anchor extends AuditableComponent {
11057
+ reference;
11058
+ floating;
11059
+ options;
11060
+ anchorName;
11061
+ isDestroyed = false;
11062
+ isRunning = false;
11063
+ nativeApplied = false;
11064
+ rafId = null;
11065
+ resizeObserver = null;
11066
+ abortController = null;
11067
+ savedRefAnchorName = "";
11068
+ savedFloatingStyles = {};
11069
+ savedPlacementAttr = null;
11070
+ savedArrowStyles = null;
11071
+ constructor(reference, floating, options = {}) {
11072
+ super();
11073
+ const refEl = resolveEl(reference);
11074
+ const floatEl = resolveEl(floating);
11075
+ if (!refEl || !floatEl) {
11076
+ throw new Error("[Wulf.Anchor] \xC9l\xE9ments reference et floating valides requis.");
11077
+ }
11078
+ this.reference = refEl;
11079
+ this.floating = floatEl;
11080
+ this.anchorName = `--wulf-anchor-${++anchorIdCounter}`;
11081
+ const arrowEl = options.arrow ? typeof options.arrow === "string" ? resolveEl(options.arrow, floatEl) ?? resolveEl(options.arrow) : resolveEl(options.arrow) : null;
11082
+ const rawPad = options.padding;
11083
+ const padding = typeof rawPad === "number" && Number.isFinite(rawPad) && rawPad >= 0 ? rawPad : 8;
11084
+ const rawArrowPad = options.arrowPadding;
11085
+ const arrowPadding = typeof rawArrowPad === "number" && Number.isFinite(rawArrowPad) && rawArrowPad >= 0 ? rawArrowPad : 6;
11086
+ this.options = {
11087
+ placement: options.placement ?? "bottom-start",
11088
+ strategy: options.strategy ?? "fixed",
11089
+ offset: options.offset ?? 8,
11090
+ flip: options.flip ?? true,
11091
+ shift: options.shift ?? true,
11092
+ padding,
11093
+ arrow: arrowEl,
11094
+ arrowPadding,
11095
+ boundary: options.boundary ?? "clippingAncestors",
11096
+ autoUpdate: options.autoUpdate ?? true,
11097
+ useNativeAnchor: options.useNativeAnchor ?? false,
11098
+ preferredPlacements: Array.isArray(options.preferredPlacements) ? [...options.preferredPlacements] : void 0,
11099
+ onPosition: options.onPosition,
11100
+ audit: options.audit ?? true
11101
+ };
11102
+ this.saveInitialState();
11103
+ this.update();
11104
+ if (this.options.autoUpdate) {
11105
+ this.start();
11106
+ }
11107
+ this.runAuditWarning(this.options.audit);
11108
+ }
11109
+ /**
11110
+ * Détecte si CSS Anchor Positioning natif (anchor-name + position-area) est supporté.
11111
+ */
11112
+ static supportsNativeAnchor() {
11113
+ return typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("anchor-name", "--wulf-a") && CSS.supports("position-area", "block-end");
11114
+ }
11115
+ /**
11116
+ * Calcule la position géométrique optimale sans muter le DOM.
11117
+ */
11118
+ static computePosition(reference, floating, options = {}) {
11119
+ const placement = options.placement ?? "bottom-start";
11120
+ const strategy = options.strategy ?? "fixed";
11121
+ const flip = options.flip ?? true;
11122
+ const shift = options.shift ?? true;
11123
+ const padding = typeof options.padding === "number" && Number.isFinite(options.padding) ? Math.max(0, options.padding) : 8;
11124
+ const arrowPadding = typeof options.arrowPadding === "number" && Number.isFinite(options.arrowPadding) ? Math.max(0, options.arrowPadding) : 6;
11125
+ const rawOffset = options.offset ?? 8;
11126
+ const mainOffset = typeof rawOffset === "number" ? rawOffset : rawOffset.mainAxis ?? 8;
11127
+ const crossOffset = typeof rawOffset === "number" ? 0 : rawOffset.crossAxis ?? 0;
11128
+ const refRect = reference.getBoundingClientRect();
11129
+ const floatRect = floating.getBoundingClientRect();
11130
+ const boundary = getBoundaryRect(floating, options.boundary ?? "clippingAncestors");
11131
+ const cb = getContainingBlockOffset(floating, strategy);
11132
+ const rtl = isRtlElement(floating) || isRtlElement(reference);
11133
+ const placeFor = (s, al) => {
11134
+ let vx2 = 0;
11135
+ let vy2 = 0;
11136
+ if (s === "top" || s === "bottom") {
11137
+ vy2 = s === "bottom" ? refRect.bottom + mainOffset : refRect.top - floatRect.height - mainOffset;
11138
+ if (!al) {
11139
+ vx2 = refRect.left + (refRect.width - floatRect.width) / 2;
11140
+ } else {
11141
+ const alignLeft = al === "start" !== rtl;
11142
+ vx2 = alignLeft ? refRect.left : refRect.right - floatRect.width;
11143
+ }
11144
+ vx2 += rtl ? -crossOffset : crossOffset;
11145
+ } else {
11146
+ vx2 = s === "right" ? refRect.right + mainOffset : refRect.left - floatRect.width - mainOffset;
11147
+ if (!al) {
11148
+ vy2 = refRect.top + (refRect.height - floatRect.height) / 2;
11149
+ } else {
11150
+ vy2 = al === "start" ? refRect.top : refRect.bottom - floatRect.height;
11151
+ }
11152
+ vy2 += crossOffset;
11153
+ }
11154
+ return { vx: vx2, vy: vy2 };
11155
+ };
11156
+ let side;
11157
+ let alignment;
11158
+ let vx;
11159
+ let vy;
11160
+ if (placement === "best") {
11161
+ const candidates = resolveCandidatePlacements(options.preferredPlacements);
11162
+ let chosen = candidates[0];
11163
+ if (floatRect.width > 0 || floatRect.height > 0) {
11164
+ const minX = boundary.x + padding - 0.5;
11165
+ const maxX = boundary.x + boundary.width - padding + 0.5;
11166
+ const minY = boundary.y + padding - 0.5;
11167
+ const maxY = boundary.y + boundary.height - padding + 0.5;
11168
+ for (const cand of candidates) {
11169
+ const [cs, ca] = parsePlacement(cand);
11170
+ const pos = placeFor(cs, ca);
11171
+ if (pos.vx >= minX && pos.vx + floatRect.width <= maxX && pos.vy >= minY && pos.vy + floatRect.height <= maxY) {
11172
+ chosen = cand;
11173
+ break;
11174
+ }
11175
+ }
11176
+ }
11177
+ [side, alignment] = parsePlacement(chosen);
11178
+ ({ vx, vy } = placeFor(side, alignment));
11179
+ } else {
11180
+ [side, alignment] = parsePlacement(placement);
11181
+ ({ vx, vy } = placeFor(side, alignment));
11182
+ if (flip) {
11183
+ const opp = OPPOSITE_SIDE[side];
11184
+ const availCurrent = side === "bottom" ? boundary.y + boundary.height - padding - (refRect.bottom + mainOffset) : side === "top" ? refRect.top - mainOffset - (boundary.y + padding) : side === "right" ? boundary.x + boundary.width - padding - (refRect.right + mainOffset) : refRect.left - mainOffset - (boundary.x + padding);
11185
+ const availOpp = opp === "bottom" ? boundary.y + boundary.height - padding - (refRect.bottom + mainOffset) : opp === "top" ? refRect.top - mainOffset - (boundary.y + padding) : opp === "right" ? boundary.x + boundary.width - padding - (refRect.right + mainOffset) : refRect.left - mainOffset - (boundary.x + padding);
11186
+ const needed = side === "top" || side === "bottom" ? floatRect.height : floatRect.width;
11187
+ if (availCurrent < needed && availOpp > availCurrent) {
11188
+ side = opp;
11189
+ ({ vx, vy } = placeFor(side, alignment));
11190
+ }
11191
+ }
11192
+ }
11193
+ if (shift) {
11194
+ if (side === "top" || side === "bottom") {
11195
+ const minX = boundary.x + padding;
11196
+ const maxX = Math.max(minX, boundary.x + boundary.width - floatRect.width - padding);
11197
+ vx = Math.min(Math.max(vx, minX), maxX);
11198
+ } else {
11199
+ const minY = boundary.y + padding;
11200
+ const maxY = Math.max(minY, boundary.y + boundary.height - floatRect.height - padding);
11201
+ vy = Math.min(Math.max(vy, minY), maxY);
11202
+ }
11203
+ }
11204
+ const effectivePlacement = alignment ? `${side}-${alignment}` : side;
11205
+ const x = Math.round((vx - cb.x) * 100) / 100;
11206
+ const y = Math.round((vy - cb.y) * 100) / 100;
11207
+ let arrowX = null;
11208
+ let arrowY = null;
11209
+ const arrowEl = options.arrow instanceof HTMLElement ? options.arrow : null;
11210
+ if (arrowEl) {
11211
+ const ar = arrowEl.getBoundingClientRect();
11212
+ if (side === "top" || side === "bottom") {
11213
+ const maxAx = Math.max(arrowPadding, floatRect.width - ar.width - arrowPadding);
11214
+ arrowX = Math.round(Math.min(Math.max(refRect.left + refRect.width / 2 - vx - ar.width / 2, arrowPadding), maxAx) * 100) / 100;
11215
+ } else {
11216
+ const maxAy = Math.max(arrowPadding, floatRect.height - ar.height - arrowPadding);
11217
+ arrowY = Math.round(Math.min(Math.max(refRect.top + refRect.height / 2 - vy - ar.height / 2, arrowPadding), maxAy) * 100) / 100;
11218
+ }
11219
+ }
11220
+ const isReferenceClipped = refRect.right <= boundary.x || refRect.left >= boundary.x + boundary.width || refRect.bottom <= boundary.y || refRect.top >= boundary.y + boundary.height;
11221
+ return {
11222
+ x,
11223
+ y,
11224
+ viewportX: Math.round(vx * 100) / 100,
11225
+ viewportY: Math.round(vy * 100) / 100,
11226
+ placement: effectivePlacement,
11227
+ side,
11228
+ alignment,
11229
+ arrowX,
11230
+ arrowY,
11231
+ isNative: false,
11232
+ isReferenceClipped
11233
+ };
11234
+ }
11235
+ update() {
11236
+ if (this.isDestroyed) {
11237
+ const fallbackPlacement = this.options.placement === "best" ? resolveCandidatePlacements(this.options.preferredPlacements)[0] : this.options.placement;
11238
+ const [side, alignment] = parsePlacement(fallbackPlacement);
11239
+ return {
11240
+ x: 0,
11241
+ y: 0,
11242
+ viewportX: 0,
11243
+ viewportY: 0,
11244
+ placement: fallbackPlacement,
11245
+ side,
11246
+ alignment,
11247
+ arrowX: null,
11248
+ arrowY: null,
11249
+ isNative: false,
11250
+ isReferenceClipped: false
11251
+ };
11252
+ }
11253
+ const canUseNative = this.options.useNativeAnchor && this.options.placement !== "best" && !this.options.arrow && this.options.strategy === "fixed" && _Anchor.supportsNativeAnchor();
11254
+ let result;
11255
+ if (canUseNative) {
11256
+ const nativePlacement = this.options.placement;
11257
+ const [side, alignment] = parsePlacement(nativePlacement);
11258
+ const rtl = isRtlElement(this.floating) || isRtlElement(this.reference);
11259
+ const fStyle = this.floating.style;
11260
+ const rStyle = this.reference.style;
11261
+ rStyle.anchorName = this.anchorName;
11262
+ fStyle.position = "fixed";
11263
+ fStyle.inset = "auto";
11264
+ fStyle.margin = "0";
11265
+ fStyle.positionAnchor = this.anchorName;
11266
+ fStyle.positionArea = toLogicalPositionArea(side, alignment, rtl);
11267
+ if (this.options.flip) {
11268
+ fStyle.positionTryFallbacks = "flip-block, flip-inline, flip-block flip-inline";
11269
+ }
11270
+ this.nativeApplied = true;
11271
+ this.floating.setAttribute("data-anchor-placement", nativePlacement);
11272
+ const fr = this.floating.getBoundingClientRect();
11273
+ result = {
11274
+ x: fr.left,
11275
+ y: fr.top,
11276
+ viewportX: fr.left,
11277
+ viewportY: fr.top,
11278
+ placement: nativePlacement,
11279
+ side,
11280
+ alignment,
11281
+ arrowX: null,
11282
+ arrowY: null,
11283
+ isNative: true,
11284
+ isReferenceClipped: false
11285
+ };
11286
+ } else {
11287
+ if (this.nativeApplied) {
11288
+ this.restoreNativeStyles();
11289
+ }
11290
+ result = _Anchor.computePosition(this.reference, this.floating, {
11291
+ ...this.options,
11292
+ arrow: this.options.arrow
11293
+ });
11294
+ this.floating.style.position = this.options.strategy;
11295
+ this.floating.style.left = `${result.x}px`;
11296
+ this.floating.style.top = `${result.y}px`;
11297
+ this.floating.style.setProperty("--wulf-anchor-x", `${result.x}px`);
11298
+ this.floating.style.setProperty("--wulf-anchor-y", `${result.y}px`);
11299
+ this.floating.setAttribute("data-anchor-placement", result.placement);
11300
+ if (this.options.arrow) {
11301
+ if (result.arrowX !== null) {
11302
+ this.options.arrow.style.left = `${result.arrowX}px`;
11303
+ this.options.arrow.style.top = "";
11304
+ this.options.arrow.style.setProperty("--wulf-anchor-arrow-x", `${result.arrowX}px`);
11305
+ } else if (result.arrowY !== null) {
11306
+ this.options.arrow.style.top = `${result.arrowY}px`;
11307
+ this.options.arrow.style.left = "";
11308
+ this.options.arrow.style.setProperty("--wulf-anchor-arrow-y", `${result.arrowY}px`);
11309
+ }
11310
+ }
11311
+ }
11312
+ if (this.options.onPosition) {
11313
+ try {
11314
+ this.options.onPosition(result);
11315
+ } catch (err) {
11316
+ console.error("[Wulf.Anchor] Erreur dans onPosition:", err);
11317
+ }
11318
+ }
11319
+ return result;
11320
+ }
11321
+ setPlacement(placement) {
11322
+ if (!this.isDestroyed) {
11323
+ this.options.placement = placement;
11324
+ this.update();
11325
+ }
11326
+ return this;
11327
+ }
11328
+ start() {
11329
+ if (this.isDestroyed || this.isRunning || typeof window === "undefined") return this;
11330
+ this.isRunning = true;
11331
+ this.abortController = new AbortController();
11332
+ const { signal } = this.abortController;
11333
+ const schedule = () => {
11334
+ if (this.isDestroyed || this.rafId !== null) return;
11335
+ this.rafId = window.requestAnimationFrame(() => {
11336
+ this.rafId = null;
11337
+ if (!this.isDestroyed) this.update();
11338
+ });
11339
+ };
11340
+ if (typeof ResizeObserver !== "undefined") {
11341
+ const lastSizes = /* @__PURE__ */ new WeakMap();
11342
+ this.resizeObserver = new ResizeObserver((entries) => {
11343
+ if (this.isDestroyed) return;
11344
+ let changed = false;
11345
+ for (const entry of entries) {
11346
+ const w = entry.borderBoxSize?.[0]?.inlineSize ?? entry.contentRect.width;
11347
+ const h = entry.borderBoxSize?.[0]?.blockSize ?? entry.contentRect.height;
11348
+ const prev = lastSizes.get(entry.target);
11349
+ if (!prev || Math.abs(w - prev.w) >= 0.5 || Math.abs(h - prev.h) >= 0.5) {
11350
+ lastSizes.set(entry.target, { w, h });
11351
+ changed = true;
11352
+ }
11353
+ }
11354
+ if (changed) {
11355
+ this.update();
11356
+ }
11357
+ });
11358
+ this.resizeObserver.observe(this.reference);
11359
+ this.resizeObserver.observe(this.floating);
11360
+ }
11361
+ const seenScrollParents = /* @__PURE__ */ new Set();
11362
+ for (const startNode of [this.reference, this.floating]) {
11363
+ let cur = startNode;
11364
+ while (cur) {
11365
+ if (!seenScrollParents.has(cur)) {
11366
+ seenScrollParents.add(cur);
11367
+ cur.addEventListener("scroll", schedule, { passive: true, signal });
11368
+ }
11369
+ cur = getParentCrossingShadow(cur);
11370
+ }
11371
+ }
11372
+ window.addEventListener("scroll", schedule, { passive: true, signal });
11373
+ window.addEventListener("resize", schedule, { passive: true, signal });
11374
+ if (window.visualViewport) {
11375
+ window.visualViewport.addEventListener("scroll", schedule, { passive: true, signal });
11376
+ window.visualViewport.addEventListener("resize", schedule, { passive: true, signal });
11377
+ }
11378
+ this.floating.addEventListener(
11379
+ "beforetoggle",
11380
+ (ev) => {
11381
+ if (ev.newState === "open") {
11382
+ schedule();
11383
+ queueMicrotask(() => {
11384
+ if (!this.isDestroyed && isTopLayerElement(this.floating)) {
11385
+ this.update();
11386
+ }
11387
+ });
11388
+ }
11389
+ },
11390
+ { signal }
11391
+ );
11392
+ return this;
11393
+ }
11394
+ stop() {
11395
+ this.isRunning = false;
11396
+ if (this.rafId !== null && typeof window !== "undefined") {
11397
+ window.cancelAnimationFrame(this.rafId);
11398
+ this.rafId = null;
11399
+ }
11400
+ this.abortController?.abort();
11401
+ this.abortController = null;
11402
+ this.resizeObserver?.disconnect();
11403
+ this.resizeObserver = null;
11404
+ return this;
11405
+ }
11406
+ audit() {
11407
+ const warnings = [];
11408
+ const floatRole = this.floating.getAttribute("role");
11409
+ if (floatRole === "tooltip") {
11410
+ const hasDesc = this.checkAriaIdReferences(this.reference, "aria-describedby", warnings, true);
11411
+ if (!hasDesc) {
11412
+ warnings.push('\xC9l\xE9ment role="tooltip" sans liaison aria-describedby valide sur la r\xE9f\xE9rence (WCAG 4.1.2).');
11413
+ }
11414
+ } else if (this.reference.hasAttribute("aria-describedby")) {
11415
+ this.checkAriaIdReferences(this.reference, "aria-describedby", warnings, true);
11416
+ }
11417
+ if (this.reference.hasAttribute("aria-controls")) {
11418
+ this.checkAriaIdReferences(this.reference, "aria-controls", warnings, false);
11419
+ }
11420
+ const hasPopup = this.reference.getAttribute("aria-haspopup");
11421
+ if (hasPopup && ROLE_BY_HASPOPUP[hasPopup] && floatRole !== ROLE_BY_HASPOPUP[hasPopup]) {
11422
+ warnings.push(
11423
+ `Attribut aria-haspopup="${hasPopup}" sur la r\xE9f\xE9rence sans role="${ROLE_BY_HASPOPUP[hasPopup]}" correspondant sur le panneau.`
11424
+ );
11425
+ }
11426
+ return warnings;
11427
+ }
11428
+ getAuditPrefix() {
11429
+ return "Wulf.Anchor";
11430
+ }
11431
+ getAuditTargetLabel() {
11432
+ return this.floating.id ? `#${this.floating.id}` : `<${this.floating.tagName.toLowerCase()}>`;
11433
+ }
11434
+ destroy() {
11435
+ if (this.isDestroyed) return;
11436
+ this.isDestroyed = true;
11437
+ this.stop();
11438
+ this.restoreNativeStyles();
11439
+ const fStyle = this.floating.style;
11440
+ fStyle.position = this.savedFloatingStyles.position;
11441
+ fStyle.left = this.savedFloatingStyles.left;
11442
+ fStyle.top = this.savedFloatingStyles.top;
11443
+ this.floating.style.removeProperty("--wulf-anchor-x");
11444
+ this.floating.style.removeProperty("--wulf-anchor-y");
11445
+ if (this.savedPlacementAttr === null) {
11446
+ this.floating.removeAttribute("data-anchor-placement");
11447
+ } else {
11448
+ this.floating.setAttribute("data-anchor-placement", this.savedPlacementAttr);
11449
+ }
11450
+ if (this.options.arrow && this.savedArrowStyles) {
11451
+ this.options.arrow.style.left = this.savedArrowStyles.left;
11452
+ this.options.arrow.style.top = this.savedArrowStyles.top;
11453
+ this.options.arrow.style.removeProperty("--wulf-anchor-arrow-x");
11454
+ this.options.arrow.style.removeProperty("--wulf-anchor-arrow-y");
11455
+ }
11456
+ }
11457
+ restoreNativeStyles() {
11458
+ const rStyle = this.reference.style;
11459
+ rStyle.anchorName = this.savedRefAnchorName;
11460
+ const fStyle = this.floating.style;
11461
+ fStyle.inset = this.savedFloatingStyles.inset;
11462
+ fStyle.margin = this.savedFloatingStyles.margin;
11463
+ fStyle.positionAnchor = this.savedFloatingStyles.positionAnchor;
11464
+ fStyle.positionArea = this.savedFloatingStyles.positionArea;
11465
+ fStyle.positionTryFallbacks = this.savedFloatingStyles.positionTryFallbacks;
11466
+ this.nativeApplied = false;
11467
+ }
11468
+ saveInitialState() {
11469
+ const rStyle = this.reference.style;
11470
+ this.savedRefAnchorName = rStyle.anchorName ?? "";
11471
+ const fStyle = this.floating.style;
11472
+ this.savedFloatingStyles = {
11473
+ position: fStyle.position,
11474
+ left: fStyle.left,
11475
+ top: fStyle.top,
11476
+ inset: fStyle.inset,
11477
+ margin: fStyle.margin,
11478
+ positionAnchor: fStyle.positionAnchor ?? "",
11479
+ positionArea: fStyle.positionArea ?? "",
11480
+ positionTryFallbacks: fStyle.positionTryFallbacks ?? ""
11481
+ };
11482
+ this.savedPlacementAttr = this.floating.getAttribute("data-anchor-placement");
11483
+ if (this.options.arrow) {
11484
+ this.savedArrowStyles = {
11485
+ left: this.options.arrow.style.left,
11486
+ top: this.options.arrow.style.top
11487
+ };
11488
+ }
11489
+ }
11490
+ };
11491
+
11492
+ // src/sortable/index.ts
11493
+ var sortable_exports = {};
11494
+ __export(sortable_exports, {
11495
+ LocalizedComponent: () => LocalizedComponent,
11496
+ Sortable: () => Sortable,
11497
+ createI18nManager: () => createI18nManager,
11498
+ default: () => Sortable,
11499
+ sortableEn: () => sortableEn,
11500
+ sortableFr: () => sortableFr,
11501
+ sortableI18n: () => sortableI18n
11502
+ });
11503
+
11504
+ // src/sortable/i18n/fr.ts
11505
+ var sortableFr = {
11506
+ grabbed: (label, position, total) => `${label} saisi en position ${position} sur ${total}. Utilisez les fl\xE8ches pour d\xE9placer, Entr\xE9e ou Espace pour d\xE9poser, \xC9chap pour annuler.`,
11507
+ moved: (label, position, total) => `${label} d\xE9plac\xE9 en position ${position} sur ${total}.`,
11508
+ dropped: (label, position, total) => `${label} d\xE9pos\xE9 en position ${position} sur ${total}.`,
11509
+ cancelled: (label, position, total) => `D\xE9placement annul\xE9. ${label} replac\xE9 en position ${position} sur ${total}.`,
11510
+ defaultItemLabel: (position) => `\xC9l\xE9ment ${position}`
11511
+ };
11512
+
11513
+ // src/sortable/i18n/en.ts
11514
+ var sortableEn = {
11515
+ grabbed: (label, position, total) => `${label} grabbed at position ${position} of ${total}. Use arrow keys to move, Enter or Space to drop, Escape to cancel.`,
11516
+ moved: (label, position, total) => `${label} moved to position ${position} of ${total}.`,
11517
+ dropped: (label, position, total) => `${label} dropped at position ${position} of ${total}.`,
11518
+ cancelled: (label, position, total) => `Reordering cancelled. ${label} returned to position ${position} of ${total}.`,
11519
+ defaultItemLabel: (position) => `Item ${position}`
11520
+ };
11521
+
11522
+ // src/sortable/i18n/index.ts
11523
+ var sortableI18n = createI18nManager("fr", {
11524
+ fr: sortableFr,
11525
+ en: sortableEn
11526
+ });
11527
+
11528
+ // src/sortable/Sortable.ts
11529
+ var INTERACTIVE_DESCENDANT_SELECTOR = 'input, textarea, select, button, a[href], label, [contenteditable], [role="button"], [role="textbox"], [role="searchbox"], [role="combobox"], [role="spinbutton"], [role="slider"]';
11530
+ var NATIVELY_FOCUSABLE_SELECTOR = "button, a[href], input, select, textarea, summary, [tabindex]";
11531
+ function clampNumber(value, fallback, min, max) {
11532
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
11533
+ return Math.min(max, Math.max(min, value));
11534
+ }
11535
+ function resolveContainer(target) {
11536
+ if (typeof target === "string") {
11537
+ if (!target) return null;
11538
+ try {
11539
+ return document.querySelector(target);
11540
+ } catch {
11541
+ return null;
11542
+ }
11543
+ }
11544
+ if (typeof HTMLElement !== "undefined" && target instanceof HTMLElement) {
11545
+ return target;
11546
+ }
11547
+ return null;
11548
+ }
11549
+ function isEditableTarget(target) {
11550
+ if (!target || typeof target.tagName !== "string") return false;
11551
+ const el = target;
11552
+ const tag = el.tagName.toUpperCase();
11553
+ if (tag === "INPUT") {
11554
+ const type = el.type?.toLowerCase() || "text";
11555
+ return !["button", "checkbox", "radio", "submit", "reset", "range", "color", "file", "image"].includes(type);
11556
+ }
11557
+ if (tag === "TEXTAREA" || tag === "SELECT") return true;
11558
+ const ce = el.getAttribute?.("contenteditable")?.toLowerCase();
11559
+ if (el.isContentEditable || ce === "true" || ce === "plaintext-only" || ce === "") {
11560
+ return true;
11561
+ }
11562
+ const role = el.getAttribute?.("role");
11563
+ if (role === "textbox" || role === "searchbox" || role === "combobox" || role === "spinbutton") {
11564
+ return true;
11565
+ }
11566
+ return Boolean(
11567
+ el.closest?.(
11568
+ '[contenteditable="true"], [contenteditable="plaintext-only"], [contenteditable=""], [role="textbox"], [role="searchbox"], [role="combobox"], [role="spinbutton"]'
11569
+ )
11570
+ );
11571
+ }
11572
+ function moveItemInDom(container, item, siblings, targetIndex) {
11573
+ if (siblings.length === 0) return;
11574
+ const clamped = Math.max(0, Math.min(targetIndex, siblings.length));
11575
+ const referenceNode = clamped < siblings.length ? siblings[clamped] : siblings[siblings.length - 1].nextSibling;
11576
+ if (item.nextSibling !== referenceNode) {
11577
+ safeMove(container, item, referenceNode);
11578
+ }
11579
+ }
11580
+ function computeReorderedArray(items, fromIndex, toIndex) {
11581
+ const next = items.slice();
11582
+ if (fromIndex < 0 || fromIndex >= next.length) return next;
11583
+ const clampedTo = Math.max(0, Math.min(toIndex, next.length - 1));
11584
+ const [moved] = next.splice(fromIndex, 1);
11585
+ next.splice(clampedTo, 0, moved);
11586
+ return next;
10515
11587
  }
11588
+ var Sortable = class extends LocalizedComponent {
11589
+ static _i18n = sortableI18n;
11590
+ static i18n = sortableI18n;
11591
+ container;
11592
+ options;
11593
+ isDestroyed = false;
11594
+ isMovingFocus = false;
11595
+ dragSessionSeq = 0;
11596
+ rootAbort = new AbortController();
11597
+ pointerDrag = null;
11598
+ keyboardGrab = null;
11599
+ hadRootClass = false;
11600
+ savedAttributes = /* @__PURE__ */ new Map();
11601
+ addedHandles = /* @__PURE__ */ new Set();
11602
+ activeAnimations = /* @__PURE__ */ new WeakMap();
11603
+ srStatusEl = null;
11604
+ announceTimerId = null;
11605
+ mutationObserver = null;
11606
+ constructor(target, options = {}) {
11607
+ super(options.i18n);
11608
+ this.options = {
11609
+ itemSelector: options.itemSelector,
11610
+ handleSelector: options.handleSelector,
11611
+ axis: options.axis ?? "y",
11612
+ autoMove: options.autoMove ?? true,
11613
+ threshold: clampNumber(options.threshold, 5, 0, 100),
11614
+ animationDuration: clampNumber(options.animationDuration, 180, 0, 2e3),
11615
+ autoScroll: options.autoScroll ?? true,
11616
+ autoScrollSpeed: clampNumber(options.autoScrollSpeed, 12, 1, 30),
11617
+ disabled: Boolean(options.disabled),
11618
+ lang: options.lang,
11619
+ getItemLabel: options.getItemLabel,
11620
+ onStart: options.onStart,
11621
+ onMove: options.onMove,
11622
+ onReorder: options.onReorder,
11623
+ onCancel: options.onCancel,
11624
+ audit: options.audit ?? true
11625
+ };
11626
+ if (typeof document === "undefined" || typeof window === "undefined") {
11627
+ this.container = null;
11628
+ return;
11629
+ }
11630
+ const resolved = resolveContainer(target);
11631
+ if (!resolved) {
11632
+ throw new Error("[Wulf.Sortable] Conteneur HTMLElement ou s\xE9lecteur CSS valide requis.");
11633
+ }
11634
+ this.container = resolved;
11635
+ this.hadRootClass = resolved.classList.contains("wulf-sortable");
11636
+ resolved.classList.add("wulf-sortable");
11637
+ this.mountStatusRegion();
11638
+ this.refresh();
11639
+ this.bindContainerEvents();
11640
+ this.observeDomChanges();
11641
+ this.runAuditWarning(this.options.audit);
11642
+ }
11643
+ getAuditPrefix() {
11644
+ return "Wulf.Sortable";
11645
+ }
11646
+ getAuditTargetLabel() {
11647
+ if (!this.container) return "<ssr>";
11648
+ if (this.container.id) return `#${this.container.id}`;
11649
+ return `<${this.container.tagName.toLowerCase()}>`;
11650
+ }
11651
+ getItems() {
11652
+ if (!this.container || this.isDestroyed) return [];
11653
+ if (this.options.itemSelector) {
11654
+ try {
11655
+ return Array.from(this.container.querySelectorAll(this.options.itemSelector)).filter(
11656
+ (el) => !el.hasAttribute("data-wulf-sortable-ignore") && !el.classList.contains("wulf-sortable-sr-status")
11657
+ );
11658
+ } catch {
11659
+ return [];
11660
+ }
11661
+ }
11662
+ const result = [];
11663
+ for (const child of Array.from(this.container.children)) {
11664
+ if (typeof HTMLElement !== "undefined" && child instanceof HTMLElement && !child.hasAttribute("data-wulf-sortable-ignore") && !child.classList.contains("wulf-sortable-sr-status")) {
11665
+ result.push(child);
11666
+ }
11667
+ }
11668
+ return result;
11669
+ }
11670
+ isDisabled() {
11671
+ return this.options.disabled;
11672
+ }
11673
+ isDragging() {
11674
+ return Boolean(this.pointerDrag?.started || this.keyboardGrab);
11675
+ }
11676
+ setDisabled(disabled) {
11677
+ const next = Boolean(disabled);
11678
+ if (this.options.disabled === next) return;
11679
+ this.options.disabled = next;
11680
+ if (next) {
11681
+ this.cancel();
11682
+ }
11683
+ }
11684
+ updateOptions(options) {
11685
+ if (this.isDestroyed || !options) return;
11686
+ if (options.i18n !== void 0) this.i18nOverrides = options.i18n;
11687
+ if (options.itemSelector !== void 0) this.options.itemSelector = options.itemSelector;
11688
+ if (options.handleSelector !== void 0) this.options.handleSelector = options.handleSelector;
11689
+ if (options.axis !== void 0) this.options.axis = options.axis;
11690
+ if (options.autoMove !== void 0) this.options.autoMove = Boolean(options.autoMove);
11691
+ if (options.threshold !== void 0) {
11692
+ this.options.threshold = clampNumber(options.threshold, 5, 0, 100);
11693
+ }
11694
+ if (options.animationDuration !== void 0) {
11695
+ this.options.animationDuration = clampNumber(options.animationDuration, 180, 0, 2e3);
11696
+ }
11697
+ if (options.autoScroll !== void 0) this.options.autoScroll = Boolean(options.autoScroll);
11698
+ if (options.autoScrollSpeed !== void 0) {
11699
+ this.options.autoScrollSpeed = clampNumber(options.autoScrollSpeed, 12, 1, 30);
11700
+ }
11701
+ if (options.lang !== void 0) this.options.lang = options.lang;
11702
+ if (options.getItemLabel !== void 0) this.options.getItemLabel = options.getItemLabel;
11703
+ if (options.onStart !== void 0) this.options.onStart = options.onStart;
11704
+ if (options.onMove !== void 0) this.options.onMove = options.onMove;
11705
+ if (options.onReorder !== void 0) this.options.onReorder = options.onReorder;
11706
+ if (options.onCancel !== void 0) this.options.onCancel = options.onCancel;
11707
+ if (options.disabled !== void 0) this.setDisabled(options.disabled);
11708
+ this.refresh();
11709
+ }
11710
+ refresh() {
11711
+ if (!this.container || this.isDestroyed) return;
11712
+ const items = this.getItems();
11713
+ for (const item of items) {
11714
+ const target = this.resolveTriggerForItem(item);
11715
+ if (target) {
11716
+ if (this.options.handleSelector && target !== item) {
11717
+ target.classList.add("wulf-sortable-handle");
11718
+ this.addedHandles.add(target);
11719
+ }
11720
+ if (!this.savedAttributes.has(target)) {
11721
+ this.savedAttributes.set(target, {
11722
+ hadTabIndex: target.hasAttribute("tabindex"),
11723
+ prevTabIndex: target.getAttribute("tabindex"),
11724
+ hadAriaPressed: target.hasAttribute("aria-pressed"),
11725
+ prevAriaPressed: target.getAttribute("aria-pressed")
11726
+ });
11727
+ }
11728
+ if (!target.matches(NATIVELY_FOCUSABLE_SELECTOR) && !target.hasAttribute("tabindex")) {
11729
+ target.setAttribute("tabindex", "0");
11730
+ }
11731
+ }
11732
+ }
11733
+ }
11734
+ move(fromIndex, toIndex) {
11735
+ if (!this.container || this.isDestroyed) return false;
11736
+ const items = this.getItems();
11737
+ if (!Number.isInteger(fromIndex) || !Number.isInteger(toIndex) || fromIndex < 0 || toIndex < 0 || fromIndex >= items.length || toIndex >= items.length || fromIndex === toIndex) {
11738
+ return false;
11739
+ }
11740
+ const item = items[fromIndex];
11741
+ const siblings = items.filter((el) => el !== item);
11742
+ const ordered = computeReorderedArray(items, fromIndex, toIndex);
11743
+ if (this.options.autoMove) {
11744
+ const beforeRects = this.snapshotRects(items);
11745
+ moveItemInDom(this.container, item, siblings, toIndex);
11746
+ this.animateFlip(items, beforeRects);
11747
+ }
11748
+ this.emitReorder({
11749
+ item,
11750
+ oldIndex: fromIndex,
11751
+ newIndex: toIndex,
11752
+ items: ordered,
11753
+ trigger: "programmatic"
11754
+ });
11755
+ return true;
11756
+ }
11757
+ cancel() {
11758
+ if (this.isDestroyed) return;
11759
+ if (this.pointerDrag) {
11760
+ this.endPointerDrag(true);
11761
+ }
11762
+ if (this.keyboardGrab) {
11763
+ this.cancelKeyboardGrab();
11764
+ }
11765
+ }
11766
+ audit() {
11767
+ if (!this.container || this.isDestroyed) return [];
11768
+ const warnings = [];
11769
+ const hasAriaLabel = Boolean(this.container.getAttribute("aria-label")?.trim());
11770
+ const hasLabelledBy = this.checkAriaIdReferences(this.container, "aria-labelledby", warnings, true);
11771
+ this.checkAriaIdReferences(this.container, "aria-describedby", warnings, true);
11772
+ if (!hasAriaLabel && !hasLabelledBy) {
11773
+ warnings.push(
11774
+ "Aucun nom accessible d\xE9tect\xE9 sur le conteneur triable (ajoutez aria-label ou aria-labelledby)."
11775
+ );
11776
+ }
11777
+ if (this.container.hasAttribute("aria-live")) {
11778
+ warnings.push(
11779
+ "\xC9vitez aria-live directement sur le conteneur triable (annoncez via une r\xE9gion status d\xE9di\xE9e ou ariaNotify)."
11780
+ );
11781
+ }
11782
+ const items = this.getItems();
11783
+ items.forEach((item, index) => {
11784
+ const rawTab = item.getAttribute("tabindex");
11785
+ if (rawTab !== null && Number.parseInt(rawTab, 10) > 0) {
11786
+ warnings.push(
11787
+ `\xC9vitez tabindex="${rawTab}" (> 0) sur l'\xE9l\xE9ment #${index + 1} pour pr\xE9server l'ordre de tabulation naturel.`
11788
+ );
11789
+ }
11790
+ if (this.options.handleSelector) {
11791
+ const handle = this.resolveTriggerForItem(item);
11792
+ if (!handle || handle === item) {
11793
+ warnings.push(`Poign\xE9e introuvable ("${this.options.handleSelector}") dans l'\xE9l\xE9ment #${index + 1}.`);
11794
+ return;
11795
+ }
11796
+ const hTab = handle.getAttribute("tabindex");
11797
+ if (hTab !== null && Number.parseInt(hTab, 10) > 0) {
11798
+ warnings.push(`\xC9vitez tabindex="${hTab}" (> 0) sur la poign\xE9e de l'\xE9l\xE9ment #${index + 1}.`);
11799
+ }
11800
+ const isFocusable = handle.matches("button:not([disabled]), a[href], input:not([disabled]), [tabindex]") && handle.getAttribute("tabindex") !== "-1";
11801
+ if (!isFocusable) {
11802
+ warnings.push(`La poign\xE9e de l'\xE9l\xE9ment #${index + 1} doit \xEAtre focusable au clavier.`);
11803
+ }
11804
+ const hLabel = handle.getAttribute("aria-label")?.trim() || handle.textContent?.trim() || "";
11805
+ const hLabelledBy = this.checkAriaIdReferences(handle, "aria-labelledby", warnings, true);
11806
+ if (!hLabel && !hLabelledBy) {
11807
+ warnings.push(`La poign\xE9e de l'\xE9l\xE9ment #${index + 1} ne poss\xE8de aucun nom accessible.`);
11808
+ }
11809
+ }
11810
+ });
11811
+ return warnings;
11812
+ }
11813
+ destroy() {
11814
+ if (this.isDestroyed) return;
11815
+ this.isDestroyed = true;
11816
+ this.cancel();
11817
+ this.rootAbort.abort();
11818
+ if (this.mutationObserver) {
11819
+ this.mutationObserver.disconnect();
11820
+ this.mutationObserver = null;
11821
+ }
11822
+ if (this.announceTimerId !== null) {
11823
+ clearTimeout(this.announceTimerId);
11824
+ this.announceTimerId = null;
11825
+ }
11826
+ if (this.srStatusEl) {
11827
+ this.srStatusEl.remove();
11828
+ this.srStatusEl = null;
11829
+ }
11830
+ if (this.container) {
11831
+ this.clearDropMarker();
11832
+ this.container.classList.remove("wulf-sortable--dragging");
11833
+ if (!this.hadRootClass) {
11834
+ this.container.classList.remove("wulf-sortable");
11835
+ }
11836
+ }
11837
+ for (const handle of this.addedHandles) {
11838
+ handle.classList.remove("wulf-sortable-handle");
11839
+ }
11840
+ this.addedHandles.clear();
11841
+ for (const [el, saved] of this.savedAttributes.entries()) {
11842
+ el.classList.remove("wulf-sortable-item--dragging", "wulf-sortable-item--grabbed");
11843
+ el.removeAttribute("data-wulf-dragging");
11844
+ el.removeAttribute("data-wulf-grabbed");
11845
+ if (saved.hadTabIndex && saved.prevTabIndex !== null) {
11846
+ el.setAttribute("tabindex", saved.prevTabIndex);
11847
+ } else if (!saved.hadTabIndex) {
11848
+ el.removeAttribute("tabindex");
11849
+ }
11850
+ if (saved.hadAriaPressed && saved.prevAriaPressed !== null) {
11851
+ el.setAttribute("aria-pressed", saved.prevAriaPressed);
11852
+ } else if (!saved.hadAriaPressed) {
11853
+ el.removeAttribute("aria-pressed");
11854
+ }
11855
+ }
11856
+ this.savedAttributes.clear();
11857
+ }
11858
+ resolveI18n() {
11859
+ if (this.options.lang) {
11860
+ const prev = sortableI18n.getLocale();
11861
+ sortableI18n.setLocale(this.options.lang);
11862
+ const dict = sortableI18n.getAll(this.i18nOverrides);
11863
+ sortableI18n.setLocale(prev);
11864
+ return dict;
11865
+ }
11866
+ return sortableI18n.getAll(this.i18nOverrides);
11867
+ }
11868
+ getItemLabelText(item, index) {
11869
+ if (typeof this.options.getItemLabel === "function") {
11870
+ try {
11871
+ const custom = stripBidiAndInvisibles(this.options.getItemLabel(item, index), 200).trim();
11872
+ if (custom) return custom;
11873
+ } catch {
11874
+ }
11875
+ }
11876
+ const raw = item.getAttribute("aria-label") || item.getAttribute("data-label") || item.textContent || "";
11877
+ const clean = stripBidiAndInvisibles(raw, 200).replace(/\s+/g, " ").trim();
11878
+ if (clean) return clean.slice(0, 80);
11879
+ return this.resolveI18n().defaultItemLabel(index + 1);
11880
+ }
11881
+ mountStatusRegion() {
11882
+ if (!this.container || typeof document === "undefined") return;
11883
+ if (typeof document.ariaNotify === "function") {
11884
+ return;
11885
+ }
11886
+ const status = document.createElement("div");
11887
+ status.className = "wulf-sortable-sr-status";
11888
+ status.setAttribute("role", "status");
11889
+ status.setAttribute("aria-live", "polite");
11890
+ status.setAttribute("aria-atomic", "true");
11891
+ status.setAttribute("data-wulf-sortable-ignore", "true");
11892
+ const root = typeof this.container.getRootNode === "function" ? this.container.getRootNode() : document;
11893
+ const mountTarget = typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot ? root : document.body || this.container;
11894
+ mountTarget.appendChild(status);
11895
+ this.srStatusEl = status;
11896
+ }
11897
+ announce(message) {
11898
+ if (this.isDestroyed || typeof document === "undefined") return;
11899
+ const clean = stripBidiAndInvisibles(message, 400).trim();
11900
+ if (!clean) return;
11901
+ const docWithNotify = document;
11902
+ if (typeof docWithNotify.ariaNotify === "function") {
11903
+ try {
11904
+ docWithNotify.ariaNotify(clean, { priority: "normal" });
11905
+ return;
11906
+ } catch {
11907
+ }
11908
+ }
11909
+ if (!this.srStatusEl) {
11910
+ this.mountStatusRegion();
11911
+ }
11912
+ if (!this.srStatusEl) return;
11913
+ if (this.announceTimerId !== null) {
11914
+ clearTimeout(this.announceTimerId);
11915
+ this.announceTimerId = null;
11916
+ }
11917
+ this.srStatusEl.textContent = "";
11918
+ this.announceTimerId = setTimeout(() => {
11919
+ this.announceTimerId = null;
11920
+ if (!this.isDestroyed && this.srStatusEl) {
11921
+ this.srStatusEl.textContent = clean;
11922
+ }
11923
+ }, 40);
11924
+ }
11925
+ resolveTriggerForItem(item) {
11926
+ if (!this.options.handleSelector) return item;
11927
+ try {
11928
+ const handle = item.querySelector(this.options.handleSelector);
11929
+ return handle ?? null;
11930
+ } catch {
11931
+ return null;
11932
+ }
11933
+ }
11934
+ findItemForEvent(event) {
11935
+ if (!this.container) return null;
11936
+ const items = this.getItems();
11937
+ if (items.length === 0) return null;
11938
+ const itemSet = new Set(items);
11939
+ const path = typeof event.composedPath === "function" ? event.composedPath() : [event.target];
11940
+ for (const node of path) {
11941
+ if (node && itemSet.has(node)) {
11942
+ return node;
11943
+ }
11944
+ if (node === this.container) break;
11945
+ }
11946
+ return null;
11947
+ }
11948
+ hasInteractiveDescendantBeforeItem(event, item) {
11949
+ const path = typeof event.composedPath === "function" ? event.composedPath() : [event.target];
11950
+ for (const node of path) {
11951
+ if (!node || node === item) break;
11952
+ if (typeof Element !== "undefined" && node instanceof Element) {
11953
+ if (isEditableTarget(node) || node.matches(INTERACTIVE_DESCENDANT_SELECTOR)) {
11954
+ return true;
11955
+ }
11956
+ }
11957
+ }
11958
+ return false;
11959
+ }
11960
+ findHandleInPath(event, item) {
11961
+ if (!this.options.handleSelector) return item;
11962
+ const path = typeof event.composedPath === "function" ? event.composedPath() : [event.target];
11963
+ for (const node of path) {
11964
+ if (!node) continue;
11965
+ if (typeof HTMLElement !== "undefined" && node instanceof HTMLElement) {
11966
+ try {
11967
+ if (node.matches(this.options.handleSelector) && item.contains(node)) {
11968
+ if (node.hasAttribute("disabled") || node.getAttribute("aria-disabled") === "true") {
11969
+ return null;
11970
+ }
11971
+ return node;
11972
+ }
11973
+ } catch {
11974
+ return null;
11975
+ }
11976
+ }
11977
+ if (node === item) break;
11978
+ }
11979
+ return null;
11980
+ }
11981
+ bindContainerEvents() {
11982
+ if (!this.container) return;
11983
+ const signal = this.rootAbort.signal;
11984
+ this.container.addEventListener("pointerdown", (e) => this.handlePointerDown(e), { signal });
11985
+ this.container.addEventListener("keydown", (e) => this.handleKeyDown(e), { signal });
11986
+ this.container.addEventListener("focusout", (e) => this.handleFocusOut(e), { signal });
11987
+ this.container.addEventListener("focusin", (e) => this.handleFocusIn(e), { signal });
11988
+ }
11989
+ observeDomChanges() {
11990
+ if (!this.container || typeof MutationObserver === "undefined") return;
11991
+ this.mutationObserver = new MutationObserver(() => {
11992
+ if (!this.isDestroyed && !this.pointerDrag?.started) {
11993
+ this.refresh();
11994
+ }
11995
+ });
11996
+ this.mutationObserver.observe(this.container, { childList: true });
11997
+ }
11998
+ handleFocusIn(event) {
11999
+ if (!this.container || this.isDestroyed) return;
12000
+ const target = event.target;
12001
+ if (!target || typeof target.matches !== "function") return;
12002
+ let isFocusVisible = false;
12003
+ try {
12004
+ isFocusVisible = target.matches(":focus-visible");
12005
+ } catch {
12006
+ isFocusVisible = false;
12007
+ }
12008
+ if (!isFocusVisible) return;
12009
+ const item = this.findItemForEvent(event);
12010
+ if (!item || typeof item.scrollIntoView !== "function") return;
12011
+ const running = typeof item.getAnimations === "function" && item.getAnimations().some((a) => a.playState === "running");
12012
+ if (!running) {
12013
+ item.scrollIntoView({ block: "nearest", inline: "nearest" });
12014
+ }
12015
+ }
12016
+ handlePointerDown(event) {
12017
+ if (!this.container || this.isDestroyed || this.options.disabled) return;
12018
+ if (this.pointerDrag || event.button !== 0 || event.isPrimary === false) return;
12019
+ if (isEditableTarget(event.target)) return;
12020
+ const item = this.findItemForEvent(event);
12021
+ if (!item) return;
12022
+ let handle = item;
12023
+ if (this.options.handleSelector) {
12024
+ handle = this.findHandleInPath(event, item);
12025
+ if (!handle) return;
12026
+ } else if (this.hasInteractiveDescendantBeforeItem(event, item)) {
12027
+ return;
12028
+ }
12029
+ if (this.keyboardGrab) {
12030
+ this.commitKeyboardGrab();
12031
+ }
12032
+ const items = this.getItems();
12033
+ const oldIndex = items.indexOf(item);
12034
+ if (oldIndex === -1 || items.length < 2) return;
12035
+ const siblings = items.filter((el) => el !== item);
12036
+ const dragAbort = new AbortController();
12037
+ this.pointerDrag = {
12038
+ sessionId: ++this.dragSessionSeq,
12039
+ pointerId: event.pointerId,
12040
+ item,
12041
+ handle,
12042
+ oldIndex,
12043
+ targetIndex: oldIndex,
12044
+ startX: event.clientX,
12045
+ startY: event.clientY,
12046
+ lastClientX: event.clientX,
12047
+ lastClientY: event.clientY,
12048
+ startScrollLeft: this.container.scrollLeft,
12049
+ startScrollTop: this.container.scrollTop,
12050
+ started: false,
12051
+ prevTranslate: item.style.translate,
12052
+ slotRect: item.getBoundingClientRect(),
12053
+ siblings,
12054
+ items,
12055
+ abortController: dragAbort,
12056
+ rafId: null,
12057
+ lastFrameTime: typeof performance !== "undefined" ? performance.now() : Date.now()
12058
+ };
12059
+ const sig = dragAbort.signal;
12060
+ document.addEventListener("pointermove", (e) => this.handlePointerMove(e), { signal: sig });
12061
+ document.addEventListener("pointerup", (e) => this.handlePointerUp(e), { signal: sig });
12062
+ document.addEventListener("pointercancel", (e) => this.handlePointerCancel(e), { signal: sig });
12063
+ document.addEventListener("keydown", (e) => this.handlePointerEscape(e), { signal: sig });
12064
+ if (this.options.threshold === 0) {
12065
+ this.activatePointerDrag(this.pointerDrag);
12066
+ }
12067
+ }
12068
+ activatePointerDrag(drag) {
12069
+ if (!this.container || drag.started) return;
12070
+ drag.started = true;
12071
+ const activeAnim = this.activeAnimations.get(drag.item);
12072
+ if (activeAnim) {
12073
+ try {
12074
+ activeAnim.cancel();
12075
+ } catch {
12076
+ }
12077
+ this.activeAnimations.delete(drag.item);
12078
+ }
12079
+ try {
12080
+ drag.handle.setPointerCapture?.(drag.pointerId);
12081
+ } catch {
12082
+ }
12083
+ drag.handle.addEventListener(
12084
+ "lostpointercapture",
12085
+ () => {
12086
+ if (this.pointerDrag === drag && drag.started) {
12087
+ this.endPointerDrag(true);
12088
+ }
12089
+ },
12090
+ { signal: drag.abortController.signal }
12091
+ );
12092
+ this.container.classList.add("wulf-sortable--dragging");
12093
+ drag.item.classList.add("wulf-sortable-item--dragging");
12094
+ drag.item.setAttribute("data-wulf-dragging", "true");
12095
+ this.safeInvoke(this.options.onStart, {
12096
+ item: drag.item,
12097
+ index: drag.oldIndex,
12098
+ trigger: "pointer"
12099
+ });
12100
+ if (this.options.autoScroll) {
12101
+ this.startAutoScrollLoop(drag);
12102
+ }
12103
+ }
12104
+ handlePointerMove(event) {
12105
+ const drag = this.pointerDrag;
12106
+ if (!drag || event.pointerId !== drag.pointerId || !this.container) return;
12107
+ drag.lastClientX = event.clientX;
12108
+ drag.lastClientY = event.clientY;
12109
+ if (!drag.started) {
12110
+ const dist = Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY);
12111
+ if (dist < this.options.threshold) return;
12112
+ this.activatePointerDrag(drag);
12113
+ }
12114
+ this.updatePointerPosition(drag);
12115
+ }
12116
+ updatePointerPosition(drag) {
12117
+ if (!this.container) return;
12118
+ const axis = this.options.axis;
12119
+ const scrollDx = this.container.scrollLeft - drag.startScrollLeft;
12120
+ const scrollDy = this.container.scrollTop - drag.startScrollTop;
12121
+ const tx = axis === "y" ? 0 : drag.lastClientX - drag.startX + scrollDx;
12122
+ const ty = axis === "x" ? 0 : drag.lastClientY - drag.startY + scrollDy;
12123
+ drag.item.style.translate = `${tx}px ${ty}px`;
12124
+ const nextTarget = this.computePointerTargetIndex(drag, tx, ty);
12125
+ this.updateDropMarker(drag, nextTarget);
12126
+ if (nextTarget !== drag.targetIndex) {
12127
+ const fromIndex = drag.targetIndex;
12128
+ drag.targetIndex = nextTarget;
12129
+ this.safeInvoke(this.options.onMove, {
12130
+ item: drag.item,
12131
+ oldIndex: drag.oldIndex,
12132
+ fromIndex,
12133
+ toIndex: nextTarget,
12134
+ items: computeReorderedArray(drag.items, drag.oldIndex, nextTarget),
12135
+ trigger: "pointer"
12136
+ });
12137
+ }
12138
+ }
12139
+ computePointerTargetIndex(drag, tx, ty) {
12140
+ if (!this.container) return drag.oldIndex;
12141
+ const axis = this.options.axis;
12142
+ const containerRect = this.container.getBoundingClientRect();
12143
+ const isRtl = this.isRtl();
12144
+ if (axis === "y") {
12145
+ const py2 = Math.max(containerRect.top, Math.min(containerRect.bottom, drag.lastClientY));
12146
+ let idx = 0;
12147
+ for (const sibling of drag.siblings) {
12148
+ const r = sibling.getBoundingClientRect();
12149
+ if (r.top + r.height / 2 < py2) {
12150
+ idx++;
12151
+ }
12152
+ }
12153
+ return idx;
12154
+ }
12155
+ if (axis === "x") {
12156
+ const px2 = Math.max(containerRect.left, Math.min(containerRect.right, drag.lastClientX));
12157
+ let idx = 0;
12158
+ for (const sibling of drag.siblings) {
12159
+ const r = sibling.getBoundingClientRect();
12160
+ const midX = r.left + r.width / 2;
12161
+ if (isRtl ? midX > px2 : midX < px2) {
12162
+ idx++;
12163
+ }
12164
+ }
12165
+ return idx;
12166
+ }
12167
+ const px = drag.lastClientX;
12168
+ const py = drag.lastClientY;
12169
+ let bestIdx = drag.oldIndex;
12170
+ let bestDistSq = Number.POSITIVE_INFINITY;
12171
+ for (let i = 0; i < drag.items.length; i++) {
12172
+ const el = drag.items[i];
12173
+ let r = el.getBoundingClientRect();
12174
+ if (el === drag.item) {
12175
+ r = new DOMRect(r.left - tx, r.top - ty, r.width, r.height);
12176
+ }
12177
+ if (px >= r.left && px <= r.right && py >= r.top && py <= r.bottom) {
12178
+ return i;
12179
+ }
12180
+ const cx = r.left + r.width / 2;
12181
+ const cy = r.top + r.height / 2;
12182
+ const dSq = (px - cx) * (px - cx) + (py - cy) * (py - cy);
12183
+ if (dSq < bestDistSq) {
12184
+ bestDistSq = dSq;
12185
+ bestIdx = i;
12186
+ }
12187
+ }
12188
+ return bestIdx;
12189
+ }
12190
+ updateDropMarker(drag, targetIndex) {
12191
+ if (!this.container) return;
12192
+ if (targetIndex === drag.oldIndex || drag.siblings.length === 0) {
12193
+ this.clearDropMarker();
12194
+ return;
12195
+ }
12196
+ const axis = this.options.axis;
12197
+ this.container.setAttribute("data-wulf-drop", axis);
12198
+ const size = 3;
12199
+ if (axis === "both") {
12200
+ const targetSlotEl = drag.items[targetIndex];
12201
+ if (targetSlotEl) {
12202
+ const r = targetSlotEl.getBoundingClientRect();
12203
+ this.setDropMarkerVars(r.left, r.top, r.width, r.height);
12204
+ }
12205
+ return;
12206
+ }
12207
+ const sibs = drag.siblings;
12208
+ const refRect = sibs[Math.min(targetIndex, sibs.length - 1)].getBoundingClientRect();
12209
+ if (axis === "y") {
12210
+ let y;
12211
+ if (targetIndex === 0) {
12212
+ y = sibs[0].getBoundingClientRect().top - size;
12213
+ } else if (targetIndex >= sibs.length) {
12214
+ y = sibs[sibs.length - 1].getBoundingClientRect().bottom;
12215
+ } else {
12216
+ const prevR = sibs[targetIndex - 1].getBoundingClientRect();
12217
+ const nextR = sibs[targetIndex].getBoundingClientRect();
12218
+ y = (prevR.bottom + nextR.top - size) / 2;
12219
+ }
12220
+ this.setDropMarkerVars(refRect.left, y, refRect.width, size);
12221
+ return;
12222
+ }
12223
+ const isRtl = this.isRtl();
12224
+ let x;
12225
+ if (targetIndex === 0) {
12226
+ const firstR = sibs[0].getBoundingClientRect();
12227
+ x = isRtl ? firstR.right : firstR.left - size;
12228
+ } else if (targetIndex >= sibs.length) {
12229
+ const lastR = sibs[sibs.length - 1].getBoundingClientRect();
12230
+ x = isRtl ? lastR.left - size : lastR.right;
12231
+ } else {
12232
+ const prevR = sibs[targetIndex - 1].getBoundingClientRect();
12233
+ const nextR = sibs[targetIndex].getBoundingClientRect();
12234
+ x = isRtl ? (nextR.right + prevR.left - size) / 2 : (prevR.right + nextR.left - size) / 2;
12235
+ }
12236
+ this.setDropMarkerVars(x, refRect.top, size, refRect.height);
12237
+ }
12238
+ setDropMarkerVars(x, y, w, h) {
12239
+ if (!this.container) return;
12240
+ this.container.style.setProperty("--wulf-drop-x", `${Math.round(x)}px`);
12241
+ this.container.style.setProperty("--wulf-drop-y", `${Math.round(y)}px`);
12242
+ this.container.style.setProperty("--wulf-drop-w", `${Math.max(1, Math.round(w))}px`);
12243
+ this.container.style.setProperty("--wulf-drop-h", `${Math.max(1, Math.round(h))}px`);
12244
+ }
12245
+ clearDropMarker() {
12246
+ if (!this.container) return;
12247
+ this.container.removeAttribute("data-wulf-drop");
12248
+ this.container.style.removeProperty("--wulf-drop-x");
12249
+ this.container.style.removeProperty("--wulf-drop-y");
12250
+ this.container.style.removeProperty("--wulf-drop-w");
12251
+ this.container.style.removeProperty("--wulf-drop-h");
12252
+ }
12253
+ startAutoScrollLoop(drag) {
12254
+ const tick = (now) => {
12255
+ if (this.pointerDrag !== drag || !drag.started || !this.container || this.isDestroyed) return;
12256
+ const dt = Math.min(64, Math.max(0, now - drag.lastFrameTime)) / 16.6667;
12257
+ drag.lastFrameTime = now;
12258
+ const cRect = this.container.getBoundingClientRect();
12259
+ const axis = this.options.axis;
12260
+ const maxSpeed = this.options.autoScrollSpeed * dt;
12261
+ let scrolled = false;
12262
+ if (axis === "y" || axis === "both") {
12263
+ const edge = Math.min(drag.slotRect.height || 40, cRect.height / 3);
12264
+ if (edge > 0) {
12265
+ if (drag.lastClientY < cRect.top + edge && this.container.scrollTop > 0) {
12266
+ const ratio = Math.min(2, (cRect.top + edge - drag.lastClientY) / edge);
12267
+ this.container.scrollTop -= maxSpeed * ratio;
12268
+ scrolled = true;
12269
+ } else if (drag.lastClientY > cRect.bottom - edge && this.container.scrollTop < this.container.scrollHeight - this.container.clientHeight) {
12270
+ const ratio = Math.min(2, (drag.lastClientY - (cRect.bottom - edge)) / edge);
12271
+ this.container.scrollTop += maxSpeed * ratio;
12272
+ scrolled = true;
12273
+ }
12274
+ }
12275
+ }
12276
+ if (axis === "x" || axis === "both") {
12277
+ const edge = Math.min(drag.slotRect.width || 40, cRect.width / 3);
12278
+ if (edge > 0) {
12279
+ if (drag.lastClientX < cRect.left + edge) {
12280
+ const ratio = Math.min(2, (cRect.left + edge - drag.lastClientX) / edge);
12281
+ this.container.scrollLeft -= maxSpeed * ratio;
12282
+ scrolled = true;
12283
+ } else if (drag.lastClientX > cRect.right - edge) {
12284
+ const ratio = Math.min(2, (drag.lastClientX - (cRect.right - edge)) / edge);
12285
+ this.container.scrollLeft += maxSpeed * ratio;
12286
+ scrolled = true;
12287
+ }
12288
+ }
12289
+ }
12290
+ if (scrolled) {
12291
+ this.updatePointerPosition(drag);
12292
+ }
12293
+ drag.rafId = requestAnimationFrame(tick);
12294
+ };
12295
+ drag.rafId = requestAnimationFrame(tick);
12296
+ }
12297
+ handlePointerUp(event) {
12298
+ const drag = this.pointerDrag;
12299
+ if (!drag || event.pointerId !== drag.pointerId) return;
12300
+ this.endPointerDrag(false);
12301
+ }
12302
+ handlePointerCancel(event) {
12303
+ const drag = this.pointerDrag;
12304
+ if (!drag || event.pointerId !== drag.pointerId) return;
12305
+ this.endPointerDrag(true);
12306
+ }
12307
+ handlePointerEscape(event) {
12308
+ if (event.key !== "Escape" || isImeComposing(event)) return;
12309
+ const drag = this.pointerDrag;
12310
+ if (!drag) return;
12311
+ event.preventDefault();
12312
+ this.endPointerDrag(true);
12313
+ }
12314
+ endPointerDrag(cancelled) {
12315
+ const drag = this.pointerDrag;
12316
+ if (!drag || !this.container) return;
12317
+ this.pointerDrag = null;
12318
+ drag.abortController.abort();
12319
+ if (drag.rafId !== null) {
12320
+ cancelAnimationFrame(drag.rafId);
12321
+ drag.rafId = null;
12322
+ }
12323
+ try {
12324
+ if (drag.handle.hasPointerCapture?.(drag.pointerId)) {
12325
+ drag.handle.releasePointerCapture(drag.pointerId);
12326
+ }
12327
+ } catch {
12328
+ }
12329
+ if (!drag.started) return;
12330
+ const releasedRect = drag.item.getBoundingClientRect();
12331
+ this.clearDropMarker();
12332
+ this.container.classList.remove("wulf-sortable--dragging");
12333
+ drag.item.classList.remove("wulf-sortable-item--dragging");
12334
+ drag.item.removeAttribute("data-wulf-dragging");
12335
+ drag.item.style.translate = drag.prevTranslate;
12336
+ const changed = !cancelled && drag.targetIndex !== drag.oldIndex;
12337
+ if (cancelled) {
12338
+ const snap = /* @__PURE__ */ new Map([[drag.item, releasedRect]]);
12339
+ this.animateFlip([drag.item], snap);
12340
+ this.safeInvoke(this.options.onCancel, {
12341
+ item: drag.item,
12342
+ index: drag.oldIndex,
12343
+ trigger: "pointer"
12344
+ });
12345
+ const label2 = this.getItemLabelText(drag.item, drag.oldIndex);
12346
+ this.announce(this.resolveI18n().cancelled(label2, drag.oldIndex + 1, drag.items.length));
12347
+ return;
12348
+ }
12349
+ if (!changed) {
12350
+ const snap = /* @__PURE__ */ new Map([[drag.item, releasedRect]]);
12351
+ this.animateFlip([drag.item], snap);
12352
+ return;
12353
+ }
12354
+ const ordered = computeReorderedArray(drag.items, drag.oldIndex, drag.targetIndex);
12355
+ if (this.options.autoMove) {
12356
+ const beforeRects = this.snapshotRects(drag.siblings);
12357
+ beforeRects.set(drag.item, releasedRect);
12358
+ moveItemInDom(this.container, drag.item, drag.siblings, drag.targetIndex);
12359
+ drag.item.scrollIntoView?.({ block: "nearest", inline: "nearest" });
12360
+ this.animateFlip(ordered, beforeRects);
12361
+ }
12362
+ this.emitReorder({
12363
+ item: drag.item,
12364
+ oldIndex: drag.oldIndex,
12365
+ newIndex: drag.targetIndex,
12366
+ items: ordered,
12367
+ trigger: "pointer"
12368
+ });
12369
+ const label = this.getItemLabelText(drag.item, drag.targetIndex);
12370
+ this.announce(this.resolveI18n().dropped(label, drag.targetIndex + 1, drag.items.length));
12371
+ }
12372
+ handleKeyDown(event) {
12373
+ if (!this.container || this.isDestroyed || this.options.disabled) return;
12374
+ if (isImeComposing(event)) return;
12375
+ if (event.ctrlKey || event.altKey || event.metaKey) return;
12376
+ if (isEditableTarget(event.target)) return;
12377
+ const item = this.findItemForEvent(event);
12378
+ if (!item) return;
12379
+ const activeTrigger = this.resolveTriggerForItem(item);
12380
+ const eventTarget = event.target;
12381
+ if (!this.options.handleSelector) {
12382
+ if (eventTarget !== item && this.hasInteractiveDescendantBeforeItem(event, item)) {
12383
+ return;
12384
+ }
12385
+ } else if (!activeTrigger || eventTarget !== activeTrigger && !activeTrigger.contains(eventTarget)) {
12386
+ return;
12387
+ }
12388
+ const triggerEl = activeTrigger ?? item;
12389
+ if (event.key === " " || event.key === "Enter") {
12390
+ event.preventDefault();
12391
+ if (this.keyboardGrab && this.keyboardGrab.item === item) {
12392
+ this.commitKeyboardGrab();
12393
+ } else {
12394
+ this.startKeyboardGrab(item, triggerEl);
12395
+ }
12396
+ return;
12397
+ }
12398
+ if (!this.keyboardGrab || this.keyboardGrab.item !== item) return;
12399
+ if (event.key === "Escape") {
12400
+ event.preventDefault();
12401
+ this.cancelKeyboardGrab();
12402
+ return;
12403
+ }
12404
+ const nextIndex = this.computeKeyboardNextIndex(event.key, this.keyboardGrab);
12405
+ if (nextIndex === null) return;
12406
+ event.preventDefault();
12407
+ this.stepKeyboardGrab(nextIndex);
12408
+ }
12409
+ startKeyboardGrab(item, trigger) {
12410
+ if (!this.container) return;
12411
+ if (this.keyboardGrab) {
12412
+ this.commitKeyboardGrab();
12413
+ }
12414
+ const items = this.getItems();
12415
+ const index = items.indexOf(item);
12416
+ if (index === -1 || items.length < 2) return;
12417
+ this.keyboardGrab = {
12418
+ item,
12419
+ trigger,
12420
+ originIndex: index,
12421
+ currentIndex: index,
12422
+ initialOrder: items.slice(),
12423
+ tailRef: items[items.length - 1]?.nextSibling ?? null
12424
+ };
12425
+ this.container.classList.add("wulf-sortable--dragging");
12426
+ item.classList.add("wulf-sortable-item--grabbed");
12427
+ item.setAttribute("data-wulf-grabbed", "true");
12428
+ trigger.setAttribute("aria-pressed", "true");
12429
+ this.safeInvoke(this.options.onStart, {
12430
+ item,
12431
+ index,
12432
+ trigger: "keyboard"
12433
+ });
12434
+ const label = this.getItemLabelText(item, index);
12435
+ this.announce(this.resolveI18n().grabbed(label, index + 1, items.length));
12436
+ }
12437
+ computeKeyboardNextIndex(key, grab) {
12438
+ const axis = this.options.axis;
12439
+ const isRtl = this.isRtl();
12440
+ const items = this.options.autoMove ? this.getItems() : computeReorderedArray(grab.initialOrder, grab.originIndex, grab.currentIndex);
12441
+ const total = items.length;
12442
+ const idx = grab.currentIndex;
12443
+ if (key === "Home") return 0;
12444
+ if (key === "End") return total - 1;
12445
+ if (axis === "y") {
12446
+ if (key === "ArrowUp") return Math.max(0, idx - 1);
12447
+ if (key === "ArrowDown") return Math.min(total - 1, idx + 1);
12448
+ return null;
12449
+ }
12450
+ if (axis === "x") {
12451
+ if (key === "ArrowLeft") return isRtl ? Math.min(total - 1, idx + 1) : Math.max(0, idx - 1);
12452
+ if (key === "ArrowRight") return isRtl ? Math.max(0, idx - 1) : Math.min(total - 1, idx + 1);
12453
+ return null;
12454
+ }
12455
+ if (key === "ArrowLeft") return isRtl ? Math.min(total - 1, idx + 1) : Math.max(0, idx - 1);
12456
+ if (key === "ArrowRight") return isRtl ? Math.max(0, idx - 1) : Math.min(total - 1, idx + 1);
12457
+ if (key !== "ArrowUp" && key !== "ArrowDown") return null;
12458
+ const currentRect = grab.item.getBoundingClientRect();
12459
+ const cx0 = currentRect.left + currentRect.width / 2;
12460
+ const cy0 = currentRect.top + currentRect.height / 2;
12461
+ const minRowDelta = Math.max(4, currentRect.height * 0.35);
12462
+ const candidates = [];
12463
+ for (let i = 0; i < total; i++) {
12464
+ if (i === idx) continue;
12465
+ const r = items[i].getBoundingClientRect();
12466
+ const cy = r.top + r.height / 2;
12467
+ if (key === "ArrowDown" && cy - cy0 > minRowDelta) {
12468
+ candidates.push({ index: i, cx: r.left + r.width / 2, cy });
12469
+ } else if (key === "ArrowUp" && cy0 - cy > minRowDelta) {
12470
+ candidates.push({ index: i, cx: r.left + r.width / 2, cy });
12471
+ }
12472
+ }
12473
+ if (candidates.length === 0) return idx;
12474
+ const targetRowCy = key === "ArrowDown" ? Math.min(...candidates.map((c) => c.cy)) : Math.max(...candidates.map((c) => c.cy));
12475
+ const rowTolerance = Math.max(8, currentRect.height * 0.5);
12476
+ const sameRow = candidates.filter((c) => Math.abs(c.cy - targetRowCy) <= rowTolerance);
12477
+ let best = sameRow[0];
12478
+ let bestDx = Math.abs(best.cx - cx0);
12479
+ for (let i = 1; i < sameRow.length; i++) {
12480
+ const dx = Math.abs(sameRow[i].cx - cx0);
12481
+ if (dx < bestDx) {
12482
+ bestDx = dx;
12483
+ best = sameRow[i];
12484
+ }
12485
+ }
12486
+ return best.index;
12487
+ }
12488
+ stepKeyboardGrab(nextIndex) {
12489
+ const grab = this.keyboardGrab;
12490
+ if (!grab || !this.container || nextIndex === grab.currentIndex) return;
12491
+ const fromIndex = grab.currentIndex;
12492
+ const currentItems = this.getItems();
12493
+ const total = currentItems.length;
12494
+ if (this.options.autoMove) {
12495
+ const beforeRects = this.snapshotRects(currentItems);
12496
+ const siblings = currentItems.filter((el) => el !== grab.item);
12497
+ this.isMovingFocus = true;
12498
+ try {
12499
+ moveItemInDom(this.container, grab.item, siblings, nextIndex);
12500
+ grab.item.scrollIntoView?.({ block: "nearest", inline: "nearest" });
12501
+ if (getDeepActiveElement() !== grab.trigger) {
12502
+ grab.trigger.focus({ preventScroll: true });
12503
+ }
12504
+ } finally {
12505
+ this.isMovingFocus = false;
12506
+ }
12507
+ this.animateFlip(currentItems, beforeRects);
12508
+ }
12509
+ grab.currentIndex = nextIndex;
12510
+ const ordered = this.options.autoMove ? this.getItems() : computeReorderedArray(grab.initialOrder, grab.originIndex, nextIndex);
12511
+ this.safeInvoke(this.options.onMove, {
12512
+ item: grab.item,
12513
+ oldIndex: grab.originIndex,
12514
+ fromIndex,
12515
+ toIndex: nextIndex,
12516
+ items: ordered,
12517
+ trigger: "keyboard"
12518
+ });
12519
+ const label = this.getItemLabelText(grab.item, nextIndex);
12520
+ this.announce(this.resolveI18n().moved(label, nextIndex + 1, total));
12521
+ }
12522
+ clearKeyboardGrabVisuals(grab) {
12523
+ this.container?.classList.remove("wulf-sortable--dragging");
12524
+ grab.item.classList.remove("wulf-sortable-item--grabbed");
12525
+ grab.item.removeAttribute("data-wulf-grabbed");
12526
+ const saved = this.savedAttributes.get(grab.trigger);
12527
+ if (saved?.hadAriaPressed && saved.prevAriaPressed !== null) {
12528
+ grab.trigger.setAttribute("aria-pressed", saved.prevAriaPressed);
12529
+ } else {
12530
+ grab.trigger.removeAttribute("aria-pressed");
12531
+ }
12532
+ }
12533
+ commitKeyboardGrab() {
12534
+ const grab = this.keyboardGrab;
12535
+ if (!grab) return;
12536
+ this.keyboardGrab = null;
12537
+ this.clearKeyboardGrabVisuals(grab);
12538
+ if (grab.currentIndex !== grab.originIndex) {
12539
+ const ordered = this.options.autoMove ? this.getItems() : computeReorderedArray(grab.initialOrder, grab.originIndex, grab.currentIndex);
12540
+ this.emitReorder({
12541
+ item: grab.item,
12542
+ oldIndex: grab.originIndex,
12543
+ newIndex: grab.currentIndex,
12544
+ items: ordered,
12545
+ trigger: "keyboard"
12546
+ });
12547
+ const label = this.getItemLabelText(grab.item, grab.currentIndex);
12548
+ this.announce(this.resolveI18n().dropped(label, grab.currentIndex + 1, ordered.length));
12549
+ }
12550
+ }
12551
+ cancelKeyboardGrab() {
12552
+ const grab = this.keyboardGrab;
12553
+ if (!grab || !this.container) return;
12554
+ this.keyboardGrab = null;
12555
+ if (this.options.autoMove && grab.currentIndex !== grab.originIndex) {
12556
+ const currentItems = this.getItems();
12557
+ const beforeRects = this.snapshotRects(currentItems);
12558
+ this.isMovingFocus = true;
12559
+ try {
12560
+ const ref = grab.tailRef && grab.tailRef.parentNode === this.container ? grab.tailRef : null;
12561
+ for (const node of grab.initialOrder) {
12562
+ if (node.parentNode === this.container && node !== ref) {
12563
+ safeMove(this.container, node, ref);
12564
+ }
12565
+ }
12566
+ grab.item.scrollIntoView?.({ block: "nearest", inline: "nearest" });
12567
+ if (getDeepActiveElement() !== grab.trigger) {
12568
+ grab.trigger.focus({ preventScroll: true });
12569
+ }
12570
+ } finally {
12571
+ this.isMovingFocus = false;
12572
+ }
12573
+ this.animateFlip(grab.initialOrder, beforeRects);
12574
+ }
12575
+ this.clearKeyboardGrabVisuals(grab);
12576
+ this.safeInvoke(this.options.onCancel, {
12577
+ item: grab.item,
12578
+ index: grab.originIndex,
12579
+ trigger: "keyboard"
12580
+ });
12581
+ const total = this.getItems().length || grab.initialOrder.length;
12582
+ const label = this.getItemLabelText(grab.item, grab.originIndex);
12583
+ this.announce(this.resolveI18n().cancelled(label, grab.originIndex + 1, total));
12584
+ }
12585
+ handleFocusOut(event) {
12586
+ if (this.isMovingFocus || !this.keyboardGrab) return;
12587
+ const grab = this.keyboardGrab;
12588
+ const nextFocus = event.relatedTarget;
12589
+ if (!nextFocus || nextFocus !== grab.trigger && !grab.trigger.contains(nextFocus)) {
12590
+ this.commitKeyboardGrab();
12591
+ }
12592
+ }
12593
+ snapshotRects(elements) {
12594
+ const map = /* @__PURE__ */ new Map();
12595
+ for (const el of elements) {
12596
+ const prev = this.activeAnimations.get(el);
12597
+ if (prev) {
12598
+ try {
12599
+ prev.finish();
12600
+ } catch {
12601
+ }
12602
+ this.activeAnimations.delete(el);
12603
+ }
12604
+ map.set(el, el.getBoundingClientRect());
12605
+ }
12606
+ return map;
12607
+ }
12608
+ animateFlip(elements, beforeRects) {
12609
+ const duration = this.options.animationDuration;
12610
+ if (duration <= 0 || prefersReducedMotion()) return;
12611
+ for (const el of elements) {
12612
+ if (typeof el.animate !== "function") continue;
12613
+ const oldRect = beforeRects.get(el);
12614
+ if (!oldRect) continue;
12615
+ const newRect = el.getBoundingClientRect();
12616
+ const dx = oldRect.left - newRect.left;
12617
+ const dy = oldRect.top - newRect.top;
12618
+ if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) continue;
12619
+ try {
12620
+ const anim = el.animate(
12621
+ [{ translate: `${dx}px ${dy}px` }, { translate: "0px 0px" }],
12622
+ { duration, easing: "cubic-bezier(0.2, 0.8, 0.2, 1)" }
12623
+ );
12624
+ this.activeAnimations.set(el, anim);
12625
+ anim.addEventListener(
12626
+ "finish",
12627
+ () => {
12628
+ if (this.activeAnimations.get(el) === anim) {
12629
+ this.activeAnimations.delete(el);
12630
+ }
12631
+ },
12632
+ { once: true }
12633
+ );
12634
+ } catch {
12635
+ }
12636
+ }
12637
+ }
12638
+ isRtl() {
12639
+ if (!this.container || typeof window === "undefined" || typeof window.getComputedStyle !== "function") {
12640
+ return false;
12641
+ }
12642
+ return window.getComputedStyle(this.container).direction === "rtl";
12643
+ }
12644
+ emitReorder(detail) {
12645
+ this.safeInvoke(this.options.onReorder, detail);
12646
+ if (this.container && typeof CustomEvent === "function") {
12647
+ this.container.dispatchEvent(
12648
+ new CustomEvent("wulf:sortable:reorder", {
12649
+ bubbles: true,
12650
+ detail
12651
+ })
12652
+ );
12653
+ }
12654
+ }
12655
+ safeInvoke(fn, detail) {
12656
+ if (typeof fn !== "function") return;
12657
+ try {
12658
+ fn(detail);
12659
+ } catch {
12660
+ }
12661
+ }
12662
+ };
12663
+
12664
+ // src/autosize/index.ts
12665
+ var autosize_exports = {};
12666
+ __export(autosize_exports, {
12667
+ Autosize: () => Autosize,
12668
+ default: () => Autosize
12669
+ });
12670
+
12671
+ // src/autosize/Autosize.ts
12672
+ function parsePositiveNum(val) {
12673
+ if (val === null || val === void 0 || val === "") return void 0;
12674
+ const n = typeof val === "number" ? val : Number(val);
12675
+ return Number.isFinite(n) && n > 0 ? n : void 0;
12676
+ }
12677
+ function parsePositiveInt(val) {
12678
+ const n = parsePositiveNum(val);
12679
+ return n !== void 0 ? Math.floor(n) || void 0 : void 0;
12680
+ }
12681
+ function resolveTextarea(target) {
12682
+ if (typeof document === "undefined") return null;
12683
+ const el = typeof target === "string" ? (() => {
12684
+ try {
12685
+ return target ? document.querySelector(target) : null;
12686
+ } catch {
12687
+ return null;
12688
+ }
12689
+ })() : target;
12690
+ return typeof HTMLTextAreaElement !== "undefined" && el instanceof HTMLTextAreaElement ? el : null;
12691
+ }
12692
+ function getParentCrossingShadow2(el) {
12693
+ if (el.assignedSlot) return el.assignedSlot;
12694
+ if (el.parentElement) return el.parentElement;
12695
+ const root = typeof el.getRootNode === "function" ? el.getRootNode() : null;
12696
+ if (typeof ShadowRoot !== "undefined" && root instanceof ShadowRoot && root.host instanceof Element) {
12697
+ return root.host;
12698
+ }
12699
+ return null;
12700
+ }
12701
+ function captureScrollAncestors(el) {
12702
+ const ancestors = [];
12703
+ let curr = getParentCrossingShadow2(el);
12704
+ while (curr) {
12705
+ if (curr.scrollTop !== 0 || curr.scrollLeft !== 0) {
12706
+ ancestors.push({ el: curr, top: curr.scrollTop, left: curr.scrollLeft });
12707
+ } else if (typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
12708
+ const oy = window.getComputedStyle(curr).overflowY;
12709
+ if (oy === "auto" || oy === "scroll" || oy === "overlay") {
12710
+ ancestors.push({ el: curr, top: curr.scrollTop, left: curr.scrollLeft });
12711
+ }
12712
+ }
12713
+ curr = getParentCrossingShadow2(curr);
12714
+ }
12715
+ const winX = typeof window !== "undefined" ? window.scrollX : 0;
12716
+ const winY = typeof window !== "undefined" ? window.scrollY : 0;
12717
+ return { ancestors, winX, winY };
12718
+ }
12719
+ function restoreScrollAncestors(snap) {
12720
+ for (const item of snap.ancestors) {
12721
+ if (item.el.scrollTop !== item.top) item.el.scrollTop = item.top;
12722
+ if (item.el.scrollLeft !== item.left) item.el.scrollLeft = item.left;
12723
+ }
12724
+ if (typeof window !== "undefined" && (window.scrollX !== snap.winX || window.scrollY !== snap.winY)) {
12725
+ window.scrollTo(snap.winX, snap.winY);
12726
+ }
12727
+ }
12728
+ var Autosize = class _Autosize extends AuditableComponent {
12729
+ element;
12730
+ mode = "fallback";
12731
+ options;
12732
+ disabled;
12733
+ isDestroyed = false;
12734
+ isMeasuring = false;
12735
+ savedStyles = null;
12736
+ abortController = null;
12737
+ resizeObserver = null;
12738
+ rafId = null;
12739
+ lastInlineSize = null;
12740
+ lastHeight = 0;
12741
+ lastAppliedHeight = null;
12742
+ manualHeightPx = null;
12743
+ constructor(target, options = {}) {
12744
+ super();
12745
+ this.element = resolveTextarea(target);
12746
+ this.options = {
12747
+ useNativeFieldSizing: options.useNativeFieldSizing ?? true,
12748
+ resize: options.resize === "vertical" ? "vertical" : "none",
12749
+ observeFonts: options.observeFonts ?? true,
12750
+ audit: options.audit ?? true,
12751
+ ...options
12752
+ };
12753
+ this.disabled = Boolean(this.options.disabled);
12754
+ if (this.element) {
12755
+ this.captureInitialStyles(this.element);
12756
+ this.lastHeight = this.readBoundingHeight(this.element);
12757
+ this.bindEvents();
12758
+ if (!this.disabled) {
12759
+ this.applyModeAndMeasure(false);
12760
+ }
12761
+ this.runAuditWarning(this.options.audit !== false);
12762
+ }
12763
+ }
12764
+ /**
12765
+ * Indique si le navigateur supporte nativement `field-sizing: content`.
12766
+ */
12767
+ static supportsNativeFieldSizing() {
12768
+ return typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("field-sizing", "content");
12769
+ }
12770
+ /**
12771
+ * Initialisation opt-in explicite de tous les `<textarea data-wulf-autosize>` dans `root`.
12772
+ * Aucun effet de bord au chargement du module.
12773
+ */
12774
+ static initAll(root, options = {}) {
12775
+ if (typeof document === "undefined") return [];
12776
+ const scope = root ?? document;
12777
+ const nodes = scope.querySelectorAll("textarea[data-wulf-autosize]");
12778
+ const instances = [];
12779
+ for (const el of nodes) {
12780
+ const resizeAttr = el.getAttribute("data-wulf-resize");
12781
+ const nativeAttr = el.getAttribute("data-wulf-native");
12782
+ const merged = {
12783
+ minRows: parsePositiveInt(el.getAttribute("data-wulf-min-rows")),
12784
+ maxRows: parsePositiveInt(el.getAttribute("data-wulf-max-rows")),
12785
+ minHeight: parsePositiveNum(el.getAttribute("data-wulf-min-height")),
12786
+ maxHeight: parsePositiveNum(el.getAttribute("data-wulf-max-height")),
12787
+ resize: resizeAttr === "vertical" ? "vertical" : "none",
12788
+ useNativeFieldSizing: nativeAttr === "false" ? false : void 0,
12789
+ ...options
12790
+ };
12791
+ instances.push(new _Autosize(el, merged));
12792
+ }
12793
+ return instances;
12794
+ }
12795
+ /**
12796
+ * Recalcule et applique la hauteur optimale de la zone de texte.
12797
+ */
12798
+ update() {
12799
+ if (this.isDestroyed || !this.element || this.disabled) {
12800
+ return this.lastHeight;
12801
+ }
12802
+ return this.applyModeAndMeasure(true);
12803
+ }
12804
+ /**
12805
+ * Efface toute hauteur manuelle mémorisée (mode `resize: 'vertical'`) et réévalue la taille.
12806
+ */
12807
+ reset() {
12808
+ if (this.isDestroyed || !this.element) return;
12809
+ this.manualHeightPx = null;
12810
+ if (!this.disabled) {
12811
+ this.applyModeAndMeasure(true);
12812
+ }
12813
+ }
12814
+ /**
12815
+ * Active ou suspend le redimensionnement automatique tout en restaurant les styles d'origine à la pause.
12816
+ */
12817
+ setDisabled(disabled) {
12818
+ if (this.isDestroyed || !this.element) return;
12819
+ const next = Boolean(disabled);
12820
+ if (this.disabled === next) return;
12821
+ this.disabled = next;
12822
+ if (next) {
12823
+ this.restoreInitialStyles();
12824
+ } else {
12825
+ this.applyModeAndMeasure(true);
12826
+ }
12827
+ }
12828
+ isDisabled() {
12829
+ return this.disabled;
12830
+ }
12831
+ /**
12832
+ * Met à jour les options à la volée et applique le nouveau dimensionnement.
12833
+ */
12834
+ updateOptions(options) {
12835
+ if (this.isDestroyed || !options) return;
12836
+ const prevDisabled = this.disabled;
12837
+ this.options = { ...this.options, ...options };
12838
+ if (options.resize !== void 0) {
12839
+ this.options.resize = options.resize === "vertical" ? "vertical" : "none";
12840
+ if (this.options.resize === "none") {
12841
+ this.manualHeightPx = null;
12842
+ }
12843
+ }
12844
+ if (options.disabled !== void 0) {
12845
+ this.disabled = Boolean(options.disabled);
12846
+ }
12847
+ if (this.element) {
12848
+ if (this.disabled) {
12849
+ if (!prevDisabled) this.restoreInitialStyles();
12850
+ } else {
12851
+ this.applyModeAndMeasure(true);
12852
+ }
12853
+ }
12854
+ }
12855
+ /**
12856
+ * Audite la conformité WAI-ARIA / WCAG du `<textarea>` ciblé.
12857
+ */
12858
+ audit() {
12859
+ const warnings = [];
12860
+ const el = this.element;
12861
+ if (!el) {
12862
+ warnings.push("\xC9l\xE9ment cible introuvable ou non valide (un <textarea> est requis).");
12863
+ return warnings;
12864
+ }
12865
+ const hasAriaLabel = Boolean(el.getAttribute("aria-label")?.trim());
12866
+ const hasAriaLabelledby = this.checkAriaIdReferences(el, "aria-labelledby", warnings, true);
12867
+ const hasAssociatedLabel = this.hasNonEmptyLabel(el);
12868
+ if (!hasAriaLabel && !hasAriaLabelledby && !hasAssociatedLabel) {
12869
+ if (el.getAttribute("placeholder")?.trim()) {
12870
+ warnings.push(
12871
+ "Un placeholder est pr\xE9sent sans libell\xE9 accessible persistant (<label>, aria-label ou aria-labelledby) \u2014 non conforme WCAG 3.3.2."
12872
+ );
12873
+ } else {
12874
+ warnings.push(
12875
+ 'Aucun nom accessible d\xE9tect\xE9 sur le <textarea> (ajoutez un <label for="...">, un <label> englobant, aria-label ou aria-labelledby).'
12876
+ );
12877
+ }
12878
+ }
12879
+ if (el.hasAttribute("aria-describedby")) {
12880
+ this.checkAriaIdReferences(el, "aria-describedby", warnings);
12881
+ }
12882
+ if (el.hasAttribute("aria-errormessage")) {
12883
+ this.checkAriaIdReferences(el, "aria-errormessage", warnings);
12884
+ }
12885
+ const tabIndexAttr = el.getAttribute("tabindex");
12886
+ if (tabIndexAttr !== null) {
12887
+ const parsed = Number.parseInt(tabIndexAttr, 10);
12888
+ if (Number.isFinite(parsed) && parsed > 0) {
12889
+ warnings.push(`\xC9vitez tabindex="${parsed}" (> 0) qui perturbe l'ordre de tabulation naturel.`);
12890
+ }
12891
+ }
12892
+ return warnings;
12893
+ }
12894
+ getAuditPrefix() {
12895
+ return "Wulf.Autosize";
12896
+ }
12897
+ getAuditTargetLabel() {
12898
+ if (!this.element) return "<textarea>";
12899
+ return this.element.id ? `#${this.element.id}` : "<textarea>";
12900
+ }
12901
+ /**
12902
+ * Détruit l'instance : coupe tous les écouteurs/observers et restaure intégralement le DOM d'origine.
12903
+ */
12904
+ destroy() {
12905
+ if (this.isDestroyed) return;
12906
+ this.isDestroyed = true;
12907
+ if (this.rafId !== null && typeof cancelAnimationFrame === "function") {
12908
+ cancelAnimationFrame(this.rafId);
12909
+ this.rafId = null;
12910
+ }
12911
+ if (this.resizeObserver) {
12912
+ this.resizeObserver.disconnect();
12913
+ this.resizeObserver = null;
12914
+ }
12915
+ if (this.abortController) {
12916
+ this.abortController.abort();
12917
+ this.abortController = null;
12918
+ }
12919
+ this.restoreInitialStyles();
12920
+ }
12921
+ // --- Implémentation interne ---
12922
+ hasNonEmptyLabel(el) {
12923
+ if (el.labels && el.labels.length > 0) {
12924
+ for (const lbl of Array.from(el.labels)) {
12925
+ if ((lbl.textContent?.trim() || "").length > 0) return true;
12926
+ }
12927
+ }
12928
+ if (el.id) {
12929
+ const root = typeof el.getRootNode === "function" ? el.getRootNode() : document;
12930
+ const scope = root && "querySelector" in root ? root : document;
12931
+ try {
12932
+ const explicit = scope.querySelector(`label[for="${safeCssEscape(el.id)}"]`);
12933
+ if (explicit && (explicit.textContent?.trim() || "").length > 0) return true;
12934
+ } catch {
12935
+ }
12936
+ }
12937
+ const parentLabel = typeof el.closest === "function" ? el.closest("label") : null;
12938
+ return Boolean(parentLabel && (parentLabel.textContent?.trim() || "").length > 0);
12939
+ }
12940
+ captureInitialStyles(el) {
12941
+ this.savedStyles = {
12942
+ height: el.style.height,
12943
+ blockSize: el.style.blockSize,
12944
+ minBlockSize: el.style.minBlockSize,
12945
+ maxBlockSize: el.style.maxBlockSize,
12946
+ overflowY: el.style.overflowY,
12947
+ resize: el.style.resize,
12948
+ fieldSizing: el.style.getPropertyValue("field-sizing"),
12949
+ hadDataAttr: el.hasAttribute("data-wulf-autosize"),
12950
+ prevDataAttr: el.getAttribute("data-wulf-autosize")
12951
+ };
12952
+ }
12953
+ restoreInitialStyles() {
12954
+ const el = this.element;
12955
+ const saved = this.savedStyles;
12956
+ if (!el || !saved) return;
12957
+ el.classList.remove(
12958
+ "wulf-autosize",
12959
+ "wulf-autosize--native",
12960
+ "wulf-autosize--fallback",
12961
+ "wulf-autosize--resize-none",
12962
+ "wulf-autosize--resize-vertical"
12963
+ );
12964
+ const restoreProp = (prop, val) => {
12965
+ if (val) el.style.setProperty(prop, val);
12966
+ else el.style.removeProperty(prop);
12967
+ };
12968
+ restoreProp("height", saved.height);
12969
+ restoreProp("block-size", saved.blockSize);
12970
+ restoreProp("min-block-size", saved.minBlockSize);
12971
+ restoreProp("max-block-size", saved.maxBlockSize);
12972
+ restoreProp("overflow-y", saved.overflowY);
12973
+ restoreProp("resize", saved.resize);
12974
+ restoreProp("field-sizing", saved.fieldSizing);
12975
+ if (saved.hadDataAttr && saved.prevDataAttr !== null) {
12976
+ el.setAttribute("data-wulf-autosize", saved.prevDataAttr);
12977
+ } else if (!saved.hadDataAttr) {
12978
+ el.removeAttribute("data-wulf-autosize");
12979
+ } else {
12980
+ el.setAttribute("data-wulf-autosize", "");
12981
+ }
12982
+ }
12983
+ bindEvents() {
12984
+ const el = this.element;
12985
+ if (!el || typeof window === "undefined") return;
12986
+ this.abortController = new AbortController();
12987
+ const { signal } = this.abortController;
12988
+ const onTextChange = () => {
12989
+ if (!this.isDestroyed && !this.disabled && this.mode === "fallback") {
12990
+ this.applyModeAndMeasure(true);
12991
+ }
12992
+ };
12993
+ el.addEventListener("input", onTextChange, { signal });
12994
+ el.addEventListener("change", onTextChange, { signal });
12995
+ if (el.form) {
12996
+ el.form.addEventListener(
12997
+ "reset",
12998
+ () => {
12999
+ queueMicrotask(() => {
13000
+ if (!this.isDestroyed && !this.disabled) {
13001
+ this.manualHeightPx = null;
13002
+ this.applyModeAndMeasure(true);
13003
+ }
13004
+ });
13005
+ },
13006
+ { signal }
13007
+ );
13008
+ }
13009
+ const onPointerRelease = () => {
13010
+ if (!this.isDestroyed && !this.disabled && this.options.resize === "vertical") {
13011
+ this.captureManualResizeIfNeeded();
13012
+ }
13013
+ };
13014
+ window.addEventListener("pointerup", onPointerRelease, { signal, passive: true });
13015
+ window.addEventListener("mouseup", onPointerRelease, { signal, passive: true });
13016
+ if (this.options.observeFonts !== false && typeof document !== "undefined" && document.fonts?.ready) {
13017
+ document.fonts.ready.then(() => {
13018
+ if (!this.isDestroyed && !this.disabled) {
13019
+ this.applyModeAndMeasure(true);
13020
+ }
13021
+ }).catch(() => {
13022
+ });
13023
+ }
13024
+ if (typeof ResizeObserver !== "undefined") {
13025
+ this.resizeObserver = new ResizeObserver((entries) => {
13026
+ if (this.isDestroyed || this.disabled || !this.element) return;
13027
+ const entry = entries[0];
13028
+ if (!entry) return;
13029
+ const inlineSize = entry.borderBoxSize && entry.borderBoxSize[0] ? entry.borderBoxSize[0].inlineSize : entry.contentRect.width;
13030
+ const blockSize = entry.borderBoxSize && entry.borderBoxSize[0] ? entry.borderBoxSize[0].blockSize : entry.contentRect.height;
13031
+ if (this.mode === "native") {
13032
+ if (blockSize > 0 && Math.abs(blockSize - this.lastHeight) >= 0.5) {
13033
+ const prev = this.lastHeight;
13034
+ this.lastHeight = blockSize;
13035
+ this.emitResize(blockSize, prev, this.isElementOverflowing(this.element));
13036
+ }
13037
+ return;
13038
+ }
13039
+ if (!this.isMeasuring && this.options.resize === "vertical") {
13040
+ this.captureManualResizeIfNeeded(blockSize);
13041
+ }
13042
+ const prevInline = this.lastInlineSize;
13043
+ const becameVisible = prevInline === 0 && inlineSize > 0;
13044
+ const widthChanged = prevInline !== null && Math.abs(inlineSize - prevInline) >= 0.5;
13045
+ this.lastInlineSize = inlineSize;
13046
+ if (becameVisible || widthChanged) {
13047
+ this.scheduleUpdate();
13048
+ }
13049
+ });
13050
+ this.resizeObserver.observe(el);
13051
+ }
13052
+ }
13053
+ captureManualResizeIfNeeded(observedHeight) {
13054
+ const el = this.element;
13055
+ if (!el || this.isMeasuring || this.lastAppliedHeight === null) return;
13056
+ const inlineHeight = el.style.height;
13057
+ if (!inlineHeight) return;
13058
+ const parsedInline = inlineHeight.endsWith("px") ? parseFloat(inlineHeight) : NaN;
13059
+ let manualPx = Number.isFinite(parsedInline) && parsedInline > 0 ? parsedInline : NaN;
13060
+ if (!Number.isFinite(manualPx)) {
13061
+ const boxH = observedHeight ?? this.readBoundingHeight(el);
13062
+ const cs = typeof window !== "undefined" && typeof window.getComputedStyle === "function" ? window.getComputedStyle(el) : null;
13063
+ if (cs && cs.boxSizing !== "border-box") {
13064
+ const pad = (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0);
13065
+ const brd = (parseFloat(cs.borderTopWidth) || 0) + (parseFloat(cs.borderBottomWidth) || 0);
13066
+ manualPx = Math.max(0, boxH - pad - brd);
13067
+ } else {
13068
+ manualPx = boxH;
13069
+ }
13070
+ }
13071
+ if (manualPx > 0 && Math.abs(manualPx - this.lastAppliedHeight) >= 2) {
13072
+ this.manualHeightPx = manualPx;
13073
+ this.lastAppliedHeight = manualPx;
13074
+ const overflowing = this.isElementOverflowing(el);
13075
+ el.style.overflowY = overflowing ? "auto" : "hidden";
13076
+ const boxHeight = observedHeight ?? this.readBoundingHeight(el);
13077
+ if (Math.abs(boxHeight - this.lastHeight) >= 0.5) {
13078
+ const prev = this.lastHeight;
13079
+ this.lastHeight = boxHeight;
13080
+ this.emitResize(boxHeight, prev, overflowing);
13081
+ }
13082
+ }
13083
+ }
13084
+ scheduleUpdate() {
13085
+ if (this.rafId !== null) return;
13086
+ const schedule = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (cb) => setTimeout(cb, 0);
13087
+ this.rafId = schedule(() => {
13088
+ this.rafId = null;
13089
+ if (!this.isDestroyed && !this.disabled) {
13090
+ this.applyModeAndMeasure(true);
13091
+ }
13092
+ });
13093
+ }
13094
+ readBoundingHeight(el) {
13095
+ return typeof el.getBoundingClientRect === "function" ? el.getBoundingClientRect().height : 0;
13096
+ }
13097
+ isElementOverflowing(el) {
13098
+ return el.scrollHeight > el.clientHeight + 1;
13099
+ }
13100
+ computeBounds(el) {
13101
+ const cs = typeof window !== "undefined" && typeof window.getComputedStyle === "function" ? window.getComputedStyle(el) : null;
13102
+ const fontSize = cs ? parseFloat(cs.fontSize) || 16 : 16;
13103
+ const rawLh = cs ? parseFloat(cs.lineHeight) : NaN;
13104
+ const lineHeight = Number.isFinite(rawLh) && rawLh > 0 ? rawLh : fontSize * 1.2;
13105
+ const paddingY = cs ? (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0) : 0;
13106
+ const borderY = cs ? (parseFloat(cs.borderTopWidth) || 0) + (parseFloat(cs.borderBottomWidth) || 0) : 0;
13107
+ const isBorderBox = cs ? cs.boxSizing === "border-box" : true;
13108
+ const extraVertical = isBorderBox ? paddingY + borderY : 0;
13109
+ const minRowsOpt = parsePositiveNum(this.options.minRows);
13110
+ const attrRows = parsePositiveInt(el.getAttribute("rows"));
13111
+ const effectiveMinRows = minRowsOpt ?? attrRows;
13112
+ const rowsMinPx = effectiveMinRows !== void 0 ? effectiveMinRows * lineHeight + extraVertical : 0;
13113
+ const minHeightOpt = parsePositiveNum(this.options.minHeight) ?? 0;
13114
+ const minPx = Math.max(rowsMinPx, minHeightOpt);
13115
+ const maxRowsOpt = parsePositiveNum(this.options.maxRows);
13116
+ const rowsMaxPx = maxRowsOpt !== void 0 ? maxRowsOpt * lineHeight + extraVertical : Infinity;
13117
+ const maxHeightOpt = parsePositiveNum(this.options.maxHeight) ?? Infinity;
13118
+ let maxPx = Math.min(rowsMaxPx, maxHeightOpt);
13119
+ if (maxPx < minPx) maxPx = minPx;
13120
+ return { minPx, maxPx, paddingY, borderY, isBorderBox };
13121
+ }
13122
+ applyModeAndMeasure(emitEvents) {
13123
+ const el = this.element;
13124
+ if (!el) return 0;
13125
+ const resizeMode = this.options.resize === "vertical" ? "vertical" : "none";
13126
+ const wantNative = this.options.useNativeFieldSizing !== false && _Autosize.supportsNativeFieldSizing() && resizeMode === "none" && this.manualHeightPx === null;
13127
+ this.mode = wantNative ? "native" : "fallback";
13128
+ el.classList.add("wulf-autosize");
13129
+ el.classList.toggle("wulf-autosize--native", wantNative);
13130
+ el.classList.toggle("wulf-autosize--fallback", !wantNative);
13131
+ el.classList.toggle("wulf-autosize--resize-none", resizeMode === "none");
13132
+ el.classList.toggle("wulf-autosize--resize-vertical", resizeMode === "vertical");
13133
+ el.setAttribute("data-wulf-autosize", this.mode);
13134
+ const bounds = this.computeBounds(el);
13135
+ if (wantNative) {
13136
+ el.style.setProperty("field-sizing", "content");
13137
+ el.style.blockSize = "auto";
13138
+ el.style.resize = "none";
13139
+ el.style.removeProperty("height");
13140
+ el.style.removeProperty("overflow-y");
13141
+ if (bounds.minPx > 0) el.style.minBlockSize = `${Math.ceil(bounds.minPx)}px`;
13142
+ else el.style.removeProperty("min-block-size");
13143
+ if (Number.isFinite(bounds.maxPx)) el.style.maxBlockSize = `${Math.ceil(bounds.maxPx)}px`;
13144
+ else el.style.removeProperty("max-block-size");
13145
+ const rect2 = typeof el.getBoundingClientRect === "function" ? el.getBoundingClientRect() : null;
13146
+ if (rect2) {
13147
+ this.lastInlineSize = rect2.width;
13148
+ if (rect2.height > 0) {
13149
+ const prev = this.lastHeight;
13150
+ this.lastHeight = rect2.height;
13151
+ if (emitEvents && Math.abs(rect2.height - prev) >= 0.5) {
13152
+ this.emitResize(rect2.height, prev, this.isElementOverflowing(el));
13153
+ }
13154
+ }
13155
+ }
13156
+ return this.lastHeight;
13157
+ }
13158
+ el.style.removeProperty("field-sizing");
13159
+ el.style.removeProperty("block-size");
13160
+ el.style.removeProperty("min-block-size");
13161
+ el.style.removeProperty("max-block-size");
13162
+ el.style.resize = resizeMode;
13163
+ const rect = typeof el.getBoundingClientRect === "function" ? el.getBoundingClientRect() : null;
13164
+ if (!el.isConnected || !rect || rect.width === 0) {
13165
+ this.lastInlineSize = rect ? rect.width : 0;
13166
+ return this.lastHeight;
13167
+ }
13168
+ this.lastInlineSize = rect.width;
13169
+ if (this.manualHeightPx !== null) {
13170
+ const locked = Math.ceil(this.manualHeightPx);
13171
+ el.style.height = `${locked}px`;
13172
+ this.lastAppliedHeight = locked;
13173
+ el.style.overflowY = this.isElementOverflowing(el) ? "auto" : "hidden";
13174
+ const boxH = this.readBoundingHeight(el);
13175
+ if (boxH > 0) this.lastHeight = boxH;
13176
+ return this.lastHeight;
13177
+ }
13178
+ const scrollSnap = captureScrollAncestors(el);
13179
+ const prevInlineHeight = el.style.height;
13180
+ this.isMeasuring = true;
13181
+ try {
13182
+ el.style.height = "auto";
13183
+ const rawScrollHeight = el.scrollHeight;
13184
+ if (rawScrollHeight === 0) {
13185
+ el.style.height = prevInlineHeight;
13186
+ restoreScrollAncestors(scrollSnap);
13187
+ return this.lastHeight;
13188
+ }
13189
+ const contentHeight = bounds.isBorderBox ? rawScrollHeight + bounds.borderY : Math.max(0, rawScrollHeight - bounds.paddingY);
13190
+ const overflowing = Number.isFinite(bounds.maxPx) && contentHeight > bounds.maxPx + 0.5;
13191
+ const finalHeight = Math.ceil(Math.min(bounds.maxPx, Math.max(bounds.minPx, contentHeight)));
13192
+ el.style.height = `${finalHeight}px`;
13193
+ el.style.overflowY = overflowing ? "auto" : "hidden";
13194
+ this.lastAppliedHeight = finalHeight;
13195
+ restoreScrollAncestors(scrollSnap);
13196
+ const prev = this.lastHeight;
13197
+ this.lastHeight = finalHeight;
13198
+ if (emitEvents && Math.abs(finalHeight - prev) >= 0.5) {
13199
+ this.emitResize(finalHeight, prev, overflowing);
13200
+ }
13201
+ return finalHeight;
13202
+ } finally {
13203
+ this.isMeasuring = false;
13204
+ }
13205
+ }
13206
+ emitResize(height, previousHeight, overflowing) {
13207
+ const el = this.element;
13208
+ if (!el) return;
13209
+ const detail = {
13210
+ textarea: el,
13211
+ height,
13212
+ previousHeight,
13213
+ overflowing,
13214
+ mode: this.mode
13215
+ };
13216
+ if (typeof this.options.onResize === "function") {
13217
+ try {
13218
+ this.options.onResize(detail);
13219
+ } catch (err) {
13220
+ console.error("[Wulf.Autosize] Erreur dans onResize :", err);
13221
+ }
13222
+ }
13223
+ if (typeof CustomEvent === "function") {
13224
+ el.dispatchEvent(new CustomEvent("wulf:autosize:resize", { detail, bubbles: true }));
13225
+ }
13226
+ }
13227
+ };
13228
+
13229
+ // src/undo/index.ts
13230
+ var undo_exports = {};
13231
+ __export(undo_exports, {
13232
+ LocalizedComponent: () => LocalizedComponent,
13233
+ Undo: () => UndoManager,
13234
+ UndoManager: () => UndoManager,
13235
+ createI18nManager: () => createI18nManager,
13236
+ default: () => UndoManager,
13237
+ undoEn: () => undoEn,
13238
+ undoFr: () => undoFr,
13239
+ undoI18n: () => undoI18n
13240
+ });
13241
+
13242
+ // src/undo/i18n/fr.ts
13243
+ var undoFr = {
13244
+ undone: (label) => label ? `Action annul\xE9e : ${label}` : "Action annul\xE9e.",
13245
+ redone: (label) => label ? `Action r\xE9tablie : ${label}` : "Action r\xE9tablie.",
13246
+ nothingToUndo: "Aucune action \xE0 annuler.",
13247
+ nothingToRedo: "Aucune action \xE0 r\xE9tablir."
13248
+ };
13249
+
13250
+ // src/undo/i18n/en.ts
13251
+ var undoEn = {
13252
+ undone: (label) => label ? `Undone: ${label}` : "Action undone.",
13253
+ redone: (label) => label ? `Redone: ${label}` : "Action redone.",
13254
+ nothingToUndo: "Nothing to undo.",
13255
+ nothingToRedo: "Nothing to redo."
13256
+ };
13257
+
13258
+ // src/undo/i18n/index.ts
13259
+ var undoI18n = createI18nManager("fr", {
13260
+ fr: undoFr,
13261
+ en: undoEn
13262
+ });
13263
+
13264
+ // src/undo/UndoManager.ts
13265
+ var SENSITIVE_AUTOCOMPLETE_TOKENS2 = /* @__PURE__ */ new Set([
13266
+ "current-password",
13267
+ "new-password",
13268
+ "one-time-code",
13269
+ "cc-number",
13270
+ "cc-csc"
13271
+ ]);
13272
+ function clampInt(val, fallback, min, max) {
13273
+ if (typeof val !== "number" || !Number.isFinite(val)) return fallback;
13274
+ return Math.min(max, Math.max(min, Math.floor(val)));
13275
+ }
13276
+ function nowMs() {
13277
+ return typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
13278
+ }
13279
+ function isApplePlatform() {
13280
+ if (typeof navigator === "undefined") return false;
13281
+ const nav = navigator;
13282
+ const plat = nav.userAgentData?.platform || navigator.platform || navigator.userAgent || "";
13283
+ return /mac|iphone|ipad|ipod/i.test(plat);
13284
+ }
13285
+ function isEditableElement(target) {
13286
+ if (!target || typeof target.tagName !== "string") return false;
13287
+ const el = target;
13288
+ const tag = el.tagName.toUpperCase();
13289
+ if (tag === "INPUT") {
13290
+ const type = el.type?.toLowerCase() || "text";
13291
+ return !["button", "checkbox", "radio", "submit", "reset", "range", "color", "file", "image"].includes(type);
13292
+ }
13293
+ if (tag === "TEXTAREA" || tag === "SELECT") return true;
13294
+ const ce = el.getAttribute?.("contenteditable")?.toLowerCase();
13295
+ if (el.isContentEditable || ce === "true" || ce === "plaintext-only" || ce === "") {
13296
+ return true;
13297
+ }
13298
+ const role = el.getAttribute?.("role");
13299
+ if (role === "textbox" || role === "searchbox" || role === "combobox" || role === "spinbutton") {
13300
+ return true;
13301
+ }
13302
+ return Boolean(
13303
+ typeof el.closest === "function" && el.closest(
13304
+ '[contenteditable="true"], [contenteditable="plaintext-only"], [contenteditable=""], [role="textbox"], [role="searchbox"], [role="combobox"], [role="spinbutton"]'
13305
+ )
13306
+ );
13307
+ }
13308
+ function isSensitiveElement(target) {
13309
+ if (!target || typeof target.tagName !== "string") return false;
13310
+ const el = target;
13311
+ if (el.tagName.toUpperCase() === "INPUT" && (el.type || "").toLowerCase() === "password") {
13312
+ return true;
13313
+ }
13314
+ const sensitiveAttr = el.getAttribute?.("data-mask-sensitive");
13315
+ if (sensitiveAttr !== null && sensitiveAttr !== void 0 && sensitiveAttr !== "false") {
13316
+ return true;
13317
+ }
13318
+ const ac = el.getAttribute?.("autocomplete");
13319
+ if (ac) {
13320
+ const tokens = ac.trim().toLowerCase().split(/\s+/);
13321
+ if (tokens.some((tok) => SENSITIVE_AUTOCOMPLETE_TOKENS2.has(tok))) {
13322
+ return true;
13323
+ }
13324
+ }
13325
+ return false;
13326
+ }
13327
+ function sanitizeLabel(label) {
13328
+ if (typeof label !== "string") return void 0;
13329
+ const clean = stripBidiAndInvisibles(label, 256).trim();
13330
+ return clean || void 0;
13331
+ }
13332
+ var UndoManager = class extends LocalizedComponent {
13333
+ static _i18n = undoI18n;
13334
+ maxDepth;
13335
+ coalesceMs;
13336
+ cloneStrategy;
13337
+ equalsFn;
13338
+ keyboardOptions;
13339
+ announceEnabled;
13340
+ announceRoot;
13341
+ langOverride;
13342
+ onChange;
13343
+ onUndo;
13344
+ onRedo;
13345
+ onError;
13346
+ stack = [];
13347
+ index = 0;
13348
+ lastPushTime = -Infinity;
13349
+ batchDepth = 0;
13350
+ batchHasChange = false;
13351
+ batchPendingState;
13352
+ batchPendingLabel;
13353
+ isApplying = false;
13354
+ paused = false;
13355
+ isDestroyed = false;
13356
+ abortController = null;
13357
+ bindings = /* @__PURE__ */ new Set();
13358
+ srStatusEl = null;
13359
+ announceTimerId = null;
13360
+ constructor(initialState, options = {}) {
13361
+ super(options.i18n);
13362
+ this.maxDepth = clampInt(options.maxDepth, 100, 1, 1e4);
13363
+ this.coalesceMs = clampInt(options.coalesceMs, 500, 0, 6e4);
13364
+ this.cloneStrategy = options.clone ?? "structured";
13365
+ this.equalsFn = options.equals;
13366
+ this.announceEnabled = options.announce ?? true;
13367
+ this.announceRoot = options.announceRoot ?? null;
13368
+ this.langOverride = options.lang;
13369
+ this.onChange = options.onChange;
13370
+ this.onUndo = options.onUndo;
13371
+ this.onRedo = options.onRedo;
13372
+ this.onError = options.onError;
13373
+ if (options.keyboard === false) {
13374
+ this.keyboardOptions = null;
13375
+ } else if (typeof options.keyboard === "object" && options.keyboard !== null) {
13376
+ this.keyboardOptions = { ...options.keyboard };
13377
+ } else {
13378
+ this.keyboardOptions = {};
13379
+ }
13380
+ this.stack = [{ state: this.cloneState(initialState), timestamp: nowMs() }];
13381
+ this.index = 0;
13382
+ this.bindKeyboard();
13383
+ this.runAuditWarning(options.audit ?? true);
13384
+ }
13385
+ /**
13386
+ * Empile un nouvel état (ou le fusionne avec le sommet selon `coalesceMs` et `mergeKey`).
13387
+ */
13388
+ push(nextState, options) {
13389
+ if (this.isDestroyed || this.isApplying) {
13390
+ return false;
13391
+ }
13392
+ const cleanLabel = sanitizeLabel(options?.label);
13393
+ const cloned = this.cloneState(nextState);
13394
+ if (this.batchDepth > 0) {
13395
+ this.batchPendingState = cloned;
13396
+ this.batchHasChange = true;
13397
+ if (cleanLabel && !this.batchPendingLabel) {
13398
+ this.batchPendingLabel = cleanLabel;
13399
+ }
13400
+ return true;
13401
+ }
13402
+ const currentEntry = this.stack[this.index];
13403
+ if (this.equalsFn && currentEntry && this.equalsFn(currentEntry.state, cloned)) {
13404
+ return false;
13405
+ }
13406
+ const previousState = currentEntry.state;
13407
+ this.stack.length = this.index + 1;
13408
+ const t = nowMs();
13409
+ const canCoalesce = options?.coalesce !== false && this.index > 0 && this.coalesceMs > 0 && t - this.lastPushTime <= this.coalesceMs && (options?.mergeKey !== void 0 && currentEntry.mergeKey === options.mergeKey || options?.mergeKey === void 0 && currentEntry.mergeKey === void 0);
13410
+ if (canCoalesce) {
13411
+ this.stack[this.index] = {
13412
+ state: cloned,
13413
+ label: cleanLabel ?? currentEntry.label,
13414
+ mergeKey: options?.mergeKey,
13415
+ timestamp: t
13416
+ };
13417
+ } else {
13418
+ this.stack.push({
13419
+ state: cloned,
13420
+ label: cleanLabel,
13421
+ mergeKey: options?.mergeKey,
13422
+ timestamp: t
13423
+ });
13424
+ this.trimToMaxDepth();
13425
+ this.index = this.stack.length - 1;
13426
+ }
13427
+ this.lastPushTime = t;
13428
+ this.syncControls();
13429
+ this.notifyCallback(this.onChange, "push", this.stack[this.index].state, previousState, this.stack[this.index].label);
13430
+ return true;
13431
+ }
13432
+ /**
13433
+ * Annule la dernière action et restaure l'état précédent.
13434
+ */
13435
+ undo() {
13436
+ if (this.isDestroyed || this.isApplying || !this.canUndo()) {
13437
+ return null;
13438
+ }
13439
+ return this.stepTo(this.index - 1, "undo");
13440
+ }
13441
+ /**
13442
+ * Rétablit l'action suivante dans l'historique.
13443
+ */
13444
+ redo() {
13445
+ if (this.isDestroyed || this.isApplying || !this.canRedo()) {
13446
+ return null;
13447
+ }
13448
+ return this.stepTo(this.index + 1, "redo");
13449
+ }
13450
+ /**
13451
+ * Saute directement à un index précis de la pile d'historique.
13452
+ */
13453
+ go(targetIndex) {
13454
+ if (this.isDestroyed || this.isApplying || !Number.isInteger(targetIndex)) {
13455
+ return null;
13456
+ }
13457
+ if (targetIndex < 0 || targetIndex >= this.stack.length || targetIndex === this.index) {
13458
+ return null;
13459
+ }
13460
+ return this.stepTo(targetIndex, "go");
13461
+ }
13462
+ /**
13463
+ * Regroupe plusieurs `push()` successifs dans une transaction atomique unique.
13464
+ * Garantit un rollback complet et la libération du verrou en cas d'exception.
13465
+ */
13466
+ batch(fn, label) {
13467
+ if (this.isDestroyed) {
13468
+ return fn();
13469
+ }
13470
+ const isRoot = this.batchDepth === 0;
13471
+ if (isRoot) {
13472
+ this.batchHasChange = false;
13473
+ this.batchPendingState = void 0;
13474
+ this.batchPendingLabel = sanitizeLabel(label);
13475
+ } else if (label && !this.batchPendingLabel) {
13476
+ this.batchPendingLabel = sanitizeLabel(label);
13477
+ }
13478
+ this.batchDepth++;
13479
+ try {
13480
+ const result = fn();
13481
+ if (isRoot && this.batchHasChange && this.batchPendingState !== void 0) {
13482
+ const pending = this.batchPendingState;
13483
+ const pendingLabel = this.batchPendingLabel;
13484
+ const currentEntry = this.stack[this.index];
13485
+ if (!this.equalsFn || !this.equalsFn(currentEntry.state, pending)) {
13486
+ const previousState = currentEntry.state;
13487
+ this.stack.length = this.index + 1;
13488
+ this.stack.push({
13489
+ state: pending,
13490
+ label: pendingLabel,
13491
+ timestamp: nowMs()
13492
+ });
13493
+ this.trimToMaxDepth();
13494
+ this.index = this.stack.length - 1;
13495
+ this.lastPushTime = -Infinity;
13496
+ this.syncControls();
13497
+ this.notifyCallback(this.onChange, "batch", pending, previousState, pendingLabel);
13498
+ }
13499
+ }
13500
+ return result;
13501
+ } catch (err) {
13502
+ if (isRoot) {
13503
+ this.batchHasChange = false;
13504
+ this.batchPendingState = void 0;
13505
+ this.batchPendingLabel = void 0;
13506
+ }
13507
+ throw err;
13508
+ } finally {
13509
+ this.batchDepth--;
13510
+ if (isRoot) {
13511
+ this.batchHasChange = false;
13512
+ this.batchPendingState = void 0;
13513
+ this.batchPendingLabel = void 0;
13514
+ }
13515
+ }
13516
+ }
13517
+ /**
13518
+ * Interrompt la fenêtre de coalescing en cours : le prochain `push()` créera une nouvelle entrée.
13519
+ */
13520
+ checkpoint() {
13521
+ this.lastPushTime = -Infinity;
13522
+ }
13523
+ /**
13524
+ * Remplace toute la pile par un nouvel état initial.
13525
+ */
13526
+ reset(newInitialState, label) {
13527
+ if (this.isDestroyed || this.isApplying) return;
13528
+ const prev = this.stack[this.index]?.state;
13529
+ const cleanLabel = sanitizeLabel(label);
13530
+ const cloned = this.cloneState(newInitialState);
13531
+ this.stack = [{ state: cloned, label: cleanLabel, timestamp: nowMs() }];
13532
+ this.index = 0;
13533
+ this.lastPushTime = -Infinity;
13534
+ this.syncControls();
13535
+ this.notifyCallback(this.onChange, "reset", cloned, prev, cleanLabel);
13536
+ }
13537
+ /**
13538
+ * Vide l'historique passé et futur tout en conservant l'état courant comme nouvelle racine.
13539
+ */
13540
+ clear() {
13541
+ if (this.isDestroyed || this.isApplying || this.stack.length === 0) return;
13542
+ const curr = this.stack[this.index];
13543
+ this.stack = [{ state: curr.state, label: curr.label, timestamp: curr.timestamp }];
13544
+ this.index = 0;
13545
+ this.lastPushTime = -Infinity;
13546
+ this.syncControls();
13547
+ this.notifyCallback(this.onChange, "clear", curr.state, curr.state, curr.label);
13548
+ }
13549
+ canUndo() {
13550
+ return !this.isDestroyed && this.index > 0;
13551
+ }
13552
+ canRedo() {
13553
+ return !this.isDestroyed && this.index < this.stack.length - 1;
13554
+ }
13555
+ getState() {
13556
+ if (this.batchDepth > 0 && this.batchHasChange && this.batchPendingState !== void 0) {
13557
+ return this.cloneState(this.batchPendingState);
13558
+ }
13559
+ if (this.stack.length === 0) {
13560
+ return void 0;
13561
+ }
13562
+ return this.cloneState(this.stack[this.index].state);
13563
+ }
13564
+ getIndex() {
13565
+ return this.index;
13566
+ }
13567
+ getLength() {
13568
+ return this.stack.length;
13569
+ }
13570
+ getUndoLabel() {
13571
+ return this.canUndo() ? this.stack[this.index].label : void 0;
13572
+ }
13573
+ getRedoLabel() {
13574
+ return this.canRedo() ? this.stack[this.index + 1].label : void 0;
13575
+ }
13576
+ getHistory() {
13577
+ return this.stack.map((entry) => ({
13578
+ state: this.cloneState(entry.state),
13579
+ label: entry.label,
13580
+ mergeKey: entry.mergeKey,
13581
+ timestamp: entry.timestamp
13582
+ }));
13583
+ }
13584
+ /**
13585
+ * Relie des boutons DOM Undo/Redo de façon non-destructive :
13586
+ * gère `aria-disabled` (avec blocage `click` en phase capture), `aria-keyshortcuts`
13587
+ * et `data-wulf-undo-label` sans jamais altérer les icônes ou libellés enfants.
13588
+ */
13589
+ bindControls(controls) {
13590
+ if (this.isDestroyed || typeof HTMLElement === "undefined") {
13591
+ return () => {
13592
+ };
13593
+ }
13594
+ const undoEl = controls.undo instanceof HTMLElement ? controls.undo : null;
13595
+ const redoEl = controls.redo instanceof HTMLElement ? controls.redo : null;
13596
+ const opts = {
13597
+ useNativeDisabled: Boolean(controls.useNativeDisabled),
13598
+ updateAriaKeyShortcuts: controls.updateAriaKeyShortcuts !== false,
13599
+ updateLabelAttribute: controls.updateLabelAttribute !== false
13600
+ };
13601
+ const ctrl = new AbortController();
13602
+ const savedUndo = undoEl ? this.captureControlAttrs(undoEl, "data-wulf-undo-label") : null;
13603
+ const savedRedo = redoEl ? this.captureControlAttrs(redoEl, "data-wulf-redo-label") : null;
13604
+ const attachClick = (el, role) => {
13605
+ el.addEventListener(
13606
+ "click",
13607
+ (event) => {
13608
+ const enabled = role === "undo" ? this.canUndo() : this.canRedo();
13609
+ if (!enabled || this.paused || this.isDestroyed) {
13610
+ event.preventDefault();
13611
+ event.stopImmediatePropagation();
13612
+ return;
13613
+ }
13614
+ if (role === "undo") this.undo();
13615
+ else this.redo();
13616
+ },
13617
+ { capture: true, signal: ctrl.signal }
13618
+ );
13619
+ };
13620
+ if (undoEl) attachClick(undoEl, "undo");
13621
+ if (redoEl) attachClick(redoEl, "redo");
13622
+ const isApple = isApplePlatform();
13623
+ const sync = () => {
13624
+ if (undoEl) {
13625
+ this.applyControlState(
13626
+ undoEl,
13627
+ this.canUndo(),
13628
+ opts,
13629
+ isApple ? "Meta+Z" : "Control+Z",
13630
+ "data-wulf-undo-label",
13631
+ this.getUndoLabel()
13632
+ );
13633
+ }
13634
+ if (redoEl) {
13635
+ this.applyControlState(
13636
+ redoEl,
13637
+ this.canRedo(),
13638
+ opts,
13639
+ isApple ? "Meta+Shift+Z" : "Control+Y Control+Shift+Z",
13640
+ "data-wulf-redo-label",
13641
+ this.getRedoLabel()
13642
+ );
13643
+ }
13644
+ };
13645
+ let unbound = false;
13646
+ const unbind = () => {
13647
+ if (unbound) return;
13648
+ unbound = true;
13649
+ ctrl.abort();
13650
+ if (undoEl && savedUndo) this.restoreControlAttrs(undoEl, "data-wulf-undo-label", savedUndo);
13651
+ if (redoEl && savedRedo) this.restoreControlAttrs(redoEl, "data-wulf-redo-label", savedRedo);
13652
+ this.bindings.delete(binding);
13653
+ };
13654
+ const binding = { undoEl, redoEl, options: opts, sync, unbind };
13655
+ this.bindings.add(binding);
13656
+ sync();
13657
+ return unbind;
13658
+ }
13659
+ pause() {
13660
+ this.paused = true;
13661
+ }
13662
+ resume() {
13663
+ if (!this.isDestroyed) {
13664
+ this.paused = false;
13665
+ }
13666
+ }
13667
+ isPaused() {
13668
+ return this.paused;
13669
+ }
13670
+ /**
13671
+ * Audite le respect de l'Axiome Primordial et l'accessibilité des contrôles liés.
13672
+ */
13673
+ audit() {
13674
+ const warnings = [];
13675
+ if (this.keyboardOptions?.allowInEditable) {
13676
+ warnings.push(
13677
+ "Option keyboard.allowInEditable: true d\xE9tect\xE9e \u2014 risque de d\xE9tourner Ctrl/Cmd+Z natif dans les zones de saisie (Axiome Primordial)."
13678
+ );
13679
+ }
13680
+ for (const binding of this.bindings) {
13681
+ for (const el of [binding.undoEl, binding.redoEl]) {
13682
+ if (!el) continue;
13683
+ const hasLabel = Boolean(el.getAttribute("aria-label")?.trim()) || this.checkAriaIdReferences(el, "aria-labelledby", warnings, true) || Boolean(el.textContent?.trim());
13684
+ if (!hasLabel) {
13685
+ warnings.push(
13686
+ `Contr\xF4le Undo/Redo li\xE9 (${el.tagName.toLowerCase()}) sans nom accessible (ajoutez du texte visible, aria-label ou aria-labelledby).`
13687
+ );
13688
+ }
13689
+ const tabIndexAttr = el.getAttribute("tabindex");
13690
+ if (tabIndexAttr !== null) {
13691
+ const parsed = Number.parseInt(tabIndexAttr, 10);
13692
+ if (Number.isFinite(parsed) && parsed > 0) {
13693
+ warnings.push(`\xC9vitez tabindex="${parsed}" (> 0) sur un contr\xF4le Undo/Redo.`);
13694
+ }
13695
+ }
13696
+ }
13697
+ }
13698
+ return warnings;
13699
+ }
13700
+ getAuditPrefix() {
13701
+ return "Wulf.Undo";
13702
+ }
13703
+ getAuditTargetLabel() {
13704
+ return `UndoManager (${this.stack.length} \xE9tat(s))`;
13705
+ }
13706
+ /**
13707
+ * Détruit l'instance : purge les listeners clavier, délie tous les contrôles,
13708
+ * supprime la live-region et libère la pile mémoire.
13709
+ */
13710
+ destroy() {
13711
+ if (this.isDestroyed) return;
13712
+ this.isDestroyed = true;
13713
+ if (this.abortController) {
13714
+ this.abortController.abort();
13715
+ this.abortController = null;
13716
+ }
13717
+ for (const binding of Array.from(this.bindings)) {
13718
+ binding.unbind();
13719
+ }
13720
+ this.bindings.clear();
13721
+ if (this.announceTimerId !== null) {
13722
+ clearTimeout(this.announceTimerId);
13723
+ this.announceTimerId = null;
13724
+ }
13725
+ if (this.srStatusEl) {
13726
+ this.srStatusEl.remove();
13727
+ this.srStatusEl = null;
13728
+ }
13729
+ this.stack = [];
13730
+ this.index = -1;
13731
+ this.batchPendingState = void 0;
13732
+ }
13733
+ // --- Implémentation interne ---
13734
+ cloneState(value) {
13735
+ if (this.cloneStrategy === "none") {
13736
+ return value;
13737
+ }
13738
+ if (typeof this.cloneStrategy === "function") {
13739
+ return this.cloneStrategy(value);
13740
+ }
13741
+ try {
13742
+ return structuredClone(value);
13743
+ } catch (err) {
13744
+ throw new TypeError(
13745
+ `[Wulf.Undo] Impossible de cloner l'\xE9tat via structuredClone() (fonction, n\u0153ud DOM ou Proxy non clonable). Utilisez { clone: "none" } ou fournissez une fonction clone personnalis\xE9e.`,
13746
+ { cause: err }
13747
+ );
13748
+ }
13749
+ }
13750
+ trimToMaxDepth() {
13751
+ const maxLen = this.maxDepth + 1;
13752
+ if (this.stack.length > maxLen) {
13753
+ this.stack.splice(0, this.stack.length - maxLen);
13754
+ }
13755
+ }
13756
+ stepTo(targetIndex, action) {
13757
+ const prevEntry = this.stack[this.index];
13758
+ const nextEntry = this.stack[targetIndex];
13759
+ const labelForAction = action === "undo" ? prevEntry?.label : nextEntry?.label;
13760
+ this.isApplying = true;
13761
+ try {
13762
+ this.index = targetIndex;
13763
+ this.lastPushTime = -Infinity;
13764
+ this.syncControls();
13765
+ const nextClone = this.cloneState(nextEntry.state);
13766
+ const prevClone = this.cloneState(prevEntry.state);
13767
+ if (action === "undo") {
13768
+ this.notifyCallback(this.onUndo, "undo", nextClone, prevClone, labelForAction);
13769
+ } else if (action === "redo") {
13770
+ this.notifyCallback(this.onRedo, "redo", nextClone, prevClone, labelForAction);
13771
+ }
13772
+ this.notifyCallback(this.onChange, action, nextClone, prevClone, labelForAction);
13773
+ if (this.announceEnabled && (action === "undo" || action === "redo")) {
13774
+ const dict = this.resolveI18n();
13775
+ this.announce(action === "undo" ? dict.undone(labelForAction) : dict.redone(labelForAction));
13776
+ }
13777
+ return this.cloneState(nextEntry.state);
13778
+ } finally {
13779
+ this.isApplying = false;
13780
+ }
13781
+ }
13782
+ notifyCallback(cb, action, state, previousState, label) {
13783
+ if (typeof cb !== "function") return;
13784
+ const detail = {
13785
+ state: this.cloneState(state),
13786
+ previousState: this.cloneState(previousState),
13787
+ action,
13788
+ label,
13789
+ index: this.index,
13790
+ length: this.stack.length,
13791
+ canUndo: this.canUndo(),
13792
+ canRedo: this.canRedo()
13793
+ };
13794
+ try {
13795
+ cb(detail);
13796
+ } catch (err) {
13797
+ const error = err instanceof Error ? err : new Error(String(err));
13798
+ if (typeof this.onError === "function") {
13799
+ try {
13800
+ this.onError(error, action);
13801
+ } catch (onErrEx) {
13802
+ console.error("[Wulf.Undo] Erreur dans onError :", onErrEx);
13803
+ }
13804
+ } else {
13805
+ console.error(`[Wulf.Undo] Erreur dans callback (${action}) :`, error);
13806
+ }
13807
+ }
13808
+ }
13809
+ bindKeyboard() {
13810
+ if (!this.keyboardOptions || typeof window === "undefined") return;
13811
+ const target = this.keyboardOptions.target ?? window;
13812
+ if (!target || typeof target.addEventListener !== "function") return;
13813
+ this.abortController = new AbortController();
13814
+ target.addEventListener(
13815
+ "keydown",
13816
+ (ev) => this.handleKeyDown(ev),
13817
+ { capture: false, signal: this.abortController.signal }
13818
+ );
13819
+ }
13820
+ handleKeyDown(event) {
13821
+ if (this.isDestroyed || this.paused || !this.keyboardOptions || event.defaultPrevented || isImeComposing(event)) {
13822
+ return;
13823
+ }
13824
+ const composed = typeof event.composedPath === "function" ? event.composedPath() : [];
13825
+ const nodes = composed.length > 0 ? composed : event.target ? [event.target] : [];
13826
+ let isEditable = false;
13827
+ let isSensitive = false;
13828
+ for (const node of nodes) {
13829
+ if (!isSensitive && isSensitiveElement(node)) isSensitive = true;
13830
+ if (!isEditable && isEditableElement(node)) isEditable = true;
13831
+ }
13832
+ if (isSensitive) return;
13833
+ if (isEditable && !this.keyboardOptions.allowInEditable) return;
13834
+ const key = (event.key || "").toLowerCase();
13835
+ if (key !== "z" && key !== "y") return;
13836
+ const isApple = isApplePlatform();
13837
+ const primaryMod = isApple ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
13838
+ const isUndo = primaryMod && !event.altKey && !event.shiftKey && key === "z";
13839
+ const isRedo = primaryMod && !event.altKey && event.shiftKey && key === "z" || !isApple && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && key === "y";
13840
+ if (isUndo && this.canUndo()) {
13841
+ if (this.keyboardOptions.preventDefault !== false) event.preventDefault();
13842
+ this.undo();
13843
+ } else if (isRedo && this.canRedo()) {
13844
+ if (this.keyboardOptions.preventDefault !== false) event.preventDefault();
13845
+ this.redo();
13846
+ }
13847
+ }
13848
+ captureControlAttrs(el, labelAttr) {
13849
+ return {
13850
+ hadDisabled: el.hasAttribute("disabled"),
13851
+ prevDisabled: el.disabled ?? false,
13852
+ hadAriaDisabled: el.hasAttribute("aria-disabled"),
13853
+ prevAriaDisabled: el.getAttribute("aria-disabled"),
13854
+ hadAriaKeyShortcuts: el.hasAttribute("aria-keyshortcuts"),
13855
+ prevAriaKeyShortcuts: el.getAttribute("aria-keyshortcuts"),
13856
+ hadLabelAttr: el.hasAttribute(labelAttr),
13857
+ prevLabelAttr: el.getAttribute(labelAttr)
13858
+ };
13859
+ }
13860
+ restoreControlAttrs(el, labelAttr, saved) {
13861
+ if ("disabled" in el) {
13862
+ if (saved.hadDisabled) {
13863
+ el.disabled = saved.prevDisabled;
13864
+ } else {
13865
+ el.removeAttribute("disabled");
13866
+ }
13867
+ }
13868
+ if (saved.hadAriaDisabled && saved.prevAriaDisabled !== null) {
13869
+ el.setAttribute("aria-disabled", saved.prevAriaDisabled);
13870
+ } else {
13871
+ el.removeAttribute("aria-disabled");
13872
+ }
13873
+ if (saved.hadAriaKeyShortcuts && saved.prevAriaKeyShortcuts !== null) {
13874
+ el.setAttribute("aria-keyshortcuts", saved.prevAriaKeyShortcuts);
13875
+ } else {
13876
+ el.removeAttribute("aria-keyshortcuts");
13877
+ }
13878
+ if (saved.hadLabelAttr && saved.prevLabelAttr !== null) {
13879
+ el.setAttribute(labelAttr, saved.prevLabelAttr);
13880
+ } else {
13881
+ el.removeAttribute(labelAttr);
13882
+ }
13883
+ }
13884
+ applyControlState(el, enabled, opts, keyShortcut, labelAttr, actionLabel) {
13885
+ if (opts.useNativeDisabled && "disabled" in el) {
13886
+ el.disabled = !enabled;
13887
+ el.removeAttribute("aria-disabled");
13888
+ } else {
13889
+ el.setAttribute("aria-disabled", enabled ? "false" : "true");
13890
+ }
13891
+ if (opts.updateAriaKeyShortcuts) {
13892
+ el.setAttribute("aria-keyshortcuts", keyShortcut);
13893
+ }
13894
+ if (opts.updateLabelAttribute) {
13895
+ if (actionLabel) el.setAttribute(labelAttr, actionLabel);
13896
+ else el.removeAttribute(labelAttr);
13897
+ }
13898
+ }
13899
+ syncControls() {
13900
+ for (const binding of this.bindings) {
13901
+ binding.sync();
13902
+ }
13903
+ }
13904
+ resolveI18n() {
13905
+ if (this.langOverride) {
13906
+ const prev = undoI18n.getLocale();
13907
+ undoI18n.setLocale(this.langOverride);
13908
+ const dict = undoI18n.getAll(this.i18nOverrides);
13909
+ undoI18n.setLocale(prev);
13910
+ return dict;
13911
+ }
13912
+ return undoI18n.getAll(this.i18nOverrides);
13913
+ }
13914
+ mountStatusRegion() {
13915
+ if (typeof document === "undefined" || this.srStatusEl) return;
13916
+ const status = document.createElement("div");
13917
+ status.setAttribute("role", "status");
13918
+ status.setAttribute("aria-live", "polite");
13919
+ status.setAttribute("aria-atomic", "true");
13920
+ status.setAttribute("data-wulf-undo-status", "true");
13921
+ status.style.position = "absolute";
13922
+ status.style.width = "1px";
13923
+ status.style.height = "1px";
13924
+ status.style.overflow = "hidden";
13925
+ status.style.clipPath = "inset(50%)";
13926
+ status.style.whiteSpace = "nowrap";
13927
+ status.style.pointerEvents = "none";
13928
+ let target = null;
13929
+ if (this.announceRoot) {
13930
+ if (typeof ShadowRoot !== "undefined" && this.announceRoot instanceof ShadowRoot) {
13931
+ target = this.announceRoot;
13932
+ } else if (typeof HTMLElement !== "undefined" && this.announceRoot instanceof HTMLElement) {
13933
+ target = this.announceRoot;
13934
+ } else if (typeof Document !== "undefined" && this.announceRoot instanceof Document) {
13935
+ target = this.announceRoot.body || this.announceRoot.documentElement;
13936
+ }
13937
+ }
13938
+ if (!target) {
13939
+ target = document.body || document.documentElement;
13940
+ }
13941
+ if (!target) return;
13942
+ target.appendChild(status);
13943
+ this.srStatusEl = status;
13944
+ }
13945
+ announce(message) {
13946
+ if (this.isDestroyed || typeof document === "undefined") return;
13947
+ const clean = stripBidiAndInvisibles(message, 400).trim();
13948
+ if (!clean) return;
13949
+ const docWithNotify = document;
13950
+ if (typeof docWithNotify.ariaNotify === "function") {
13951
+ try {
13952
+ docWithNotify.ariaNotify(clean, { priority: "normal" });
13953
+ return;
13954
+ } catch {
13955
+ }
13956
+ }
13957
+ if (!this.srStatusEl) {
13958
+ this.mountStatusRegion();
13959
+ }
13960
+ if (!this.srStatusEl) return;
13961
+ if (this.announceTimerId !== null) {
13962
+ clearTimeout(this.announceTimerId);
13963
+ this.announceTimerId = null;
13964
+ }
13965
+ this.srStatusEl.textContent = "";
13966
+ this.announceTimerId = setTimeout(() => {
13967
+ this.announceTimerId = null;
13968
+ if (!this.isDestroyed && this.srStatusEl) {
13969
+ this.srStatusEl.textContent = clean;
13970
+ }
13971
+ }, 40);
13972
+ }
13973
+ };
10516
13974
  return __toCommonJS(index_exports);
10517
13975
  })();
10518
- 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 (__) {} } } } } }
13976
+ 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; } var __set = function(obj, key, val) { try { Object.defineProperty(obj, key, { value: val, writable: true, configurable: true, enumerable: true }); } catch (_) { try { obj[key] = val; } catch (__) {} } }; if (typeof __WulfIIFE !== "undefined" && __WulfIIFE) { var __e = __WulfIIFE; var __skip = ["__proto__","constructor","prototype","Mask","Scroll","Masonry","Toast","FocusTrap","Shortcut","Anchor","Sortable","Autosize","Undo"]; for (var k in __e) { if (Object.hasOwn(__e, k) && __skip.indexOf(k) === -1 && __w[k] === undefined) { __set(__w, k, __e[k]); } } if (__e.Mask && __e.Mask.Mask) __set(__w, "Mask", __e.Mask.Mask); if (__e.Scroll && __e.Scroll.Scroll) __set(__w, "Scroll", __e.Scroll.Scroll); if (__e.WulfMasonry) __set(__w, "Masonry", Object.assign(__e.WulfMasonry, { Masonry: __e.WulfMasonry, LayoutEngine: __e.LayoutEngine, i18n: __e.Masonry && __e.Masonry.masonryI18n })); if (__e.WulfToast) __set(__w, "Toast", Object.assign(__e.WulfToast, { Toast: __e.WulfToast, ToastInstance: __e.ToastInstance, ToastManager: __e.ToastManager, i18n: __e.Toast && __e.Toast.toastI18n })); if (__e.WulfFocusTrap) __set(__w, "FocusTrap", Object.assign(__e.WulfFocusTrap, { FocusTrap: __e.WulfFocusTrap, default: __e.WulfFocusTrap })); if (__e.ShortcutManager) __set(__w, "Shortcut", Object.assign(__e.ShortcutManager, { ShortcutManager: __e.ShortcutManager, ShortcutFormatter: __e.ShortcutFormatter, default: __e.ShortcutManager })); if (__e.WulfAnchor) __set(__w, "Anchor", Object.assign(__e.WulfAnchor, { Anchor: __e.WulfAnchor, default: __e.WulfAnchor })); if (__e.WulfSortable) __set(__w, "Sortable", Object.assign(__e.WulfSortable, { Sortable: __e.WulfSortable, i18n: __e.Sortable && __e.Sortable.sortableI18n, default: __e.WulfSortable })); if (__e.WulfAutosize) __set(__w, "Autosize", Object.assign(__e.WulfAutosize, { Autosize: __e.WulfAutosize, default: __e.WulfAutosize })); if (__e.WulfUndo) __set(__w, "Undo", Object.assign(__e.WulfUndo, { Undo: __e.WulfUndo, UndoManager: __e.WulfUndo, i18n: __e.Undo && __e.Undo.undoI18n, default: __e.WulfUndo })); }}
10519
13977
  //# sourceMappingURL=index.global.js.map