@italia/globals 0.1.0-alpha.1 → 1.0.0-alpha.10

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 (58) hide show
  1. package/custom-elements.json +2122 -179
  2. package/dist/src/base-component/base-component.d.ts +28 -13
  3. package/dist/src/base-component/base-component.d.ts.map +1 -1
  4. package/dist/src/base-component/base-component.js +27 -17
  5. package/dist/src/base-component/base-component.js.map +1 -1
  6. package/dist/src/controllers/aria-keyboard-accordion-controller.d.ts +15 -0
  7. package/dist/src/controllers/aria-keyboard-accordion-controller.d.ts.map +1 -0
  8. package/dist/src/controllers/aria-keyboard-accordion-controller.js +52 -0
  9. package/dist/src/controllers/aria-keyboard-accordion-controller.js.map +1 -0
  10. package/dist/src/controllers/aria-keyboard-list-controller.d.ts +18 -0
  11. package/dist/src/controllers/aria-keyboard-list-controller.d.ts.map +1 -0
  12. package/dist/src/controllers/aria-keyboard-list-controller.js +58 -0
  13. package/dist/src/controllers/aria-keyboard-list-controller.js.map +1 -0
  14. package/dist/src/controllers/collapse-controller.d.ts +12 -0
  15. package/dist/src/controllers/collapse-controller.d.ts.map +1 -0
  16. package/dist/src/controllers/collapse-controller.js +95 -0
  17. package/dist/src/controllers/collapse-controller.js.map +1 -0
  18. package/dist/src/controllers/focus-trap-controller.d.ts +92 -0
  19. package/dist/src/controllers/focus-trap-controller.d.ts.map +1 -0
  20. package/dist/src/controllers/focus-trap-controller.js +497 -0
  21. package/dist/src/controllers/focus-trap-controller.js.map +1 -0
  22. package/dist/src/controllers/roving-tabindex-controller.d.ts +92 -0
  23. package/dist/src/controllers/roving-tabindex-controller.d.ts.map +1 -0
  24. package/dist/src/controllers/roving-tabindex-controller.js +206 -0
  25. package/dist/src/controllers/roving-tabindex-controller.js.map +1 -0
  26. package/dist/src/form/form-control.d.ts +61 -0
  27. package/dist/src/form/form-control.d.ts.map +1 -0
  28. package/dist/src/form/form-control.js +259 -0
  29. package/dist/src/form/form-control.js.map +1 -0
  30. package/dist/src/form/form-controller.d.ts +68 -0
  31. package/dist/src/form/form-controller.d.ts.map +1 -0
  32. package/dist/src/form/form-controller.js +408 -0
  33. package/dist/src/form/form-controller.js.map +1 -0
  34. package/dist/src/form/locales/it.d.ts +4 -0
  35. package/dist/src/form/locales/it.d.ts.map +1 -0
  36. package/dist/src/form/locales/it.js +12 -0
  37. package/dist/src/form/locales/it.js.map +1 -0
  38. package/dist/src/index.d.ts +20 -4
  39. package/dist/src/index.d.ts.map +1 -1
  40. package/dist/src/index.js +18 -4
  41. package/dist/src/index.js.map +1 -1
  42. package/dist/src/mixins/validity.d.ts +19 -19
  43. package/dist/src/mixins/validity.d.ts.map +1 -1
  44. package/dist/src/mixins/validity.js +6 -68
  45. package/dist/src/mixins/validity.js.map +1 -1
  46. package/dist/src/stories/formControlReusableStories.d.ts +19 -0
  47. package/dist/src/stories/formControlReusableStories.d.ts.map +1 -0
  48. package/dist/src/stories/formControlReusableStories.js +64 -0
  49. package/dist/src/stories/formControlReusableStories.js.map +1 -0
  50. package/dist/src/window-manager.d.ts +33 -0
  51. package/dist/src/window-manager.d.ts.map +1 -0
  52. package/dist/src/window-manager.js +78 -0
  53. package/dist/src/window-manager.js.map +1 -0
  54. package/package.json +10 -8
  55. package/dist/src/mixins/form.d.ts +0 -363
  56. package/dist/src/mixins/form.d.ts.map +0 -1
  57. package/dist/src/mixins/form.js +0 -36
  58. package/dist/src/mixins/form.js.map +0 -1
