@italia/globals 1.0.0-alpha.8 → 1.0.0-beta.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 (34) hide show
  1. package/custom-elements.json +341 -19
  2. package/dist/src/base-component/base-component.d.ts +2 -0
  3. package/dist/src/base-component/base-component.d.ts.map +1 -1
  4. package/dist/src/base-component/base-component.js +20 -0
  5. package/dist/src/base-component/base-component.js.map +1 -1
  6. package/dist/src/controllers/focus-trap-controller.d.ts +42 -22
  7. package/dist/src/controllers/focus-trap-controller.d.ts.map +1 -1
  8. package/dist/src/controllers/focus-trap-controller.js +350 -123
  9. package/dist/src/controllers/focus-trap-controller.js.map +1 -1
  10. package/dist/src/controllers/roving-tabindex-controller.d.ts +9 -2
  11. package/dist/src/controllers/roving-tabindex-controller.d.ts.map +1 -1
  12. package/dist/src/controllers/roving-tabindex-controller.js +11 -5
  13. package/dist/src/controllers/roving-tabindex-controller.js.map +1 -1
  14. package/dist/src/directives/setAttributes.d.ts.map +1 -1
  15. package/dist/src/directives/setAttributes.js +69 -3
  16. package/dist/src/directives/setAttributes.js.map +1 -1
  17. package/dist/src/form/form-control.js +1 -1
  18. package/dist/src/form/form-control.js.map +1 -1
  19. package/dist/src/form/form-controller.d.ts.map +1 -1
  20. package/dist/src/form/form-controller.js +8 -0
  21. package/dist/src/form/form-controller.js.map +1 -1
  22. package/dist/src/index.d.ts +2 -0
  23. package/dist/src/index.d.ts.map +1 -1
  24. package/dist/src/index.js +3 -1
  25. package/dist/src/index.js.map +1 -1
  26. package/dist/src/utils/dispatch-cancelable.d.ts +31 -0
  27. package/dist/src/utils/dispatch-cancelable.d.ts.map +1 -0
  28. package/dist/src/utils/dispatch-cancelable.js +43 -0
  29. package/dist/src/utils/dispatch-cancelable.js.map +1 -0
  30. package/dist/src/utils/focus-fallback.d.ts +27 -0
  31. package/dist/src/utils/focus-fallback.d.ts.map +1 -0
  32. package/dist/src/utils/focus-fallback.js +63 -0
  33. package/dist/src/utils/focus-fallback.js.map +1 -0
  34. package/package.json +4 -4
@@ -1,11 +1,179 @@
1
1
  /**
2
- * Controller per gestire il focus trap all'interno di un elemento.
3
- * Implementa le linee guida WAI-ARIA per i dialog modali.
2
+ * Safari/VoiceOver iOS workarounds catalogue — why timers exist here:
4
3
  *
5
-
6
- * ```
4
+ * 1. `activate()` rAF + setTimeout(50): Safari does not reliably update the VoiceOver
5
+ * accessibility tree synchronously. rAF ensures the element is painted before we
6
+ * attempt to focus it. setTimeout(50) yields 50ms so VoiceOver can settle its
7
+ * accessibility tree before announcing the newly focused element.
8
+ * Empirically, VoiceOver iOS needs 100–300ms; the animated path in it-modal already
9
+ * provides ~316ms naturally via animation.finished, so the 50ms here only truly
10
+ * matters for the no-animation / prefers-reduced-motion path.
11
+ *
12
+ * 2. `_restoreFocus()` setTimeout(0): Same settle reason on close. The caller
13
+ * (it-modal finishHide) adds a belt-and-suspenders 20ms setTimeout; _restoreFocus
14
+ * is skipped via { skipFocusRestore: true } in that case to avoid double-focus.
15
+ *
16
+ * 3. `activate()` iOS body-focus fallback: On iOS Safari, tapping a button does not
17
+ * reliably move document.activeElement away from body. We fall back to getTrigger()
18
+ * so _previousActiveElement is always a real DOM element to restore focus to on close.
19
+ *
20
+ * There is no WebKit/Safari API to detect when VoiceOver has settled its accessibility
21
+ * tree. setTimeout-based workarounds are the same pattern used by Bootstrap 5, the
22
+ * focus-trap npm package, and a11y-dialog.
7
23
  */
