@italia/icon 0.0.1-alpha.0 → 0.1.0-alpha.2

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