@italia/modal 1.0.0-alpha.5

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.
@@ -0,0 +1,2804 @@
1
+ import { directive, Directive } from 'lit/directive.js';
2
+ import { LitElement, css, html } from 'lit';
3
+ import { state, query, property, customElement } from 'lit/decorators.js';
4
+ import { classMap } from 'lit/directives/class-map.js';
5
+ import { ifDefined } from 'lit/directives/if-defined.js';
6
+
7
+ /******************************************************************************
8
+ Copyright (c) Microsoft Corporation.
9
+
10
+ Permission to use, copy, modify, and/or distribute this software for any
11
+ purpose with or without fee is hereby granted.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
+ PERFORMANCE OF THIS SOFTWARE.
20
+ ***************************************************************************** */
21
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
22
+
23
+
24
+ function __decorate(decorators, target, key, desc) {
25
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
26
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
27
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
28
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
29
+ }
30
+
31
+ function __metadata(metadataKey, metadataValue) {
32
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
33
+ }
34
+
35
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
36
+ var e = new Error(message);
37
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
38
+ };
39
+
40
+ class SetAttributesDirective extends Directive {
41
+ update(part, [attributes]) {
42
+ const el = part.element;
43
+ for (const [name, value] of Object.entries(attributes)) {
44
+ if (value != null)
45
+ el.setAttribute(name, value);
46
+ else
47
+ el.removeAttribute(name);
48
+ }
49
+ return null;
50
+ }
51
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
52
+ render(_attributes) {
53
+ return null;
54
+ }
55
+ }
56
+ /* How to use:
57
+
58
+ <textarea ${setAttributes(this._ariaAttributes)} ... />
59
+ */
60
+ directive(SetAttributesDirective);
61
+
62
+ function r(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f);}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}
63
+
64
+ const connectedElements = new Set();
65
+ if (window && !window.translations) {
66
+ window.translations = new Map();
67
+ }
68
+ const { translations } = window;
69
+ let fallback;
70
+ // TODO: We need some way for users to be able to set these on the server.
71
+ let documentDirection = 'ltr';
72
+ // Fallback for server.
73
+ let documentLanguage = 'en';
74
+ const isClient = typeof MutationObserver !== 'undefined' &&
75
+ typeof document !== 'undefined' &&
76
+ typeof document.documentElement !== 'undefined';
77
+ /** Updates all localized elements that are currently connected */
78
+ function update() {
79
+ if (isClient) {
80
+ documentDirection = document.documentElement.dir || 'ltr';
81
+ documentLanguage = document.documentElement.lang || navigator.language;
82
+ }
83
+ [...connectedElements.keys()].forEach((el) => {
84
+ const litEl = el;
85
+ if (typeof litEl.requestUpdate === 'function') {
86
+ litEl.requestUpdate();
87
+ }
88
+ });
89
+ }
90
+ if (isClient) {
91
+ const documentElementObserver = new MutationObserver(update);
92
+ documentDirection = document.documentElement.dir || 'ltr';
93
+ documentLanguage = document.documentElement.lang || navigator.language;
94
+ // Watch for changes on <html lang>
95
+ documentElementObserver.observe(document.documentElement, {
96
+ attributes: true,
97
+ attributeFilter: ['dir', 'lang'],
98
+ });
99
+ }
100
+ /** Registers one or more translations */
101
+ function registerTranslation(...translation) {
102
+ translation.forEach((t) => {
103
+ const code = t.$code.toLowerCase();
104
+ if (translations.has(code)) {
105
+ // Merge translations that share the same language code
106
+ translations.set(code, { ...translations.get(code), ...t });
107
+ }
108
+ else {
109
+ translations.set(code, t);
110
+ }
111
+ // The first translation that's registered is the fallback
112
+ if (!fallback) {
113
+ fallback = t;
114
+ }
115
+ });
116
+ update();
117
+ }
118
+ window.registerTranslation = registerTranslation;
119
+ /**
120
+ * Localize Reactive Controller for components built with Lit
121
+ *
122
+ * To use this controller, import the class and instantiate it in a custom element constructor:
123
+ *
124
+ * private localize = new LocalizeController(this);
125
+ *
126
+ * This will add the element to the set and make it respond to changes to <html dir|lang> automatically. To make it
127
+ * respond to changes to its own dir|lang properties, make it a property:
128
+ *
129
+ * @property() dir: string;
130
+ * @property() lang: string;
131
+ *
132
+ * To use a translation method, call it like this:
133
+ *
134
+ * ${this.localize.term('term_key_here')}
135
+ * ${this.localize.date('2021-12-03')}
136
+ * ${this.localize.number(1000000)}
137
+ */
138
+ class LocalizeController {
139
+ constructor(host) {
140
+ this.host = host;
141
+ this.host.addController(this);
142
+ }
143
+ hostConnected() {
144
+ connectedElements.add(this.host);
145
+ }
146
+ hostDisconnected() {
147
+ connectedElements.delete(this.host);
148
+ }
149
+ /**
150
+ * Gets the host element's directionality as determined by the `dir` attribute. The return value is transformed to
151
+ * lowercase.
152
+ */
153
+ dir() {
154
+ return `${this.host.dir || documentDirection}`.toLowerCase();
155
+ }
156
+ /**
157
+ * Gets the host element's language as determined by the `lang` attribute. The return value is transformed to
158
+ * lowercase.
159
+ */
160
+ lang() {
161
+ return `${this.host.lang || documentLanguage}`.toLowerCase();
162
+ }
163
+ // eslint-disable-next-line class-methods-use-this
164
+ getTranslationData(lang) {
165
+ // Convert "en_US" to "en-US". Note that both underscores and dashes are allowed per spec, but underscores result in
166
+ // a RangeError by the call to `new Intl.Locale()`. See: https://unicode.org/reports/tr35/#unicode-locale-identifier
167
+ const locale = new Intl.Locale(lang.replace(/_/g, '-'));
168
+ const language = locale?.language.toLowerCase();
169
+ const region = locale?.region?.toLowerCase() ?? '';
170
+ const primary = translations.get(`${language}-${region}`);
171
+ const secondary = translations.get(language);
172
+ return { locale, language, region, primary, secondary };
173
+ }
174
+ /** Determines if the specified term exists, optionally checking the fallback translation. */
175
+ exists(key, options) {
176
+ const { primary, secondary } = this.getTranslationData(options.lang ?? this.lang());
177
+ const mergedOptions = {
178
+ includeFallback: false,
179
+ ...options,
180
+ };
181
+ if ((primary && primary[key]) ||
182
+ (secondary && secondary[key]) ||
183
+ (mergedOptions.includeFallback && fallback && fallback[key])) {
184
+ return true;
185
+ }
186
+ return false;
187
+ }
188
+ /** Outputs a translated term. */
189
+ term(key, ...args) {
190
+ const { primary, secondary } = this.getTranslationData(this.lang());
191
+ let term;
192
+ // Look for a matching term using regionCode, code, then the fallback
193
+ if (primary && primary[key]) {
194
+ term = primary[key];
195
+ }
196
+ else if (secondary && secondary[key]) {
197
+ term = secondary[key];
198
+ }
199
+ else if (fallback && fallback[key]) {
200
+ term = fallback[key];
201
+ }
202
+ else {
203
+ // eslint-disable-next-line no-console
204
+ console.error(`No translation found for: ${String(key)}`);
205
+ return String(key);
206
+ }
207
+ if (typeof term === 'function') {
208
+ return term(...args);
209
+ }
210
+ return term;
211
+ }
212
+ /** Outputs a localized date in the specified format. */
213
+ date(dateToFormat, options) {
214
+ const date = new Date(dateToFormat);
215
+ return new Intl.DateTimeFormat(this.lang(), options).format(date);
216
+ }
217
+ /** Outputs a localized number in the specified format. */
218
+ number(numberToFormat, options) {
219
+ const num = Number(numberToFormat);
220
+ return Number.isNaN(num) ? '' : new Intl.NumberFormat(this.lang(), options).format(num);
221
+ }
222
+ /** Outputs a localized time in relative format. */
223
+ relativeTime(value, unit, options) {
224
+ return new Intl.RelativeTimeFormat(this.lang(), options).format(value, unit);
225
+ }
226
+ }
227
+
228
+ /**
229
+ * @param Base The base class.
230
+ * @returns A mix-in implementing `localizations` method.
231
+ *
232
+ *@example
233
+ * <!-- Terms -->
234
+ ${this.$localize.term('hello')}
235
+ or
236
+ ${this.$t('hello')}
237
+
238
+ <!-- Dates -->
239
+ ${this.$localize.date('2021-09-15 14:00:00 ET', { month: 'long', day: 'numeric', year: 'numeric' })}
240
+ or
241
+ ${this.$d('2021-09-15 14:00:00 ET', { month: 'long', day: 'numeric', year: 'numeric' })}
242
+
243
+ <!-- Numbers/currency -->
244
+ ${this.$localize.number(1000, { style: 'currency', currency: 'USD'})}
245
+ or
246
+ ${this.$n(1000,{ style: 'currency', currency: 'USD'})}
247
+
248
+ <!-- Determining language -->
249
+ ${this.$localize.lang()}
250
+
251
+ <!-- Determining directionality, e.g. 'ltr' or 'rtl' -->
252
+ ${this.$localize.dir()}
253
+
254
+
255
+ *** HOW TO DEFINE TRANSLATIONS: ***
256
+ // Simple terms
257
+ upload: 'Upload',
258
+
259
+ // Terms with placeholders
260
+ greetUser: (name: string) => `Hello, ${name}!`,
261
+
262
+ // Plurals
263
+ numFilesSelected: (count: number) => {
264
+ if (count === 0) return 'No files selected';
265
+ if (count === 1) return '1 file selected';
266
+ return `${count} files selected`;
267
+ }
268
+ */
269
+ const LocalizeMixin = (Base) => class extends Base {
270
+ constructor() {
271
+ super(...arguments);
272
+ this.localize = new LocalizeController(this);
273
+ }
274
+ // Provide default values to avoid definite assignment errors and avoid decorators
275
+ // commentati perchè danno problemi su React.js. Sono attributi nativi, e assegnare un valore di default a react da fastidio
276
+ // dir: string = '';
277
+ // lang: string = '';
278
+ /**
279
+ * Restituisce tutta l'utility di traduzione
280
+ *
281
+
282
+ *
283
+ * @returns tutta l'utility di traduzione
284
+ *
285
+ * @example
286
+ * this.$localize.lang() -> ritorna la lingua corrente
287
+ * this.$localize.dir() -> ritorna la direzione della lingua corrente
288
+ */
289
+ get $localize() {
290
+ return this.localize;
291
+ }
292
+ /**
293
+ * Restituisce una stringa localizzata a partire da una chiave di termine.
294
+ *
295
+ * Utilizza il `LocalizeController` per accedere al dizionario corrente e
296
+ * tradurre la chiave fornita secondo la lingua attiva.
297
+ *
298
+ * @param t - La chiave del termine da localizzare (es. 'hello', 'submit', ecc.).
299
+ * @returns La stringa tradotta in base alla lingua attiva. Se la chiave non è trovata, restituisce la chiave stessa.
300
+ *
301
+ * @example
302
+ * this.$t('hello'); // → "Ciao" (in locale it-IT)
303
+ */
304
+ $t(t) {
305
+ // format term
306
+ return this.localize.term(t);
307
+ }
308
+ /**
309
+ * Formatta una data in base alla localizzazione attiva.
310
+ *
311
+ * Utilizza il `LocalizeController` per restituire una stringa localizzata
312
+ * secondo le opzioni fornite (es. mese esteso, anno, ecc.).
313
+ *
314
+ * @param n - La data da formattare come stringa compatibile (es. ISO o con timezone, es. '2021-09-15 14:00:00 ET').
315
+ * @param p - Le opzioni di formattazione per `Intl.DateTimeFormat` (es. { year: 'numeric', month: 'long', day: 'numeric' }).
316
+ * @returns Una stringa rappresentante la data formattata secondo la localizzazione attiva.
317
+ *
318
+ * @example
319
+ * this.$d('2021-09-15 14:00:00 ET', { year: 'numeric', month: 'long', day: 'numeric' });
320
+ * // → "15 settembre 2021" (in locale it-IT)
321
+ */
322
+ $d(d, p) {
323
+ // format date
324
+ return this.localize.date(d, p);
325
+ }
326
+ /**
327
+ * Formatta un numero secondo le impostazioni locali dell'utente corrente.
328
+ *
329
+ * Utilizza il `LocalizeController` per applicare formattazione numerica,
330
+ * incluse opzioni come separatori, decimali, valute, ecc.
331
+ *
332
+ * @param d - Il numero da formattare.
333
+ * @param p - Le opzioni di formattazione (es. { style: 'currency', currency: 'EUR' }).
334
+ * @returns Una stringa rappresentante il numero formattato secondo la localizzazione attiva.
335
+ *
336
+ * @example
337
+ * this.$n(1234.56, { style: 'currency', currency: 'USD' }); // → "$1,234.56" (in locale en-US)
338
+ */
339
+ $n(d, p) {
340
+ return this.localize.number(d, p);
341
+ }
342
+ };
343
+
344
+ /* eslint-disable no-console */
345
+ class Logger {
346
+ constructor(tag) {
347
+ this.tag = tag;
348
+ }
349
+ format(level, msg) {
350
+ return [`[${this.tag}] ${msg}`];
351
+ }
352
+ warn(msg) {
353
+ console.warn(...this.format('warn', msg));
354
+ }
355
+ error(msg) {
356
+ console.error(...this.format('error', msg));
357
+ }
358
+ info(msg) {
359
+ console.info(...this.format('info', msg));
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Factory function per creare una base class estendibile
365
+ * con stili personalizzati.
366
+ */
367
+ class BaseComponent extends LitElement {
368
+ constructor() {
369
+ super();
370
+ this.composeClass = clsx;
371
+ this.logger = new Logger(this.tagName.toLowerCase());
372
+ }
373
+ get _ariaAttributes() {
374
+ const attributes = {};
375
+ for (const attr of this.getAttributeNames()) {
376
+ if (attr === 'it-role') {
377
+ attributes.role = this.getAttribute(attr);
378
+ }
379
+ else if (attr.startsWith('it-aria-')) {
380
+ attributes[attr.replace(/^it-/, '')] = this.getAttribute(attr);
381
+ }
382
+ }
383
+ return attributes;
384
+ }
385
+ // eslint-disable-next-line class-methods-use-this
386
+ generateId(prefix) {
387
+ return `${prefix}-${Math.random().toString(36).slice(2)}`;
388
+ }
389
+ // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars
390
+ addFocus(element) {
391
+ // new TrackFocus(element); // per il momento è stato disattivato perchè ci sono le pseudo classi ::focus-visible per fare quello che fa TrackFocus. Si possono aggiungere regole css in bsi-italia 3 dato che stiamo facendo una breaking release di bsi.
392
+ }
393
+ // eslint-disable-next-line class-methods-use-this
394
+ getActiveElement() {
395
+ let active = document.activeElement;
396
+ while (active && active.shadowRoot && active.shadowRoot.activeElement) {
397
+ active = active.shadowRoot.activeElement;
398
+ }
399
+ return active;
400
+ }
401
+ get focusElement() {
402
+ return this;
403
+ }
404
+ // eslint-disable-next-line class-methods-use-this
405
+ get prefersReducedMotion() {
406
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
407
+ }
408
+ connectedCallback() {
409
+ super.connectedCallback();
410
+ // generate internal _id
411
+ const prefix = this.id?.length > 0 ? this.id : this.tagName.toLowerCase();
412
+ this._id = this.generateId(prefix);
413
+ }
414
+ }
415
+ const BaseLocalizedComponent = LocalizeMixin(BaseComponent);
416
+
417
+ /**
418
+ * Controller per gestire il focus trap all'interno di un elemento.
419
+ * Implementa le linee guida WAI-ARIA per i dialog modali.
420
+ *
421
+
422
+ * ```
423
+ */
424
+ class FocusTrapController {
425
+ /**
426
+ * Verifica se un elemento è effettivamente focusabile e tabbabile.
427
+ * Elementi con tabindex="-1" sono focusabili programmaticamente ma non tabbabili.
428
+ */
429
+ static isFocusable(el) {
430
+ if (typeof el.focus !== 'function')
431
+ return false;
432
+ // Escludi elementi disabilitati
433
+ if (el.hasAttribute('disabled'))
434
+ return false;
435
+ // Escludi elementi con tabindex negativo (focusabili programmaticamente ma non tabbabili)
436
+ const tabindex = el.getAttribute('tabindex');
437
+ if (tabindex && parseInt(tabindex, 10) < 0) {
438
+ return false;
439
+ }
440
+ // Per custom elements (it-*), controlla anche il loro tabindex
441
+ if (el.tagName.toLowerCase().startsWith('it-')) {
442
+ // Se ha tabindex esplicito negativo, non è tabbabile
443
+ if (tabindex && parseInt(tabindex, 10) < 0) {
444
+ return false;
445
+ }
446
+ return true;
447
+ }
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.
452
+ try {
453
+ // Se non ci sono bounding rects, probabilmente non è visibile
454
+ if (el.getClientRects()?.length === 0)
455
+ return false;
456
+ 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;
463
+ }
464
+ catch (e) {
465
+ return false;
466
+ }
467
+ }
468
+ constructor(host, config) {
469
+ this.observer = null;
470
+ this._isActive = false;
471
+ this._previousActiveElement = null;
472
+ this._focusableElements = [];
473
+ this._handleKeyDown = (event) => {
474
+ if (!this._isActive)
475
+ return;
476
+ switch (event.key) {
477
+ case 'Escape':
478
+ if (!this.config.disableEscape && this.config.onEscape) {
479
+ event.preventDefault();
480
+ this.config.onEscape();
481
+ }
482
+ break;
483
+ case 'Tab':
484
+ this._handleTab(event);
485
+ break;
486
+ }
487
+ };
488
+ this.host = host;
489
+ this.config = config;
490
+ this.host.addController(this);
491
+ }
492
+ // eslint-disable-next-line class-methods-use-this
493
+ hostConnected() {
494
+ // Controller ready
495
+ // Set up our MutationObserver
496
+ const observerOptions = {
497
+ childList: true,
498
+ attributes: true,
499
+ subtree: true,
500
+ };
501
+ this.observer = new MutationObserver(this.updateFocusableElements.bind(this));
502
+ this.observer.observe(this.host, observerOptions);
503
+ }
504
+ hostDisconnected() {
505
+ this.deactivate();
506
+ if (this.observer) {
507
+ this.observer.disconnect();
508
+ this.observer = null;
509
+ }
510
+ }
511
+ /** Indica se il focus trap è attivo */
512
+ get isActive() {
513
+ return this._isActive;
514
+ }
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
+ activate() {
521
+ if (this._isActive)
522
+ return;
523
+ this._isActive = true;
524
+ this._previousActiveElement = FocusTrapController.getActiveElement();
525
+ this.host.addEventListener('keydown', this._handleKeyDown);
526
+ this.updateFocusableElements();
527
+ if (typeof this.focusInitial === 'function')
528
+ this.focusInitial();
529
+ else
530
+ this.focusFirst();
531
+ }
532
+ /**
533
+ * Disattiva il focus trap.
534
+ * Ripristina il focus all'elemento precedentemente attivo.
535
+ */
536
+ deactivate() {
537
+ if (!this._isActive)
538
+ return;
539
+ this._isActive = false;
540
+ this.host.removeEventListener('keydown', this._handleKeyDown);
541
+ this._restoreFocus();
542
+ }
543
+ /**
544
+ * Aggiorna la lista degli elementi focusabili.
545
+ * Chiamare dopo modifiche al DOM.
546
+ */
547
+ updateFocusableElements() {
548
+ const container = this.config.getContainer();
549
+ const trigger = this.config.getTrigger();
550
+ if (!container) {
551
+ this._focusableElements = [];
552
+ this._first = undefined;
553
+ this._last = undefined;
554
+ return;
555
+ }
556
+ const candidates = [];
557
+ // Tutti gli elementi focusable direttamente nel container
558
+ const direct = Array.from(container.querySelectorAll(FocusTrapController.FOCUSABLE_SELECTORS));
559
+ candidates.push(...direct);
560
+ // Tutti gli elementi slottati
561
+ const slots = Array.from(container.querySelectorAll('slot'));
562
+ slots.forEach((slot) => {
563
+ slot.assignedElements({ flatten: true }).forEach((el) => {
564
+ if (!(el instanceof HTMLElement))
565
+ return;
566
+ if (el === trigger) {
567
+ return;
568
+ }
569
+ // focusable diretto
570
+ if (el.matches(FocusTrapController.FOCUSABLE_SELECTORS)) {
571
+ candidates.push(el);
572
+ }
573
+ // nested focusable dentro l'elemento assegnato
574
+ Array.from(el.querySelectorAll(FocusTrapController.FOCUSABLE_SELECTORS)).forEach((nested) => candidates.push(nested));
575
+ });
576
+ });
577
+ // Filtra solo elementi veramente focusabili e rimuovi duplicati
578
+ this._focusableElements = Array.from(new Set(candidates)).filter((el) => {
579
+ // Escludi esplicitamente il container/dialog stesso
580
+ if (el === this.config.getContainer())
581
+ return false;
582
+ return FocusTrapController.isFocusable(el);
583
+ });
584
+ // Aggiorna primo/ultimo
585
+ this._first = this._focusableElements?.[0];
586
+ this._last = this._focusableElements[this._focusableElements.length - 1];
587
+ }
588
+ /** Sposta il focus sul primo elemento focusabile */
589
+ focusFirst() {
590
+ if (this._first) {
591
+ this._first.focus();
592
+ }
593
+ }
594
+ /** Sposta il focus sull'ultimo elemento focusabile */
595
+ focusLast() {
596
+ if (this._last) {
597
+ this._last.focus();
598
+ }
599
+ }
600
+ /** Ritorna l'elemento attivo corrente, attraversando shadow DOM e slot */
601
+ static getActiveElement() {
602
+ let active = document.activeElement;
603
+ while (active && active.shadowRoot && active.shadowRoot.activeElement) {
604
+ active = active.shadowRoot.activeElement;
605
+ }
606
+ return active;
607
+ }
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
+ _handleTab(event) {
623
+ if (this._focusableElements.length === 0) {
624
+ event.preventDefault();
625
+ return;
626
+ }
627
+ // SEMPRE previeni il default - gestiamo noi la navigazione
628
+ event.preventDefault();
629
+ const firstElement = this._first;
630
+ const lastElement = this._last;
631
+ 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
+ let currentIndex = this._focusableElements.indexOf(activeElement);
636
+ // Se non trovato, potrebbe essere un elemento interno ad un custom element
637
+ if (currentIndex === -1 && activeElement) {
638
+ // Risali attraverso gli shadow host
639
+ let parent = activeElement.getRootNode()?.host;
640
+ while (parent && currentIndex === -1) {
641
+ currentIndex = this._focusableElements.indexOf(parent);
642
+ if (currentIndex === -1) {
643
+ parent = parent.getRootNode()?.host;
644
+ }
645
+ }
646
+ }
647
+ 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
655
+ 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
+ }
662
+ else {
663
+ // Vai al successivo
664
+ this._focusableElements[currentIndex + 1]?.focus();
665
+ }
666
+ }
667
+ _restoreFocus() {
668
+ if (this._previousActiveElement && typeof this._previousActiveElement.focus === 'function') {
669
+ this._previousActiveElement.focus();
670
+ }
671
+ this._previousActiveElement = null;
672
+ }
673
+ }
674
+ FocusTrapController.FOCUSABLE_SELECTORS = [
675
+ 'a[href]',
676
+ 'button:not([disabled])',
677
+ 'textarea:not([disabled])',
678
+ 'input:not([disabled]):not([type="hidden"])',
679
+ 'select:not([disabled])',
680
+ '[tabindex]',
681
+ // '[role="dialog"]',
682
+ // Custom elements focusabili
683
+ 'it-button:not([disabled])',
684
+ ].join(',');
685
+
686
+ //
687
+ // We store a WeakMap of forms + controls so we can keep references to all FormControl within a given form. As
688
+ // elements connect and disconnect to/from the DOM, their containing form is used as the key and the form control is
689
+ // added and removed from the form's set, respectively.
690
+ //
691
+ const formCollections = new WeakMap();
692
+ //
693
+ // We store a WeakMap of reportValidity() overloads so we can override it when form controls connect to the DOM and
694
+ // restore the original behavior when they disconnect.
695
+ //
696
+ const reportValidityOverloads = new WeakMap();
697
+ const checkValidityOverloads = new WeakMap();
698
+ //
699
+ // We store a Set of controls that users have interacted with. This allows us to determine the interaction state
700
+ // without littering the DOM with additional data attributes.
701
+ //
702
+ const userInteractedControls = new WeakSet();
703
+ //
704
+ // We store a WeakMap of interactions for each form control so we can track when all conditions are met for validation.
705
+ //
706
+ const interactions = new WeakMap();
707
+ /** A reactive controller to allow form controls to participate in form submission, validation, etc. */
708
+ class FormControlController {
709
+ constructor(host, options) {
710
+ this.submittedOnce = false;
711
+ this.handleFormData = (event) => {
712
+ // console.log('handleFormData');
713
+ const disabled = this.options.disabled(this.host);
714
+ const name = this.options.name(this.host);
715
+ const value = this.options.value(this.host);
716
+ const tagName = this.host.tagName.toLowerCase();
717
+ // For buttons, we only submit the value if they were the submitter. This is currently done in doAction() by
718
+ // injecting the name/value on a temporary button, so we can just skip them here.
719
+ const isButton = tagName === 'it-button';
720
+ if (this.host.isConnected &&
721
+ !disabled &&
722
+ !isButton &&
723
+ typeof name === 'string' &&
724
+ name.length > 0 &&
725
+ typeof value !== 'undefined') {
726
+ switch (tagName) {
727
+ case 'it-radio':
728
+ if (this.host.checked) {
729
+ event.formData.append(name, value);
730
+ }
731
+ break;
732
+ case 'it-checkbox':
733
+ if (this.host.checked) {
734
+ if (event.formData.getAll(name).indexOf(value) < 0) {
735
+ // handle group checkbox
736
+ event.formData.append(name, value);
737
+ }
738
+ }
739
+ break;
740
+ case 'it-checkbox-group':
741
+ // non settare valori in formData, perchè ogni singola checkbox setta il suo valore
742
+ break;
743
+ default:
744
+ if (Array.isArray(value)) {
745
+ value.forEach((val) => {
746
+ event.formData.append(name, val.toString());
747
+ });
748
+ }
749
+ else {
750
+ event.formData.append(name, value.toString());
751
+ }
752
+ }
753
+ }
754
+ };
755
+ this.handleFormSubmit = (event) => {
756
+ const disabled = this.options.disabled(this.host);
757
+ const reportValidity = this.options.reportValidity;
758
+ // Update the interacted state for all controls when the form is submitted
759
+ if (this.form && !this.form.noValidate) {
760
+ formCollections.get(this.form)?.forEach((control) => {
761
+ this.setUserInteracted(control, true);
762
+ });
763
+ }
764
+ const resReportValidity = reportValidity(this.host);
765
+ if (this.form && !this.form.noValidate && !disabled && !resReportValidity) {
766
+ event.preventDefault();
767
+ // event.stopImmediatePropagation(); // se lo attiviamo, valida un campo alla volta
768
+ // Scroll al primo controllo non valido
769
+ const formControls = formCollections.get(this.form);
770
+ if (formControls) {
771
+ for (const control of formControls) {
772
+ if (!control.validity?.valid) {
773
+ // Scroll smooth verso il controllo non valido
774
+ control.scrollIntoView({
775
+ behavior: 'smooth',
776
+ block: 'center',
777
+ });
778
+ break;
779
+ }
780
+ }
781
+ }
782
+ }
783
+ this.submittedOnce = true;
784
+ };
785
+ this.handleFormReset = () => {
786
+ this.options.setValue(this.host, '');
787
+ this.submittedOnce = false;
788
+ this.setUserInteracted(this.host, false);
789
+ interactions.set(this.host, []);
790
+ };
791
+ this.handleInteraction = (event) => {
792
+ const emittedEvents = interactions.get(this.host);
793
+ if (!emittedEvents.includes(event.type)) {
794
+ emittedEvents.push(event.type);
795
+ }
796
+ // Mark it as user-interacted as soon as all associated events have been emitted
797
+ if (emittedEvents.length === this.options.assumeInteractionOn.length) {
798
+ this.setUserInteracted(this.host, true);
799
+ }
800
+ };
801
+ this.checkFormValidity = () => {
802
+ // console.log('checkFormValidity');
803
+ //
804
+ // This is very similar to the `reportFormValidity` function, but it does not trigger native constraint validation
805
+ // Allow the user to simply check if the form is valid and handling validity in their own way.
806
+ //
807
+ // We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
808
+ // validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
809
+ // be necessary once we can use ElementInternals.
810
+ //
811
+ // Note that we're also honoring the form's novalidate attribute.
812
+ //
813
+ if (this.form && !this.form.noValidate) {
814
+ // This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
815
+ // elements that support the constraint validation API.
816
+ const elements = this.form.querySelectorAll('*');
817
+ for (const element of elements) {
818
+ if (typeof element.checkValidity === 'function') {
819
+ if (!element.checkValidity()) {
820
+ return false;
821
+ }
822
+ }
823
+ }
824
+ }
825
+ return true;
826
+ };
827
+ this.reportFormValidity = () => {
828
+ // console.log('reportFormValidity');
829
+ //
830
+ // FormControl work hard to act like regular form controls. They support the Constraint Validation API
831
+ // and its associated methods such as setCustomValidity() and reportValidity(). However, the HTMLFormElement also
832
+ // has a reportValidity() method that will trigger validation on all child controls. Since we're not yet using
833
+ // ElementInternals, we need to overload this method so it looks for any element with the reportValidity() method.
834
+ //
835
+ // We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
836
+ // validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
837
+ // be necessary once we can use ElementInternals.
838
+ //
839
+ // Note that we're also honoring the form's novalidate attribute.
840
+ //
841
+ if (this.form && !this.form.noValidate) {
842
+ // This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
843
+ // elements that support the constraint validation API.
844
+ const elements = this.form.querySelectorAll('*');
845
+ for (const element of elements) {
846
+ if (typeof element.reportValidity === 'function') {
847
+ if (!element.reportValidity()) {
848
+ return false;
849
+ }
850
+ }
851
+ }
852
+ }
853
+ return true;
854
+ };
855
+ (this.host = host).addController(this);
856
+ this.options = {
857
+ form: (input) => {
858
+ // If there's a form attribute, use it to find the target form by id
859
+ // Controls may not always reflect the 'form' property. For example, `<it-button>` doesn't reflect.
860
+ const formId = input.form;
861
+ if (formId) {
862
+ const root = input.getRootNode();
863
+ const form = root.querySelector(`#${formId}`);
864
+ if (form) {
865
+ return form;
866
+ }
867
+ }
868
+ return input.closest('form');
869
+ },
870
+ name: (input) => input.name,
871
+ value: (input) => input.value,
872
+ disabled: (input) => input.disabled ?? false,
873
+ reportValidity: (input) => typeof input.reportValidity === 'function' ? input.reportValidity() : true,
874
+ checkValidity: (input) => (typeof input.checkValidity === 'function' ? input.checkValidity() : true),
875
+ setValue: (input, value) => {
876
+ // eslint-disable-next-line no-param-reassign
877
+ input.value = value;
878
+ },
879
+ assumeInteractionOn: ['it-input'],
880
+ ...options,
881
+ };
882
+ }
883
+ hostConnected() {
884
+ const form = this.options.form(this.host);
885
+ if (form) {
886
+ this.attachForm(form);
887
+ }
888
+ // Listen for interactions
889
+ interactions.set(this.host, []);
890
+ this.options.assumeInteractionOn.forEach((event) => {
891
+ this.host.addEventListener(event, this.handleInteraction);
892
+ });
893
+ }
894
+ hostDisconnected() {
895
+ this.detachForm();
896
+ // Clean up interactions
897
+ interactions.delete(this.host);
898
+ this.options.assumeInteractionOn.forEach((event) => {
899
+ this.host.removeEventListener(event, this.handleInteraction);
900
+ });
901
+ }
902
+ hostUpdated() {
903
+ const form = this.options.form(this.host);
904
+ // Detach if the form no longer exists
905
+ if (!form) {
906
+ this.detachForm();
907
+ }
908
+ // If the form has changed, reattach it
909
+ if (form && this.form !== form) {
910
+ this.detachForm();
911
+ this.attachForm(form);
912
+ }
913
+ if (this.host.hasUpdated) {
914
+ this.setValidity(this.host.validity.valid);
915
+ }
916
+ }
917
+ attachForm(form) {
918
+ if (form) {
919
+ this.form = form;
920
+ // Add this element to the form's collection
921
+ if (formCollections.has(this.form)) {
922
+ formCollections.get(this.form).add(this.host);
923
+ }
924
+ else {
925
+ formCollections.set(this.form, new Set([this.host]));
926
+ }
927
+ this.form.addEventListener('formdata', this.handleFormData);
928
+ this.form.addEventListener('submit', this.handleFormSubmit);
929
+ this.form.addEventListener('reset', this.handleFormReset);
930
+ // Overload the form's reportValidity() method so it looks at FormControl
931
+ if (!reportValidityOverloads.has(this.form)) {
932
+ reportValidityOverloads.set(this.form, this.form.reportValidity);
933
+ this.form.reportValidity = () => this.reportFormValidity();
934
+ }
935
+ // Overload the form's checkValidity() method so it looks at FormControl
936
+ if (!checkValidityOverloads.has(this.form)) {
937
+ checkValidityOverloads.set(this.form, this.form.checkValidity);
938
+ this.form.checkValidity = () => this.checkFormValidity();
939
+ }
940
+ }
941
+ else {
942
+ this.form = undefined;
943
+ }
944
+ }
945
+ detachForm() {
946
+ if (!this.form)
947
+ return;
948
+ const formCollection = formCollections.get(this.form);
949
+ if (!formCollection) {
950
+ return;
951
+ }
952
+ this.submittedOnce = false;
953
+ // Remove this host from the form's collection
954
+ formCollection.delete(this.host);
955
+ // Check to make sure there's no other form controls in the collection. If we do this
956
+ // without checking if any other controls are still in the collection, then we will wipe out the
957
+ // validity checks for all other elements.
958
+ // see: https://github.com/shoelace-style/shoelace/issues/1703
959
+ if (formCollection.size <= 0) {
960
+ this.form.removeEventListener('formdata', this.handleFormData);
961
+ this.form.removeEventListener('submit', this.handleFormSubmit);
962
+ this.form.removeEventListener('reset', this.handleFormReset);
963
+ // Remove the overload and restore the original method
964
+ if (reportValidityOverloads.has(this.form)) {
965
+ this.form.reportValidity = reportValidityOverloads.get(this.form);
966
+ reportValidityOverloads.delete(this.form);
967
+ }
968
+ if (checkValidityOverloads.has(this.form)) {
969
+ this.form.checkValidity = checkValidityOverloads.get(this.form);
970
+ checkValidityOverloads.delete(this.form);
971
+ }
972
+ // So it looks weird here to not always set the form to undefined. But I _think_ if we unattach this.form here,
973
+ // we end up in this fun spot where future validity checks don't have a reference to the form validity handler.
974
+ // First form element in sets the validity handler. So we can't clean up `this.form` until there are no other form elements in the form.
975
+ this.form = undefined;
976
+ }
977
+ }
978
+ // eslint-disable-next-line class-methods-use-this
979
+ setUserInteracted(el, hasInteracted) {
980
+ if (hasInteracted) {
981
+ userInteractedControls.add(el);
982
+ }
983
+ else {
984
+ userInteractedControls.delete(el);
985
+ }
986
+ el.requestUpdate();
987
+ }
988
+ doAction(type, submitter) {
989
+ // console.log('doaction', type);
990
+ if (this.form) {
991
+ const button = document.createElement('button');
992
+ button.type = type;
993
+ button.style.position = 'absolute';
994
+ button.style.width = '0';
995
+ button.style.height = '0';
996
+ button.style.clipPath = 'inset(50%)';
997
+ button.style.overflow = 'hidden';
998
+ button.style.whiteSpace = 'nowrap';
999
+ // Pass name, value, and form attributes through to the temporary button
1000
+ if (submitter) {
1001
+ button.name = submitter.name;
1002
+ button.value = submitter.value;
1003
+ ['formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget'].forEach((attr) => {
1004
+ if (submitter.hasAttribute(attr)) {
1005
+ button.setAttribute(attr, submitter.getAttribute(attr));
1006
+ }
1007
+ });
1008
+ }
1009
+ this.form.append(button);
1010
+ button.click();
1011
+ button.remove();
1012
+ }
1013
+ }
1014
+ /** Returns the associated `<form>` element, if one exists. */
1015
+ getForm() {
1016
+ return this.form ?? null;
1017
+ }
1018
+ /** Resets the form, restoring all the control to their default value */
1019
+ reset(submitter) {
1020
+ this.doAction('reset', submitter);
1021
+ }
1022
+ /** Submits the form, triggering validation and form data injection. */
1023
+ submit(submitter) {
1024
+ // Calling form.submit() bypasses the submit event and constraint validation. To prevent this, we can inject a
1025
+ // native submit button into the form, "click" it, then remove it to simulate a standard form submission.
1026
+ this.doAction('submit', submitter);
1027
+ }
1028
+ /**
1029
+ * Synchronously sets the form control's validity. Call this when you know the future validity but need to update
1030
+ * the host element immediately, i.e. before Lit updates the component in the next update.
1031
+ */
1032
+ setValidity(isValid) {
1033
+ const host = this.host;
1034
+ const hasInteracted = Boolean(userInteractedControls.has(host));
1035
+ const required = Boolean(host.required);
1036
+ //
1037
+ // We're mapping the following "states" to data attributes. In the future, we can use ElementInternals.states to
1038
+ // create a similar mapping, but instead of [data-invalid] it will look like :--invalid.
1039
+ //
1040
+ // See this RFC for more details: https://github.com/shoelace-style/shoelace/issues/1011
1041
+ //
1042
+ host.toggleAttribute('data-required', required);
1043
+ host.toggleAttribute('data-optional', !required);
1044
+ host.toggleAttribute('data-invalid', !isValid);
1045
+ host.toggleAttribute('data-valid', isValid);
1046
+ host.toggleAttribute('data-user-invalid', !isValid && hasInteracted);
1047
+ host.toggleAttribute('data-user-valid', isValid && hasInteracted);
1048
+ }
1049
+ userInteracted() {
1050
+ const hasInteracted = Boolean(userInteractedControls.has(this.host));
1051
+ return hasInteracted;
1052
+ }
1053
+ /**
1054
+ * Updates the form control's validity based on the current value of `host.validity.valid`. Call this when anything
1055
+ * that affects constraint validation changes so the component receives the correct validity states.
1056
+ */
1057
+ updateValidity() {
1058
+ const host = this.host;
1059
+ this.setValidity(host.validity.valid);
1060
+ }
1061
+ /**
1062
+ * Dispatches a non-bubbling, cancelable custom event of type `it-invalid`.
1063
+ * If the `it-invalid` event will be cancelled then the original `invalid`
1064
+ * event (which may have been passed as argument) will also be cancelled.
1065
+ * If no original `invalid` event has been passed then the `it-invalid`
1066
+ * event will be cancelled before being dispatched.
1067
+ */
1068
+ emitInvalidEvent(originalInvalidEvent) {
1069
+ const itInvalidEvent = new CustomEvent('it-invalid', {
1070
+ bubbles: false,
1071
+ composed: false,
1072
+ cancelable: true,
1073
+ detail: {},
1074
+ });
1075
+ if (!originalInvalidEvent) {
1076
+ itInvalidEvent.preventDefault();
1077
+ }
1078
+ if (!this.host.dispatchEvent(itInvalidEvent)) {
1079
+ originalInvalidEvent?.preventDefault();
1080
+ }
1081
+ }
1082
+ }
1083
+
1084
+ const translation = {
1085
+ $code: 'it',
1086
+ $name: 'Italiano',
1087
+ $dir: 'ltr',
1088
+ validityRequired: 'Questo campo è obbligatorio.',
1089
+ validityGroupRequired: "Scegli almeno un'opzione",
1090
+ validityPattern: 'Il valore non corrisponde al formato richiesto.',
1091
+ validityMinlength: 'Il valore deve essere lungo almeno {minlength} caratteri.',
1092
+ validityMaxlength: 'Il valore deve essere lungo al massimo {maxlength} caratteri.',
1093
+ };
1094
+
1095
+ registerTranslation(translation);
1096
+ class FormControl extends BaseLocalizedComponent {
1097
+ constructor() {
1098
+ super(...arguments);
1099
+ this.formControlController = new FormControlController(this, {
1100
+ assumeInteractionOn: ['it-input', 'it-blur', 'it-change'],
1101
+ });
1102
+ // TODO: verificare se serve davvero con il fatto che usiamo form-controller
1103
+ // static formAssociated = true;
1104
+ // @property()
1105
+ // internals = this.attachInternals();
1106
+ this._touched = false;
1107
+ /** The name of the input, submitted as a name/value pair with form data. */
1108
+ this.name = '';
1109
+ /** The current value of the input, submitted as a name/value pair with form data. */
1110
+ this.value = '';
1111
+ /** If the input is disabled. */
1112
+ this.disabled = false;
1113
+ /**
1114
+ * By default, form controls are associated with the nearest containing `<form>` element. This attribute allows you
1115
+ * to place the form control outside of a form and associate it with the form that has this `id`. The form must be in
1116
+ * the same document or shadow root for this to work.
1117
+ */
1118
+ this.form = '';
1119
+ /** If you implement your custom validation and you won't to trigger default validation */
1120
+ this.customValidation = false;
1121
+ /** If your input is invalid from your custom validition, set this attribute with message validation */
1122
+ this.validationText = '';
1123
+ /**
1124
+ * Specifies the granularity that the value must adhere to, or the special value `any` which means no stepping is
1125
+ * implied, allowing any numeric value. Only applies to date and number input types.
1126
+ */
1127
+ this.step = 'any';
1128
+ /** The input's minimum length. */
1129
+ this.minlength = -1;
1130
+ /** The input's maximum length. */
1131
+ this.maxlength = -1;
1132
+ /** If the input is required. */
1133
+ this.required = false;
1134
+ /* For grouped input, like checkbox-group */
1135
+ this.isInGroup = false;
1136
+ this.validationMessage = '';
1137
+ }
1138
+ /** Gets the validity state object */
1139
+ get validity() {
1140
+ return this.inputElement?.validity;
1141
+ }
1142
+ /** Gets the associated form, if one exists. */
1143
+ getForm() {
1144
+ return this.formControlController.getForm();
1145
+ }
1146
+ // Form validation methods
1147
+ checkValidity() {
1148
+ const inputValid = this.inputElement?.checkValidity() ?? true; // this.inputElement.checkValidity() è la validazione del browser
1149
+ return inputValid;
1150
+ }
1151
+ /** Checks for validity and shows the browser's validation message if the control is invalid. */
1152
+ reportValidity() {
1153
+ // const ret = this.inputElement.checkValidity();
1154
+ const ret = this.checkValidity(); // chiama la checkValidity, che se è stata overridata chiama quella
1155
+ this.handleValidationMessages();
1156
+ return ret; // this.inputElement.reportValidity();
1157
+ }
1158
+ /** Sets a custom validation message. Pass an empty string to restore validity. */
1159
+ setCustomValidity(message) {
1160
+ this.inputElement.setCustomValidity(message);
1161
+ this.validationMessage = this.inputElement.validationMessage;
1162
+ this.formControlController.updateValidity();
1163
+ }
1164
+ // Handlers
1165
+ _handleReady() {
1166
+ requestAnimationFrame(() => {
1167
+ this.dispatchEvent(new CustomEvent('it-input-ready', { bubbles: true, detail: { el: this.inputElement } }));
1168
+ });
1169
+ }
1170
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1171
+ _handleInput(e) {
1172
+ this.handleValidationMessages();
1173
+ this.dispatchEvent(new CustomEvent('it-input', {
1174
+ detail: { value: this.inputElement.value, el: this.inputElement },
1175
+ bubbles: true,
1176
+ composed: true,
1177
+ }));
1178
+ }
1179
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1180
+ _handleBlur(e) {
1181
+ this._touched = true;
1182
+ this.handleValidationMessages();
1183
+ this.dispatchEvent(new FocusEvent('it-blur', { bubbles: true, composed: true }));
1184
+ }
1185
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1186
+ _handleFocus(e) {
1187
+ this.dispatchEvent(new FocusEvent('it-focus', { bubbles: true, composed: true }));
1188
+ }
1189
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1190
+ _handleClick(e) {
1191
+ this.dispatchEvent(new MouseEvent('it-click', { bubbles: true, composed: true }));
1192
+ }
1193
+ /*
1194
+ Override default browser validation messages
1195
+ */
1196
+ handleValidationMessages() {
1197
+ if (!this.customValidation) {
1198
+ const _v = this.inputElement.validity;
1199
+ const isRequiredHandledByGroup = this.isInGroup === true;
1200
+ if (_v.valueMissing && !isRequiredHandledByGroup) {
1201
+ this.setCustomValidity(this.$t('validityRequired'));
1202
+ }
1203
+ else if (_v.patternMismatch) {
1204
+ this.setCustomValidity(this.$t('validityPattern'));
1205
+ }
1206
+ else if (_v.tooShort) {
1207
+ this.setCustomValidity(this.$t('validityMinlength').replace('{minlength}', this.minlength.toString()));
1208
+ }
1209
+ else if (_v.tooLong) {
1210
+ this.setCustomValidity(this.$t('validityMaxlength').replace('{maxlength}', this.maxlength.toString()));
1211
+ }
1212
+ else {
1213
+ /* nothing. Usa il messaggio di errore della validazione
1214
+ di default del browser per altri errori di validità come:
1215
+ - typeMismatch
1216
+ - rangeUnderflow
1217
+ - rangeOverflow
1218
+ - stepMismatch
1219
+ - badInput */
1220
+ const otherConstraintErrors = _v.typeMismatch || _v.rangeUnderflow || _v.rangeOverflow || _v.stepMismatch || _v.badInput;
1221
+ if (!otherConstraintErrors) {
1222
+ this.setCustomValidity('');
1223
+ }
1224
+ }
1225
+ }
1226
+ this.validationMessage = this.inputElement.validationMessage;
1227
+ }
1228
+ _handleInvalid(event) {
1229
+ this.formControlController.setValidity(false);
1230
+ this.formControlController.emitInvalidEvent(event);
1231
+ }
1232
+ _handleChange(e) {
1233
+ const target = e.target;
1234
+ let value;
1235
+ if (target instanceof HTMLInputElement) {
1236
+ switch (target.type) {
1237
+ case 'checkbox':
1238
+ case 'radio':
1239
+ value = target.checked;
1240
+ break;
1241
+ case 'file':
1242
+ value = target.files; // FileList
1243
+ break;
1244
+ default:
1245
+ value = target.value;
1246
+ }
1247
+ }
1248
+ else if (target instanceof HTMLSelectElement) {
1249
+ if (target.multiple) {
1250
+ value = Array.from(target.selectedOptions).map((o) => o.value);
1251
+ }
1252
+ else {
1253
+ value = target.value;
1254
+ }
1255
+ }
1256
+ else {
1257
+ // textarea o altri input con value
1258
+ value = target.value;
1259
+ }
1260
+ this.dispatchEvent(new CustomEvent('it-change', {
1261
+ detail: { value, el: target },
1262
+ bubbles: true,
1263
+ composed: true,
1264
+ }));
1265
+ }
1266
+ updated(changedProperties) {
1267
+ super.updated?.(changedProperties);
1268
+ if (this.customValidation) {
1269
+ this.setCustomValidity(this.validationText ?? '');
1270
+ }
1271
+ else if (this.formControlController.userInteracted()) {
1272
+ this.formControlController.updateValidity();
1273
+ }
1274
+ }
1275
+ }
1276
+ __decorate([
1277
+ state(),
1278
+ __metadata("design:type", Object)
1279
+ ], FormControl.prototype, "_touched", void 0);
1280
+ __decorate([
1281
+ query('.it-form__control'),
1282
+ __metadata("design:type", HTMLInputElement)
1283
+ ], FormControl.prototype, "inputElement", void 0);
1284
+ __decorate([
1285
+ property({ type: String, reflect: true }) // from FormControl
1286
+ ,
1287
+ __metadata("design:type", Object)
1288
+ ], FormControl.prototype, "name", void 0);
1289
+ __decorate([
1290
+ property({ reflect: true }),
1291
+ __metadata("design:type", Object)
1292
+ ], FormControl.prototype, "value", void 0);
1293
+ __decorate([
1294
+ property({ type: Boolean, reflect: true }) // from FormControl
1295
+ ,
1296
+ __metadata("design:type", Object)
1297
+ ], FormControl.prototype, "disabled", void 0);
1298
+ __decorate([
1299
+ property({ reflect: true, type: String }),
1300
+ __metadata("design:type", Object)
1301
+ ], FormControl.prototype, "form", void 0);
1302
+ __decorate([
1303
+ property({ type: Boolean, reflect: true, attribute: 'custom-validation' }),
1304
+ __metadata("design:type", Object)
1305
+ ], FormControl.prototype, "customValidation", void 0);
1306
+ __decorate([
1307
+ property({ attribute: 'validity-message', reflect: true }),
1308
+ __metadata("design:type", String)
1309
+ ], FormControl.prototype, "validationText", void 0);
1310
+ __decorate([
1311
+ property(),
1312
+ __metadata("design:type", String)
1313
+ ], FormControl.prototype, "pattern", void 0);
1314
+ __decorate([
1315
+ property(),
1316
+ __metadata("design:type", Object)
1317
+ ], FormControl.prototype, "min", void 0);
1318
+ __decorate([
1319
+ property(),
1320
+ __metadata("design:type", Object)
1321
+ ], FormControl.prototype, "max", void 0);
1322
+ __decorate([
1323
+ property(),
1324
+ __metadata("design:type", Object)
1325
+ ], FormControl.prototype, "step", void 0);
1326
+ __decorate([
1327
+ property({ type: Number }),
1328
+ __metadata("design:type", Object)
1329
+ ], FormControl.prototype, "minlength", void 0);
1330
+ __decorate([
1331
+ property({ type: Number }),
1332
+ __metadata("design:type", Object)
1333
+ ], FormControl.prototype, "maxlength", void 0);
1334
+ __decorate([
1335
+ property({ type: Boolean, reflect: true }) // from FormControl
1336
+ ,
1337
+ __metadata("design:type", Object)
1338
+ ], FormControl.prototype, "required", void 0);
1339
+ __decorate([
1340
+ property({ type: Boolean }),
1341
+ __metadata("design:type", Object)
1342
+ ], FormControl.prototype, "isInGroup", void 0);
1343
+ __decorate([
1344
+ state(),
1345
+ __metadata("design:type", Object)
1346
+ ], FormControl.prototype, "validationMessage", void 0);
1347
+
1348
+ class WindowManager {
1349
+ static init() {
1350
+ if (this.initialized)
1351
+ return;
1352
+ this.lastScrollY = window.scrollY;
1353
+ this.lastWidth = window.innerWidth;
1354
+ this.lastHeight = window.innerHeight;
1355
+ window.addEventListener('scroll', () => {
1356
+ this.lastScrollY = window.scrollY;
1357
+ this.requestTick();
1358
+ });
1359
+ window.addEventListener('resize', () => {
1360
+ this.lastWidth = window.innerWidth;
1361
+ this.lastHeight = window.innerHeight;
1362
+ this.requestTick(true); // force recalculation
1363
+ });
1364
+ this.initialized = true;
1365
+ }
1366
+ static requestTick(forceRecalc = false) {
1367
+ if (!this.ticking) {
1368
+ requestAnimationFrame(() => this.tick(forceRecalc));
1369
+ this.ticking = true;
1370
+ }
1371
+ }
1372
+ static tick(forceRecalc) {
1373
+ this.ticking = false;
1374
+ const state = {
1375
+ scrollY: this.lastScrollY,
1376
+ width: this.lastWidth,
1377
+ height: this.lastHeight,
1378
+ };
1379
+ this.subscribers.forEach((cb) => cb(state, forceRecalc));
1380
+ }
1381
+ static subscribe(cb) {
1382
+ this.subscribers.add(cb);
1383
+ }
1384
+ static unsubscribe(cb) {
1385
+ this.subscribers.delete(cb);
1386
+ }
1387
+ /**
1388
+ * Blocca lo scroll del body. Usa ref counting per gestire modal nested.
1389
+ * Chiamare unlockBodyScroll() per ogni lockBodyScroll().
1390
+ */
1391
+ static lockBodyScroll() {
1392
+ this.scrollLockCount += 1;
1393
+ if (this.scrollLockCount === 1) {
1394
+ this.scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
1395
+ document.body.classList.add('modal-open');
1396
+ document.body.style.overflow = 'hidden';
1397
+ document.body.style.paddingRight = `${this.scrollbarWidth}px`;
1398
+ }
1399
+ }
1400
+ /**
1401
+ * Sblocca lo scroll del body. Rimuove il lock solo quando tutti i consumer hanno chiamato unlock.
1402
+ */
1403
+ static unlockBodyScroll() {
1404
+ this.scrollLockCount = Math.max(0, this.scrollLockCount - 1);
1405
+ if (this.scrollLockCount === 0) {
1406
+ document.body.classList.remove('modal-open');
1407
+ document.body.style.overflow = '';
1408
+ document.body.style.paddingRight = '';
1409
+ }
1410
+ }
1411
+ /** Ritorna la larghezza della scrollbar (utile per compensazioni) */
1412
+ static getScrollbarWidth() {
1413
+ return this.scrollbarWidth || window.innerWidth - document.documentElement.clientWidth;
1414
+ }
1415
+ }
1416
+ WindowManager.initialized = false;
1417
+ WindowManager.subscribers = new Set();
1418
+ WindowManager.lastScrollY = 0;
1419
+ WindowManager.lastWidth = 0;
1420
+ WindowManager.lastHeight = 0;
1421
+ WindowManager.ticking = false;
1422
+ // Body scroll lock (ref counting per modal nested)
1423
+ WindowManager.scrollLockCount = 0;
1424
+ WindowManager.scrollbarWidth = 0;
1425
+
1426
+ if (typeof window !== 'undefined') {
1427
+ window._itAnalytics = window._itAnalytics || {};
1428
+ window._itAnalytics = {
1429
+ ...window._itAnalytics,
1430
+ version: '1.0.0-alpha.5',
1431
+ };
1432
+ }
1433
+
1434
+ var styles = css`@charset "UTF-8";
1435
+ /***************************** 1 ****************************************/
1436
+ /***************************** 2 ****************************************/
1437
+ /***************************** 1 ****************************************/
1438
+ /***************************** 2 ****************************************/
1439
+ /***************************** 1 ****************************************/
1440
+ /***************************** 2 ****************************************/
1441
+ /***************************** 3 ****************************************/
1442
+ /***************************** 1 ****************************************/
1443
+ /***************************** 2 ****************************************/
1444
+ /***************************** 3 ****************************************/
1445
+ /***************************** NEUTRAL 1 ****************************************/
1446
+ /***************************** NEUTRAL 2 ****************************************/
1447
+ /***************************** NEUTRAL 2 / 3 ****************************************/
1448
+ .d-none {
1449
+ display: none !important;
1450
+ }
1451
+
1452
+ .d-block {
1453
+ display: block !important;
1454
+ }
1455
+
1456
+ .d-flex {
1457
+ display: flex !important;
1458
+ }
1459
+
1460
+ .overflow-auto {
1461
+ overflow: auto !important;
1462
+ }
1463
+
1464
+ .overflow-hidden {
1465
+ overflow: hidden !important;
1466
+ }
1467
+
1468
+ @media (min-width: 576px) {
1469
+ .d-sm-none {
1470
+ display: none !important;
1471
+ }
1472
+ .d-sm-block {
1473
+ display: block !important;
1474
+ }
1475
+ .d-sm-flex {
1476
+ display: flex !important;
1477
+ }
1478
+ }
1479
+ @media (min-width: 768px) {
1480
+ .d-md-none {
1481
+ display: none !important;
1482
+ }
1483
+ .d-md-block {
1484
+ display: block !important;
1485
+ }
1486
+ .d-md-flex {
1487
+ display: flex !important;
1488
+ }
1489
+ }
1490
+ @media (min-width: 992px) {
1491
+ .d-lg-none {
1492
+ display: none !important;
1493
+ }
1494
+ .d-lg-block {
1495
+ display: block !important;
1496
+ }
1497
+ .d-lg-flex {
1498
+ display: flex !important;
1499
+ }
1500
+ }
1501
+ @media (min-width: 1200px) {
1502
+ .d-xl-none {
1503
+ display: none !important;
1504
+ }
1505
+ .d-xl-block {
1506
+ display: block !important;
1507
+ }
1508
+ .d-xl-flex {
1509
+ display: flex !important;
1510
+ }
1511
+ }
1512
+ @media (min-width: 1400px) {
1513
+ .d-xxl-none {
1514
+ display: none !important;
1515
+ }
1516
+ .d-xxl-block {
1517
+ display: block !important;
1518
+ }
1519
+ .d-xxl-flex {
1520
+ display: flex !important;
1521
+ }
1522
+ }
1523
+ @media print {
1524
+ .d-print-none {
1525
+ display: none !important;
1526
+ }
1527
+ .d-print-block {
1528
+ display: block !important;
1529
+ }
1530
+ .d-print-flex {
1531
+ display: flex !important;
1532
+ }
1533
+ }
1534
+ .modal {
1535
+ --bsi-modal-bg: var(--bsi-color-background-inverse);
1536
+ --bsi-modal-border-color: transparent;
1537
+ --bsi-modal-border-radius: var(--bsi-radius-smooth);
1538
+ --bsi-modal-border-width: 0;
1539
+ --bsi-modal-box-shadow: var(--bsi-elevation-medium);
1540
+ --bsi-modal-footer-bg: transparent;
1541
+ --bsi-modal-footer-border-color: var(--bsi-modal-header-border-color);
1542
+ --bsi-modal-footer-border-width: var(--bsi-modal-header-border-width);
1543
+ --bsi-modal-footer-gap: var(--bsi-spacing-s);
1544
+ --bsi-modal-header-border-color: var(--bsi-color-border-subtle);
1545
+ --bsi-modal-header-border-width: 0;
1546
+ --bsi-modal-inner-border-radius: var(--bsi-radius-smooth);
1547
+ --bsi-modal-margin: auto;
1548
+ --bsi-modal-padding: var(--bsi-spacing-m);
1549
+ --bsi-modal-title-font-size: var(--bsi-heading-5-font-size);
1550
+ --bsi-modal-title-font-weight: var(--bsi-heading-font-weight-weak);
1551
+ --bsi-modal-title-line-height: var(--bsi-heading-line-height);
1552
+ --bsi-modal-transition: transform 0.3s ease-in-out;
1553
+ --bsi-modal-width: 500px;
1554
+ --bsi-modal-zindex: 1055;
1555
+ }
1556
+
1557
+ .modal-dialog {
1558
+ position: relative;
1559
+ width: auto;
1560
+ margin: var(--bsi-modal-margin);
1561
+ pointer-events: none;
1562
+ }
1563
+ .modal.show .modal-dialog {
1564
+ transform: none;
1565
+ }
1566
+ .modal.modal-static .modal-dialog {
1567
+ transform: scale(1.02);
1568
+ }
1569
+
1570
+ .modal-dialog-scrollable {
1571
+ height: calc(100% - var(--bsi-modal-margin) * 2);
1572
+ }
1573
+ .modal-dialog-scrollable .modal-content {
1574
+ max-height: 100%;
1575
+ overflow: hidden;
1576
+ }
1577
+ .modal-dialog-scrollable .modal-body {
1578
+ overflow-y: auto;
1579
+ }
1580
+
1581
+ .modal-dialog-centered {
1582
+ display: flex;
1583
+ align-items: center;
1584
+ min-height: calc(100% - var(--bsi-modal-margin) * 2);
1585
+ }
1586
+
1587
+ .modal-body {
1588
+ position: relative;
1589
+ flex: 1 1 auto;
1590
+ padding: var(--bsi-modal-padding);
1591
+ color: var(--bsi-color-text-base);
1592
+ }
1593
+
1594
+ .modal-content {
1595
+ position: relative;
1596
+ display: flex;
1597
+ flex-direction: column;
1598
+ width: 100%;
1599
+ border: var(--bsi-modal-border-width) solid var(--bsi-modal-border-color);
1600
+ outline: 0;
1601
+ background-color: var(--bsi-modal-bg);
1602
+ pointer-events: auto;
1603
+ background-clip: padding-box;
1604
+ border-radius: var(--bsi-modal-border-radius);
1605
+ }
1606
+
1607
+ .modal-backdrop {
1608
+ --bsi-backdrop-zindex: 1050;
1609
+ --bsi-backdrop-bg: hsl(0, 0%, 0%);
1610
+ --bsi-backdrop-opacity: 0.8;
1611
+ position: fixed;
1612
+ top: 0;
1613
+ left: 0;
1614
+ z-index: var(--bsi-backdrop-zindex);
1615
+ width: 100vw;
1616
+ height: 100vh;
1617
+ background-color: var(--bsi-backdrop-bg);
1618
+ }
1619
+ .modal-backdrop.fade {
1620
+ opacity: 0;
1621
+ }
1622
+ .modal-backdrop.show {
1623
+ opacity: var(--bsi-backdrop-opacity);
1624
+ }
1625
+
1626
+ .modal-header {
1627
+ display: flex;
1628
+ flex-shrink: 0;
1629
+ align-items: center;
1630
+ justify-content: space-between;
1631
+ padding: var(--bsi-modal-padding) var(--bsi-modal-padding) 0;
1632
+ border-bottom: var(--bsi-modal-header-border-width) solid var(--bsi-modal-header-border-color);
1633
+ }
1634
+
1635
+ .modal-footer {
1636
+ position: relative;
1637
+ display: flex;
1638
+ flex-shrink: 0;
1639
+ flex-wrap: wrap;
1640
+ gap: var(--bsi-modal-footer-gap);
1641
+ align-items: center;
1642
+ justify-content: flex-end;
1643
+ padding: 0 var(--bsi-modal-padding) var(--bsi-modal-padding);
1644
+ border-top: var(--bsi-modal-footer-border-width) solid var(--bsi-modal-footer-border-color);
1645
+ background-color: var(--bsi-modal-footer-bg);
1646
+ border-bottom-right-radius: var(--bsi-modal-border-radius);
1647
+ border-bottom-left-radius: var(--bsi-modal-border-radius);
1648
+ }
1649
+ .modal-footer.modal-footer-shadow {
1650
+ box-shadow: 0 15px 25px 5px rgba(0, 0, 0, 0.3);
1651
+ }
1652
+
1653
+ .modal-title {
1654
+ margin-bottom: 0;
1655
+ font-size: var(--bsi-modal-title-font-size);
1656
+ font-weight: var(--bsi-modal-title-font-weight);
1657
+ line-height: var(--bsi-modal-title-line-height);
1658
+ }
1659
+
1660
+ @media (min-width: 576px) {
1661
+ .modal {
1662
+ --bsi-modal-margin: 1.5rem;
1663
+ --bsi-modal-box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
1664
+ }
1665
+ .modal-dialog {
1666
+ max-width: var(--bsi-modal-width);
1667
+ }
1668
+ .modal-sm {
1669
+ --bsi-modal-width: 300px;
1670
+ }
1671
+ }
1672
+ @media (min-width: 992px) {
1673
+ .modal-lg,
1674
+ .modal-xl {
1675
+ --bsi-modal-width: 800px;
1676
+ }
1677
+ }
1678
+ @media (min-width: 1200px) {
1679
+ .modal-xl {
1680
+ --bsi-modal-width: 1140px;
1681
+ }
1682
+ }
1683
+ .modal-fullscreen {
1684
+ width: 100vw;
1685
+ max-width: none;
1686
+ height: 100%;
1687
+ margin: 0;
1688
+ }
1689
+ .modal-fullscreen .modal-content {
1690
+ height: 100%;
1691
+ border: 0;
1692
+ border-radius: 0;
1693
+ }
1694
+ .modal-fullscreen .modal-header,
1695
+ .modal-fullscreen .modal-footer {
1696
+ border-radius: 0;
1697
+ }
1698
+ .modal-fullscreen .modal-body {
1699
+ overflow-y: auto;
1700
+ }
1701
+
1702
+ @media (max-width: 575.98px) {
1703
+ .modal-fullscreen-sm-down {
1704
+ width: 100vw;
1705
+ max-width: none;
1706
+ height: 100%;
1707
+ margin: 0;
1708
+ }
1709
+ .modal-fullscreen-sm-down .modal-content {
1710
+ height: 100%;
1711
+ border: 0;
1712
+ border-radius: 0;
1713
+ }
1714
+ .modal-fullscreen-sm-down .modal-header,
1715
+ .modal-fullscreen-sm-down .modal-footer {
1716
+ border-radius: 0;
1717
+ }
1718
+ .modal-fullscreen-sm-down .modal-body {
1719
+ overflow-y: auto;
1720
+ }
1721
+ }
1722
+ @media (max-width: 767.98px) {
1723
+ .modal-fullscreen-md-down {
1724
+ width: 100vw;
1725
+ max-width: none;
1726
+ height: 100%;
1727
+ margin: 0;
1728
+ }
1729
+ .modal-fullscreen-md-down .modal-content {
1730
+ height: 100%;
1731
+ border: 0;
1732
+ border-radius: 0;
1733
+ }
1734
+ .modal-fullscreen-md-down .modal-header,
1735
+ .modal-fullscreen-md-down .modal-footer {
1736
+ border-radius: 0;
1737
+ }
1738
+ .modal-fullscreen-md-down .modal-body {
1739
+ overflow-y: auto;
1740
+ }
1741
+ }
1742
+ @media (max-width: 991.98px) {
1743
+ .modal-fullscreen-lg-down {
1744
+ width: 100vw;
1745
+ max-width: none;
1746
+ height: 100%;
1747
+ margin: 0;
1748
+ }
1749
+ .modal-fullscreen-lg-down .modal-content {
1750
+ height: 100%;
1751
+ border: 0;
1752
+ border-radius: 0;
1753
+ }
1754
+ .modal-fullscreen-lg-down .modal-header,
1755
+ .modal-fullscreen-lg-down .modal-footer {
1756
+ border-radius: 0;
1757
+ }
1758
+ .modal-fullscreen-lg-down .modal-body {
1759
+ overflow-y: auto;
1760
+ }
1761
+ }
1762
+ @media (max-width: 1199.98px) {
1763
+ .modal-fullscreen-xl-down {
1764
+ width: 100vw;
1765
+ max-width: none;
1766
+ height: 100%;
1767
+ margin: 0;
1768
+ }
1769
+ .modal-fullscreen-xl-down .modal-content {
1770
+ height: 100%;
1771
+ border: 0;
1772
+ border-radius: 0;
1773
+ }
1774
+ .modal-fullscreen-xl-down .modal-header,
1775
+ .modal-fullscreen-xl-down .modal-footer {
1776
+ border-radius: 0;
1777
+ }
1778
+ .modal-fullscreen-xl-down .modal-body {
1779
+ overflow-y: auto;
1780
+ }
1781
+ }
1782
+ @media (max-width: 1399.98px) {
1783
+ .modal-fullscreen-xxl-down {
1784
+ width: 100vw;
1785
+ max-width: none;
1786
+ height: 100%;
1787
+ margin: 0;
1788
+ }
1789
+ .modal-fullscreen-xxl-down .modal-content {
1790
+ height: 100%;
1791
+ border: 0;
1792
+ border-radius: 0;
1793
+ }
1794
+ .modal-fullscreen-xxl-down .modal-header,
1795
+ .modal-fullscreen-xxl-down .modal-footer {
1796
+ border-radius: 0;
1797
+ }
1798
+ .modal-fullscreen-xxl-down .modal-body {
1799
+ overflow-y: auto;
1800
+ }
1801
+ }
1802
+ /* stylelint-disable-next-line no-duplicate-selectors */
1803
+ .modal {
1804
+ position: fixed;
1805
+ top: 0;
1806
+ left: 0;
1807
+ z-index: var(--bsi-modal-zindex);
1808
+ display: none;
1809
+ width: 100%;
1810
+ height: 100%;
1811
+ padding-right: 0 !important;
1812
+ overflow-x: hidden;
1813
+ overflow-y: auto;
1814
+ outline: 0;
1815
+ }
1816
+ .modal.alert-modal .modal-dialog .modal-content .modal-header {
1817
+ align-items: start;
1818
+ justify-content: left;
1819
+ }
1820
+ .modal.alert-modal .modal-dialog .modal-content .modal-header .icon {
1821
+ flex-shrink: 0;
1822
+ margin-right: 16px;
1823
+ fill: hsl(210, 100%, 40%);
1824
+ }
1825
+ .modal.it-dialog-link-list .modal-dialog .modal-content .modal-header {
1826
+ --bsi-modal-header-border-color: var(--bsi-color-border-subtle);
1827
+ --bsi-modal-header-border-width: 1px;
1828
+ padding-bottom: var(--bsi-modal-padding);
1829
+ }
1830
+ .modal.it-dialog-link-list .modal-dialog .modal-content .modal-body .link-list-wrapper .link-list {
1831
+ margin-bottom: 0;
1832
+ padding-bottom: var(--bsi-modal-padding);
1833
+ }
1834
+ .modal.popconfirm-modal .modal-dialog {
1835
+ margin-right: auto;
1836
+ margin-left: auto;
1837
+ }
1838
+ .modal.popconfirm-modal .modal-dialog .modal-body p {
1839
+ font-size: var(--bsi-caption-font-size);
1840
+ line-height: var(--bsi-caption-line-height);
1841
+ }
1842
+ .modal.popconfirm-modal .modal-dialog .modal-footer {
1843
+ justify-content: flex-start;
1844
+ }
1845
+ .modal.it-dialog-scrollable .modal-dialog .modal-content {
1846
+ display: flex;
1847
+ flex-direction: column;
1848
+ height: calc(100vh - 208px);
1849
+ border-radius: 0;
1850
+ }
1851
+ .modal.it-dialog-scrollable .modal-dialog .modal-content .modal-header {
1852
+ flex-shrink: 0;
1853
+ padding-bottom: var(--bsi-modal-padding);
1854
+ }
1855
+ .modal.it-dialog-scrollable .modal-dialog .modal-content .modal-body {
1856
+ padding-top: 0;
1857
+ overflow-y: auto;
1858
+ }
1859
+ .modal.it-dialog-scrollable .modal-dialog .modal-content .modal-footer {
1860
+ padding-top: var(--bsi-modal-padding);
1861
+ flex-shrink: 0;
1862
+ }
1863
+ .modal.it-dialog-scrollable .modal-dialog.modal-dialog-left {
1864
+ height: 100vh;
1865
+ margin: 0 var(--bsi-spacing-m) 0 0;
1866
+ }
1867
+ .modal.it-dialog-scrollable .modal-dialog.modal-dialog-left .modal-content {
1868
+ height: 100vh;
1869
+ }
1870
+ .modal.it-dialog-scrollable .modal-dialog.modal-dialog-right {
1871
+ height: 100vh;
1872
+ margin: 0 0 0 var(--bsi-spacing-m);
1873
+ float: right;
1874
+ }
1875
+ .modal.it-dialog-scrollable .modal-dialog.modal-dialog-right .modal-content {
1876
+ height: 100vh;
1877
+ }
1878
+ .modal.fade .modal-dialog {
1879
+ transition: var(--bsi-modal-transition);
1880
+ }
1881
+ @media (prefers-reduced-motion: reduce) {
1882
+ .modal.fade .modal-dialog {
1883
+ transition: none;
1884
+ }
1885
+ }
1886
+ .modal.fade .modal-dialog.modal-dialog-left {
1887
+ transform: translateX(-100%);
1888
+ transition: transform 0.3s ease-in-out;
1889
+ }
1890
+ .modal.fade .modal-dialog.modal-dialog-right {
1891
+ transform: translateX(100%);
1892
+ transition: transform 0.3s ease-in-out;
1893
+ }
1894
+ .modal.fade .modal-dialog.modal-dialog-centered {
1895
+ transform: translate(0, -5%);
1896
+ }
1897
+ .modal.fade.show .modal-dialog.modal-dialog-left {
1898
+ transform: translateX(0);
1899
+ }
1900
+ .modal.fade.show .modal-dialog.modal-dialog-right {
1901
+ transform: translateX(0);
1902
+ }
1903
+ .modal.fade.show .modal-dialog.modal-dialog-centered {
1904
+ transform: translate(0, 0);
1905
+ }
1906
+
1907
+ @media (min-width: 768px) {
1908
+ .modal .modal-dialog {
1909
+ margin-right: auto;
1910
+ margin-left: auto;
1911
+ }
1912
+ .modal .modal-dialog.modal-dialog-left {
1913
+ margin: 0;
1914
+ }
1915
+ .modal .modal-dialog.modal-dialog-left .modal-content {
1916
+ height: 100vh;
1917
+ }
1918
+ .modal .modal-dialog.modal-dialog-right {
1919
+ margin: 0;
1920
+ float: right;
1921
+ }
1922
+ .modal .modal-dialog.modal-dialog-right .modal-content {
1923
+ height: 100vh;
1924
+ }
1925
+ .modal.it-dialog-scrollable .modal-dialog {
1926
+ margin: 64px auto;
1927
+ }
1928
+ .modal.it-dialog-scrollable .modal-dialog .modal-content {
1929
+ height: calc(100vh - 128px);
1930
+ }
1931
+ }
1932
+ body {
1933
+ font-family: var(--bsi-font-sans);
1934
+ }
1935
+
1936
+ p,
1937
+ ul,
1938
+ ol,
1939
+ dl {
1940
+ font-size: var(--bsi-body-font-size);
1941
+ line-height: var(--bsi-body-line-height);
1942
+ }
1943
+
1944
+ caption,
1945
+ figcaption {
1946
+ font-size: var(--bsi-caption-font-size);
1947
+ line-height: var(--bsi-caption-line-height);
1948
+ }
1949
+
1950
+ b,
1951
+ strong {
1952
+ font-weight: var(--bsi-font-weight-strong);
1953
+ }
1954
+
1955
+ mark,
1956
+ code {
1957
+ padding: 0 var(--bsi-spacing-3xs);
1958
+ }
1959
+
1960
+ mark {
1961
+ background-color: var(--bsi-highlight-background);
1962
+ }
1963
+
1964
+ pre,
1965
+ code,
1966
+ kbd,
1967
+ samp {
1968
+ border-radius: var(--bsi-radius-smooth);
1969
+ font-family: var(--bsi-font-mono);
1970
+ }
1971
+
1972
+ ins,
1973
+ del {
1974
+ position: relative;
1975
+ display: flex;
1976
+ align-items: center;
1977
+ padding: var(--bsi-spacing-3xs) var(--bsi-spacing-m);
1978
+ font: var(--bsi-body-font-size);
1979
+ text-decoration: none;
1980
+ }
1981
+
1982
+ ins {
1983
+ background-color: var(--bsi-ins-background);
1984
+ text-decoration: none;
1985
+ }
1986
+
1987
+ del {
1988
+ background-color: var(--bsi-del-background);
1989
+ }
1990
+
1991
+ del::before,
1992
+ ins::before {
1993
+ position: absolute;
1994
+ left: 0.5rem;
1995
+ }
1996
+
1997
+ del::before {
1998
+ content: "−";
1999
+ }
2000
+
2001
+ ins::before {
2002
+ content: "+";
2003
+ }
2004
+
2005
+ kbd {
2006
+ margin: 0 2px;
2007
+ padding: 2px var(--bsi-spacing-3xs);
2008
+ border: var(--bsi-border-base) solid var(--bsi-color-border-subtle);
2009
+ background-color: var(--bsi-color-background-secondary-lighter);
2010
+ box-shadow: var(--bsi-elevation-low), 0 2px 0 0 hsla(255, 0%, 100%, 0.7) inset;
2011
+ color: var(--bsi-color-text-secondary);
2012
+ font-size: var(--bsi-font-size-1);
2013
+ font-weight: var(--bsi-font-weight-solid);
2014
+ white-space: nowrap;
2015
+ }
2016
+ kbd kbd {
2017
+ padding: 0;
2018
+ font-size: var(--bsi-code-font-size);
2019
+ }
2020
+
2021
+ small,
2022
+ .small {
2023
+ font-size: var(--bsi-caption-font-size);
2024
+ }
2025
+
2026
+ .x-small {
2027
+ font-size: var(--bsi-font-size-1);
2028
+ }
2029
+
2030
+ h1,
2031
+ .h1 {
2032
+ font-size: var(--bsi-heading-1-font-size);
2033
+ }
2034
+
2035
+ h2,
2036
+ .h2 {
2037
+ font-size: var(--bsi-heading-2-font-size);
2038
+ }
2039
+
2040
+ h3,
2041
+ .h3 {
2042
+ font-size: var(--bsi-heading-3-font-size);
2043
+ }
2044
+
2045
+ h4,
2046
+ .h4 {
2047
+ font-size: var(--bsi-heading-4-font-size);
2048
+ }
2049
+
2050
+ h5,
2051
+ .h5 {
2052
+ font-size: var(--bsi-heading-5-font-size);
2053
+ }
2054
+
2055
+ h6,
2056
+ .h6 {
2057
+ font-size: var(--bsi-heading-6-font-size);
2058
+ }
2059
+
2060
+ h1,
2061
+ .h1,
2062
+ h2,
2063
+ .h2,
2064
+ h3,
2065
+ .h3,
2066
+ h4,
2067
+ .h4,
2068
+ h5,
2069
+ .h5,
2070
+ h6,
2071
+ .h6 {
2072
+ margin-top: 0;
2073
+ margin-bottom: var(--bsi-heading-spacing);
2074
+ line-height: var(--bsi-heading-line-height);
2075
+ }
2076
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + h1, p + h1,
2077
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + .h1,
2078
+ p + .h1,
2079
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + h2,
2080
+ p + h2,
2081
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + .h2,
2082
+ p + .h2,
2083
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + h3,
2084
+ p + h3,
2085
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + .h3,
2086
+ p + .h3,
2087
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + h4,
2088
+ p + h4,
2089
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + .h4,
2090
+ p + .h4,
2091
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + h5,
2092
+ p + h5,
2093
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + .h5,
2094
+ p + .h5,
2095
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + h6,
2096
+ p + h6,
2097
+ :is(h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6) + .h6,
2098
+ p + .h6 {
2099
+ padding-top: var(--bsi-spacing-s);
2100
+ }
2101
+
2102
+ h1,
2103
+ h2,
2104
+ h3,
2105
+ .h1,
2106
+ .h2,
2107
+ .h3 {
2108
+ font-weight: var(--bsi-heading-font-weight);
2109
+ }
2110
+
2111
+ h4,
2112
+ h5,
2113
+ h6,
2114
+ .h4,
2115
+ .h5,
2116
+ .h6 {
2117
+ font-weight: var(--bsi-heading-font-weight-weak);
2118
+ }
2119
+
2120
+ h1,
2121
+ .h1,
2122
+ .display-1 {
2123
+ letter-spacing: -1px;
2124
+ }
2125
+
2126
+ .font-serif {
2127
+ font-family: var(--bsi-font-serif) !important;
2128
+ }
2129
+
2130
+ .font-sans-serif {
2131
+ font-family: var(--bsi-font-sans) !important;
2132
+ }
2133
+
2134
+ .font-monospace {
2135
+ font-family: var(--bsi-font-mono) !important;
2136
+ }
2137
+
2138
+ .display-1 {
2139
+ font-size: var(--bsi-display-font-size);
2140
+ font-weight: var(--bsi-heading-font-weight);
2141
+ line-height: var(--bsi-heading-line-height);
2142
+ }
2143
+
2144
+ .lead {
2145
+ font-size: var(--bsi-lead-font-size);
2146
+ font-weight: var(--bsi-lead-font-weight);
2147
+ line-height: var(--bsi-lead-line-height);
2148
+ }
2149
+
2150
+ blockquote,
2151
+ .blockquote {
2152
+ margin: var(--bsi-spacing-m) 0;
2153
+ margin-left: var(--bsi-spacin-inline-xs);
2154
+ padding: var(--bsi-spacing-s);
2155
+ border-left: var(--bsi-border-thick) solid var(--bsi-border-color-secondary);
2156
+ font-size: var(--bsi-body-font-size);
2157
+ line-height: var(--bsi-body-line-height);
2158
+ }
2159
+ blockquote > :last-child,
2160
+ .blockquote > :last-child {
2161
+ margin-bottom: 0;
2162
+ }
2163
+ blockquote.text-end,
2164
+ .blockquote.text-end {
2165
+ margin-right: var(--bsi-spacin-inline-xs);
2166
+ border-right: var(--bsi-border-thick) solid var(--bsi-border-color-secondary);
2167
+ }
2168
+ blockquote.text-center, blockquote.text-end, blockquote.blockquote-simple,
2169
+ .blockquote.text-center,
2170
+ .blockquote.text-end,
2171
+ .blockquote.blockquote-simple {
2172
+ margin-left: 0;
2173
+ border-right: none;
2174
+ border-left: none;
2175
+ }
2176
+ blockquote.text-center, blockquote.blockquote-simple,
2177
+ .blockquote.text-center,
2178
+ .blockquote.blockquote-simple {
2179
+ padding: 0;
2180
+ }
2181
+ blockquote.blockquote-simple,
2182
+ .blockquote.blockquote-simple {
2183
+ font-style: italic;
2184
+ }
2185
+ blockquote.blockquote-card,
2186
+ .blockquote.blockquote-card {
2187
+ margin-left: 0;
2188
+ padding: var(--bsi-spacing-m);
2189
+ background-color: var(--bsi-color-background-inverse);
2190
+ box-shadow: var(--bsi-elevation-low);
2191
+ }
2192
+ blockquote.blockquote-card .blockquote-footer,
2193
+ .blockquote.blockquote-card .blockquote-footer {
2194
+ font-size: inherit;
2195
+ }
2196
+ blockquote.blockquote-card .blockquote-footer:before,
2197
+ .blockquote.blockquote-card .blockquote-footer:before {
2198
+ content: none;
2199
+ }
2200
+ blockquote.blockquote-card.dark,
2201
+ .blockquote.blockquote-card.dark {
2202
+ border-left: none;
2203
+ background-color: var(--bsi-color-background-primary);
2204
+ color: var(--bsi-color-text-inverse);
2205
+ }
2206
+ blockquote.blockquote-card.dark .blockquote-footer,
2207
+ .blockquote.blockquote-card.dark .blockquote-footer {
2208
+ color: var(--bsi-color-text-inverse);
2209
+ }
2210
+
2211
+ .blockquote-footer {
2212
+ margin-top: 0;
2213
+ margin-bottom: var(--bsi-spacing-s);
2214
+ color: var(--bsi-color-text-secondary);
2215
+ font-size: var(--bsi-label-font-size);
2216
+ }
2217
+ .blockquote-footer::before {
2218
+ content: "— ";
2219
+ }
2220
+ .bg-dark .blockquote-footer {
2221
+ color: var(--bsi-color-text-muted);
2222
+ }
2223
+
2224
+ .initialism {
2225
+ font-size: var(--bsi-label-font-size-s);
2226
+ text-transform: uppercase;
2227
+ }
2228
+
2229
+ .visually-hidden,
2230
+ .visually-hidden-focusable:not(:focus):not(:focus-within) {
2231
+ position: absolute !important;
2232
+ width: 1px !important;
2233
+ height: 1px !important;
2234
+ padding: 0 !important;
2235
+ margin: -1px !important;
2236
+ overflow: hidden !important;
2237
+ clip: rect(0, 0, 0, 0) !important;
2238
+ white-space: nowrap !important;
2239
+ border: 0 !important;
2240
+ }
2241
+
2242
+ :host {
2243
+ display: block;
2244
+ }
2245
+
2246
+ :host(:not([open])) .modal,
2247
+ :host(:not([open])) .modal-backdrop {
2248
+ display: none !important;
2249
+ }
2250
+
2251
+ .modal-backdrop {
2252
+ position: fixed;
2253
+ z-index: 1050;
2254
+ top: 0;
2255
+ left: 0;
2256
+ width: 100vw;
2257
+ height: 100vh;
2258
+ background-color: hsl(0, 0%, 0%);
2259
+ }
2260
+
2261
+ .modal {
2262
+ position: fixed;
2263
+ z-index: 1055;
2264
+ top: 0;
2265
+ left: 0;
2266
+ display: flex;
2267
+ width: 100%;
2268
+ height: 100%;
2269
+ outline: 0;
2270
+ overflow-x: hidden;
2271
+ overflow-y: auto;
2272
+ }
2273
+
2274
+ .it-dialog-scrollable {
2275
+ overflow-y: hidden;
2276
+ }
2277
+
2278
+ .modal-dialog {
2279
+ height: fit-content;
2280
+ }
2281
+ @media (min-width: 768px) {
2282
+ .modal-dialog {
2283
+ margin: 64px auto;
2284
+ }
2285
+ }
2286
+
2287
+ .modal-footer {
2288
+ flex-shrink: 0;
2289
+ padding-top: var(--bsi-modal-padding);
2290
+ }
2291
+
2292
+ .modal-dialog-scrollable {
2293
+ height: unset;
2294
+ }
2295
+
2296
+ .modal-dialog-centered {
2297
+ min-height: unset;
2298
+ margin: auto;
2299
+ }
2300
+
2301
+ .modal.alert-modal .modal-dialog .modal-content .modal-header {
2302
+ align-items: center;
2303
+ justify-content: space-between;
2304
+ gap: var(--it-spacing-2x);
2305
+ }
2306
+
2307
+ .modal.it-dialog-scrollable .modal-dialog.modal-dialog-right {
2308
+ position: fixed;
2309
+ right: 0;
2310
+ }`;
2311
+
2312
+ /**
2313
+ * Componente Modal per finestre di dialogo modali.
2314
+ *
2315
+ * @element it-modal
2316
+ *
2317
+ * @slot trigger - Elemento che apre la modale (es. it-button)
2318
+ * @slot content - Contenuto principale della modale (body)
2319
+ * @slot header-icon - Icona opzionale nell'header
2320
+ * @slot footer - Azioni del footer (pulsanti)
2321
+ *
2322
+ * @fires it-modal-open - Quando la modale si apre
2323
+ * @fires it-modal-close - Quando la modale si chiude
2324
+ */
2325
+ let ItModal = class ItModal extends BaseComponent {
2326
+ get _triggerElement() {
2327
+ if (!this._triggerSlot) {
2328
+ this.logger.error('No trigger provided');
2329
+ return null;
2330
+ }
2331
+ const elements = this._triggerSlot.assignedElements({ flatten: true });
2332
+ if (elements.length === 0) {
2333
+ return null;
2334
+ }
2335
+ return elements[0];
2336
+ }
2337
+ constructor() {
2338
+ super();
2339
+ this.open = false;
2340
+ this.modalTitle = '';
2341
+ this.modalDescription = '';
2342
+ this.size = '';
2343
+ this.scrollable = false;
2344
+ this.staticBackdrop = false;
2345
+ this.hideCloseButton = false;
2346
+ this.itAriaLabel = '';
2347
+ this.closeLabel = '';
2348
+ this.disableAnimation = false;
2349
+ this.footerShadow = false;
2350
+ this._titleId = '';
2351
+ this._triggerId = '';
2352
+ this._descriptionId = '';
2353
+ this.isAnimating = false;
2354
+ this._dialogAnimationDuration = 300; // ms - matches Bootstrap Italia modal-transition
2355
+ this._backdropAnimationDuration = 150; // ms - standard fade
2356
+ this._focusTrap = new FocusTrapController(this, {
2357
+ getContainer: () => this._modalElement,
2358
+ initialFocus: () => this._modalElement,
2359
+ getTrigger: () => this._triggerElement,
2360
+ onEscape: () => {
2361
+ this.hide();
2362
+ },
2363
+ disableEscape: false,
2364
+ });
2365
+ this._onTriggerSlotChange = () => {
2366
+ this._setupTriggerListeners();
2367
+ };
2368
+ this._onHeaderSlotChange = () => {
2369
+ this.requestUpdate();
2370
+ };
2371
+ this._onTriggerClick = (event) => {
2372
+ event.stopPropagation();
2373
+ this.show();
2374
+ };
2375
+ this._onTriggerKeydown = (event) => {
2376
+ if (event.key === 'Enter' || event.key === ' ') {
2377
+ event.preventDefault();
2378
+ this.show();
2379
+ }
2380
+ };
2381
+ this._handleCloseClick = () => {
2382
+ this.hide();
2383
+ };
2384
+ this._handleBackdropClick = () => {
2385
+ if (!this.staticBackdrop) {
2386
+ this.hide();
2387
+ }
2388
+ };
2389
+ // eslint-disable-next-line class-methods-use-this
2390
+ this._handleDialogClick = (event) => {
2391
+ const path = event.composedPath();
2392
+ // Check that is not footer or react synthetic events break on buttons
2393
+ const isInFooter = path.some((el) => el instanceof HTMLElement && el.slot === 'footer');
2394
+ if (!isInFooter) {
2395
+ event.stopPropagation(); // solo per backdrop
2396
+ }
2397
+ };
2398
+ this._triggerId = this.generateId('modal-trigger');
2399
+ this._titleId = this.generateId('modal-title');
2400
+ this._descriptionId = this.generateId('modal-description');
2401
+ }
2402
+ connectedCallback() {
2403
+ super.connectedCallback?.();
2404
+ }
2405
+ disconnectedCallback() {
2406
+ super.disconnectedCallback?.();
2407
+ this._removeTriggerListeners();
2408
+ this._cleanupAnimations();
2409
+ WindowManager.unlockBodyScroll();
2410
+ }
2411
+ updated(changedProperties) {
2412
+ if (changedProperties.has('open')) {
2413
+ // Cancel any ongoing animations before starting new ones
2414
+ this._cleanupAnimations();
2415
+ if (this.open) {
2416
+ this._showModal();
2417
+ }
2418
+ else {
2419
+ this._hideModal();
2420
+ }
2421
+ }
2422
+ }
2423
+ _setupTriggerListeners() {
2424
+ const trigger = this._triggerElement;
2425
+ if (!trigger)
2426
+ return;
2427
+ trigger.setAttribute('id', this._triggerId);
2428
+ // Rimuovi eventuali listener precedenti
2429
+ trigger.removeEventListener('click', this._onTriggerClick);
2430
+ trigger.removeEventListener('keydown', this._onTriggerKeydown);
2431
+ // Aggiungi nuovi listener
2432
+ trigger.addEventListener('click', this._onTriggerClick);
2433
+ trigger.addEventListener('keydown', this._onTriggerKeydown);
2434
+ }
2435
+ _removeTriggerListeners() {
2436
+ const trigger = this._triggerElement;
2437
+ if (!trigger)
2438
+ return;
2439
+ trigger.removeEventListener('click', this._onTriggerClick);
2440
+ trigger.removeEventListener('keydown', this._onTriggerKeydown);
2441
+ }
2442
+ show() {
2443
+ if (this.open || this.isAnimating)
2444
+ return;
2445
+ this.open = true;
2446
+ }
2447
+ hide() {
2448
+ if (!this.open || this.isAnimating)
2449
+ return;
2450
+ this._hideModal();
2451
+ }
2452
+ toggle() {
2453
+ this.open = !this.open;
2454
+ }
2455
+ _showModal() {
2456
+ if (this.isAnimating)
2457
+ return;
2458
+ this.isAnimating = true;
2459
+ // Deactivate focus trap first if it was active
2460
+ this._focusTrap.deactivate();
2461
+ WindowManager.lockBodyScroll();
2462
+ requestAnimationFrame(() => {
2463
+ // Determine transform based on position
2464
+ let dialogStartTransform = 'translate(0, 0)'; // default: no transform
2465
+ if (this.position === 'center') {
2466
+ dialogStartTransform = 'translate(0, -5%)';
2467
+ }
2468
+ else if (this.position === 'left') {
2469
+ dialogStartTransform = 'translateX(-100%)';
2470
+ }
2471
+ else if (this.position === 'right') {
2472
+ dialogStartTransform = 'translateX(100%)';
2473
+ }
2474
+ const dialogDuration = !this.disableAnimation && !this.prefersReducedMotion ? this._dialogAnimationDuration : 0;
2475
+ const backdropDuration = !this.disableAnimation && !this.prefersReducedMotion ? this._backdropAnimationDuration : 0;
2476
+ // Animate backdrop fade in
2477
+ if (this._backdropElement) {
2478
+ this._backdropAnimation = this._backdropElement.animate([{ opacity: '0' }, { opacity: '0.8' }], {
2479
+ duration: backdropDuration,
2480
+ easing: 'linear',
2481
+ fill: 'forwards',
2482
+ });
2483
+ }
2484
+ // Animate dialog transform (slide/drop in)
2485
+ if (this._dialogElement && dialogDuration > 0) {
2486
+ this._dialogAnimation = this._dialogElement.animate([{ transform: dialogStartTransform }, { transform: 'translate(0, 0)' }], {
2487
+ duration: dialogDuration,
2488
+ easing: 'ease-in-out',
2489
+ fill: 'forwards',
2490
+ });
2491
+ this._dialogAnimation.finished
2492
+ .then(() => {
2493
+ // Only activate focus trap if modal is still open
2494
+ if (this.open) {
2495
+ try {
2496
+ this._focusTrap.activate();
2497
+ }
2498
+ catch {
2499
+ // Swallow errors if focus trap fails
2500
+ }
2501
+ }
2502
+ })
2503
+ .catch(() => {
2504
+ // Animation cancelled or failed
2505
+ })
2506
+ .finally(() => {
2507
+ this.isAnimating = false;
2508
+ });
2509
+ }
2510
+ else {
2511
+ // No dialog element or no animation, just finish
2512
+ if (this.open) {
2513
+ try {
2514
+ this._focusTrap.activate();
2515
+ }
2516
+ catch {
2517
+ // Swallow errors if focus trap fails
2518
+ }
2519
+ }
2520
+ this.isAnimating = false;
2521
+ }
2522
+ });
2523
+ this.dispatchEvent(new CustomEvent('it-modal-open', {
2524
+ detail: { modal: this },
2525
+ bubbles: true,
2526
+ composed: true,
2527
+ }));
2528
+ }
2529
+ _hideModal() {
2530
+ if (this.isAnimating)
2531
+ return;
2532
+ this.isAnimating = true;
2533
+ // Deactivate focus trap immediately to prevent focus issues
2534
+ this._focusTrap.deactivate();
2535
+ // Determine end transform based on position
2536
+ let dialogEndTransform = 'translate(0, 0)'; // default: no transform
2537
+ let dialogCloseDuration = this._dialogAnimationDuration / 1.33;
2538
+ if (this.position === 'center') {
2539
+ dialogEndTransform = 'translate(0, -5%)';
2540
+ // Dialog più veloce quando è centrato per una chiusura più reattiva
2541
+ dialogCloseDuration = this._dialogAnimationDuration / 2;
2542
+ }
2543
+ else if (this.position === 'left') {
2544
+ dialogEndTransform = 'translateX(-100%)';
2545
+ }
2546
+ else if (this.position === 'right') {
2547
+ dialogEndTransform = 'translateX(100%)';
2548
+ }
2549
+ const dialogDuration = !this.disableAnimation && !this.prefersReducedMotion ? dialogCloseDuration : 0;
2550
+ const backdropDuration = !this.disableAnimation && !this.prefersReducedMotion ? this._backdropAnimationDuration / 1.33 : 0;
2551
+ const finishHide = () => {
2552
+ // Ensure focus trap is deactivated
2553
+ this._focusTrap.deactivate();
2554
+ this._cleanupAnimations();
2555
+ WindowManager.unlockBodyScroll();
2556
+ // Set open to false after animation completes
2557
+ this.open = false;
2558
+ };
2559
+ // Animate dialog and backdrop in parallel for smoother close
2560
+ const animations = [];
2561
+ if (this._dialogElement && dialogDuration > 0) {
2562
+ this._dialogAnimation = this._dialogElement.animate([
2563
+ { transform: 'translate(0, 0)', opacity: '1' },
2564
+ { transform: dialogEndTransform, opacity: '0' },
2565
+ ], {
2566
+ duration: dialogDuration,
2567
+ easing: 'ease-in',
2568
+ fill: 'forwards',
2569
+ });
2570
+ animations.push(this._dialogAnimation.finished);
2571
+ }
2572
+ if (this._backdropElement && backdropDuration > 0) {
2573
+ this._backdropAnimation = this._backdropElement.animate([{ opacity: '0.8' }, { opacity: '0' }], {
2574
+ duration: backdropDuration,
2575
+ easing: 'linear',
2576
+ fill: 'forwards',
2577
+ });
2578
+ animations.push(this._backdropAnimation.finished);
2579
+ }
2580
+ if (animations.length > 0) {
2581
+ Promise.all(animations)
2582
+ .then(() => finishHide())
2583
+ .catch(() => {
2584
+ // Animation was cancelled
2585
+ finishHide();
2586
+ })
2587
+ .finally(() => {
2588
+ this.isAnimating = false;
2589
+ });
2590
+ }
2591
+ else {
2592
+ // No animation, finish immediately
2593
+ finishHide();
2594
+ this.isAnimating = false;
2595
+ }
2596
+ this.dispatchEvent(new CustomEvent('it-modal-close', {
2597
+ detail: { modal: this },
2598
+ bubbles: true,
2599
+ composed: true,
2600
+ }));
2601
+ }
2602
+ _cleanupAnimations() {
2603
+ if (this._dialogAnimation) {
2604
+ try {
2605
+ this._dialogAnimation.cancel();
2606
+ }
2607
+ catch {
2608
+ /* ignore */
2609
+ }
2610
+ this._dialogAnimation = undefined;
2611
+ }
2612
+ if (this._backdropAnimation) {
2613
+ try {
2614
+ this._backdropAnimation.cancel();
2615
+ }
2616
+ catch {
2617
+ /* ignore */
2618
+ }
2619
+ this._backdropAnimation = undefined;
2620
+ }
2621
+ }
2622
+ get _modalClasses() {
2623
+ return {
2624
+ modal: true,
2625
+ fade: !this.disableAnimation,
2626
+ show: this.open && !this.disableAnimation,
2627
+ 'alert-modal': this.variant === 'alert',
2628
+ 'popconfirm-modal': this.variant === 'popconfirm',
2629
+ 'it-dialog-link-list': this.variant === 'link-list',
2630
+ 'it-dialog-scrollable': this.scrollable || this.position === 'left' || this.position === 'right',
2631
+ };
2632
+ }
2633
+ get _modalBodyClasses() {
2634
+ return {
2635
+ 'modal-dialog': true,
2636
+ 'modal-dialog-centered': this.position === 'center',
2637
+ 'modal-dialog-left': this.position === 'left',
2638
+ 'modal-dialog-right': this.position === 'right',
2639
+ 'modal-dialog-scrollable': this.scrollable,
2640
+ 'modal-sm': this.size === 'sm',
2641
+ 'modal-lg': this.size === 'lg',
2642
+ 'modal-xl': this.size === 'xl',
2643
+ };
2644
+ }
2645
+ render() {
2646
+ const hasHeader = this.modalTitle || this._headerSlot?.assignedElements({ flatten: true }).length > 0;
2647
+ const ariaLabelledBy = hasHeader ? this._titleId : undefined;
2648
+ const ariaLabel = !hasHeader ? this.itAriaLabel : undefined;
2649
+ const headerClass = hasHeader || (this.variant !== 'popconfirm' && !this.hideCloseButton) ? 'modal-header' : '';
2650
+ const hasDescription = this.modalDescription || this._descriptionSlot?.assignedElements({ flatten: true }).length > 0;
2651
+ const ariaDescribedBy = hasDescription ? this._descriptionId : undefined;
2652
+ const enableFocusContent = this.scrollable || this.position === 'left' || this.position === 'right';
2653
+ return html `
2654
+ <slot name="trigger" @slotchange=${this._onTriggerSlotChange}></slot>
2655
+
2656
+ <div
2657
+ class="${classMap(this._modalClasses)}"
2658
+ role="dialog"
2659
+ aria-modal="true"
2660
+ aria-labelledby="${ifDefined(ariaLabelledBy)}"
2661
+ aria-describedby="${ifDefined(ariaDescribedBy)}"
2662
+ aria-label="${ifDefined(ariaLabel)}"
2663
+ aria-hidden="${!this.open}"
2664
+ tabindex="-1"
2665
+ @click="${this._handleBackdropClick}"
2666
+ part="modal"
2667
+ >
2668
+ <div
2669
+ class="${classMap(this._modalBodyClasses)}"
2670
+ role="document"
2671
+ @click="${this._handleDialogClick}"
2672
+ part="modal-content-wrapper"
2673
+ >
2674
+ <div class="visually-hidden" id="${this._descriptionId}">
2675
+ <slot name="description" @slotchange="${this._onHeaderSlotChange}">${this.modalDescription}</slot>
2676
+ </div>
2677
+ <div class="modal-content" part="modal-content">
2678
+ <div class="${headerClass}" part="modal-header">
2679
+ <slot name="header-icon"></slot>
2680
+ <h2 id="${this._titleId}" class="modal-title">
2681
+ <slot name="header" @slotchange="${this._onHeaderSlotChange}">${this.modalTitle}</slot>
2682
+ </h2>
2683
+ ${!this.hideCloseButton && this.variant !== 'popconfirm'
2684
+ ? html `<it-button
2685
+ class="btn-close"
2686
+ variant="link"
2687
+ icon
2688
+ size="lg"
2689
+ exportparts="focusable, button"
2690
+ @click="${this._handleCloseClick}"
2691
+ >
2692
+ <it-icon name="it-close" size="lg"></it-icon>
2693
+ <span class="visually-hidden">${this.closeLabel}</span>
2694
+ </it-button>`
2695
+ : ''}
2696
+ </div>
2697
+
2698
+ <div class="modal-body" tabindex="${enableFocusContent ? '0' : '-1'}" part="focusable modal-body">
2699
+ <slot name="content"></slot>
2700
+ </div>
2701
+ <div class="modal-footer ${this.footerShadow ? 'modal-footer-shadow' : ''}" part="modal-footer">
2702
+ <slot name="footer"></slot>
2703
+ </div>
2704
+ </div>
2705
+ </div>
2706
+ </div>
2707
+
2708
+ <div
2709
+ class="modal-backdrop ${this.disableAnimation ? 'fade' : ''} ${this.open ? 'show' : ''}"
2710
+ aria-hidden="true"
2711
+ @click="${this._handleBackdropClick}"
2712
+ part="modal-backdrop"
2713
+ ></div>
2714
+ `;
2715
+ }
2716
+ };
2717
+ ItModal.styles = styles;
2718
+ ItModal.shadowRootOptions = {
2719
+ ...BaseComponent.shadowRootOptions,
2720
+ delegatesFocus: true,
2721
+ };
2722
+ __decorate([
2723
+ property({ type: Boolean, reflect: true }),
2724
+ __metadata("design:type", Object)
2725
+ ], ItModal.prototype, "open", void 0);
2726
+ __decorate([
2727
+ property({ type: String, attribute: 'modal-title', reflect: true }),
2728
+ __metadata("design:type", Object)
2729
+ ], ItModal.prototype, "modalTitle", void 0);
2730
+ __decorate([
2731
+ property({ type: String, attribute: 'modal-description', reflect: true }),
2732
+ __metadata("design:type", Object)
2733
+ ], ItModal.prototype, "modalDescription", void 0);
2734
+ __decorate([
2735
+ property({ type: String, reflect: true }),
2736
+ __metadata("design:type", String)
2737
+ ], ItModal.prototype, "size", void 0);
2738
+ __decorate([
2739
+ property({ type: String, reflect: true }),
2740
+ __metadata("design:type", Object)
2741
+ ], ItModal.prototype, "position", void 0);
2742
+ __decorate([
2743
+ property({ type: Boolean, reflect: true }),
2744
+ __metadata("design:type", Object)
2745
+ ], ItModal.prototype, "scrollable", void 0);
2746
+ __decorate([
2747
+ property({ type: Boolean, attribute: 'static-backdrop', reflect: true }),
2748
+ __metadata("design:type", Object)
2749
+ ], ItModal.prototype, "staticBackdrop", void 0);
2750
+ __decorate([
2751
+ property({ type: Boolean, attribute: 'hide-close-button', reflect: true }),
2752
+ __metadata("design:type", Object)
2753
+ ], ItModal.prototype, "hideCloseButton", void 0);
2754
+ __decorate([
2755
+ property({ type: String, reflect: true }),
2756
+ __metadata("design:type", Object)
2757
+ ], ItModal.prototype, "variant", void 0);
2758
+ __decorate([
2759
+ property({ type: String, attribute: 'it-aria-label' }),
2760
+ __metadata("design:type", String)
2761
+ ], ItModal.prototype, "itAriaLabel", void 0);
2762
+ __decorate([
2763
+ property({ type: String, attribute: 'close-label', reflect: true }),
2764
+ __metadata("design:type", Object)
2765
+ ], ItModal.prototype, "closeLabel", void 0);
2766
+ __decorate([
2767
+ property({ type: Boolean, attribute: 'disable-animation', reflect: true }),
2768
+ __metadata("design:type", Object)
2769
+ ], ItModal.prototype, "disableAnimation", void 0);
2770
+ __decorate([
2771
+ property({ type: Boolean, attribute: 'footer-shadow', reflect: true }),
2772
+ __metadata("design:type", Object)
2773
+ ], ItModal.prototype, "footerShadow", void 0);
2774
+ __decorate([
2775
+ query('[role="dialog"]'),
2776
+ __metadata("design:type", HTMLElement)
2777
+ ], ItModal.prototype, "_modalElement", void 0);
2778
+ __decorate([
2779
+ query('slot[name="trigger"]'),
2780
+ __metadata("design:type", HTMLSlotElement)
2781
+ ], ItModal.prototype, "_triggerSlot", void 0);
2782
+ __decorate([
2783
+ query('slot[name="header"]'),
2784
+ __metadata("design:type", HTMLSlotElement)
2785
+ ], ItModal.prototype, "_headerSlot", void 0);
2786
+ __decorate([
2787
+ query('slot[name="description"]'),
2788
+ __metadata("design:type", HTMLSlotElement)
2789
+ ], ItModal.prototype, "_descriptionSlot", void 0);
2790
+ __decorate([
2791
+ query('.modal-backdrop'),
2792
+ __metadata("design:type", HTMLElement)
2793
+ ], ItModal.prototype, "_backdropElement", void 0);
2794
+ __decorate([
2795
+ query('.modal-dialog'),
2796
+ __metadata("design:type", HTMLElement)
2797
+ ], ItModal.prototype, "_dialogElement", void 0);
2798
+ ItModal = __decorate([
2799
+ customElement('it-modal'),
2800
+ __metadata("design:paramtypes", [])
2801
+ ], ItModal);
2802
+
2803
+ export { ItModal };
2804
+ //# sourceMappingURL=it-modal.js.map