8
24
  export class FocusTrapController {
25
+ static getManagedHostAncestor(element) {
26
+ let current = element;
27
+ while (current) {
28
+ const parentEl = current instanceof HTMLElement ? current.parentElement : null;
29
+ if (parentEl && parentEl.matches(FocusTrapController.MANAGED_HOST_SELECTORS))
30
+ return parentEl;
31
+ if (parentEl) {
32
+ current = parentEl;
33
+ continue;
34
+ }
35
+ const rootNode = current.getRootNode();
36
+ if (rootNode instanceof ShadowRoot) {
37
+ const hostElement = rootNode.host;
38
+ if (hostElement instanceof HTMLElement) {
39
+ if (hostElement.matches(FocusTrapController.MANAGED_HOST_SELECTORS))
40
+ return hostElement;
41
+ current = hostElement;
42
+ continue;
43
+ }
44
+ }
45
+ break;
46
+ }
47
+ return null;
48
+ }
49
+ static isInsideManagedHost(element) {
50
+ return FocusTrapController.getManagedHostAncestor(element) !== null;
51
+ }
52
+ static getManagedMenuHostAncestor(element) {
53
+ let current = element;
54
+ while (current) {
55
+ const parentEl = current instanceof HTMLElement ? current.parentElement : null;
56
+ if (parentEl && parentEl.matches(FocusTrapController.MANAGED_MENU_HOST_SELECTORS))
57
+ return parentEl;
58
+ if (parentEl) {
59
+ current = parentEl;
60
+ continue;
61
+ }
62
+ const rootNode = current.getRootNode();
63
+ if (rootNode instanceof ShadowRoot) {
64
+ const hostElement = rootNode.host;
65
+ if (hostElement instanceof HTMLElement) {
66
+ if (hostElement.matches(FocusTrapController.MANAGED_MENU_HOST_SELECTORS))
67
+ return hostElement;
68
+ current = hostElement;
69
+ continue;
70
+ }
71
+ }
72
+ break;
73
+ }
74
+ return null;
75
+ }
76
+ static collectFocusableCandidates(root, candidates, trigger, visited) {
77
+ const rootAsNode = root;
78
+ if (visited.has(rootAsNode))
79
+ return;
80
+ visited.add(rootAsNode);
81
+ const elements = Array.from(root.querySelectorAll('*'));
82
+ elements.forEach((el) => {
83
+ if (el === trigger)
84
+ return;
85
+ // Keep custom host components as single tab stops: their internal light/shadow
86
+ // descendants must not appear as separate trap candidates.
87
+ if (FocusTrapController.isInsideManagedHost(el))
88
+ return;
89
+ if (el.matches(FocusTrapController.FOCUSABLE_SELECTORS)) {
90
+ candidates.push(el);
91
+ // Stop here: focusCandidate() handles delegation to the inner focusable.
92
+ // Prevent recursion into this element's shadow DOM so inner buttons/triggers
93
+ // are not added as separate tab stops.
94
+ if (el.shadowRoot)
95
+ visited.add(el.shadowRoot);
96
+ return;
97
+ }
98
+ if (el instanceof HTMLSlotElement) {
99
+ el.assignedElements({ flatten: true }).forEach((assigned) => {
100
+ if (!(assigned instanceof HTMLElement) || assigned === trigger)
101
+ return;
102
+ if (assigned.matches(FocusTrapController.FOCUSABLE_SELECTORS)) {
103
+ candidates.push(assigned);
104
+ // Same rule: don't recurse into a focusable element.
105
+ if (assigned.shadowRoot)
106
+ visited.add(assigned.shadowRoot);
107
+ return;
108
+ }
109
+ FocusTrapController.collectFocusableCandidates(assigned, candidates, trigger, visited);
110
+ if (assigned.shadowRoot) {
111
+ FocusTrapController.collectFocusableCandidates(assigned.shadowRoot, candidates, trigger, visited);
112
+ }
113
+ });
114
+ return;
115
+ }
116
+ if (el.shadowRoot) {
117
+ FocusTrapController.collectFocusableCandidates(el.shadowRoot, candidates, trigger, visited);
118
+ }
119
+ });
120
+ }
121
+ static getFirstFocusableInShadow(host) {
122
+ const visited = new Set();
123
+ const walk = (root) => {
124
+ const rootAsNode = root;
125
+ if (visited.has(rootAsNode))
126
+ return null;
127
+ visited.add(rootAsNode);
128
+ const direct = Array.from(root.querySelectorAll(FocusTrapController.NATIVE_FOCUSABLE_SELECTORS));
129
+ const firstDirect = direct.find((el) => FocusTrapController.isFocusable(el));
130
+ if (firstDirect)
131
+ return firstDirect;
132
+ const all = Array.from(root.querySelectorAll('*'));
133
+ for (const el of all) {
134
+ if (el instanceof HTMLSlotElement) {
135
+ const assigned = el.assignedElements({ flatten: true });
136
+ for (const assignedEl of assigned) {
137
+ if (!(assignedEl instanceof HTMLElement))
138
+ continue;
139
+ if (assignedEl.matches(FocusTrapController.NATIVE_FOCUSABLE_SELECTORS)) {
140
+ if (FocusTrapController.isFocusable(assignedEl))
141
+ return assignedEl;
142
+ }
143
+ const nestedAssigned = walk(assignedEl);
144
+ if (nestedAssigned)
145
+ return nestedAssigned;
146
+ if (assignedEl.shadowRoot) {
147
+ const nestedAssignedShadow = walk(assignedEl.shadowRoot);
148
+ if (nestedAssignedShadow)
149
+ return nestedAssignedShadow;
150
+ }
151
+ }
152
+ }
153
+ if (el.shadowRoot) {
154
+ const nested = walk(el.shadowRoot);
155
+ if (nested)
156
+ return nested;
157
+ }
158
+ }
159
+ return null;
160
+ };
161
+ if (!host.shadowRoot)
162
+ return null;
163
+ return walk(host.shadowRoot);
164
+ }
165
+ static focusCandidate(target) {
166
+ if (!target)
167
+ return;
168
+ if (target.tagName.toLowerCase().startsWith('it-')) {
169
+ const innerFocusable = FocusTrapController.getFirstFocusableInShadow(target);
170
+ if (innerFocusable) {
171
+ innerFocusable.focus({ preventScroll: true });
172
+ return;
173
+ }
174
+ }
175
+ target.focus({ preventScroll: true });
176
+ }
9
177
  /**
10
178
  * Verifica se un elemento è effettivamente focusabile e tabbabile.
11
179
  * Elementi con tabindex="-1" sono focusabili programmaticamente ma non tabbabili.
@@ -13,39 +181,22 @@ export class FocusTrapController {
13
181
  static isFocusable(el) {
14
182
  if (typeof el.focus !== 'function')
15
183
  return false;
16
- // Escludi elementi disabilitati
17
- if (el.hasAttribute('disabled'))
184
+ if (el.hasAttribute('disabled') || el.hasAttribute('inert') || el.hasAttribute('it-inert'))
18
185
  return false;
19
- // Escludi elementi con tabindex negativo (focusabili programmaticamente ma non tabbabili)
20
186
  const tabindex = el.getAttribute('tabindex');
21
- if (tabindex && parseInt(tabindex, 10) < 0) {
187
+ if (tabindex && parseInt(tabindex, 10) < 0)
22
188
  return false;
23
- }
24
- // Per custom elements (it-*), controlla anche il loro tabindex
25
189
  if (el.tagName.toLowerCase().startsWith('it-')) {
26
- // Se ha tabindex esplicito negativo, non è tabbabile
27
- if (tabindex && parseInt(tabindex, 10) < 0) {
190
+ if (tabindex && parseInt(tabindex, 10) < 0)
28
191
  return false;
29
- }
30
192
  return true;
31
193
  }
32
- // Per elementi standard, controlliamo anche visibilità in modo robusto.
33
- // Alcuni elementi (es. inline anchors, elementi dentro container positionati) possono
34
- // avere offsetParent === null pur essendo visibili/focusabili. Usiamo quindi getClientRects
35
- // e computedStyle come controllo più affidabile.
194
+ // Fix Race Condition Safari: durante l'apertura non fidarti di getClientRects o opacità
36
195
  try {
37
- // Se non ci sono bounding rects, probabilmente non è visibile
38
- if (el.getClientRects()?.length === 0)
39
- return false;
40
196
  const style = window.getComputedStyle(el);
41
- if (!style)
42
- return false;
43
- if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0')
44
- return false;
45
- // Altrimenti consideriamo l'elemento focusabile
46
- return true;
197
+ return style && style.display !== 'none' && style.visibility !== 'hidden';
47
198
  }
48
- catch (e) {
199
+ catch {
49
200
  return false;
50
201
  }
51
202
  }
@@ -54,6 +205,13 @@ export class FocusTrapController {
54
205
  this._isActive = false;
55
206
  this._previousActiveElement = null;
56
207
  this._focusableElements = [];
208
+ /** Last known index resolved from real focusin events inside the trap.
209
+ * Used as a fallback when assistive tech retargeting makes activeElement
210
+ * temporarily unmappable during Tab navigation. */
211
+ this._lastKnownFocusIndex = -1;
212
+ /** Timer ID for the focus call scheduled inside activate(). Cancelled by deactivate()
213
+ * to prevent focus firing after the trap has been torn down (fast open/close, unmount). */
214
+ this._pendingFocusTimer = null;
57
215
  this._handleKeyDown = (event) => {
58
216
  if (!this._isActive)
59
217
  return;
@@ -71,19 +229,38 @@ export class FocusTrapController {
71
229
  break;
72
230
  }
73
231
  };
232
+ this._handleFocusIn = (event) => {
233
+ if (!this._isActive)
234
+ return;
235
+ if (this._focusableElements.length === 0) {
236
+ this.updateFocusableElements();
237
+ if (this._focusableElements.length === 0)
238
+ return;
239
+ }
240
+ const path = event.composedPath();
241
+ let index = this._focusableElements.findIndex((candidate) => path.includes(candidate));
242
+ if (index === -1) {
243
+ const target = path[0];
244
+ if (target instanceof HTMLElement) {
245
+ index = this._focusableElements.indexOf(target);
246
+ }
247
+ }
248
+ if (index === -1) {
249
+ const active = FocusTrapController.getActiveElement();
250
+ if (active) {
251
+ index = this._focusableElements.findIndex((candidate) => candidate.contains(active));
252
+ }
253
+ }
254
+ if (index !== -1) {
255
+ this._lastKnownFocusIndex = index;
256
+ }
257
+ };
74
258
  this.host = host;
75
259
  this.config = config;
76
260
  this.host.addController(this);
77
261
  }