@@ -0,0 +1,92 @@
1
+ import { ReactiveController, ReactiveControllerHost } from 'lit';
2
+ export interface FocusTrapConfig {
3
+ /** Funzione che ritorna l'elemento contenitore del trap */
4
+ getContainer: () => HTMLElement | ShadowRoot | null;
5
+ /** Funzione che ritorna l'elemento trigger che ha attivato il focus trap */
6
+ getTrigger: () => HTMLElement | ShadowRoot | null;
7
+ /** Opzionale: funzione che ritorna l'elemento da mettere a fuoco all'apertura (può essere tabindex -1) */
8
+ initialFocus?: () => HTMLElement | null;
9
+ /** Callback quando viene premuto Escape */
10
+ onEscape?: () => void;
11
+ /** Se true, non chiude con Escape */
12
+ disableEscape?: boolean;
13
+ }
14
+ /**
15
+ * Safari/VoiceOver iOS workarounds catalogue — why timers exist here:
16
+ *
17
+ * 1. `activate()` rAF + setTimeout(50): Safari does not reliably update the VoiceOver
18
+ * accessibility tree synchronously. rAF ensures the element is painted before we
19
+ * attempt to focus it. setTimeout(50) yields 50ms so VoiceOver can settle its
20
+ * accessibility tree before announcing the newly focused element.
21
+ * Empirically, VoiceOver iOS needs 100–300ms; the animated path in it-modal already
22
+ * provides ~316ms naturally via animation.finished, so the 50ms here only truly
23
+ * matters for the no-animation / prefers-reduced-motion path.
24
+ *
25
+ * 2. `_restoreFocus()` setTimeout(0): Same settle reason on close. The caller
26
+ * (it-modal finishHide) adds a belt-and-suspenders 20ms setTimeout; _restoreFocus
27
+ * is skipped via { skipFocusRestore: true } in that case to avoid double-focus.
28
+ *
29
+ * 3. `activate()` iOS body-focus fallback: On iOS Safari, tapping a button does not
30
+ * reliably move document.activeElement away from body. We fall back to getTrigger()
31
+ * so _previousActiveElement is always a real DOM element to restore focus to on close.
32
+ *
33
+ * There is no WebKit/Safari API to detect when VoiceOver has settled its accessibility
34
+ * tree. setTimeout-based workarounds are the same pattern used by Bootstrap 5, the
35
+ * focus-trap npm package, and a11y-dialog.
36
+ */
37
+ export declare class FocusTrapController implements ReactiveController {
38
+ private host;
39
+ private config;
40
+ private observer;
41
+ private _isActive;
42
+ private _previousActiveElement;
43
+ private _focusableElements;
44
+ private _first?;
45
+ private _last?;
46
+ /** Last known index resolved from real focusin events inside the trap.
47
+ * Used as a fallback when assistive tech retargeting makes activeElement
48
+ * temporarily unmappable during Tab navigation. */
49
+ private _lastKnownFocusIndex;
50
+ /** Timer ID for the focus call scheduled inside activate(). Cancelled by deactivate()
51
+ * to prevent focus firing after the trap has been torn down (fast open/close, unmount). */
52
+ private _pendingFocusTimer;
53
+ private static readonly FOCUSABLE_SELECTORS;
54
+ private static readonly NATIVE_FOCUSABLE_SELECTORS;
55
+ private static readonly MANAGED_HOST_SELECTORS;
56
+ private static readonly MANAGED_MENU_HOST_SELECTORS;
57
+ private static getManagedHostAncestor;
58
+ private static isInsideManagedHost;
59
+ private static getManagedMenuHostAncestor;
60
+ private static collectFocusableCandidates;
61
+ private static getFirstFocusableInShadow;
62
+ private static focusCandidate;
63
+ /**
64
+ * Verifica se un elemento è effettivamente focusabile e tabbabile.
65
+ * Elementi con tabindex="-1" sono focusabili programmaticamente ma non tabbabili.
66
+ */
67
+ private static isFocusable;
68
+ constructor(host: ReactiveControllerHost & HTMLElement, config: FocusTrapConfig);
69
+ hostConnected(): void;
70
+ hostDisconnected(): void;
71
+ get isActive(): boolean;
72
+ activate(): void;
73
+ deactivate(options?: {
74
+ skipFocusRestore?: boolean;
75
+ }): void;
76
+ /**
77
+ * Aggiorna la lista degli elementi focusabili.
78
+ * Chiamare dopo modifiche al DOM.
79
+ */
80
+ updateFocusableElements(): void;
81
+ /** Sposta il focus sul primo elemento focusabile */
82
+ focusFirst(): void;
83
+ /** Sposta il focus sull'ultimo elemento focusabile */
84
+ focusLast(): void;
85
+ /** Ritorna l'elemento attivo corrente, attraversando shadow DOM e slot */
86
+ static getActiveElement(): HTMLElement | null;
87
+ private _handleKeyDown;
88
+ private _handleFocusIn;
89
+ private _handleTab;
90
+ private _restoreFocus;
91
+ }
92
+ //# sourceMappingURL=focus-trap-controller.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focus-trap-controller.d.ts","sourceRoot":"","sources":["../../../src/controllers/focus-trap-controller.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,MAAM,KAAK,CAAC;AAEjE,MAAM,WAAW,eAAe;IAC9B,2DAA2D;IAC3D,YAAY,EAAE,MAAM,WAAW,GAAG,UAAU,GAAG,IAAI,CAAC;IACpD,4EAA4E;IAC5E,UAAU,EAAE,MAAM,WAAW,GAAG,UAAU,GAAG,IAAI,CAAC;IAClD,0GAA0G;IAC1G,YAAY,CAAC,EAAE,MAAM,WAAW,GAAG,IAAI,CAAC;IACxC,2CAA2C;IAC3C,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IACtB,qCAAqC;IACrC,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,mBAAoB,YAAW,kBAAkB;IAC5D,OAAO,CAAC,IAAI,CAAuC;IAEnD,OAAO,CAAC,MAAM,CAAkB;IAEhC,OAAO,CAAC,QAAQ,CAAiC;IAEjD,OAAO,CAAC,SAAS,CAAS;IAE1B,OAAO,CAAC,sBAAsB,CAA4B;IAE1D,OAAO,CAAC,kBAAkB,CAAqB;IAE/C,OAAO,CAAC,MAAM,CAAC,CAAc;IAE7B,OAAO,CAAC,KAAK,CAAC,CAAc;IAE5B;;wDAEoD;IACpD,OAAO,CAAC,oBAAoB,CAAM;IAElC;gGAC4F;IAC5F,OAAO,CAAC,kBAAkB,CAA8C;IAExE,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,mBAAmB,CAU/B;IAEZ,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,0BAA0B,CAOtC;IAEZ,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,sBAAsB,CAIlC;IAEZ,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,2BAA2B,CAGvC;IAEZ,OAAO,CAAC,MAAM,CAAC,sBAAsB;IA4BrC,OAAO,CAAC,MAAM,CAAC,mBAAmB;IAIlC,OAAO,CAAC,MAAM,CAAC,0BAA0B;IA4BzC,OAAO,CAAC,MAAM,CAAC,0BAA0B;IAqDzC,OAAO,CAAC,MAAM,CAAC,yBAAyB;IA2CxC,OAAO,CAAC,MAAM,CAAC,cAAc;IAc7B;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,WAAW;gBAoBd,IAAI,EAAE,sBAAsB,GAAG,WAAW,EAAE,MAAM,EAAE,eAAe;IAM/E,aAAa;IAMb,gBAAgB;IAQhB,IAAI,QAAQ,IAAI,OAAO,CAEtB;IAED,QAAQ,IAAI,IAAI;IAkChB,UAAU,CAAC,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI;IAmB1D;;;OAGG;IACH,uBAAuB,IAAI,IAAI;IA2C/B,oDAAoD;IACpD,UAAU,IAAI,IAAI;IAIlB,sDAAsD;IACtD,SAAS,IAAI,IAAI;IAMjB,0EAA0E;IAC1E,MAAM,CAAC,gBAAgB,IAAI,WAAW,GAAG,IAAI;IAQ7C,OAAO,CAAC,cAAc,CAepB;IAEF,OAAO,CAAC,cAAc,CA4BpB;IAEF,OAAO,CAAC,UAAU;IAuElB,OAAO,CAAC,aAAa;CActB"}
@@ -0,0 +1,497 @@
1
+ /**
2
+ * Safari/VoiceOver iOS workarounds catalogue — why timers exist here:
3
+ *
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.
23
+ */
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
+ }
177
+ /**
178
+ * Verifica se un elemento è effettivamente focusabile e tabbabile.
179
+ * Elementi con tabindex="-1" sono focusabili programmaticamente ma non tabbabili.
180
+ */
181
+ static isFocusable(el) {
182
+ if (typeof el.focus !== 'function')
183
+ return false;
184
+ if (el.hasAttribute('disabled') || el.hasAttribute('inert') || el.hasAttribute('it-inert'))
185
+ return false;
186
+ const tabindex = el.getAttribute('tabindex');
187
+ if (tabindex && parseInt(tabindex, 10) < 0)
188
+ return false;
189
+ if (el.tagName.toLowerCase().startsWith('it-')) {
190
+ if (tabindex && parseInt(tabindex, 10) < 0)
191
+ return false;
192
+ return true;
193
+ }
194
+ // Fix Race Condition Safari: durante l'apertura non fidarti di getClientRects o opacità
195
+ try {
196
+ const style = window.getComputedStyle(el);
197
+ return style && style.display !== 'none' && style.visibility !== 'hidden';
198
+ }
199
+ catch {
200
+ return false;
201
+ }
202
+ }
203
+ constructor(host, config) {
204
+ this.observer = null;
205
+ this._isActive = false;
206
+ this._previousActiveElement = null;
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;
215
+ this._handleKeyDown = (event) => {
216
+ if (!this._isActive)
217
+ return;
218
+ switch (event.key) {
219
+ case 'Escape':
220
+ if (!this.config.disableEscape && this.config.onEscape) {
221
+ event.preventDefault();
222
+ this.config.onEscape();
223
+ }
224
+ break;
225
+ case 'Tab':
226
+ this._handleTab(event);
227
+ break;
228
+ default:
229
+ break;
230
+ }
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
+ };
258
+ this.host = host;
259
+ this.config = config;
260
+ this.host.addController(this);
261
+ }
262
+ hostConnected() {
263
+ const observerOptions = { childList: true, attributes: true, subtree: true };
264
+ this.observer = new MutationObserver(this.updateFocusableElements.bind(this));
265
+ this.observer.observe(this.host, observerOptions);
266
+ }
267
+ hostDisconnected() {
268
+ this.deactivate();
269
+ if (this.observer) {
270
+ this.observer.disconnect();
271
+ this.observer = null;
272
+ }
273
+ }
274
+ get isActive() {
275
+ return this._isActive;
276
+ }
277
+ activate() {
278
+ if (this._isActive)
279
+ return;
280
+ this._isActive = true;
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);
289
+ this.updateFocusableElements();
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
+ console.warn("FocusTrap: missing 'initialFocus' callback, provide one");
307
+ }
308
+ });
309
+ }
310
+ deactivate(options) {
311
+ if (!this._isActive)
312
+ return;
313
+ // Cancel any in-flight focus timer so it cannot fire after the trap is torn down
314
+ // (e.g. fast open/close cycle, component unmounted while opening).
315
+ if (this._pendingFocusTimer !== null) {
316
+ clearTimeout(this._pendingFocusTimer);
317
+ this._pendingFocusTimer = null;
318
+ }
319
+ this._isActive = false;
320
+ document.removeEventListener('keydown', this._handleKeyDown, true);
321
+ document.removeEventListener('focusin', this._handleFocusIn, true);
322
+ this._lastKnownFocusIndex = -1;
323
+ if (!options?.skipFocusRestore) {
324
+ this._restoreFocus();
325
+ }
326
+ else {
327
+ this._previousActiveElement = null;
328
+ }
329
+ }
330
+ /**
331
+ * Aggiorna la lista degli elementi focusabili.
332
+ * Chiamare dopo modifiche al DOM.
333
+ */
334
+ updateFocusableElements() {
335
+ const container = this.config.getContainer();
336
+ const trigger = this.config.getTrigger();
337
+ if (!container) {
338
+ this._focusableElements = [];
339
+ this._first = undefined;
340
+ this._last = undefined;
341
+ return;
342
+ }
343
+ const candidates = [];
344
+ FocusTrapController.collectFocusableCandidates(container, candidates, trigger, new Set());
345
+ // Include anche i figli light DOM dell'host (es. contenuti slottati della modale)
346
+ Array.from(this.host.children).forEach((child) => {
347
+ if (!(child instanceof HTMLElement) || child === trigger)
348
+ return;
349
+ if (child.matches(FocusTrapController.FOCUSABLE_SELECTORS)) {
350
+ candidates.push(child);
351
+ // Don't recurse: same stop-on-focusable rule.
352
+ return;
353
+ }
354
+ const childVisited = new Set();
355
+ FocusTrapController.collectFocusableCandidates(child, candidates, trigger, childVisited);
356
+ if (child.shadowRoot) {
357
+ FocusTrapController.collectFocusableCandidates(child.shadowRoot, candidates, trigger, childVisited);
358
+ }
359
+ });
360
+ // Filtra solo elementi veramente focusabili e rimuovi duplicati
361
+ this._focusableElements = Array.from(new Set(candidates)).filter((el) => {
362
+ // Escludi esplicitamente il container/dialog stesso
363
+ if (el === this.config.getContainer())
364
+ return false;
365
+ return FocusTrapController.isFocusable(el);
366
+ });
367
+ // Aggiorna primo/ultimo
368
+ this._first = this._focusableElements?.[0];
369
+ this._last = this._focusableElements[this._focusableElements.length - 1];
370
+ }
371
+ /** Sposta il focus sul primo elemento focusabile */
372
+ focusFirst() {
373
+ if (this._first)
374
+ this._first.focus();
375
+ }
376
+ /** Sposta il focus sull'ultimo elemento focusabile */
377
+ focusLast() {
378
+ if (this._last) {
379
+ this._last.focus();
380
+ }
381
+ }
382
+ /** Ritorna l'elemento attivo corrente, attraversando shadow DOM e slot */
383
+ static getActiveElement() {
384
+ let active = document.activeElement;
385
+ while (active && active.shadowRoot && active.shadowRoot.activeElement) {
386
+ active = active.shadowRoot.activeElement;
387
+ }
388
+ return active;
389
+ }
390
+ _handleTab(event) {
391
+ const activeElement = FocusTrapController.getActiveElement();
392
+ // Let native Tab behavior handle navigation inside open dropdown/megamenu.
393
+ // This allows entering and traversing internal menu items correctly.
394
+ if (activeElement) {
395
+ const managedHost = FocusTrapController.getManagedMenuHostAncestor(activeElement);
396
+ if (managedHost && managedHost.getAttribute('data-it-aria-expanded') === 'true') {
397
+ return;
398
+ }
399
+ }
400
+ // Ricalcola sempre al Tab: gli elementi slottati possono completare il render
401
+ // del proprio shadow DOM dopo l'attivazione iniziale del trap.
402
+ this.updateFocusableElements();
403
+ if (this._focusableElements.length === 0)
404
+ return; // Se è ancora vuoto, non bloccare il Tab
405
+ event.preventDefault();
406
+ let currentIndex = this._focusableElements.indexOf(activeElement);
407
+ if (currentIndex === -1 && activeElement) {
408
+ // 1. Walk shadow host chain (covers delegatesFocus custom elements)
409
+ let parent = activeElement.getRootNode()?.host;
410
+ while (parent && currentIndex === -1) {
411
+ currentIndex = this._focusableElements.indexOf(parent);
412
+ if (currentIndex === -1)
413
+ parent = parent.getRootNode()?.host;
414
+ }
415
+ }
416
+ if (currentIndex === -1) {
417
+ // 2. Composed path fallback: handles focus inside nested shadow/slotted
418
+ // content (e.g. anchors inside it-dropdown-item) by mapping the active
419
+ // target to the first focusable host found in the event path.
420
+ const composedPath = event.composedPath();
421
+ currentIndex = this._focusableElements.findIndex((candidate) => composedPath.includes(candidate));
422
+ }
423
+ if (currentIndex === -1 && activeElement) {
424
+ // 3. contains() fallback: handles focus inside an open dropdown/megamenu whose
425
+ // items live in light DOM (not shadow DOM), so the parent-walk above doesn't
426
+ // reach the host. Map to the host's index so Tab/Shift+Tab move to the
427
+ // correct adjacent element.
428
+ currentIndex = this._focusableElements.findIndex((candidate) => candidate.contains(activeElement));
429
+ }
430
+ if (currentIndex === -1) {
431
+ // 4. AT fallback: with some screen readers, document.activeElement and/or
432
+ // event target can be unreliable while navigating inside composite widgets.
433
+ // If a dropdown/megamenu is currently open, use its host index as anchor
434
+ // so forward/backward Tab continue from that position instead of wrapping.
435
+ currentIndex = this._focusableElements.findIndex((candidate) => candidate.matches('it-dropdown, it-megamenu') && candidate.getAttribute('data-it-aria-expanded') === 'true');
436
+ }
437
+ if (currentIndex === -1 && this._lastKnownFocusIndex >= 0) {
438
+ // 5. Last-known fallback: if assistive tech retargeting hides the active
439
+ // element for this key event, continue from the most recent resolved
440
+ // focus index captured via focusin.
441
+ currentIndex = Math.min(this._lastKnownFocusIndex, this._focusableElements.length - 1);
442
+ }
443
+ if (event.shiftKey) {
444
+ if (currentIndex <= 0)
445
+ FocusTrapController.focusCandidate(this._last);
446
+ else
447
+ FocusTrapController.focusCandidate(this._focusableElements[currentIndex - 1]);
448
+ }
449
+ else if (currentIndex === -1 || currentIndex >= this._focusableElements.length - 1)
450
+ FocusTrapController.focusCandidate(this._first);
451
+ else
452
+ FocusTrapController.focusCandidate(this._focusableElements[currentIndex + 1]);
453
+ }
454
+ _restoreFocus() {
455
+ const target = this._previousActiveElement;
456
+ this._previousActiveElement = null;
457
+ if (target && typeof target.focus === 'function' && document.contains(target)) {
458
+ // FIX Safari: blur the current element first so VoiceOver doesn't stay on the
459
+ // modal element while the accessibility tree processes the focus change.
460
+ FocusTrapController.getActiveElement()?.blur();
461
+ // FIX Safari/VoiceOver iOS: defer to the next macrotask so the accessibility
462
+ // tree has time to process the DOM mutation before announcing the restored element.
463
+ setTimeout(() => {
464
+ target.focus({ preventScroll: true });
465
+ }, 0);
466
+ }
467
+ }
468
+ }
469
+ FocusTrapController.FOCUSABLE_SELECTORS = [
470
+ 'a[href]',
471
+ 'button:not([disabled])',
472
+ 'textarea:not([disabled])',
473
+ 'input:not([disabled]):not([type="hidden"])',
474
+ 'select:not([disabled])',
475
+ '[tabindex]',
476
+ 'it-button:not([disabled])',
477
+ 'it-dropdown:not([disabled])',
478
+ 'it-megamenu:not([disabled])',
479
+ ].join(',');
480
+ FocusTrapController.NATIVE_FOCUSABLE_SELECTORS = [
481
+ 'a[href]',
482
+ 'button:not([disabled])',
483
+ 'textarea:not([disabled])',
484
+ 'input:not([disabled]):not([type="hidden"])',
485
+ 'select:not([disabled])',
486
+ '[tabindex]:not([tabindex="-1"])',
487
+ ].join(',');
488
+ FocusTrapController.MANAGED_HOST_SELECTORS = [
489
+ 'it-button:not([disabled])',
490
+ 'it-dropdown:not([disabled])',
491
+ 'it-megamenu:not([disabled])',
492
+ ].join(',');
493
+ FocusTrapController.MANAGED_MENU_HOST_SELECTORS = [
494
+ 'it-dropdown:not([disabled])',
495
+ 'it-megamenu:not([disabled])',
496
+ ].join(',');
497
+ //# sourceMappingURL=focus-trap-controller.js.map