@italia/modal 1.0.0-alpha.8 → 1.0.0-alpha.9

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.
@@ -415,11 +415,27 @@ class BaseComponent extends LitElement {
415
415
  const BaseLocalizedComponent = LocalizeMixin(BaseComponent);
416
416
 
417
417
  /**
418
- * Controller per gestire il focus trap all'interno di un elemento.
419
- * Implementa le linee guida WAI-ARIA per i dialog modali.
418
+ * Safari/VoiceOver iOS workarounds catalogue — why timers exist here:
420
419
  *
421
-
422
- * ```
420
+ * 1. `activate()` rAF + setTimeout(50): Safari does not reliably update the VoiceOver
421
+ * accessibility tree synchronously. rAF ensures the element is painted before we
422
+ * attempt to focus it. setTimeout(50) yields 50ms so VoiceOver can settle its
423
+ * accessibility tree before announcing the newly focused element.
424
+ * Empirically, VoiceOver iOS needs 100–300ms; the animated path in it-modal already
425
+ * provides ~316ms naturally via animation.finished, so the 50ms here only truly
426
+ * matters for the no-animation / prefers-reduced-motion path.
427
+ *
428
+ * 2. `_restoreFocus()` setTimeout(0): Same settle reason on close. The caller
429
+ * (it-modal finishHide) adds a belt-and-suspenders 20ms setTimeout; _restoreFocus
430
+ * is skipped via { skipFocusRestore: true } in that case to avoid double-focus.
431
+ *
432
+ * 3. `activate()` iOS body-focus fallback: On iOS Safari, tapping a button does not
433
+ * reliably move document.activeElement away from body. We fall back to getTrigger()
434
+ * so _previousActiveElement is always a real DOM element to restore focus to on close.
435
+ *
436
+ * There is no WebKit/Safari API to detect when VoiceOver has settled its accessibility
437
+ * tree. setTimeout-based workarounds are the same pattern used by Bootstrap 5, the
438
+ * focus-trap npm package, and a11y-dialog.
423
439
  */
424
440
  class FocusTrapController {
425
441
  /**
@@ -429,39 +445,22 @@ class FocusTrapController {
429
445
  static isFocusable(el) {
430
446
  if (typeof el.focus !== 'function')
431
447
  return false;
432
- // Escludi elementi disabilitati
433
- if (el.hasAttribute('disabled'))
448
+ if (el.hasAttribute('disabled') || el.hasAttribute('inert') || el.hasAttribute('it-inert'))
434
449
  return false;
435
- // Escludi elementi con tabindex negativo (focusabili programmaticamente ma non tabbabili)
436
450
  const tabindex = el.getAttribute('tabindex');
437
- if (tabindex && parseInt(tabindex, 10) < 0) {
451
+ if (tabindex && parseInt(tabindex, 10) < 0)
438
452
  return false;
439
- }
440
- // Per custom elements (it-*), controlla anche il loro tabindex
441
453
  if (el.tagName.toLowerCase().startsWith('it-')) {
442
- // Se ha tabindex esplicito negativo, non è tabbabile
443
- if (tabindex && parseInt(tabindex, 10) < 0) {
454
+ if (tabindex && parseInt(tabindex, 10) < 0)
444
455
  return false;
445
- }
446
456
  return true;
447
457
  }
448
- // Per elementi standard, controlliamo anche visibilità in modo robusto.
449
- // Alcuni elementi (es. inline anchors, elementi dentro container positionati) possono
450
- // avere offsetParent === null pur essendo visibili/focusabili. Usiamo quindi getClientRects
451
- // e computedStyle come controllo più affidabile.
458
+ // Fix Race Condition Safari: durante l'apertura non fidarti di getClientRects o opacità
452
459
  try {
453
- // Se non ci sono bounding rects, probabilmente non è visibile
454
- if (el.getClientRects()?.length === 0)
455
- return false;
456
460
  const style = window.getComputedStyle(el);
457
- if (!style)
458
- return false;
459
- if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0')
460
- return false;
461
- // Altrimenti consideriamo l'elemento focusabile
462
- return true;
461
+ return style && style.display !== 'none' && style.visibility !== 'hidden';
463
462
  }
464
- catch (e) {
463
+ catch {
465
464
  return false;
466
465
  }
467
466
  }
@@ -470,6 +469,9 @@ class FocusTrapController {
470
469
  this._isActive = false;
471
470
  this._previousActiveElement = null;
472
471
  this._focusableElements = [];
472
+ /** Timer ID for the focus call scheduled inside activate(). Cancelled by deactivate()
473
+ * to prevent focus firing after the trap has been torn down (fast open/close, unmount). */
474
+ this._pendingFocusTimer = null;
473
475
  this._handleKeyDown = (event) => {
474
476
  if (!this._isActive)
475
477
  return;
@@ -489,15 +491,8 @@ class FocusTrapController {
489
491
  this.config = config;
490
492
  this.host.addController(this);
491
493
  }
492
- // eslint-disable-next-line class-methods-use-this
493
494
  hostConnected() {
494
- // Controller ready
495
- // Set up our MutationObserver
496
- const observerOptions = {
497
- childList: true,
498
- attributes: true,
499
- subtree: true,
500
- };
495
+ const observerOptions = { childList: true, attributes: true, subtree: true };
501
496
  this.observer = new MutationObserver(this.updateFocusableElements.bind(this));
502
497
  this.observer.observe(this.host, observerOptions);
503
498
  }
@@ -508,37 +503,57 @@ class FocusTrapController {
508
503
  this.observer = null;
509
504
  }
510
505
  }
511
- /** Indica se il focus trap è attivo */
512
506
  get isActive() {
513
507
  return this._isActive;
514
508
  }
515
- /**
516
- * Attiva il focus trap.
517
- * Salva l'elemento attivo corrente e attiva i listener.
518
- * NOTA: chiamare updateFocusableElements() e focusFirst() separatamente quando necessario.
519
- */
520
509
  activate() {
521
510
  if (this._isActive)
522
511
  return;
523
512
  this._isActive = true;
524
- this._previousActiveElement = FocusTrapController.getActiveElement();
525
- this.host.addEventListener('keydown', this._handleKeyDown);
513
+ // FIX iOS: Safari non dà focus al tap. Se activeElement è body, salviamo il trigger della config.
514
+ const currentActive = FocusTrapController.getActiveElement();
515
+ this._previousActiveElement =
516
+ !currentActive || currentActive === document.body ? this.config.getTrigger() : currentActive;
517
+ // Usa document capture: cattura Tab/Escape prima di qualsiasi handler,
518
+ // indipendentemente da shadow DOM, delegatesFocus e slot retargeting.
519
+ document.addEventListener('keydown', this._handleKeyDown, true);
526
520
  this.updateFocusableElements();
527
- if (typeof this.focusInitial === 'function')
528
- this.focusInitial();
529
- else
530
- this.focusFirst();
521
+ // FIX Safari: trick engine
522
+ // Diamo al browser un istante per processare il ricalcolo del layout
523
+ requestAnimationFrame(() => {
524
+ if (this.config.initialFocus) {
525
+ const el = this.config.initialFocus();
526
+ if (el) {
527
+ // 50ms gives VoiceOver iOS time to settle its accessibility tree before
528
+ // announcing the focused element. See class-level comment for details.
529
+ this._pendingFocusTimer = setTimeout(() => {
530
+ this._pendingFocusTimer = null;
531
+ el.focus({ preventScroll: true });
532
+ }, 50);
533
+ }
534
+ }
535
+ else {
536
+ console.warn("FocusTrap: missing 'initialFocus' callback, provide one");
537
+ }
538
+ });
531
539
  }
532
- /**
533
- * Disattiva il focus trap.
534
- * Ripristina il focus all'elemento precedentemente attivo.
535
- */
536
- deactivate() {
540
+ deactivate(options) {
537
541
  if (!this._isActive)
538
542
  return;
543
+ // Cancel any in-flight focus timer so it cannot fire after the trap is torn down
544
+ // (e.g. fast open/close cycle, component unmounted while opening).
545
+ if (this._pendingFocusTimer !== null) {
546
+ clearTimeout(this._pendingFocusTimer);
547
+ this._pendingFocusTimer = null;
548
+ }
539
549
  this._isActive = false;
540
- this.host.removeEventListener('keydown', this._handleKeyDown);
541
- this._restoreFocus();
550
+ document.removeEventListener('keydown', this._handleKeyDown, true);
551
+ if (!options?.skipFocusRestore) {
552
+ this._restoreFocus();
553
+ }
554
+ else {
555
+ this._previousActiveElement = null;
556
+ }
542
557
  }
543
558
  /**
544
559
  * Aggiorna la lista degli elementi focusabili.
@@ -554,7 +569,6 @@ class FocusTrapController {
554
569
  return;
555
570
  }
556
571
  const candidates = [];
557
- // Tutti gli elementi focusable direttamente nel container
558
572
  const direct = Array.from(container.querySelectorAll(FocusTrapController.FOCUSABLE_SELECTORS));
559
573
  candidates.push(...direct);
560
574
  // Tutti gli elementi slottati
@@ -563,14 +577,10 @@ class FocusTrapController {
563
577
  slot.assignedElements({ flatten: true }).forEach((el) => {
564
578
  if (!(el instanceof HTMLElement))
565
579
  return;
566
- if (el === trigger) {
580
+ if (el === trigger)
567
581
  return;
568
- }
569
- // focusable diretto
570
- if (el.matches(FocusTrapController.FOCUSABLE_SELECTORS)) {
582
+ if (el.matches(FocusTrapController.FOCUSABLE_SELECTORS))
571
583
  candidates.push(el);
572
- }
573
- // nested focusable dentro l'elemento assegnato
574
584
  Array.from(el.querySelectorAll(FocusTrapController.FOCUSABLE_SELECTORS)).forEach((nested) => candidates.push(nested));
575
585
  });
576
586
  });
@@ -587,9 +597,8 @@ class FocusTrapController {
587
597
  }
588
598
  /** Sposta il focus sul primo elemento focusabile */
589
599
  focusFirst() {
590
- if (this._first) {
600
+ if (this._first)
591
601
  this._first.focus();
592
- }
593
602
  }
594
603
  /** Sposta il focus sull'ultimo elemento focusabile */
595
604
  focusLast() {
@@ -605,70 +614,47 @@ class FocusTrapController {
605
614
  }
606
615
  return active;
607
616
  }
608
- /**
609
- * Metti a fuoco l'elemento iniziale specificato nella config, se presente.
610
- * Se non è fornito, fallback sul primo elemento tabbabile.
611
- */
612
- focusInitial() {
613
- if (this.config.initialFocus) {
614
- const el = this.config.initialFocus();
615
- if (el && typeof el.focus === 'function') {
616
- el.focus();
617
- return;
618
- }
619
- }
620
- this.focusFirst();
621
- }
622
617
  _handleTab(event) {
623
- if (this._focusableElements.length === 0) {
624
- event.preventDefault();
625
- return;
626
- }
627
- // SEMPRE previeni il default - gestiamo noi la navigazione
618
+ // ANTI RACE CONDITION: se l'utente è troppo veloce, forza un ricalcolo immediato
619
+ if (this._focusableElements.length === 0)
620
+ this.updateFocusableElements();
621
+ if (this._focusableElements.length === 0)
622
+ return; // Se è ancora vuoto, non bloccare il Tab
628
623
  event.preventDefault();
629
- const firstElement = this._first;
630
- const lastElement = this._last;
631
624
  const activeElement = FocusTrapController.getActiveElement();
632
- // Trova l'indice dell'elemento attivo
633
- // Se activeElement è dentro uno shadow DOM di un custom element,
634
- // cerca il custom element host nella lista
635
625
  let currentIndex = this._focusableElements.indexOf(activeElement);
636
- // Se non trovato, potrebbe essere un elemento interno ad un custom element
637
626
  if (currentIndex === -1 && activeElement) {
638
- // Risali attraverso gli shadow host
639
627
  let parent = activeElement.getRootNode()?.host;
640
628
  while (parent && currentIndex === -1) {
641
629
  currentIndex = this._focusableElements.indexOf(parent);
642
- if (currentIndex === -1) {
630
+ if (currentIndex === -1)
643
631
  parent = parent.getRootNode()?.host;
644
- }
645
632
  }
646
633
  }
647
634
  if (event.shiftKey) {
648
- // Shift + Tab: vai al precedente
649
- if (currentIndex <= 0) {
650
- // Se sei sul primo o non sei nella lista, vai all'ultimo
651
- lastElement?.focus();
652
- }
653
- else {
654
- // Vai al precedente
635
+ if (currentIndex <= 0)
636
+ this._last?.focus();
637
+ else
655
638
  this._focusableElements[currentIndex - 1]?.focus();
656
- }
657
- }
658
- else if (currentIndex === -1 || currentIndex >= this._focusableElements.length - 1) {
659
- // Tab: se non sei nella lista o sei sull'ultimo, vai al primo
660
- firstElement?.focus();
661
639
  }
662
- else {
663
- // Vai al successivo
640
+ else if (currentIndex === -1 || currentIndex >= this._focusableElements.length - 1)
641
+ this._first?.focus();
642
+ else
664
643
  this._focusableElements[currentIndex + 1]?.focus();
665
- }
666
644
  }
667
645
  _restoreFocus() {
668
- if (this._previousActiveElement && typeof this._previousActiveElement.focus === 'function') {
669
- this._previousActiveElement.focus();
670
- }
646
+ const target = this._previousActiveElement;
671
647
  this._previousActiveElement = null;
648
+ if (target && typeof target.focus === 'function' && document.contains(target)) {
649
+ // FIX Safari: blur the current element first so VoiceOver doesn't stay on the
650
+ // modal element while the accessibility tree processes the focus change.
651
+ FocusTrapController.getActiveElement()?.blur();
652
+ // FIX Safari/VoiceOver iOS: defer to the next macrotask so the accessibility
653
+ // tree has time to process the DOM mutation before announcing the restored element.
654
+ setTimeout(() => {
655
+ target.focus({ preventScroll: true });
656
+ }, 0);
657
+ }
672
658
  }
673
659
  }
674
660
  FocusTrapController.FOCUSABLE_SELECTORS = [
@@ -678,8 +664,6 @@ FocusTrapController.FOCUSABLE_SELECTORS = [
678
664
  'input:not([disabled]):not([type="hidden"])',
679
665
  'select:not([disabled])',
680
666
  '[tabindex]',
681
- // '[role="dialog"]',
682
- // Custom elements focusabili
683
667
  'it-button:not([disabled])',
684
668
  ].join(',');
685
669
 
@@ -742,6 +726,14 @@ class FormControlController {
742
726
  case 'it-toggle-group':
743
727
  // non settare valori in formData, perchè ogni singola checkbox setta il suo valore
744
728
  break;
729
+ case 'it-upload':
730
+ // value is File[] — append each File object directly (not as string)
731
+ if (Array.isArray(value)) {
732
+ value.forEach((file) => {
733
+ event.formData.append(name, file);
734
+ });
735
+ }
736
+ break;
745
737
  default:
746
738
  if (Array.isArray(value)) {
747
739
  value.forEach((val) => {
@@ -1429,7 +1421,7 @@ if (typeof window !== 'undefined') {
1429
1421
  window._itAnalytics = window._itAnalytics || {};
1430
1422
  window._itAnalytics = {
1431
1423
  ...window._itAnalytics,
1432
- version: '1.0.0-alpha.8',
1424
+ version: '1.0.0-alpha.9',
1433
1425
  };
1434
1426
  }
1435
1427
 
@@ -2073,7 +2065,7 @@ h6,
2073
2065
  .h6 {
2074
2066
  margin-top: 0;
2075
2067
  margin-bottom: var(--bsi-heading-spacing);
2076
- line-height: var(--bsi-heading-line-height);
2068
+ line-height: var(--bsi-heading-leading);
2077
2069
  }
2078
2070
  :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + h1, p + h1,
2079
2071
  :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + .h1,
@@ -2140,13 +2132,13 @@ h1,
2140
2132
  .display-1 {
2141
2133
  font-size: var(--bsi-display-font-size);
2142
2134
  font-weight: var(--bsi-heading-font-weight);
2143
- line-height: var(--bsi-heading-line-height);
2135
+ line-height: var(--bsi-heading-leading);
2144
2136
  }
2145
2137
 
2146
2138
  .lead {
2147
2139
  font-size: var(--bsi-lead-font-size);
2148
2140
  font-weight: var(--bsi-lead-font-weight);
2149
- line-height: var(--bsi-lead-line-height);
2141
+ line-height: var(--bsi-lead-leading);
2150
2142
  }
2151
2143
 
2152
2144
  blockquote,
@@ -2243,6 +2235,24 @@ blockquote.blockquote-card.dark .blockquote-footer,
2243
2235
 
2244
2236
  :host {
2245
2237
  display: block;
2238
+ --it-focus-ring-safari-fix: none;
2239
+ }
2240
+
2241
+ /* Rimuovi il flash visivo solo durante l'apertura programmata */
2242
+ [part=modal]:focus {
2243
+ box-shadow: var(--it-focus-ring-safari-fix) !important;
2244
+ outline: var(--it-focus-ring-safari-fix) !important;
2245
+ }
2246
+
2247
+ [role=dialog]:focus,
2248
+ [role=dialog]:focus-visible,
2249
+ .btn-close:focus:not(:focus-visible) {
2250
+ box-shadow: none !important;
2251
+ outline: 0 !important;
2252
+ }
2253
+
2254
+ .btn-close:focus-visible {
2255
+ outline: 2px solid var(--it-focus-color) !important;
2246
2256
  }
2247
2257
 
2248
2258
  :host(:not([open])) .modal,
@@ -2311,34 +2321,15 @@ blockquote.blockquote-card.dark .blockquote-footer,
2311
2321
  right: 0;
2312
2322
  }`;
2313
2323
 
2314
- /**
2315
- * Componente Modal per finestre di dialogo modali.
2316
- *
2317
- * @element it-modal
2318
- *
2319
- * @slot trigger - Elemento che apre la modale (es. it-button)
2320
- * @slot content - Contenuto principale della modale (body)
2321
- * @slot header-icon - Icona opzionale nell'header
2322
- * @slot footer - Azioni del footer (pulsanti)
2323
- *
2324
- * @fires it-modal-open - Quando la modale si apre
2325
- * @fires it-modal-close - Quando la modale si chiude
2326
- */
2324
+ const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
2327
2325
  let ItModal = class ItModal extends BaseComponent {
2328
2326
  get _triggerElement() {
2329
- if (!this._triggerSlot) {
2330
- this.logger.error('No trigger provided');
2331
- return null;
2332
- }
2333
- const elements = this._triggerSlot.assignedElements({ flatten: true });
2334
- if (elements.length === 0) {
2335
- return null;
2336
- }
2337
- return elements[0];
2327
+ const elements = this._triggerSlot?.assignedElements({ flatten: true });
2328
+ return elements?.[0] || null;
2338
2329
  }
2339
2330
  constructor() {
2340
2331
  super();
2341
- this.open = false;
2332
+ this.open = undefined;
2342
2333
  this.modalTitle = '';
2343
2334
  this.modalDescription = '';
2344
2335
  this.size = '';
@@ -2353,53 +2344,74 @@ let ItModal = class ItModal extends BaseComponent {
2353
2344
  this._triggerId = '';
2354
2345
  this._descriptionId = '';
2355
2346
  this.isAnimating = false;
2356
- this._dialogAnimationDuration = 300; // ms - matches Bootstrap Italia modal-transition
2357
- this._backdropAnimationDuration = 150; // ms - standard fade
2358
- this._focusTrap = new FocusTrapController(this, {
2359
- getContainer: () => this._modalElement,
2360
- initialFocus: () => this._modalElement,
2361
- getTrigger: () => this._triggerElement,
2362
- onEscape: () => {
2347
+ this._isSelfClosing = false;
2348
+ this._originalTrigger = null;
2349
+ this._safariMouseInteraction = false;
2350
+ this._dialogAnimationDuration = 300;
2351
+ this._backdropAnimationDuration = 150;
2352
+ this._inertElements = [];
2353
+ this._triggerPointerBefore = null;
2354
+ /** Timer ID for the focus-restore call in finishHide. Cancelled on reconnect/unmount
2355
+ * to prevent a stale focus from a previous close cycle firing during a new open. */
2356
+ this._restoreFocusTimer = null;
2357
+ // eslint-disable-next-line class-methods-use-this
2358
+ this._handleDialogClick = (event) => {
2359
+ const path = event.composedPath();
2360
+ // Check that is not footer or react synthetic events break on buttons
2361
+ const isInFooter = path.some((el) => el instanceof HTMLElement && el.slot === 'footer');
2362
+ if (!isInFooter) {
2363
+ event.stopPropagation(); // solo per backdrop
2364
+ }
2365
+ };
2366
+ this._handleBackdropClick = () => {
2367
+ if (!this.staticBackdrop) {
2363
2368
  this.hide();
2364
- },
2365
- disableEscape: false,
2366
- });
2369
+ }
2370
+ };
2367
2371
  this._onTriggerSlotChange = () => {
2368
2372
  this._setupTriggerListeners();
2369
2373
  };
2370
2374
  this._onHeaderSlotChange = () => {
2371
2375
  this.requestUpdate();
2372
2376
  };
2373
- this._onTriggerClick = (event) => {
2377
+ this._onTriggerClick = async (event) => {
2374
2378
  event.stopPropagation();
2379
+ const trigger = this._triggerElement;
2380
+ if (!trigger)
2381
+ return;
2382
+ if (isSafari) {
2383
+ this._safariMouseInteraction = true;
2384
+ }
2385
+ await this.updateComplete; // Assicurati che l'update sia completo prima di applicare il focus workaround
2375
2386
  this.show();
2376
2387
  };
2377
- this._onTriggerKeydown = (event) => {
2388
+ this._onTriggerKeydown = async (event) => {
2378
2389
  if (event.key === 'Enter' || event.key === ' ') {
2379
2390
  event.preventDefault();
2380
2391
  this.show();
2381
2392
  }
2382
- };
2383
- this._handleCloseClick = () => {
2384
- this.hide();
2385
- };
2386
- this._handleBackdropClick = () => {
2387
- if (!this.staticBackdrop) {
2388
- this.hide();
2389
- }
2390
- };
2391
- // eslint-disable-next-line class-methods-use-this
2392
- this._handleDialogClick = (event) => {
2393
- const path = event.composedPath();
2394
- // Check that is not footer or react synthetic events break on buttons
2395
- const isInFooter = path.some((el) => el instanceof HTMLElement && el.slot === 'footer');
2396
- if (!isInFooter) {
2397
- event.stopPropagation(); // solo per backdrop
2393
+ else {
2394
+ const trigger = this._triggerElement;
2395
+ if (!trigger)
2396
+ return;
2397
+ if (isSafari) {
2398
+ this._safariMouseInteraction = false;
2399
+ }
2400
+ await this.updateComplete; // Assicurati che l'update sia completo prima di applicare il focus workaround
2398
2401
  }
2399
2402
  };
2400
2403
  this._triggerId = this.generateId('modal-trigger');
2401
2404
  this._titleId = this.generateId('modal-title');
2402
2405
  this._descriptionId = this.generateId('modal-description');
2406
+ this._focusTrap = new FocusTrapController(this, {
2407
+ getContainer: () => this._modalElement,
2408
+ initialFocus: () => this._modalElement,
2409
+ getTrigger: () => this._triggerElement,
2410
+ onEscape: () => {
2411
+ this._safariMouseInteraction = false;
2412
+ this.hide();
2413
+ },
2414
+ });
2403
2415
  }
2404
2416
  connectedCallback() {
2405
2417
  super.connectedCallback?.();
@@ -2408,59 +2420,118 @@ let ItModal = class ItModal extends BaseComponent {
2408
2420
  super.disconnectedCallback?.();
2409
2421
  this._removeTriggerListeners();
2410
2422
  this._cleanupAnimations();
2411
- WindowManager.unlockBodyScroll();
2412
- }
2413
- updated(changedProperties) {
2414
- if (changedProperties.has('open')) {
2415
- // Cancel any ongoing animations before starting new ones
2416
- this._cleanupAnimations();
2417
- if (this.open) {
2418
- this._showModal();
2419
- }
2420
- else {
2421
- this._hideModal();
2422
- }
2423
+ this._removeInert();
2424
+ if (this._restoreFocusTimer !== null) {
2425
+ clearTimeout(this._restoreFocusTimer);
2426
+ this._restoreFocusTimer = null;
2423
2427
  }
2424
- }
2425
- _setupTriggerListeners() {
2426
- const trigger = this._triggerElement;
2427
- if (!trigger)
2428
- return;
2429
- trigger.setAttribute('id', this._triggerId);
2430
- // Rimuovi eventuali listener precedenti
2431
- trigger.removeEventListener('click', this._onTriggerClick);
2432
- trigger.removeEventListener('keydown', this._onTriggerKeydown);
2433
- // Aggiungi nuovi listener
2434
- trigger.addEventListener('click', this._onTriggerClick);
2435
- trigger.addEventListener('keydown', this._onTriggerKeydown);
2436
- }
2437
- _removeTriggerListeners() {
2438
- const trigger = this._triggerElement;
2439
- if (!trigger)
2440
- return;
2441
- trigger.removeEventListener('click', this._onTriggerClick);
2442
- trigger.removeEventListener('keydown', this._onTriggerKeydown);
2428
+ WindowManager.unlockBodyScroll();
2443
2429
  }
2444
2430
  show() {
2445
2431
  if (this.open || this.isAnimating)
2446
2432
  return;
2433
+ this._originalTrigger = this._triggerElement;
2434
+ this.dispatchEvent(new CustomEvent('it-modal-open', { detail: { modal: this }, bubbles: true, composed: true }));
2447
2435
  this.open = true;
2448
2436
  }
2449
2437
  hide() {
2450
2438
  if (!this.open || this.isAnimating)
2451
2439
  return;
2440
+ this.dispatchEvent(new CustomEvent('it-modal-close', { detail: { modal: this }, bubbles: true, composed: true }));
2452
2441
  this._hideModal();
2453
2442
  }
2454
2443
  toggle() {
2455
2444
  this.open = !this.open;
2456
2445
  }
2457
- _showModal() {
2446
+ updated(changedProperties) {
2447
+ if (changedProperties.has('open')) {
2448
+ if (this._isSelfClosing) {
2449
+ this._isSelfClosing = false;
2450
+ return;
2451
+ }
2452
+ this._cleanupAnimations();
2453
+ if (this.open !== undefined) {
2454
+ if (this.open)
2455
+ this._showModal();
2456
+ else
2457
+ this._hideModal();
2458
+ }
2459
+ }
2460
+ if (changedProperties.has('_safariMouseInteraction')) {
2461
+ let realButton = this._triggerElement;
2462
+ if (realButton?.tagName.toLowerCase() === 'it-button') {
2463
+ realButton = this._triggerElement?.shadowRoot?.querySelector('button');
2464
+ }
2465
+ if (!realButton)
2466
+ return;
2467
+ // Fix Safari: se l'interazione è da mouse, rimuovi outline e box-shadow forzati per evitare il doppio focus ring
2468
+ if (this._safariMouseInteraction) {
2469
+ realButton.style.setProperty('outline', '0', 'important');
2470
+ realButton.style.setProperty('box-shadow', 'none', 'important');
2471
+ }
2472
+ else {
2473
+ realButton.style.removeProperty('outline');
2474
+ realButton.style.removeProperty('box-shadow');
2475
+ }
2476
+ }
2477
+ }
2478
+ _applyInert() {
2479
+ this._removeInert();
2480
+ const trigger = this._triggerElement;
2481
+ if (trigger) {
2482
+ this._triggerPointerBefore = trigger.style.pointerEvents;
2483
+ trigger.style.pointerEvents = 'none';
2484
+ trigger.setAttribute('inert', '');
2485
+ if (trigger.tagName.toLowerCase().startsWith('it-')) {
2486
+ trigger.setAttribute('it-inert', '');
2487
+ }
2488
+ }
2489
+ const ignored = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'LINK']);
2490
+ for (let cur = this; cur && cur !== document.body; cur = cur.parentElement) {
2491
+ const parent = cur.parentElement;
2492
+ if (!parent)
2493
+ break;
2494
+ Array.from(parent.children).forEach((node) => {
2495
+ if (node !== cur && !ignored.has(node.tagName) && node instanceof HTMLElement) {
2496
+ node.setAttribute('inert', '');
2497
+ // // FIX FOR SAFARI/VOICEOVER:
2498
+ // // If it's a web component with a shadow root, VoiceOver might still
2499
+ // // find the inner button.
2500
+ if (node.shadowRoot && isSafari) {
2501
+ node.setAttribute('inert', '');
2502
+ node.setAttribute('it-inert', '');
2503
+ }
2504
+ this._inertElements.push(node);
2505
+ }
2506
+ });
2507
+ }
2508
+ }
2509
+ _removeInert() {
2510
+ this._inertElements.forEach((el) => {
2511
+ el.removeAttribute('inert');
2512
+ el.removeAttribute('it-inert');
2513
+ });
2514
+ if (this._triggerElement && this._triggerPointerBefore !== null) {
2515
+ this._triggerElement.style.pointerEvents = this._triggerPointerBefore;
2516
+ this._triggerElement.removeAttribute('inert');
2517
+ this._triggerElement.removeAttribute('it-inert');
2518
+ }
2519
+ this._inertElements = [];
2520
+ this._triggerPointerBefore = null;
2521
+ }
2522
+ async _showModal() {
2458
2523
  if (this.isAnimating)
2459
2524
  return;
2525
+ // Cancel any stale close-focus-restore timer so it doesn't fire during the new open.
2526
+ if (this._restoreFocusTimer !== null) {
2527
+ clearTimeout(this._restoreFocusTimer);
2528
+ this._restoreFocusTimer = null;
2529
+ }
2460
2530
  this.isAnimating = true;
2461
- // Deactivate focus trap first if it was active
2462
- this._focusTrap.deactivate();
2531
+ this._applyInert();
2463
2532
  WindowManager.lockBodyScroll();
2533
+ // ASPETTA LIT o race conditions solo per Safari
2534
+ await this.updateComplete;
2464
2535
  requestAnimationFrame(() => {
2465
2536
  // Determine transform based on position
2466
2537
  let dialogStartTransform = 'translate(0, 0)'; // default: no transform
@@ -2492,48 +2563,27 @@ let ItModal = class ItModal extends BaseComponent {
2492
2563
  });
2493
2564
  this._dialogAnimation.finished
2494
2565
  .then(() => {
2495
- // Only activate focus trap if modal is still open
2496
2566
  if (this.open) {
2497
- try {
2498
- this._focusTrap.activate();
2499
- }
2500
- catch {
2501
- // Swallow errors if focus trap fails
2502
- }
2567
+ this._focusTrap.activate();
2503
2568
  }
2504
- })
2505
- .catch(() => {
2506
- // Animation cancelled or failed
2507
2569
  })
2508
2570
  .finally(() => {
2509
2571
  this.isAnimating = false;
2510
2572
  });
2511
2573
  }
2512
2574
  else {
2513
- // No dialog element or no animation, just finish
2514
- if (this.open) {
2515
- try {
2516
- this._focusTrap.activate();
2517
- }
2518
- catch {
2519
- // Swallow errors if focus trap fails
2520
- }
2521
- }
2575
+ // No animation: activate immediately. The 50ms inside activate()'s setTimeout
2576
+ // gives VoiceOver iOS enough time to settle its accessibility tree.
2577
+ // See FocusTrapController class comment for full rationale.
2578
+ this._focusTrap.activate();
2522
2579
  this.isAnimating = false;
2523
2580
  }
2524
2581
  });
2525
- this.dispatchEvent(new CustomEvent('it-modal-open', {
2526
- detail: { modal: this },
2527
- bubbles: true,
2528
- composed: true,
2529
- }));
2530
2582
  }
2531
2583
  _hideModal() {
2532
2584
  if (this.isAnimating)
2533
2585
  return;
2534
2586
  this.isAnimating = true;
2535
- // Deactivate focus trap immediately to prevent focus issues
2536
- this._focusTrap.deactivate();
2537
2587
  // Determine end transform based on position
2538
2588
  let dialogEndTransform = 'translate(0, 0)'; // default: no transform
2539
2589
  let dialogCloseDuration = this._dialogAnimationDuration / 1.33;
@@ -2551,12 +2601,27 @@ let ItModal = class ItModal extends BaseComponent {
2551
2601
  const dialogDuration = !this.disableAnimation && !this.prefersReducedMotion ? dialogCloseDuration : 0;
2552
2602
  const backdropDuration = !this.disableAnimation && !this.prefersReducedMotion ? this._backdropAnimationDuration / 1.33 : 0;
2553
2603
  const finishHide = () => {
2554
- // Ensure focus trap is deactivated
2555
- this._focusTrap.deactivate();
2604
+ const target = this._originalTrigger ?? this._triggerElement;
2605
+ this._removeInert();
2556
2606
  this._cleanupAnimations();
2607
+ // skipFocusRestore: we manage focus restore ourselves with the timer below.
2608
+ // Without this, _restoreFocus() fires at 0ms and the timer fires at 20ms,
2609
+ // causing VoiceOver to announce the restored element twice.
2610
+ this._focusTrap.deactivate({ skipFocusRestore: true });
2557
2611
  WindowManager.unlockBodyScroll();
2558
- // Set open to false after animation completes
2612
+ this._isSelfClosing = true;
2613
+ this.isAnimating = false;
2559
2614
  this.open = false;
2615
+ if (target) {
2616
+ this._restoreFocusTimer = setTimeout(() => {
2617
+ this._restoreFocusTimer = null;
2618
+ if (!this.open)
2619
+ target.focus({ preventScroll: true });
2620
+ }, 20);
2621
+ }
2622
+ this._originalTrigger = null;
2623
+ if (isSafari)
2624
+ this._safariMouseInteraction = false;
2560
2625
  };
2561
2626
  // Animate dialog and backdrop in parallel for smoother close
2562
2627
  const animations = [];
@@ -2593,39 +2658,38 @@ let ItModal = class ItModal extends BaseComponent {
2593
2658
  else {
2594
2659
  // No animation, finish immediately
2595
2660
  finishHide();
2596
- this.isAnimating = false;
2597
2661
  }
2598
- this.dispatchEvent(new CustomEvent('it-modal-close', {
2599
- detail: { modal: this },
2600
- bubbles: true,
2601
- composed: true,
2602
- }));
2603
2662
  }
2604
2663
  _cleanupAnimations() {
2605
- if (this._dialogAnimation) {
2606
- try {
2607
- this._dialogAnimation.cancel();
2608
- }
2609
- catch {
2610
- /* ignore */
2611
- }
2612
- this._dialogAnimation = undefined;
2613
- }
2614
- if (this._backdropAnimation) {
2615
- try {
2616
- this._backdropAnimation.cancel();
2617
- }
2618
- catch {
2619
- /* ignore */
2620
- }
2621
- this._backdropAnimation = undefined;
2622
- }
2664
+ this._dialogAnimation?.cancel();
2665
+ this._backdropAnimation?.cancel();
2666
+ this._dialogAnimation = undefined;
2667
+ this._backdropAnimation = undefined;
2668
+ }
2669
+ _setupTriggerListeners() {
2670
+ const trigger = this._triggerElement;
2671
+ if (!trigger)
2672
+ return;
2673
+ trigger.setAttribute('id', this._triggerId);
2674
+ // Rimuovi eventuali listener precedenti
2675
+ trigger.removeEventListener('click', this._onTriggerClick);
2676
+ trigger.removeEventListener('keydown', this._onTriggerKeydown);
2677
+ // Aggiungi nuovi listener
2678
+ trigger.addEventListener('click', this._onTriggerClick);
2679
+ trigger.addEventListener('keydown', this._onTriggerKeydown);
2680
+ }
2681
+ _removeTriggerListeners() {
2682
+ const trigger = this._triggerElement;
2683
+ if (!trigger)
2684
+ return;
2685
+ trigger.removeEventListener('click', this._onTriggerClick);
2686
+ trigger.removeEventListener('keydown', this._onTriggerKeydown);
2623
2687
  }
2624
2688
  get _modalClasses() {
2625
2689
  return {
2626
2690
  modal: true,
2627
2691
  fade: !this.disableAnimation,
2628
- show: this.open && !this.disableAnimation,
2692
+ show: Boolean(this.open) && !this.disableAnimation,
2629
2693
  'alert-modal': this.variant === 'alert',
2630
2694
  'popconfirm-modal': this.variant === 'popconfirm',
2631
2695
  'it-dialog-link-list': this.variant === 'link-list',
@@ -2645,28 +2709,30 @@ let ItModal = class ItModal extends BaseComponent {
2645
2709
  };
2646
2710
  }
2647
2711
  render() {
2648
- const hasHeader = this.modalTitle || this._headerSlot?.assignedElements({ flatten: true }).length > 0;
2649
- const ariaLabelledBy = hasHeader ? this._titleId : undefined;
2650
- const ariaLabel = !hasHeader ? this.itAriaLabel : undefined;
2651
- const headerClass = hasHeader || (this.variant !== 'popconfirm' && !this.hideCloseButton) ? 'modal-header' : '';
2652
- const hasDescription = this.modalDescription || this._descriptionSlot?.assignedElements({ flatten: true }).length > 0;
2653
- const ariaDescribedBy = hasDescription ? this._descriptionId : undefined;
2712
+ const hasHeader = this.modalTitle || (this._headerSlot?.assignedElements({ flatten: true }).length || 0) > 0;
2713
+ const ariaLabel = !hasHeader ? this.itAriaLabel || undefined : undefined;
2654
2714
  const enableFocusContent = this.scrollable || this.position === 'left' || this.position === 'right';
2655
2715
  return html `
2656
2716
  <slot name="trigger" @slotchange=${this._onTriggerSlotChange}></slot>
2657
-
2658
2717
  <div
2659
2718
  class="${classMap(this._modalClasses)}"
2660
2719
  role="dialog"
2661
2720
  aria-modal="true"
2662
- aria-labelledby="${ifDefined(ariaLabelledBy)}"
2663
- aria-describedby="${ifDefined(ariaDescribedBy)}"
2721
+ aria-labelledby="${ifDefined(hasHeader ? this._titleId : undefined)}"
2722
+ aria-describedby="${ifDefined(this._descriptionId)}"
2664
2723
  aria-label="${ifDefined(ariaLabel)}"
2665
2724
  aria-hidden="${!this.open}"
2666
2725
  tabindex="-1"
2667
2726
  @click="${this._handleBackdropClick}"
2668
2727
  part="modal"
2669
2728
  >
2729
+ <!-- TRICK SAFARI ENGINE -->
2730
+ <div
2731
+ id="safari-focus-anchor"
2732
+ tabindex="-1"
2733
+ aria-hidden="true"
2734
+ style="position: absolute; width: 0; height: 0; outline: none;"
2735
+ ></div>
2670
2736
  <div
2671
2737
  class="${classMap(this._modalBodyClasses)}"
2672
2738
  role="document"
@@ -2677,7 +2743,10 @@ let ItModal = class ItModal extends BaseComponent {
2677
2743
  <slot name="description" @slotchange="${this._onHeaderSlotChange}">${this.modalDescription}</slot>
2678
2744
  </div>
2679
2745
  <div class="modal-content" part="modal-content">
2680
- <div class="${headerClass}" part="modal-header">
2746
+ <div
2747
+ class="${hasHeader || (this.variant !== 'popconfirm' && !this.hideCloseButton) ? 'modal-header' : ''}"
2748
+ part="modal-header"
2749
+ >
2681
2750
  <slot name="header-icon"></slot>
2682
2751
  <h2 id="${this._titleId}" class="modal-title">
2683
2752
  <slot name="header" @slotchange="${this._onHeaderSlotChange}">${this.modalTitle}</slot>
@@ -2688,14 +2757,12 @@ let ItModal = class ItModal extends BaseComponent {
2688
2757
  variant="link"
2689
2758
  size="lg"
2690
2759
  exportparts="focusable, button"
2691
- @click="${this._handleCloseClick}"
2692
- >
2693
- <it-icon name="it-close" size="lg"></it-icon>
2694
- <span class="visually-hidden">${this.closeLabel}</span>
2695
- </it-button>`
2760
+ @click="${() => this.hide()}"
2761
+ ><it-icon name="it-close" size="lg"></it-icon
2762
+ ><span class="visually-hidden">${this.closeLabel}</span></it-button
2763
+ >`
2696
2764
  : ''}
2697
2765
  </div>
2698
-
2699
2766
  <div class="modal-body" tabindex="${enableFocusContent ? '0' : '-1'}" part="focusable modal-body">
2700
2767
  <slot name="content"></slot>
2701
2768
  </div>
@@ -2705,21 +2772,17 @@ let ItModal = class ItModal extends BaseComponent {
2705
2772
  </div>
2706
2773
  </div>
2707
2774
  </div>
2708
-
2709
2775
  <div
2710
2776
  class="modal-backdrop ${this.disableAnimation ? 'fade' : ''} ${this.open ? 'show' : ''}"
2711
2777
  aria-hidden="true"
2712
- @click="${this._handleBackdropClick}"
2778
+ @click="${() => !this.staticBackdrop && this.hide()}"
2713
2779
  part="modal-backdrop"
2714
2780
  ></div>
2715
2781
  `;
2716
2782
  }
2717
2783
  };
2718
2784
  ItModal.styles = styles;
2719
- ItModal.shadowRootOptions = {
2720
- ...BaseComponent.shadowRootOptions,
2721
- delegatesFocus: true,
2722
- };
2785
+ ItModal.shadowRootOptions = { ...BaseComponent.shadowRootOptions, delegatesFocus: true };
2723
2786
  __decorate([
2724
2787
  property({ type: Boolean, reflect: true }),
2725
2788
  __metadata("design:type", Object)
@@ -2738,7 +2801,7 @@ __decorate([
2738
2801
  ], ItModal.prototype, "size", void 0);
2739
2802
  __decorate([
2740
2803
  property({ type: String, reflect: true }),
2741
- __metadata("design:type", Object)
2804
+ __metadata("design:type", String)
2742
2805
  ], ItModal.prototype, "position", void 0);
2743
2806
  __decorate([
2744
2807
  property({ type: Boolean, reflect: true }),
@@ -2754,11 +2817,11 @@ __decorate([
2754
2817
  ], ItModal.prototype, "hideCloseButton", void 0);
2755
2818
  __decorate([
2756
2819
  property({ type: String, reflect: true }),
2757
- __metadata("design:type", Object)
2820
+ __metadata("design:type", String)
2758
2821
  ], ItModal.prototype, "variant", void 0);
2759
2822
  __decorate([
2760
2823
  property({ type: String, attribute: 'it-aria-label' }),
2761
- __metadata("design:type", String)
2824
+ __metadata("design:type", Object)
2762
2825
  ], ItModal.prototype, "itAriaLabel", void 0);
2763
2826
  __decorate([
2764
2827
  property({ type: String, attribute: 'close-label', reflect: true }),
@@ -2796,6 +2859,10 @@ __decorate([
2796
2859
  query('.modal-dialog'),
2797
2860
  __metadata("design:type", HTMLElement)
2798
2861
  ], ItModal.prototype, "_dialogElement", void 0);
2862
+ __decorate([
2863
+ state(),
2864
+ __metadata("design:type", Object)
2865
+ ], ItModal.prototype, "_safariMouseInteraction", void 0);
2799
2866
  ItModal = __decorate([
2800
2867
  customElement('it-modal'),
2801
2868
  __metadata("design:paramtypes", [])