78
- // eslint-disable-next-line class-methods-use-this
79
262
  hostConnected() {
80
- // Controller ready
81
- // Set up our MutationObserver
82
- const observerOptions = {
83
- childList: true,
84
- attributes: true,
85
- subtree: true,
86
- };
263
+ const observerOptions = { childList: true, attributes: true, subtree: true };
87
264
  this.observer = new MutationObserver(this.updateFocusableElements.bind(this));
88
265
  this.observer.observe(this.host, observerOptions);
89
266
  }
@@ -94,37 +271,62 @@ export class FocusTrapController {
94
271
  this.observer = null;
95
272
  }
96
273
  }
97
- /** Indica se il focus trap è attivo */
98
274
  get isActive() {
99
275
  return this._isActive;
100
276
  }
101
- /**
102
- * Attiva il focus trap.
103
- * Salva l'elemento attivo corrente e attiva i listener.
104
- * NOTA: chiamare updateFocusableElements() e focusFirst() separatamente quando necessario.
105
- */
106
277
  activate() {
107
278
  if (this._isActive)
108
279
  return;
109
280
  this._isActive = true;
110
- this._previousActiveElement = FocusTrapController.getActiveElement();
111
- this.host.addEventListener('keydown', this._handleKeyDown);
281
+ // FIX iOS: Safari non dà focus al tap. Se activeElement è body, salviamo il trigger della config.
282
+ const currentActive = FocusTrapController.getActiveElement();
283
+ this._previousActiveElement =
284
+ !currentActive || currentActive === document.body ? this.config.getTrigger() : currentActive;
285
+ // Usa document capture: cattura Tab/Escape prima di qualsiasi handler,
286
+ // indipendentemente da shadow DOM, delegatesFocus e slot retargeting.
287
+ document.addEventListener('keydown', this._handleKeyDown, true);
288
+ document.addEventListener('focusin', this._handleFocusIn, true);
112
289
  this.updateFocusableElements();
113
- if (typeof this.focusInitial === 'function')
114
- this.focusInitial();
115
- else
116
- this.focusFirst();
290
+ this._lastKnownFocusIndex = -1;
291
+ // FIX Safari: trick engine
292
+ // Diamo al browser un istante per processare il ricalcolo del layout
293
+ requestAnimationFrame(() => {
294
+ if (this.config.initialFocus) {
295
+ const el = this.config.initialFocus();
296
+ if (el) {
297
+ // 50ms gives VoiceOver iOS time to settle its accessibility tree before
298
+ // announcing the focused element. See class-level comment for details.
299
+ this._pendingFocusTimer = setTimeout(() => {
300
+ this._pendingFocusTimer = null;
301
+ el.focus({ preventScroll: true });
302
+ }, 50);
303
+ }
304
+ }
305
+ else {
306
+ // eslint-disable-next-line no-console
307
+ console.warn("FocusTrap: missing 'initialFocus' callback, provide one");
308
+ }
309
+ });
117
310
  }
