@italia/accordion 0.1.0-alpha.2 → 1.0.0-alpha.4

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.
@@ -1,8 +1,384 @@
1
- import { _ as __decorate, a as __metadata, B as BaseComponent } from '../form-control-ddGGHusp.js';
2
- import { html } from 'lit';
3
- import { queryAssignedElements, property, customElement } from 'lit/decorators.js';
4
- import { s as styles } from '../accordion-Du1RVx-L.js';
5
- import 'lit/directive.js';
1
+ import { _ as __decorate, a as __metadata, s as styles } from '../accordion-DrJ-1sEg.js';
2
+ import { directive, Directive } from 'lit/directive.js';
3
+ import { LitElement, html } from 'lit';
4
+ import { state, query, property, queryAssignedElements, customElement } from 'lit/decorators.js';
5
+
6
+ class SetAttributesDirective extends Directive {
7
+ update(part, [attributes]) {
8
+ const el = part.element;
9
+ for (const [name, value] of Object.entries(attributes)) {
10
+ if (value != null)
11
+ el.setAttribute(name, value);
12
+ else
13
+ el.removeAttribute(name);
14
+ }
15
+ return null;
16
+ }
17
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
18
+ render(_attributes) {
19
+ return null;
20
+ }
21
+ }
22
+ /* How to use:
23
+
24
+ <textarea ${setAttributes(this._ariaAttributes)} ... />
25
+ */
26
+ directive(SetAttributesDirective);
27
+
28
+ 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}
29
+
30
+ const connectedElements = new Set();
31
+ if (window && !window.translations) {
32
+ window.translations = new Map();
33
+ }
34
+ const { translations } = window;
35
+ let fallback;
36
+ // TODO: We need some way for users to be able to set these on the server.
37
+ let documentDirection = 'ltr';
38
+ // Fallback for server.
39
+ let documentLanguage = 'en';
40
+ const isClient = typeof MutationObserver !== 'undefined' &&
41
+ typeof document !== 'undefined' &&
42
+ typeof document.documentElement !== 'undefined';
43
+ /** Updates all localized elements that are currently connected */
44
+ function update() {
45
+ if (isClient) {
46
+ documentDirection = document.documentElement.dir || 'ltr';
47
+ documentLanguage = document.documentElement.lang || navigator.language;
48
+ }
49
+ [...connectedElements.keys()].forEach((el) => {
50
+ const litEl = el;
51
+ if (typeof litEl.requestUpdate === 'function') {
52
+ litEl.requestUpdate();
53
+ }
54
+ });
55
+ }
56
+ if (isClient) {
57
+ const documentElementObserver = new MutationObserver(update);
58
+ documentDirection = document.documentElement.dir || 'ltr';
59
+ documentLanguage = document.documentElement.lang || navigator.language;
60
+ // Watch for changes on <html lang>
61
+ documentElementObserver.observe(document.documentElement, {
62
+ attributes: true,
63
+ attributeFilter: ['dir', 'lang'],
64
+ });
65
+ }
66
+ /** Registers one or more translations */
67
+ function registerTranslation(...translation) {
68
+ translation.forEach((t) => {
69
+ const code = t.$code.toLowerCase();
70
+ if (translations.has(code)) {
71
+ // Merge translations that share the same language code
72
+ translations.set(code, { ...translations.get(code), ...t });
73
+ }
74
+ else {
75
+ translations.set(code, t);
76
+ }
77
+ // The first translation that's registered is the fallback
78
+ if (!fallback) {
79
+ fallback = t;
80
+ }
81
+ });
82
+ update();
83
+ }
84
+ window.registerTranslation = registerTranslation;
85
+ /**
86
+ * Localize Reactive Controller for components built with Lit
87
+ *
88
+ * To use this controller, import the class and instantiate it in a custom element constructor:
89
+ *
90
+ * private localize = new LocalizeController(this);
91
+ *
92
+ * This will add the element to the set and make it respond to changes to <html dir|lang> automatically. To make it
93
+ * respond to changes to its own dir|lang properties, make it a property:
94
+ *
95
+ * @property() dir: string;
96
+ * @property() lang: string;
97
+ *
98
+ * To use a translation method, call it like this:
99
+ *
100
+ * ${this.localize.term('term_key_here')}
101
+ * ${this.localize.date('2021-12-03')}
102
+ * ${this.localize.number(1000000)}
103
+ */
104
+ class LocalizeController {
105
+ constructor(host) {
106
+ this.host = host;
107
+ this.host.addController(this);
108
+ }
109
+ hostConnected() {
110
+ connectedElements.add(this.host);
111
+ }
112
+ hostDisconnected() {
113
+ connectedElements.delete(this.host);
114
+ }
115
+ /**
116
+ * Gets the host element's directionality as determined by the `dir` attribute. The return value is transformed to
117
+ * lowercase.
118
+ */
119
+ dir() {
120
+ return `${this.host.dir || documentDirection}`.toLowerCase();
121
+ }
122
+ /**
123
+ * Gets the host element's language as determined by the `lang` attribute. The return value is transformed to
124
+ * lowercase.
125
+ */
126
+ lang() {
127
+ return `${this.host.lang || documentLanguage}`.toLowerCase();
128
+ }
129
+ // eslint-disable-next-line class-methods-use-this
130
+ getTranslationData(lang) {
131
+ // Convert "en_US" to "en-US". Note that both underscores and dashes are allowed per spec, but underscores result in
132
+ // a RangeError by the call to `new Intl.Locale()`. See: https://unicode.org/reports/tr35/#unicode-locale-identifier
133
+ const locale = new Intl.Locale(lang.replace(/_/g, '-'));
134
+ const language = locale?.language.toLowerCase();
135
+ const region = locale?.region?.toLowerCase() ?? '';
136
+ const primary = translations.get(`${language}-${region}`);
137
+ const secondary = translations.get(language);
138
+ return { locale, language, region, primary, secondary };
139
+ }
140
+ /** Determines if the specified term exists, optionally checking the fallback translation. */
141
+ exists(key, options) {
142
+ const { primary, secondary } = this.getTranslationData(options.lang ?? this.lang());
143
+ const mergedOptions = {
144
+ includeFallback: false,
145
+ ...options,
146
+ };
147
+ if ((primary && primary[key]) ||
148
+ (secondary && secondary[key]) ||
149
+ (mergedOptions.includeFallback && fallback && fallback[key])) {
150
+ return true;
151
+ }
152
+ return false;
153
+ }
154
+ /** Outputs a translated term. */
155
+ term(key, ...args) {
156
+ const { primary, secondary } = this.getTranslationData(this.lang());
157
+ let term;
158
+ // Look for a matching term using regionCode, code, then the fallback
159
+ if (primary && primary[key]) {
160
+ term = primary[key];
161
+ }
162
+ else if (secondary && secondary[key]) {
163
+ term = secondary[key];
164
+ }
165
+ else if (fallback && fallback[key]) {
166
+ term = fallback[key];
167
+ }
168
+ else {
169
+ // eslint-disable-next-line no-console
170
+ console.error(`No translation found for: ${String(key)}`);
171
+ return String(key);
172
+ }
173
+ if (typeof term === 'function') {
174
+ return term(...args);
175
+ }
176
+ return term;
177
+ }
178
+ /** Outputs a localized date in the specified format. */
179
+ date(dateToFormat, options) {
180
+ const date = new Date(dateToFormat);
181
+ return new Intl.DateTimeFormat(this.lang(), options).format(date);
182
+ }
183
+ /** Outputs a localized number in the specified format. */
184
+ number(numberToFormat, options) {
185
+ const num = Number(numberToFormat);
186
+ return Number.isNaN(num) ? '' : new Intl.NumberFormat(this.lang(), options).format(num);
187
+ }
188
+ /** Outputs a localized time in relative format. */
189
+ relativeTime(value, unit, options) {
190
+ return new Intl.RelativeTimeFormat(this.lang(), options).format(value, unit);
191
+ }
192
+ }
193
+
194
+ /**
195
+ * @param Base The base class.
196
+ * @returns A mix-in implementing `localizations` method.
197
+ *
198
+ *@example
199
+ * <!-- Terms -->
200
+ ${this.$localize.term('hello')}
201
+ or
202
+ ${this.$t('hello')}
203
+
204
+ <!-- Dates -->
205
+ ${this.$localize.date('2021-09-15 14:00:00 ET', { month: 'long', day: 'numeric', year: 'numeric' })}
206
+ or
207
+ ${this.$d('2021-09-15 14:00:00 ET', { month: 'long', day: 'numeric', year: 'numeric' })}
208
+
209
+ <!-- Numbers/currency -->
210
+ ${this.$localize.number(1000, { style: 'currency', currency: 'USD'})}
211
+ or
212
+ ${this.$n(1000,{ style: 'currency', currency: 'USD'})}
213
+
214
+ <!-- Determining language -->
215
+ ${this.$localize.lang()}
216
+
217
+ <!-- Determining directionality, e.g. 'ltr' or 'rtl' -->
218
+ ${this.$localize.dir()}
219
+
220
+
221
+ *** HOW TO DEFINE TRANSLATIONS: ***
222
+ // Simple terms
223
+ upload: 'Upload',
224
+
225
+ // Terms with placeholders
226
+ greetUser: (name: string) => `Hello, ${name}!`,
227
+
228
+ // Plurals
229
+ numFilesSelected: (count: number) => {
230
+ if (count === 0) return 'No files selected';
231
+ if (count === 1) return '1 file selected';
232
+ return `${count} files selected`;
233
+ }
234
+ */
235
+ const LocalizeMixin = (Base) => class extends Base {
236
+ constructor() {
237
+ super(...arguments);
238
+ this.localize = new LocalizeController(this);
239
+ }
240
+ // Provide default values to avoid definite assignment errors and avoid decorators
241
+ // commentati perchè danno problemi su React.js. Sono attributi nativi, e assegnare un valore di default a react da fastidio
242
+ // dir: string = '';
243
+ // lang: string = '';
244
+ /**
245
+ * Restituisce tutta l'utility di traduzione
246
+ *
247
+
248
+ *
249
+ * @returns tutta l'utility di traduzione
250
+ *
251
+ * @example
252
+ * this.$localize.lang() -> ritorna la lingua corrente
253
+ * this.$localize.dir() -> ritorna la direzione della lingua corrente
254
+ */
255
+ get $localize() {
256
+ return this.localize;
257
+ }
258
+ /**
259
+ * Restituisce una stringa localizzata a partire da una chiave di termine.
260
+ *
261
+ * Utilizza il `LocalizeController` per accedere al dizionario corrente e
262
+ * tradurre la chiave fornita secondo la lingua attiva.
263
+ *
264
+ * @param t - La chiave del termine da localizzare (es. 'hello', 'submit', ecc.).
265
+ * @returns La stringa tradotta in base alla lingua attiva. Se la chiave non è trovata, restituisce la chiave stessa.
266
+ *
267
+ * @example
268
+ * this.$t('hello'); // → "Ciao" (in locale it-IT)
269
+ */
270
+ $t(t) {
271
+ // format term
272
+ return this.localize.term(t);
273
+ }
274
+ /**
275
+ * Formatta una data in base alla localizzazione attiva.
276
+ *
277
+ * Utilizza il `LocalizeController` per restituire una stringa localizzata
278
+ * secondo le opzioni fornite (es. mese esteso, anno, ecc.).
279
+ *
280
+ * @param n - La data da formattare come stringa compatibile (es. ISO o con timezone, es. '2021-09-15 14:00:00 ET').
281
+ * @param p - Le opzioni di formattazione per `Intl.DateTimeFormat` (es. { year: 'numeric', month: 'long', day: 'numeric' }).
282
+ * @returns Una stringa rappresentante la data formattata secondo la localizzazione attiva.
283
+ *
284
+ * @example
285
+ * this.$d('2021-09-15 14:00:00 ET', { year: 'numeric', month: 'long', day: 'numeric' });
286
+ * // → "15 settembre 2021" (in locale it-IT)
287
+ */
288
+ $d(d, p) {
289
+ // format date
290
+ return this.localize.date(d, p);
291
+ }
292
+ /**
293
+ * Formatta un numero secondo le impostazioni locali dell'utente corrente.
294
+ *
295
+ * Utilizza il `LocalizeController` per applicare formattazione numerica,
296
+ * incluse opzioni come separatori, decimali, valute, ecc.
297
+ *
298
+ * @param d - Il numero da formattare.
299
+ * @param p - Le opzioni di formattazione (es. { style: 'currency', currency: 'EUR' }).
300
+ * @returns Una stringa rappresentante il numero formattato secondo la localizzazione attiva.
301
+ *
302
+ * @example
303
+ * this.$n(1234.56, { style: 'currency', currency: 'USD' }); // → "$1,234.56" (in locale en-US)
304
+ */
305
+ $n(d, p) {
306
+ return this.localize.number(d, p);
307
+ }
308
+ };
309
+
310
+ /* eslint-disable no-console */
311
+ class Logger {
312
+ constructor(tag) {
313
+ this.tag = tag;
314
+ }
315
+ format(level, msg) {
316
+ return [`[${this.tag}] ${msg}`];
317
+ }
318
+ warn(msg) {
319
+ console.warn(...this.format('warn', msg));
320
+ }
321
+ error(msg) {
322
+ console.error(...this.format('error', msg));
323
+ }
324
+ info(msg) {
325
+ console.info(...this.format('info', msg));
326
+ }
327
+ }
328
+
329
+ /**
330
+ * Factory function per creare una base class estendibile
331
+ * con stili personalizzati.
332
+ */
333
+ class BaseComponent extends LitElement {
334
+ constructor() {
335
+ super();
336
+ this.composeClass = clsx;
337
+ this.logger = new Logger(this.tagName.toLowerCase());
338
+ }
339
+ get _ariaAttributes() {
340
+ const attributes = {};
341
+ for (const attr of this.getAttributeNames()) {
342
+ if (attr === 'it-role') {
343
+ attributes.role = this.getAttribute(attr);
344
+ }
345
+ else if (attr.startsWith('it-aria-')) {
346
+ attributes[attr.replace(/^it-/, '')] = this.getAttribute(attr);
347
+ }
348
+ }
349
+ return attributes;
350
+ }
351
+ // eslint-disable-next-line class-methods-use-this
352
+ generateId(prefix) {
353
+ return `${prefix}-${Math.random().toString(36).slice(2)}`;
354
+ }
355
+ // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars
356
+ addFocus(element) {
357
+ // 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.
358
+ }
359
+ // eslint-disable-next-line class-methods-use-this
360
+ getActiveElement() {
361
+ let active = document.activeElement;
362
+ while (active && active.shadowRoot && active.shadowRoot.activeElement) {
363
+ active = active.shadowRoot.activeElement;
364
+ }
365
+ return active;
366
+ }
367
+ get focusElement() {
368
+ return this;
369
+ }
370
+ // eslint-disable-next-line class-methods-use-this
371
+ get prefersReducedMotion() {
372
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
373
+ }
374
+ connectedCallback() {
375
+ super.connectedCallback();
376
+ // generate internal _id
377
+ const prefix = this.id?.length > 0 ? this.id : this.tagName.toLowerCase();
378
+ this._id = this.generateId(prefix);
379
+ }
380
+ }
381
+ const BaseLocalizedComponent = LocalizeMixin(BaseComponent);
6
382
 