118
- /**
119
- * Disattiva il focus trap.
120
- * Ripristina il focus all'elemento precedentemente attivo.
121
- */
122
- deactivate() {
311
+ deactivate(options) {
123
312
  if (!this._isActive)
124
313
  return;
314
+ // Cancel any in-flight focus timer so it cannot fire after the trap is torn down
315
+ // (e.g. fast open/close cycle, component unmounted while opening).
316
+ if (this._pendingFocusTimer !== null) {
317
+ clearTimeout(this._pendingFocusTimer);
318
+ this._pendingFocusTimer = null;
319
+ }
125
320
  this._isActive = false;
126
- this.host.removeEventListener('keydown', this._handleKeyDown);
127
- this._restoreFocus();
321
+ document.removeEventListener('keydown', this._handleKeyDown, true);
322
+ document.removeEventListener('focusin', this._handleFocusIn, true);
323
+ this._lastKnownFocusIndex = -1;
324
+ if (!options?.skipFocusRestore) {
325
+ this._restoreFocus();
326
+ }
327
+ else {
328
+ this._previousActiveElement = null;
329
+ }
128
330
  }
129
331
  /**
130
332
  * Aggiorna la lista degli elementi focusabili.
@@ -140,25 +342,21 @@ export class FocusTrapController {
140
342
  return;
141
343
  }
142
344
  const candidates = [];
143
- // Tutti gli elementi focusable direttamente nel container
144
- const direct = Array.from(container.querySelectorAll(FocusTrapController.FOCUSABLE_SELECTORS));
145
- candidates.push(...direct);
146
- // Tutti gli elementi slottati
147
- const slots = Array.from(container.querySelectorAll('slot'));
148
- slots.forEach((slot) => {
149
- slot.assignedElements({ flatten: true }).forEach((el) => {
150
- if (!(el instanceof HTMLElement))
151
- return;
152
- if (el === trigger) {
153
- return;
154
- }
155
- // focusable diretto
156
- if (el.matches(FocusTrapController.FOCUSABLE_SELECTORS)) {
157
- candidates.push(el);
158
- }
159
- // nested focusable dentro l'elemento assegnato
160
- Array.from(el.querySelectorAll(FocusTrapController.FOCUSABLE_SELECTORS)).forEach((nested) => candidates.push(nested));
161
- });
345
+ FocusTrapController.collectFocusableCandidates(container, candidates, trigger, new Set());
346
+ // Include anche i figli light DOM dell'host (es. contenuti slottati della modale)
347
+ Array.from(this.host.children).forEach((child) => {
348
+ if (!(child instanceof HTMLElement) || child === trigger)
349
+ return;
350
+ if (child.matches(FocusTrapController.FOCUSABLE_SELECTORS)) {
351
+ candidates.push(child);
352
+ // Don't recurse: same stop-on-focusable rule.
353
+ return;
354
+ }
355
+ const childVisited = new Set();
356
+ FocusTrapController.collectFocusableCandidates(child, candidates, trigger, childVisited);
357
+ if (child.shadowRoot) {
358
+ FocusTrapController.collectFocusableCandidates(child.shadowRoot, candidates, trigger, childVisited);
359
+ }
162
360
  });
163
361
  // Filtra solo elementi veramente focusabili e rimuovi duplicati
164
362
  this._focusableElements = Array.from(new Set(candidates)).filter((el) => {
@@ -173,9 +371,8 @@ export class FocusTrapController {
173
371
  }
174
372
  /** Sposta il focus sul primo elemento focusabile */
175
373
  focusFirst() {
176
- if (this._first) {
374
+ if (this._first)
177
375
  this._first.focus();
178
- }
179
376
  }
180
377
  /** Sposta il focus sull'ultimo elemento focusabile */
181
378
  focusLast() {
@@ -191,70 +388,83 @@ export class FocusTrapController {
191
388
  }
192
389
  return active;
193
390
  }
194
- /**
195
- * Metti a fuoco l'elemento iniziale specificato nella config, se presente.
196
- * Se non è fornito, fallback sul primo elemento tabbabile.
197
- */
198
- focusInitial() {
199
- if (this.config.initialFocus) {
200
- const el = this.config.initialFocus();
201
- if (el && typeof el.focus === 'function') {
202
- el.focus();
391
+ _handleTab(event) {
392
+ const activeElement = FocusTrapController.getActiveElement();
393
+ // Let native Tab behavior handle navigation inside open dropdown/megamenu.
394
+ // This allows entering and traversing internal menu items correctly.
395
+ if (activeElement) {
396
+ const managedHost = FocusTrapController.getManagedMenuHostAncestor(activeElement);
397
+ if (managedHost && managedHost.getAttribute('data-it-aria-expanded') === 'true') {
203
398
  return;
204
399
  }
205
400
  }
206
- this.focusFirst();
207
- }
208
- _handleTab(event) {
209
- if (this._focusableElements.length === 0) {
210
- event.preventDefault();
211
- return;
212
- }
213
- // SEMPRE previeni il default - gestiamo noi la navigazione
401
+ // Ricalcola sempre al Tab: gli elementi slottati possono completare il render
402
+ // del proprio shadow DOM dopo l'attivazione iniziale del trap.
403
+ this.updateFocusableElements();
404
+ if (this._focusableElements.length === 0)
405
+ return; // Se è ancora vuoto, non bloccare il Tab
214
406
  event.preventDefault();
215
- const firstElement = this._first;
216
- const lastElement = this._last;
217
- const activeElement = FocusTrapController.getActiveElement();
218
- // Trova l'indice dell'elemento attivo
219
- // Se activeElement è dentro uno shadow DOM di un custom element,
220
- // cerca il custom element host nella lista
221
407
  let currentIndex = this._focusableElements.indexOf(activeElement);
222
- // Se non trovato, potrebbe essere un elemento interno ad un custom element
223
408
  if (currentIndex === -1 && activeElement) {
224
- // Risali attraverso gli shadow host
409
+ // 1. Walk shadow host chain (covers delegatesFocus custom elements)
225
410
  let parent = activeElement.getRootNode()?.host;
226
411
  while (parent && currentIndex === -1) {
227
412
  currentIndex = this._focusableElements.indexOf(parent);
228
- if (currentIndex === -1) {
413
+ if (currentIndex === -1)
229
414
  parent = parent.getRootNode()?.host;
230
- }
231
415
  }
232
416
  }
233
- if (event.shiftKey) {
234
- // Shift + Tab: vai al precedente
235
- if (currentIndex <= 0) {
236
- // Se sei sul primo o non sei nella lista, vai all'ultimo
237
- lastElement?.focus();
238
- }
239
- else {
240
- // Vai al precedente
241
- this._focusableElements[currentIndex - 1]?.focus();
242
- }
417
+ if (currentIndex === -1) {
418
+ // 2. Composed path fallback: handles focus inside nested shadow/slotted
419
+ // content (e.g. anchors inside it-dropdown-item) by mapping the active
420
+ // target to the first focusable host found in the event path.
421
+ const composedPath = event.composedPath();
422
+ currentIndex = this._focusableElements.findIndex((candidate) => composedPath.includes(candidate));
243
423
  }
244
- else if (currentIndex === -1 || currentIndex >= this._focusableElements.length - 1) {
245
- // Tab: se non sei nella lista o sei sull'ultimo, vai al primo
246
- firstElement?.focus();
424
+ if (currentIndex === -1 && activeElement) {
425
+ // 3. contains() fallback: handles focus inside an open dropdown/megamenu whose
426
+ // items live in light DOM (not shadow DOM), so the parent-walk above doesn't
427
+ // reach the host. Map to the host's index so Tab/Shift+Tab move to the
428
+ // correct adjacent element.
429
+ currentIndex = this._focusableElements.findIndex((candidate) => candidate.contains(activeElement));
247
430
  }
248
- else {
249
- // Vai al successivo
250
- this._focusableElements[currentIndex + 1]?.focus();
431
+ if (currentIndex === -1) {
432
+ // 4. AT fallback: with some screen readers, document.activeElement and/or
433
+ // event target can be unreliable while navigating inside composite widgets.
434
+ // If a dropdown/megamenu is currently open, use its host index as anchor
435
+ // so forward/backward Tab continue from that position instead of wrapping.
436
+ currentIndex = this._focusableElements.findIndex((candidate) => candidate.matches('it-dropdown, it-megamenu') && candidate.getAttribute('data-it-aria-expanded') === 'true');
437
+ }
438
+ if (currentIndex === -1 && this._lastKnownFocusIndex >= 0) {
439
+ // 5. Last-known fallback: if assistive tech retargeting hides the active
440
+ // element for this key event, continue from the most recent resolved
441
+ // focus index captured via focusin.
442
+ currentIndex = Math.min(this._lastKnownFocusIndex, this._focusableElements.length - 1);
251
443
  }
444
+ if (event.shiftKey) {
445
+ if (currentIndex <= 0)
446
+ FocusTrapController.focusCandidate(this._last);
447
+ else
448
+ FocusTrapController.focusCandidate(this._focusableElements[currentIndex - 1]);
449
+ }
450
+ else if (currentIndex === -1 || currentIndex >= this._focusableElements.length - 1)
451
+ FocusTrapController.focusCandidate(this._first);
452
+ else
453
+ FocusTrapController.focusCandidate(this._focusableElements[currentIndex + 1]);
252
454
  }
253
455
  _restoreFocus() {
254
- if (this._previousActiveElement && typeof this._previousActiveElement.focus === 'function') {
255
- this._previousActiveElement.focus();
256
- }
456
+ const target = this._previousActiveElement;
257
457
  this._previousActiveElement = null;
458
+ if (target && typeof target.focus === 'function' && document.contains(target)) {
459
+ // FIX Safari: blur the current element first so VoiceOver doesn't stay on the
460
+ // modal element while the accessibility tree processes the focus change.
461
+ FocusTrapController.getActiveElement()?.blur();
462
+ // FIX Safari/VoiceOver iOS: defer to the next macrotask so the accessibility
463
+ // tree has time to process the DOM mutation before announcing the restored element.
464
+ setTimeout(() => {
465
+ target.focus({ preventScroll: true });
466
+ }, 0);
467
+ }
258
468
  }
259
469
  }
260
470
  FocusTrapController.FOCUSABLE_SELECTORS = [
@@ -264,8 +474,25 @@ FocusTrapController.FOCUSABLE_SELECTORS = [
264
474
  'input:not([disabled]):not([type="hidden"])',
265
475
  'select:not([disabled])',
266
476
  '[tabindex]',
267
- // '[role="dialog"]',
268
- // Custom elements focusabili
269
477
  'it-button:not([disabled])',
478
+ 'it-dropdown:not([disabled])',
479
+ 'it-megamenu:not([disabled])',
480
+ ].join(',');
481
+ FocusTrapController.NATIVE_FOCUSABLE_SELECTORS = [
482
+ 'a[href]',
483
+ 'button:not([disabled])',
484
+ 'textarea:not([disabled])',
485
+ 'input:not([disabled]):not([type="hidden"])',
486
+ 'select:not([disabled])',
487
+ '[tabindex]:not([tabindex="-1"])',
488
+ ].join(',');
489
+ FocusTrapController.MANAGED_HOST_SELECTORS = [
490
+ 'it-button:not([disabled])',
491
+ 'it-dropdown:not([disabled])',
492
+ 'it-megamenu:not([disabled])',
493
+ ].join(',');
494
+ FocusTrapController.MANAGED_MENU_HOST_SELECTORS = [
495
+ 'it-dropdown:not([disabled])',
496
+ 'it-megamenu:not([disabled])',
270
497
  ].join(',');
271
498
  //# sourceMappingURL=focus-trap-controller.js.map