7
383
  class AriaKeyboardAccordionController {
8
384
  constructor(host) {
@@ -54,6 +430,676 @@ class AriaKeyboardAccordionController {
54
430
  }
55
431
  }
56
432
 
433
+ //
434
+ // We store a WeakMap of forms + controls so we can keep references to all FormControl within a given form. As
435
+ // elements connect and disconnect to/from the DOM, their containing form is used as the key and the form control is
436
+ // added and removed from the form's set, respectively.
437
+ //
438
+ const formCollections = new WeakMap();
439
+ //
440
+ // We store a WeakMap of reportValidity() overloads so we can override it when form controls connect to the DOM and
441
+ // restore the original behavior when they disconnect.
442
+ //
443
+ const reportValidityOverloads = new WeakMap();
444
+ const checkValidityOverloads = new WeakMap();
445
+ //
446
+ // We store a Set of controls that users have interacted with. This allows us to determine the interaction state
447
+ // without littering the DOM with additional data attributes.
448
+ //
449
+ const userInteractedControls = new WeakSet();
450
+ //
451
+ // We store a WeakMap of interactions for each form control so we can track when all conditions are met for validation.
452
+ //
453
+ const interactions = new WeakMap();
454
+ /** A reactive controller to allow form controls to participate in form submission, validation, etc. */
455
+ class FormControlController {
456
+ constructor(host, options) {
457
+ this.submittedOnce = false;
458
+ this.handleFormData = (event) => {
459
+ // console.log('handleFormData');
460
+ const disabled = this.options.disabled(this.host);
461
+ const name = this.options.name(this.host);
462
+ const value = this.options.value(this.host);
463
+ const tagName = this.host.tagName.toLowerCase();
464
+ // For buttons, we only submit the value if they were the submitter. This is currently done in doAction() by
465
+ // injecting the name/value on a temporary button, so we can just skip them here.
466
+ const isButton = tagName === 'it-button';
467
+ if (this.host.isConnected &&
468
+ !disabled &&
469
+ !isButton &&
470
+ typeof name === 'string' &&
471
+ name.length > 0 &&
472
+ typeof value !== 'undefined') {
473
+ switch (tagName) {
474
+ case 'it-radio':
475
+ if (this.host.checked) {
476
+ event.formData.append(name, value);
477
+ }
478
+ break;
479
+ case 'it-checkbox':
480
+ if (this.host.checked) {
481
+ if (event.formData.getAll(name).indexOf(value) < 0) {
482
+ // handle group checkbox
483
+ event.formData.append(name, value);
484
+ }
485
+ }
486
+ break;
487
+ case 'it-checkbox-group':
488
+ // non settare valori in formData, perchè ogni singola checkbox setta il suo valore
489
+ break;
490
+ default:
491
+ if (Array.isArray(value)) {
492
+ value.forEach((val) => {
493
+ event.formData.append(name, val.toString());
494
+ });
495
+ }
496
+ else {
497
+ event.formData.append(name, value.toString());
498
+ }
499
+ }
500
+ }
501
+ };
502
+ this.handleFormSubmit = (event) => {
503
+ const disabled = this.options.disabled(this.host);
504
+ const reportValidity = this.options.reportValidity;
505
+ // Update the interacted state for all controls when the form is submitted
506
+ if (this.form && !this.form.noValidate) {
507
+ formCollections.get(this.form)?.forEach((control) => {
508
+ this.setUserInteracted(control, true);
509
+ });
510
+ }
511
+ const resReportValidity = reportValidity(this.host);
512
+ if (this.form && !this.form.noValidate && !disabled && !resReportValidity) {
513
+ event.preventDefault();
514
+ // event.stopImmediatePropagation(); // se lo attiviamo, valida un campo alla volta
515
+ // Scroll al primo controllo non valido
516
+ const formControls = formCollections.get(this.form);
517
+ if (formControls) {
518
+ for (const control of formControls) {
519
+ if (!control.validity?.valid) {
520
+ // Scroll smooth verso il controllo non valido
521
+ control.scrollIntoView({
522
+ behavior: 'smooth',
523
+ block: 'center',
524
+ });
525
+ break;
526
+ }
527
+ }
528
+ }
529
+ }
530
+ this.submittedOnce = true;
531
+ };
532
+ this.handleFormReset = () => {
533
+ this.options.setValue(this.host, '');
534
+ this.submittedOnce = false;
535
+ this.setUserInteracted(this.host, false);
536
+ interactions.set(this.host, []);
537
+ };
538
+ this.handleInteraction = (event) => {
539
+ const emittedEvents = interactions.get(this.host);
540
+ if (!emittedEvents.includes(event.type)) {
541
+ emittedEvents.push(event.type);
542
+ }
543
+ // Mark it as user-interacted as soon as all associated events have been emitted
544
+ if (emittedEvents.length === this.options.assumeInteractionOn.length) {
545
+ this.setUserInteracted(this.host, true);
546
+ }
547
+ };
548
+ this.checkFormValidity = () => {
549
+ // console.log('checkFormValidity');
550
+ //
551
+ // This is very similar to the `reportFormValidity` function, but it does not trigger native constraint validation
552
+ // Allow the user to simply check if the form is valid and handling validity in their own way.
553
+ //
554
+ // We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
555
+ // validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
556
+ // be necessary once we can use ElementInternals.
557
+ //
558
+ // Note that we're also honoring the form's novalidate attribute.
559
+ //
560
+ if (this.form && !this.form.noValidate) {
561
+ // This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
562
+ // elements that support the constraint validation API.
563
+ const elements = this.form.querySelectorAll('*');
564
+ for (const element of elements) {
565
+ if (typeof element.checkValidity === 'function') {
566
+ if (!element.checkValidity()) {
567
+ return false;
568
+ }
569
+ }
570
+ }
571
+ }
572
+ return true;
573
+ };
574
+ this.reportFormValidity = () => {
575
+ // console.log('reportFormValidity');
576
+ //
577
+ // FormControl work hard to act like regular form controls. They support the Constraint Validation API
578
+ // and its associated methods such as setCustomValidity() and reportValidity(). However, the HTMLFormElement also
579
+ // has a reportValidity() method that will trigger validation on all child controls. Since we're not yet using
580
+ // ElementInternals, we need to overload this method so it looks for any element with the reportValidity() method.
581
+ //
582
+ // We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
583
+ // validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
584
+ // be necessary once we can use ElementInternals.
585
+ //
586
+ // Note that we're also honoring the form's novalidate attribute.
587
+ //
588
+ if (this.form && !this.form.noValidate) {
589
+ // This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
590
+ // elements that support the constraint validation API.
591
+ const elements = this.form.querySelectorAll('*');
592
+ for (const element of elements) {
593
+ if (typeof element.reportValidity === 'function') {
594
+ if (!element.reportValidity()) {
595
+ return false;
596
+ }
597
+ }
598
+ }
599
+ }
600
+ return true;
601
+ };
602
+ (this.host = host).addController(this);
603
+ this.options = {
604
+ form: (input) => {
605
+ // If there's a form attribute, use it to find the target form by id
606
+ // Controls may not always reflect the 'form' property. For example, `<it-button>` doesn't reflect.
607
+ const formId = input.form;
608
+ if (formId) {
609
+ const root = input.getRootNode();
610
+ const form = root.querySelector(`#${formId}`);
611
+ if (form) {
612
+ return form;
613
+ }
614
+ }
615
+ return input.closest('form');
616
+ },
617
+ name: (input) => input.name,
618
+ value: (input) => input.value,
619
+ disabled: (input) => input.disabled ?? false,
620
+ reportValidity: (input) => typeof input.reportValidity === 'function' ? input.reportValidity() : true,
621
+ checkValidity: (input) => (typeof input.checkValidity === 'function' ? input.checkValidity() : true),
622
+ setValue: (input, value) => {
623
+ // eslint-disable-next-line no-param-reassign
624
+ input.value = value;
625
+ },
626
+ assumeInteractionOn: ['it-input'],
627
+ ...options,
628
+ };
629
+ }
630
+ hostConnected() {
631
+ const form = this.options.form(this.host);
632
+ if (form) {
633
+ this.attachForm(form);
634
+ }
635
+ // Listen for interactions
636
+ interactions.set(this.host, []);
637
+ this.options.assumeInteractionOn.forEach((event) => {
638
+ this.host.addEventListener(event, this.handleInteraction);
639
+ });
640
+ }
641
+ hostDisconnected() {
642
+ this.detachForm();
643
+ // Clean up interactions
644
+ interactions.delete(this.host);
645
+ this.options.assumeInteractionOn.forEach((event) => {
646
+ this.host.removeEventListener(event, this.handleInteraction);
647
+ });
648
+ }
649
+ hostUpdated() {
650
+ const form = this.options.form(this.host);
651
+ // Detach if the form no longer exists
652
+ if (!form) {
653
+ this.detachForm();
654
+ }
655
+ // If the form has changed, reattach it
656
+ if (form && this.form !== form) {
657
+ this.detachForm();
658
+ this.attachForm(form);
659
+ }
660
+ if (this.host.hasUpdated) {
661
+ this.setValidity(this.host.validity.valid);
662
+ }
663
+ }
664
+ attachForm(form) {
665
+ if (form) {
666
+ this.form = form;
667
+ // Add this element to the form's collection
668
+ if (formCollections.has(this.form)) {
669
+ formCollections.get(this.form).add(this.host);
670
+ }
671
+ else {
672
+ formCollections.set(this.form, new Set([this.host]));
673
+ }
674
+ this.form.addEventListener('formdata', this.handleFormData);
675
+ this.form.addEventListener('submit', this.handleFormSubmit);
676
+ this.form.addEventListener('reset', this.handleFormReset);
677
+ // Overload the form's reportValidity() method so it looks at FormControl
678
+ if (!reportValidityOverloads.has(this.form)) {
679
+ reportValidityOverloads.set(this.form, this.form.reportValidity);
680
+ this.form.reportValidity = () => this.reportFormValidity();
681
+ }
682
+ // Overload the form's checkValidity() method so it looks at FormControl
683
+ if (!checkValidityOverloads.has(this.form)) {
684
+ checkValidityOverloads.set(this.form, this.form.checkValidity);
685
+ this.form.checkValidity = () => this.checkFormValidity();
686
+ }
687
+ }
688
+ else {
689
+ this.form = undefined;
690
+ }
691
+ }
692
+ detachForm() {
693
+ if (!this.form)
694
+ return;
695
+ const formCollection = formCollections.get(this.form);
696
+ if (!formCollection) {
697
+ return;
698
+ }
699
+ this.submittedOnce = false;
700
+ // Remove this host from the form's collection
701
+ formCollection.delete(this.host);
702
+ // Check to make sure there's no other form controls in the collection. If we do this
703
+ // without checking if any other controls are still in the collection, then we will wipe out the
704
+ // validity checks for all other elements.
705
+ // see: https://github.com/shoelace-style/shoelace/issues/1703
706
+ if (formCollection.size <= 0) {
707
+ this.form.removeEventListener('formdata', this.handleFormData);
708
+ this.form.removeEventListener('submit', this.handleFormSubmit);
709
+ this.form.removeEventListener('reset', this.handleFormReset);
710
+ // Remove the overload and restore the original method
711
+ if (reportValidityOverloads.has(this.form)) {
712
+ this.form.reportValidity = reportValidityOverloads.get(this.form);
713
+ reportValidityOverloads.delete(this.form);
714
+ }
715
+ if (checkValidityOverloads.has(this.form)) {
716
+ this.form.checkValidity = checkValidityOverloads.get(this.form);
717
+ checkValidityOverloads.delete(this.form);
718
+ }
719
+ // So it looks weird here to not always set the form to undefined. But I _think_ if we unattach this.form here,
720
+ // we end up in this fun spot where future validity checks don't have a reference to the form validity handler.
721
+ // 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.
722
+ this.form = undefined;
723
+ }
724
+ }
725
+ // eslint-disable-next-line class-methods-use-this
726
+ setUserInteracted(el, hasInteracted) {
727
+ if (hasInteracted) {
728
+ userInteractedControls.add(el);
729
+ }
730
+ else {
731
+ userInteractedControls.delete(el);
732
+ }
733
+ el.requestUpdate();
734
+ }
735
+ doAction(type, submitter) {
736
+ // console.log('doaction', type);
737
+ if (this.form) {
738
+ const button = document.createElement('button');
739
+ button.type = type;
740
+ button.style.position = 'absolute';
741
+ button.style.width = '0';
742
+ button.style.height = '0';
743
+ button.style.clipPath = 'inset(50%)';
744
+ button.style.overflow = 'hidden';
745
+ button.style.whiteSpace = 'nowrap';
746
+ // Pass name, value, and form attributes through to the temporary button
747
+ if (submitter) {
748
+ button.name = submitter.name;
749
+ button.value = submitter.value;
750
+ ['formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget'].forEach((attr) => {
751
+ if (submitter.hasAttribute(attr)) {
752
+ button.setAttribute(attr, submitter.getAttribute(attr));
753
+ }
754
+ });
755
+ }
756
+ this.form.append(button);
757
+ button.click();
758
+ button.remove();
759
+ }
760
+ }
761
+ /** Returns the associated `<form>` element, if one exists. */
762
+ getForm() {
763
+ return this.form ?? null;
764
+ }
765
+ /** Resets the form, restoring all the control to their default value */
766
+ reset(submitter) {
767
+ this.doAction('reset', submitter);
768
+ }
769
+ /** Submits the form, triggering validation and form data injection. */
770
+ submit(submitter) {
771
+ // Calling form.submit() bypasses the submit event and constraint validation. To prevent this, we can inject a
772
+ // native submit button into the form, "click" it, then remove it to simulate a standard form submission.
773
+ this.doAction('submit', submitter);
774
+ }
775
+ /**
776
+ * Synchronously sets the form control's validity. Call this when you know the future validity but need to update
777
+ * the host element immediately, i.e. before Lit updates the component in the next update.
778
+ */
779
+ setValidity(isValid) {
780
+ const host = this.host;
781
+ const hasInteracted = Boolean(userInteractedControls.has(host));
782
+ const required = Boolean(host.required);
783
+ //
784
+ // We're mapping the following "states" to data attributes. In the future, we can use ElementInternals.states to
785
+ // create a similar mapping, but instead of [data-invalid] it will look like :--invalid.
786
+ //
787
+ // See this RFC for more details: https://github.com/shoelace-style/shoelace/issues/1011
788
+ //
789
+ host.toggleAttribute('data-required', required);
790
+ host.toggleAttribute('data-optional', !required);
791
+ host.toggleAttribute('data-invalid', !isValid);
792
+ host.toggleAttribute('data-valid', isValid);
793
+ host.toggleAttribute('data-user-invalid', !isValid && hasInteracted);
794
+ host.toggleAttribute('data-user-valid', isValid && hasInteracted);
795
+ }
796
+ userInteracted() {
797
+ const hasInteracted = Boolean(userInteractedControls.has(this.host));
798
+ return hasInteracted;
799
+ }
800
+ /**
801
+ * Updates the form control's validity based on the current value of `host.validity.valid`. Call this when anything
802
+ * that affects constraint validation changes so the component receives the correct validity states.
803
+ */
804
+ updateValidity() {
805
+ const host = this.host;
806
+ this.setValidity(host.validity.valid);
807
+ }
808
+ /**
809
+ * Dispatches a non-bubbling, cancelable custom event of type `it-invalid`.
810
+ * If the `it-invalid` event will be cancelled then the original `invalid`
811
+ * event (which may have been passed as argument) will also be cancelled.
812
+ * If no original `invalid` event has been passed then the `it-invalid`
813
+ * event will be cancelled before being dispatched.
814
+ */
815
+ emitInvalidEvent(originalInvalidEvent) {
816
+ const itInvalidEvent = new CustomEvent('it-invalid', {
817
+ bubbles: false,
818
+ composed: false,
819
+ cancelable: true,
820
+ detail: {},
821
+ });
822
+ if (!originalInvalidEvent) {
823
+ itInvalidEvent.preventDefault();
824
+ }
825
+ if (!this.host.dispatchEvent(itInvalidEvent)) {
826
+ originalInvalidEvent?.preventDefault();
827
+ }
828
+ }
829
+ }
830
+
831
+ const translation = {
832
+ $code: 'it',
833
+ $name: 'Italiano',
834
+ $dir: 'ltr',
835
+ validityRequired: 'Questo campo è obbligatorio.',
836
+ validityGroupRequired: "Scegli almeno un'opzione",
837
+ validityPattern: 'Il valore non corrisponde al formato richiesto.',
838
+ validityMinlength: 'Il valore deve essere lungo almeno {minlength} caratteri.',
839
+ validityMaxlength: 'Il valore deve essere lungo al massimo {maxlength} caratteri.',
840
+ };
841
+
842
+ registerTranslation(translation);
843
+ class FormControl extends BaseLocalizedComponent {
844
+ constructor() {
845
+ super(...arguments);
846
+ this.formControlController = new FormControlController(this, {
847
+ assumeInteractionOn: ['it-input', 'it-blur', 'it-change'],
848
+ });
849
+ // TODO: verificare se serve davvero con il fatto che usiamo form-controller
850
+ // static formAssociated = true;
851
+ // @property()
852
+ // internals = this.attachInternals();
853
+ this._touched = false;
854
+ /** The name of the input, submitted as a name/value pair with form data. */
855
+ this.name = '';
856
+ /** The current value of the input, submitted as a name/value pair with form data. */
857
+ this.value = '';
858
+ /** If the input is disabled. */
859
+ this.disabled = false;
860
+ /**
861
+ * By default, form controls are associated with the nearest containing `<form>` element. This attribute allows you
862
+ * to place the form control outside of a form and associate it with the form that has this `id`. The form must be in
863
+ * the same document or shadow root for this to work.
864
+ */
865
+ this.form = '';
866
+ /** If you implement your custom validation and you won't to trigger default validation */
867
+ this.customValidation = false;
868
+ /** If your input is invalid from your custom validition, set this attribute with message validation */
869
+ this.validationText = '';
870
+ /**
871
+ * Specifies the granularity that the value must adhere to, or the special value `any` which means no stepping is
872
+ * implied, allowing any numeric value. Only applies to date and number input types.
873
+ */
874
+ this.step = 'any';
875
+ /** The input's minimum length. */
876
+ this.minlength = -1;
877
+ /** The input's maximum length. */
878
+ this.maxlength = -1;
879
+ /** If the input is required. */
880
+ this.required = false;
881
+ /* For grouped input, like checkbox-group */
882
+ this.isInGroup = false;
883
+ this.validationMessage = '';
884
+ }
885
+ /** Gets the validity state object */
886
+ get validity() {
887
+ return this.inputElement?.validity;
888
+ }
889
+ /** Gets the associated form, if one exists. */
890
+ getForm() {
891
+ return this.formControlController.getForm();
892
+ }
893
+ // Form validation methods
894
+ checkValidity() {
895
+ const inputValid = this.inputElement?.checkValidity() ?? true; // this.inputElement.checkValidity() è la validazione del browser
896
+ return inputValid;
897
+ }
898
+ /** Checks for validity and shows the browser's validation message if the control is invalid. */
899
+ reportValidity() {
900
+ // const ret = this.inputElement.checkValidity();
901
+ const ret = this.checkValidity(); // chiama la checkValidity, che se è stata overridata chiama quella
902
+ this.handleValidationMessages();
903
+ return ret; // this.inputElement.reportValidity();
904
+ }
905
+ /** Sets a custom validation message. Pass an empty string to restore validity. */
906
+ setCustomValidity(message) {
907
+ this.inputElement.setCustomValidity(message);
908
+ this.validationMessage = this.inputElement.validationMessage;
909
+ this.formControlController.updateValidity();
910
+ }
911
+ // Handlers
912
+ _handleReady() {
913
+ requestAnimationFrame(() => {
914
+ this.dispatchEvent(new CustomEvent('it-input-ready', { bubbles: true, detail: { el: this.inputElement } }));
915
+ });
916
+ }
917
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
918
+ _handleInput(e) {
919
+ this.handleValidationMessages();
920
+ this.dispatchEvent(new CustomEvent('it-input', {
921
+ detail: { value: this.inputElement.value, el: this.inputElement },
922
+ bubbles: true,
923
+ composed: true,
924
+ }));
925
+ }
926
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
927
+ _handleBlur(e) {
928
+ this._touched = true;
929
+ this.handleValidationMessages();
930
+ this.dispatchEvent(new FocusEvent('it-blur', { bubbles: true, composed: true }));
931
+ }
932
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
933
+ _handleFocus(e) {
934
+ this.dispatchEvent(new FocusEvent('it-focus', { bubbles: true, composed: true }));
935
+ }
936
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
937
+ _handleClick(e) {
938
+ this.dispatchEvent(new MouseEvent('it-click', { bubbles: true, composed: true }));
939
+ }
940
+ /*
941
+ Override default browser validation messages
942
+ */
943
+ handleValidationMessages() {
944
+ if (!this.customValidation) {
945
+ const _v = this.inputElement.validity;
946
+ const isRequiredHandledByGroup = this.isInGroup === true;
947
+ if (_v.valueMissing && !isRequiredHandledByGroup) {
948
+ this.setCustomValidity(this.$t('validityRequired'));
949
+ }
950
+ else if (_v.patternMismatch) {
951
+ this.setCustomValidity(this.$t('validityPattern'));
952
+ }
953
+ else if (_v.tooShort) {
954
+ this.setCustomValidity(this.$t('validityMinlength').replace('{minlength}', this.minlength.toString()));
955
+ }
956
+ else if (_v.tooLong) {
957
+ this.setCustomValidity(this.$t('validityMaxlength').replace('{maxlength}', this.maxlength.toString()));
958
+ }
959
+ else {
960
+ /* nothing. Usa il messaggio di errore della validazione
961
+ di default del browser per altri errori di validità come:
962
+ - typeMismatch
963
+ - rangeUnderflow
964
+ - rangeOverflow
965
+ - stepMismatch
966
+ - badInput */
967
+ const otherConstraintErrors = _v.typeMismatch || _v.rangeUnderflow || _v.rangeOverflow || _v.stepMismatch || _v.badInput;
968
+ if (!otherConstraintErrors) {
969
+ this.setCustomValidity('');
970
+ }
971
+ }
972
+ }
973
+ this.validationMessage = this.inputElement.validationMessage;
974
+ }
975
+ _handleInvalid(event) {
976
+ this.formControlController.setValidity(false);
977
+ this.formControlController.emitInvalidEvent(event);
978
+ }
979
+ _handleChange(e) {
980
+ const target = e.target;
981
+ let value;
982
+ if (target instanceof HTMLInputElement) {
983
+ switch (target.type) {
984
+ case 'checkbox':
985
+ case 'radio':
986
+ value = target.checked;
987
+ break;
988
+ case 'file':
989
+ value = target.files; // FileList
990
+ break;
991
+ default:
992
+ value = target.value;
993
+ }
994
+ }
995
+ else if (target instanceof HTMLSelectElement) {
996
+ if (target.multiple) {
997
+ value = Array.from(target.selectedOptions).map((o) => o.value);
998
+ }
999
+ else {
1000
+ value = target.value;
1001
+ }
1002
+ }
1003
+ else {
1004
+ // textarea o altri input con value
1005
+ value = target.value;
1006
+ }
1007
+ this.dispatchEvent(new CustomEvent('it-change', {
1008
+ detail: { value, el: target },
1009
+ bubbles: true,
1010
+ composed: true,
1011
+ }));
1012
+ }
1013
+ updated(changedProperties) {
1014
+ super.updated?.(changedProperties);
1015
+ if (this.customValidation) {
1016
+ this.setCustomValidity(this.validationText ?? '');
1017
+ }
1018
+ else if (this.formControlController.userInteracted()) {
1019
+ this.formControlController.updateValidity();
1020
+ }
1021
+ }
1022
+ }
1023
+ __decorate([
1024
+ state(),
1025
+ __metadata("design:type", Object)
1026
+ ], FormControl.prototype, "_touched", void 0);
1027
+ __decorate([
1028
+ query('.it-form__control'),
1029
+ __metadata("design:type", HTMLInputElement)
1030
+ ], FormControl.prototype, "inputElement", void 0);
1031
+ __decorate([
1032
+ property({ type: String, reflect: true }) // from FormControl
1033
+ ,
1034
+ __metadata("design:type", Object)
1035
+ ], FormControl.prototype, "name", void 0);
1036
+ __decorate([
1037
+ property({ reflect: true }),
1038
+ __metadata("design:type", Object)
1039
+ ], FormControl.prototype, "value", void 0);
1040
+ __decorate([
1041
+ property({ type: Boolean, reflect: true }) // from FormControl
1042
+ ,
1043
+ __metadata("design:type", Object)
1044
+ ], FormControl.prototype, "disabled", void 0);
1045
+ __decorate([
1046
+ property({ reflect: true, type: String }),
1047
+ __metadata("design:type", Object)
1048
+ ], FormControl.prototype, "form", void 0);
1049
+ __decorate([
1050
+ property({ type: Boolean, reflect: true, attribute: 'custom-validation' }),
1051
+ __metadata("design:type", Object)
1052
+ ], FormControl.prototype, "customValidation", void 0);
1053
+ __decorate([
1054
+ property({ attribute: 'validity-message', reflect: true }),
1055
+ __metadata("design:type", String)
1056
+ ], FormControl.prototype, "validationText", void 0);
1057
+ __decorate([
1058
+ property(),
1059
+ __metadata("design:type", String)
1060
+ ], FormControl.prototype, "pattern", void 0);
1061
+ __decorate([
1062
+ property(),
1063
+ __metadata("design:type", Object)
1064
+ ], FormControl.prototype, "min", void 0);
1065
+ __decorate([
1066
+ property(),
1067
+ __metadata("design:type", Object)
1068
+ ], FormControl.prototype, "max", void 0);
1069
+ __decorate([
1070
+ property(),
1071
+ __metadata("design:type", Object)
1072
+ ], FormControl.prototype, "step", void 0);
1073
+ __decorate([
1074
+ property({ type: Number }),
1075
+ __metadata("design:type", Object)
1076
+ ], FormControl.prototype, "minlength", void 0);
1077
+ __decorate([
1078
+ property({ type: Number }),
1079
+ __metadata("design:type", Object)
1080
+ ], FormControl.prototype, "maxlength", void 0);
1081
+ __decorate([
1082
+ property({ type: Boolean, reflect: true }) // from FormControl
1083
+ ,
1084
+ __metadata("design:type", Object)
1085
+ ], FormControl.prototype, "required", void 0);
1086
+ __decorate([
1087
+ property({ type: Boolean }),
1088
+ __metadata("design:type", Object)
1089
+ ], FormControl.prototype, "isInGroup", void 0);
1090
+ __decorate([
1091
+ state(),
1092
+ __metadata("design:type", Object)
1093
+ ], FormControl.prototype, "validationMessage", void 0);
1094
+
1095
+ if (typeof window !== 'undefined') {
1096
+ window._itAnalytics = window._itAnalytics || {};
1097
+ window._itAnalytics = {
1098
+ ...window._itAnalytics,
1099
+ version: '1.0.0-alpha.4',
1100
+ };
1101
+ }
1102
+
57
1103
  let ItAccordion = class ItAccordion extends BaseComponent {
58
1104
  constructor() {
59
1105
  super(...arguments);