@italia/icon 0.1.0-alpha.1 → 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,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,45 +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 that the value is invalid (generic).
57
- */
58
- VALIDATION_STATUS["INVALID"] = "invalid";
59
- /**
60
- * One indicating missing required value.
61
- */
62
- VALIDATION_STATUS["ERROR_REQUIRED"] = "required";
63
- /**
64
- * One indicating that the value does not match the pattern.
65
- */
66
- VALIDATION_STATUS["PATTERN"] = "pattern";
67
- /**
68
- * One indicating that the value is shorter than the minimum length.
69
- */
70
- VALIDATION_STATUS["MINLENGTH"] = "minlength";
71
- /**
72
- * One indicating that the value is less than the maximum length.
73
- */
74
- VALIDATION_STATUS["MAXLENGTH"] = "maxlength";
75
- })(VALIDATION_STATUS || (VALIDATION_STATUS = {}));
76
-
77
38
  class SetAttributesDirective extends Directive {
78
39
  update(part, [attributes]) {
79
40
  const el = part.element;
@@ -96,19 +57,26 @@ class SetAttributesDirective extends Directive {
96
57
  */
97
58
  directive(SetAttributesDirective);
98
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
+
99
62
  const connectedElements = new Set();
100
63
  if (window && !window.translations) {
101
64
  window.translations = new Map();
102
65
  }
103
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';
104
72
  const isClient = typeof MutationObserver !== 'undefined' &&
105
73
  typeof document !== 'undefined' &&
106
74
  typeof document.documentElement !== 'undefined';
107
75
  /** Updates all localized elements that are currently connected */
108
76
  function update() {
109
77
  if (isClient) {
110
- document.documentElement.dir || 'ltr';
111
- document.documentElement.lang || navigator.language;
78
+ documentDirection = document.documentElement.dir || 'ltr';
79
+ documentLanguage = document.documentElement.lang || navigator.language;
112
80
  }
113
81
  [...connectedElements.keys()].forEach((el) => {
114
82
  const litEl = el;
@@ -119,8 +87,8 @@ function update() {
119
87
  }
120
88
  if (isClient) {
121
89
  const documentElementObserver = new MutationObserver(update);
122
- document.documentElement.dir || 'ltr';
123
- document.documentElement.lang || navigator.language;
90
+ documentDirection = document.documentElement.dir || 'ltr';
91
+ documentLanguage = document.documentElement.lang || navigator.language;
124
92
  // Watch for changes on <html lang>
125
93
  documentElementObserver.observe(document.documentElement, {
126
94
  attributes: true,
@@ -138,10 +106,238 @@ function registerTranslation(...translation) {
138
106
  else {
139
107
  translations.set(code, t);
140
108
  }
109
+ // The first translation that's registered is the fallback
110
+ if (!fallback) {
111
+ fallback = t;
112
+ }
141
113
  });
142
114
  update();
143
115
  }
144
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
+ };
145
341
 
146
342
  /* eslint-disable no-console */
147
343
  class Logger {
@@ -169,9 +365,21 @@ class Logger {
169
365
  class BaseComponent extends LitElement {
170
366
  constructor() {
171
367
  super();
172
- this._ariaAttributes = {}; // tutti gli attributi aria-* passati al Web component
368
+ this.composeClass = clsx;
173
369
  this.logger = new Logger(this.tagName.toLowerCase());
174
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
+ }
175
383
  // eslint-disable-next-line class-methods-use-this
176
384
  generateId(prefix) {
177
385
  return `${prefix}-${Math.random().toString(36).slice(2)}`;
@@ -181,30 +389,698 @@ class BaseComponent extends LitElement {
181
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.
182
390
  }
183
391
  // eslint-disable-next-line class-methods-use-this
184
- composeClass(...classes) {
185
- let composedClass = '';
186
- classes
187
- .filter((c) => c.length > 0)
188
- .forEach((newClass) => {
189
- composedClass += ` ${newClass}`;
190
- });
191
- return composedClass.trim();
192
- }
193
- getAriaAttributes() {
194
- for (const attr of this.getAttributeNames()) {
195
- if (attr.startsWith('aria-')) {
196
- this._ariaAttributes[attr] = this.getAttribute(attr);
197
- }
392
+ getActiveElement() {
393
+ let active = document.activeElement;
394
+ while (active && active.shadowRoot && active.shadowRoot.activeElement) {
395
+ active = active.shadowRoot.activeElement;
198
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;
199
405
  }
200
406
  connectedCallback() {
201
- super.connectedCallback?.();
202
- this.getAriaAttributes();
407
+ super.connectedCallback();
203
408
  // generate internal _id
204
409
  const prefix = this.id?.length > 0 ? this.id : this.tagName.toLowerCase();
205
410
  this._id = this.generateId(prefix);
206
411
  }
207
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.submittedOnce = false;
440
+ this.handleFormData = (event) => {
441
+ // console.log('handleFormData');
442
+ const disabled = this.options.disabled(this.host);
443
+ const name = this.options.name(this.host);
444
+ const value = this.options.value(this.host);
445
+ const tagName = this.host.tagName.toLowerCase();
446
+ // For buttons, we only submit the value if they were the submitter. This is currently done in doAction() by
447
+ // injecting the name/value on a temporary button, so we can just skip them here.
448
+ const isButton = tagName === 'it-button';
449
+ if (this.host.isConnected &&
450
+ !disabled &&
451
+ !isButton &&
452
+ typeof name === 'string' &&
453
+ name.length > 0 &&
454
+ typeof value !== 'undefined') {
455
+ switch (tagName) {
456
+ case 'it-radio':
457
+ if (this.host.checked) {
458
+ event.formData.append(name, value);
459
+ }
460
+ break;
461
+ case 'it-checkbox':
462
+ if (this.host.checked) {
463
+ if (event.formData.getAll(name).indexOf(value) < 0) {
464
+ // handle group checkbox
465
+ event.formData.append(name, value);
466
+ }
467
+ }
468
+ break;
469
+ case 'it-checkbox-group':
470
+ // non settare valori in formData, perchè ogni singola checkbox setta il suo valore
471
+ break;
472
+ default:
473
+ if (Array.isArray(value)) {
474
+ value.forEach((val) => {
475
+ event.formData.append(name, val.toString());
476
+ });
477
+ }
478
+ else {
479
+ event.formData.append(name, value.toString());
480
+ }
481
+ }
482
+ }
483
+ };
484
+ this.handleFormSubmit = (event) => {
485
+ const disabled = this.options.disabled(this.host);
486
+ const reportValidity = this.options.reportValidity;
487
+ // Update the interacted state for all controls when the form is submitted
488
+ if (this.form && !this.form.noValidate) {
489
+ formCollections.get(this.form)?.forEach((control) => {
490
+ this.setUserInteracted(control, true);
491
+ });
492
+ }
493
+ const resReportValidity = reportValidity(this.host);
494
+ if (this.form && !this.form.noValidate && !disabled && !resReportValidity) {
495
+ event.preventDefault();
496
+ // event.stopImmediatePropagation(); // se lo attiviamo, valida un campo alla volta
497
+ // Scroll al primo controllo non valido
498
+ const formControls = formCollections.get(this.form);
499
+ if (formControls) {
500
+ for (const control of formControls) {
501
+ if (!control.validity?.valid) {
502
+ // Scroll smooth verso il controllo non valido
503
+ control.scrollIntoView({
504
+ behavior: 'smooth',
505
+ block: 'center',
506
+ });
507
+ break;
508
+ }
509
+ }
510
+ }
511
+ }
512
+ this.submittedOnce = true;
513
+ };
514
+ this.handleFormReset = () => {
515
+ this.options.setValue(this.host, '');
516
+ this.submittedOnce = false;
517
+ this.setUserInteracted(this.host, false);
518
+ interactions.set(this.host, []);
519
+ };
520
+ this.handleInteraction = (event) => {
521
+ const emittedEvents = interactions.get(this.host);
522
+ if (!emittedEvents.includes(event.type)) {
523
+ emittedEvents.push(event.type);
524
+ }
525
+ // Mark it as user-interacted as soon as all associated events have been emitted
526
+ if (emittedEvents.length === this.options.assumeInteractionOn.length) {
527
+ this.setUserInteracted(this.host, true);
528
+ }
529
+ };
530
+ this.checkFormValidity = () => {
531
+ // console.log('checkFormValidity');
532
+ //
533
+ // This is very similar to the `reportFormValidity` function, but it does not trigger native constraint validation
534
+ // Allow the user to simply check if the form is valid and handling validity in their own way.
535
+ //
536
+ // We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
537
+ // validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
538
+ // be necessary once we can use ElementInternals.
539
+ //
540
+ // Note that we're also honoring the form's novalidate attribute.
541
+ //
542
+ if (this.form && !this.form.noValidate) {
543
+ // This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
544
+ // elements that support the constraint validation API.
545
+ const elements = this.form.querySelectorAll('*');
546
+ for (const element of elements) {
547
+ if (typeof element.checkValidity === 'function') {
548
+ if (!element.checkValidity()) {
549
+ return false;
550
+ }
551
+ }
552
+ }
553
+ }
554
+ return true;
555
+ };
556
+ this.reportFormValidity = () => {
557
+ // console.log('reportFormValidity');
558
+ //
559
+ // FormControl work hard to act like regular form controls. They support the Constraint Validation API
560
+ // and its associated methods such as setCustomValidity() and reportValidity(). However, the HTMLFormElement also
561
+ // has a reportValidity() method that will trigger validation on all child controls. Since we're not yet using
562
+ // ElementInternals, we need to overload this method so it looks for any element with the reportValidity() method.
563
+ //
564
+ // We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
565
+ // validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
566
+ // be necessary once we can use ElementInternals.
567
+ //
568
+ // Note that we're also honoring the form's novalidate attribute.
569
+ //
570
+ if (this.form && !this.form.noValidate) {
571
+ // This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
572
+ // elements that support the constraint validation API.
573
+ const elements = this.form.querySelectorAll('*');
574
+ for (const element of elements) {
575
+ if (typeof element.reportValidity === 'function') {
576
+ if (!element.reportValidity()) {
577
+ return false;
578
+ }
579
+ }
580
+ }
581
+ }
582
+ return true;
583
+ };
584
+ (this.host = host).addController(this);
585
+ this.options = {
586
+ form: (input) => {
587
+ // If there's a form attribute, use it to find the target form by id
588
+ // Controls may not always reflect the 'form' property. For example, `<it-button>` doesn't reflect.
589
+ const formId = input.form;
590
+ if (formId) {
591
+ const root = input.getRootNode();
592
+ const form = root.querySelector(`#${formId}`);
593
+ if (form) {
594
+ return form;
595
+ }
596
+ }
597
+ return input.closest('form');
598
+ },
599
+ name: (input) => input.name,
600
+ value: (input) => input.value,
601
+ disabled: (input) => input.disabled ?? false,
602
+ reportValidity: (input) => typeof input.reportValidity === 'function' ? input.reportValidity() : true,
603
+ checkValidity: (input) => (typeof input.checkValidity === 'function' ? input.checkValidity() : true),
604
+ setValue: (input, value) => {
605
+ // eslint-disable-next-line no-param-reassign
606
+ input.value = value;
607
+ },
608
+ assumeInteractionOn: ['it-input'],
609
+ ...options,
610
+ };
611
+ }
612
+ hostConnected() {
613
+ const form = this.options.form(this.host);
614
+ if (form) {
615
+ this.attachForm(form);
616
+ }
617
+ // Listen for interactions
618
+ interactions.set(this.host, []);
619
+ this.options.assumeInteractionOn.forEach((event) => {
620
+ this.host.addEventListener(event, this.handleInteraction);
621
+ });
622
+ }
623
+ hostDisconnected() {
624
+ this.detachForm();
625
+ // Clean up interactions
626
+ interactions.delete(this.host);
627
+ this.options.assumeInteractionOn.forEach((event) => {
628
+ this.host.removeEventListener(event, this.handleInteraction);
629
+ });
630
+ }
631
+ hostUpdated() {
632
+ const form = this.options.form(this.host);
633
+ // Detach if the form no longer exists
634
+ if (!form) {
635
+ this.detachForm();
636
+ }
637
+ // If the form has changed, reattach it
638
+ if (form && this.form !== form) {
639
+ this.detachForm();
640
+ this.attachForm(form);
641
+ }
642
+ if (this.host.hasUpdated) {
643
+ this.setValidity(this.host.validity.valid);
644
+ }
645
+ }
646
+ attachForm(form) {
647
+ if (form) {
648
+ this.form = form;
649
+ // Add this element to the form's collection
650
+ if (formCollections.has(this.form)) {
651
+ formCollections.get(this.form).add(this.host);
652
+ }
653
+ else {
654
+ formCollections.set(this.form, new Set([this.host]));
655
+ }
656
+ this.form.addEventListener('formdata', this.handleFormData);
657
+ this.form.addEventListener('submit', this.handleFormSubmit);
658
+ this.form.addEventListener('reset', this.handleFormReset);
659
+ // Overload the form's reportValidity() method so it looks at FormControl
660
+ if (!reportValidityOverloads.has(this.form)) {
661
+ reportValidityOverloads.set(this.form, this.form.reportValidity);
662
+ this.form.reportValidity = () => this.reportFormValidity();
663
+ }
664
+ // Overload the form's checkValidity() method so it looks at FormControl
665
+ if (!checkValidityOverloads.has(this.form)) {
666
+ checkValidityOverloads.set(this.form, this.form.checkValidity);
667
+ this.form.checkValidity = () => this.checkFormValidity();
668
+ }
669
+ }
670
+ else {
671
+ this.form = undefined;
672
+ }
673
+ }
674
+ detachForm() {
675
+ if (!this.form)
676
+ return;
677
+ const formCollection = formCollections.get(this.form);
678
+ if (!formCollection) {
679
+ return;
680
+ }
681
+ this.submittedOnce = false;
682
+ // Remove this host from the form's collection
683
+ formCollection.delete(this.host);
684
+ // Check to make sure there's no other form controls in the collection. If we do this
685
+ // without checking if any other controls are still in the collection, then we will wipe out the
686
+ // validity checks for all other elements.
687
+ // see: https://github.com/shoelace-style/shoelace/issues/1703
688
+ if (formCollection.size <= 0) {
689
+ this.form.removeEventListener('formdata', this.handleFormData);
690
+ this.form.removeEventListener('submit', this.handleFormSubmit);
691
+ this.form.removeEventListener('reset', this.handleFormReset);
692
+ // Remove the overload and restore the original method
693
+ if (reportValidityOverloads.has(this.form)) {
694
+ this.form.reportValidity = reportValidityOverloads.get(this.form);
695
+ reportValidityOverloads.delete(this.form);
696
+ }
697
+ if (checkValidityOverloads.has(this.form)) {
698
+ this.form.checkValidity = checkValidityOverloads.get(this.form);
699
+ checkValidityOverloads.delete(this.form);
700
+ }
701
+ // So it looks weird here to not always set the form to undefined. But I _think_ if we unattach this.form here,
702
+ // we end up in this fun spot where future validity checks don't have a reference to the form validity handler.
703
+ // 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.
704
+ this.form = undefined;
705
+ }
706
+ }
707
+ // eslint-disable-next-line class-methods-use-this
708
+ setUserInteracted(el, hasInteracted) {
709
+ if (hasInteracted) {
710
+ userInteractedControls.add(el);
711
+ }
712
+ else {
713
+ userInteractedControls.delete(el);
714
+ }
715
+ el.requestUpdate();
716
+ }
717
+ doAction(type, submitter) {
718
+ // console.log('doaction', type);
719
+ if (this.form) {
720
+ const button = document.createElement('button');
721
+ button.type = type;
722
+ button.style.position = 'absolute';
723
+ button.style.width = '0';
724
+ button.style.height = '0';
725
+ button.style.clipPath = 'inset(50%)';
726
+ button.style.overflow = 'hidden';
727
+ button.style.whiteSpace = 'nowrap';
728
+ // Pass name, value, and form attributes through to the temporary button
729
+ if (submitter) {
730
+ button.name = submitter.name;
731
+ button.value = submitter.value;
732
+ ['formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget'].forEach((attr) => {
733
+ if (submitter.hasAttribute(attr)) {
734
+ button.setAttribute(attr, submitter.getAttribute(attr));
735
+ }
736
+ });
737
+ }
738
+ this.form.append(button);
739
+ button.click();
740
+ button.remove();
741
+ }
742
+ }
743
+ /** Returns the associated `<form>` element, if one exists. */
744
+ getForm() {
745
+ return this.form ?? null;
746
+ }
747
+ /** Resets the form, restoring all the control to their default value */
748
+ reset(submitter) {
749
+ this.doAction('reset', submitter);
750
+ }
751
+ /** Submits the form, triggering validation and form data injection. */
752
+ submit(submitter) {
753
+ // Calling form.submit() bypasses the submit event and constraint validation. To prevent this, we can inject a
754
+ // native submit button into the form, "click" it, then remove it to simulate a standard form submission.
755
+ this.doAction('submit', submitter);
756
+ }
757
+ /**
758
+ * Synchronously sets the form control's validity. Call this when you know the future validity but need to update
759
+ * the host element immediately, i.e. before Lit updates the component in the next update.
760
+ */
761
+ setValidity(isValid) {
762
+ const host = this.host;
763
+ const hasInteracted = Boolean(userInteractedControls.has(host));
764
+ const required = Boolean(host.required);
765
+ //
766
+ // We're mapping the following "states" to data attributes. In the future, we can use ElementInternals.states to
767
+ // create a similar mapping, but instead of [data-invalid] it will look like :--invalid.
768
+ //
769
+ // See this RFC for more details: https://github.com/shoelace-style/shoelace/issues/1011
770
+ //
771
+ host.toggleAttribute('data-required', required);
772
+ host.toggleAttribute('data-optional', !required);
773
+ host.toggleAttribute('data-invalid', !isValid);
774
+ host.toggleAttribute('data-valid', isValid);
775
+ host.toggleAttribute('data-user-invalid', !isValid && hasInteracted);
776
+ host.toggleAttribute('data-user-valid', isValid && hasInteracted);
777
+ }
778
+ userInteracted() {
779
+ const hasInteracted = Boolean(userInteractedControls.has(this.host));
780
+ return hasInteracted;
781
+ }
782
+ /**
783
+ * Updates the form control's validity based on the current value of `host.validity.valid`. Call this when anything
784
+ * that affects constraint validation changes so the component receives the correct validity states.
785
+ */
786
+ updateValidity() {
787
+ const host = this.host;
788
+ this.setValidity(host.validity.valid);
789
+ }
790
+ /**
791
+ * Dispatches a non-bubbling, cancelable custom event of type `it-invalid`.
792
+ * If the `it-invalid` event will be cancelled then the original `invalid`
793
+ * event (which may have been passed as argument) will also be cancelled.
794
+ * If no original `invalid` event has been passed then the `it-invalid`
795
+ * event will be cancelled before being dispatched.
796
+ */
797
+ emitInvalidEvent(originalInvalidEvent) {
798
+ const itInvalidEvent = new CustomEvent('it-invalid', {
799
+ bubbles: false,
800
+ composed: false,
801
+ cancelable: true,
802
+ detail: {},
803
+ });
804
+ if (!originalInvalidEvent) {
805
+ itInvalidEvent.preventDefault();
806
+ }
807
+ if (!this.host.dispatchEvent(itInvalidEvent)) {
808
+ originalInvalidEvent?.preventDefault();
809
+ }
810
+ }
811
+ }
812
+
813
+ const translation = {
814
+ $code: 'it',
815
+ $name: 'Italiano',
816
+ $dir: 'ltr',
817
+ validityRequired: 'Questo campo è obbligatorio.',
818
+ validityGroupRequired: "Scegli almeno un'opzione",
819
+ validityPattern: 'Il valore non corrisponde al formato richiesto.',
820
+ validityMinlength: 'Il valore deve essere lungo almeno {minlength} caratteri.',
821
+ validityMaxlength: 'Il valore deve essere lungo al massimo {maxlength} caratteri.',
822
+ };
823
+
824
+ registerTranslation(translation);
825
+ class FormControl extends BaseLocalizedComponent {
826
+ constructor() {
827
+ super(...arguments);
828
+ this.formControlController = new FormControlController(this, {
829
+ assumeInteractionOn: ['it-input', 'it-blur', 'it-change'],
830
+ });
831
+ // TODO: verificare se serve davvero con il fatto che usiamo form-controller
832
+ // static formAssociated = true;
833
+ // @property()
834
+ // internals = this.attachInternals();
835
+ this._touched = false;
836
+ /** The name of the input, submitted as a name/value pair with form data. */
837
+ this.name = '';
838
+ /** The current value of the input, submitted as a name/value pair with form data. */
839
+ this.value = '';
840
+ /** If the input is disabled. */
841
+ this.disabled = false;
842
+ /**
843
+ * By default, form controls are associated with the nearest containing `<form>` element. This attribute allows you
844
+ * to place the form control outside of a form and associate it with the form that has this `id`. The form must be in
845
+ * the same document or shadow root for this to work.
846
+ */
847
+ this.form = '';
848
+ /** If you implement your custom validation and you won't to trigger default validation */
849
+ this.customValidation = false;
850
+ /** If your input is invalid from your custom validition, set this attribute with message validation */
851
+ this.validationText = '';
852
+ /**
853
+ * Specifies the granularity that the value must adhere to, or the special value `any` which means no stepping is
854
+ * implied, allowing any numeric value. Only applies to date and number input types.
855
+ */
856
+ this.step = 'any';
857
+ /** The input's minimum length. */
858
+ this.minlength = -1;
859
+ /** The input's maximum length. */
860
+ this.maxlength = -1;
861
+ /** If the input is required. */
862
+ this.required = false;
863
+ /* For grouped input, like checkbox-group */
864
+ this.isInGroup = false;
865
+ this.validationMessage = '';
866
+ }
867
+ /** Gets the validity state object */
868
+ get validity() {
869
+ return this.inputElement?.validity;
870
+ }
871
+ /** Gets the associated form, if one exists. */
872
+ getForm() {
873
+ return this.formControlController.getForm();
874
+ }
875
+ // Form validation methods
876
+ checkValidity() {
877
+ const inputValid = this.inputElement?.checkValidity() ?? true; // this.inputElement.checkValidity() è la validazione del browser
878
+ return inputValid;
879
+ }
880
+ /** Checks for validity and shows the browser's validation message if the control is invalid. */
881
+ reportValidity() {
882
+ // const ret = this.inputElement.checkValidity();
883
+ const ret = this.checkValidity(); // chiama la checkValidity, che se è stata overridata chiama quella
884
+ this.handleValidationMessages();
885
+ return ret; // this.inputElement.reportValidity();
886
+ }
887
+ /** Sets a custom validation message. Pass an empty string to restore validity. */
888
+ setCustomValidity(message) {
889
+ this.inputElement.setCustomValidity(message);
890
+ this.validationMessage = this.inputElement.validationMessage;
891
+ this.formControlController.updateValidity();
892
+ }
893
+ // Handlers
894
+ _handleReady() {
895
+ requestAnimationFrame(() => {
896
+ this.dispatchEvent(new CustomEvent('it-input-ready', { bubbles: true, detail: { el: this.inputElement } }));
897
+ });
898
+ }
899
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
900
+ _handleInput(e) {
901
+ this.handleValidationMessages();
902
+ this.dispatchEvent(new CustomEvent('it-input', {
903
+ detail: { value: this.inputElement.value, el: this.inputElement },
904
+ bubbles: true,
905
+ composed: true,
906
+ }));
907
+ }
908
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
909
+ _handleBlur(e) {
910
+ this._touched = true;
911
+ this.handleValidationMessages();
912
+ this.dispatchEvent(new FocusEvent('it-blur', { bubbles: true, composed: true }));
913
+ }
914
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
915
+ _handleFocus(e) {
916
+ this.dispatchEvent(new FocusEvent('it-focus', { bubbles: true, composed: true }));
917
+ }
918
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
919
+ _handleClick(e) {
920
+ this.dispatchEvent(new MouseEvent('it-click', { bubbles: true, composed: true }));
921
+ }
922
+ /*
923
+ Override default browser validation messages
924
+ */
925
+ handleValidationMessages() {
926
+ if (!this.customValidation) {
927
+ const _v = this.inputElement.validity;
928
+ const isRequiredHandledByGroup = this.isInGroup === true;
929
+ if (_v.valueMissing && !isRequiredHandledByGroup) {
930
+ this.setCustomValidity(this.$t('validityRequired'));
931
+ }
932
+ else if (_v.patternMismatch) {
933
+ this.setCustomValidity(this.$t('validityPattern'));
934
+ }
935
+ else if (_v.tooShort) {
936
+ this.setCustomValidity(this.$t('validityMinlength').replace('{minlength}', this.minlength.toString()));
937
+ }
938
+ else if (_v.tooLong) {
939
+ this.setCustomValidity(this.$t('validityMaxlength').replace('{maxlength}', this.maxlength.toString()));
940
+ }
941
+ else {
942
+ /* nothing. Usa il messaggio di errore della validazione
943
+ di default del browser per altri errori di validità come:
944
+ - typeMismatch
945
+ - rangeUnderflow
946
+ - rangeOverflow
947
+ - stepMismatch
948
+ - badInput */
949
+ const otherConstraintErrors = _v.typeMismatch || _v.rangeUnderflow || _v.rangeOverflow || _v.stepMismatch || _v.badInput;
950
+ if (!otherConstraintErrors) {
951
+ this.setCustomValidity('');
952
+ }
953
+ }
954
+ }
955
+ this.validationMessage = this.inputElement.validationMessage;
956
+ }
957
+ _handleInvalid(event) {
958
+ this.formControlController.setValidity(false);
959
+ this.formControlController.emitInvalidEvent(event);
960
+ }
961
+ _handleChange(e) {
962
+ const target = e.target;
963
+ let value;
964
+ if (target instanceof HTMLInputElement) {
965
+ switch (target.type) {
966
+ case 'checkbox':
967
+ case 'radio':
968
+ value = target.checked;
969
+ break;
970
+ case 'file':
971
+ value = target.files; // FileList
972
+ break;
973
+ default:
974
+ value = target.value;
975
+ }
976
+ }
977
+ else if (target instanceof HTMLSelectElement) {
978
+ if (target.multiple) {
979
+ value = Array.from(target.selectedOptions).map((o) => o.value);
980
+ }
981
+ else {
982
+ value = target.value;
983
+ }
984
+ }
985
+ else {
986
+ // textarea o altri input con value
987
+ value = target.value;
988
+ }
989
+ this.dispatchEvent(new CustomEvent('it-change', {
990
+ detail: { value, el: target },
991
+ bubbles: true,
992
+ composed: true,
993
+ }));
994
+ }
995
+ updated(changedProperties) {
996
+ super.updated?.(changedProperties);
997
+ if (this.customValidation) {
998
+ this.setCustomValidity(this.validationText ?? '');
999
+ }
1000
+ else if (this.formControlController.userInteracted()) {
1001
+ this.formControlController.updateValidity();
1002
+ }
1003
+ }
1004
+ }
1005
+ __decorate([
1006
+ state(),
1007
+ __metadata("design:type", Object)
1008
+ ], FormControl.prototype, "_touched", void 0);
1009
+ __decorate([
1010
+ query('.it-form__control'),
1011
+ __metadata("design:type", HTMLInputElement)
1012
+ ], FormControl.prototype, "inputElement", void 0);
1013
+ __decorate([
1014
+ property({ type: String, reflect: true }) // from FormControl
1015
+ ,
1016
+ __metadata("design:type", Object)
1017
+ ], FormControl.prototype, "name", void 0);
1018
+ __decorate([
1019
+ property({ reflect: true }),
1020
+ __metadata("design:type", Object)
1021
+ ], FormControl.prototype, "value", void 0);
1022
+ __decorate([
1023
+ property({ type: Boolean, reflect: true }) // from FormControl
1024
+ ,
1025
+ __metadata("design:type", Object)
1026
+ ], FormControl.prototype, "disabled", void 0);
1027
+ __decorate([
1028
+ property({ reflect: true, type: String }),
1029
+ __metadata("design:type", Object)
1030
+ ], FormControl.prototype, "form", void 0);
1031
+ __decorate([
1032
+ property({ type: Boolean, reflect: true, attribute: 'custom-validation' }),
1033
+ __metadata("design:type", Object)
1034
+ ], FormControl.prototype, "customValidation", void 0);
1035
+ __decorate([
1036
+ property({ attribute: 'validity-message', reflect: true }),
1037
+ __metadata("design:type", String)
1038
+ ], FormControl.prototype, "validationText", void 0);
1039
+ __decorate([
1040
+ property(),
1041
+ __metadata("design:type", String)
1042
+ ], FormControl.prototype, "pattern", void 0);
1043
+ __decorate([
1044
+ property(),
1045
+ __metadata("design:type", Object)
1046
+ ], FormControl.prototype, "min", void 0);
1047
+ __decorate([
1048
+ property(),
1049
+ __metadata("design:type", Object)
1050
+ ], FormControl.prototype, "max", void 0);
1051
+ __decorate([
1052
+ property(),
1053
+ __metadata("design:type", Object)
1054
+ ], FormControl.prototype, "step", void 0);
1055
+ __decorate([
1056
+ property({ type: Number }),
1057
+ __metadata("design:type", Object)
1058
+ ], FormControl.prototype, "minlength", void 0);
1059
+ __decorate([
1060
+ property({ type: Number }),
1061
+ __metadata("design:type", Object)
1062
+ ], FormControl.prototype, "maxlength", void 0);
1063
+ __decorate([
1064
+ property({ type: Boolean, reflect: true }) // from FormControl
1065
+ ,
1066
+ __metadata("design:type", Object)
1067
+ ], FormControl.prototype, "required", void 0);
1068
+ __decorate([
1069
+ property({ type: Boolean }),
1070
+ __metadata("design:type", Object)
1071
+ ], FormControl.prototype, "isInGroup", void 0);
1072
+ __decorate([
1073
+ state(),
1074
+ __metadata("design:type", Object)
1075
+ ], FormControl.prototype, "validationMessage", void 0);
1076
+
1077
+ if (typeof window !== 'undefined') {
1078
+ window._itAnalytics = window._itAnalytics || {};
1079
+ window._itAnalytics = {
1080
+ ...window._itAnalytics,
1081
+ version: '1.0.0-alpha.4',
1082
+ };
1083
+ }
208
1084
 
209
1085
  const registry = {
210
1086
  'it-android-square': () => import('../it-android-square-DfqyrO5U.js'),
@@ -637,8 +1513,24 @@ var styles = css`/***************************** 1 ******************************
637
1513
  display: inline-block;
638
1514
  }
639
1515
 
1516
+ :host([align=top]) {
1517
+ vertical-align: top;
1518
+ }
1519
+
1520
+ :host([align=middle]),
1521
+ :host(:not([align])) {
1522
+ vertical-align: middle;
1523
+ }
1524
+
1525
+ :host([align=bottom]) {
1526
+ vertical-align: bottom;
1527
+ }
1528
+
640
1529
  .icon-white {
641
1530
  fill: #fff !important;
1531
+ }
1532
+ .icon-white path {
1533
+ fill: #fff !important;
642
1534
  }`;
643
1535
 
644
1536
  let ItIcon = class ItIcon extends BaseComponent {
@@ -756,9 +1648,17 @@ let ItIcon = class ItIcon extends BaseComponent {
756
1648
  this.applySvgAttributes(this.svgElement);
757
1649
  }
758
1650
  updateClasses() {
759
- return this.composeClass('icon', this.size ? `icon-${this.size}` : '', this.color ? `icon-${this.color}` : '',
760
- // this.background ? `bg-${this.background}` : '',
761
- this.align ? `align-${this.align}` : '', this.padded ? `icon-padded` : '');
1651
+ return [
1652
+ 'icon',
1653
+ this.size ? `icon-${this.size}` : '',
1654
+ this.color ? `icon-${this.color}` : '',
1655
+ // this.background ? `bg-${this.background}` : '',
1656
+ this.align ? `align-${this.align}` : '',
1657
+ this.padded ? `icon-padded` : '',
1658
+ ]
1659
+ .filter(Boolean)
1660
+ .join(' ')
1661
+ .trim();
762
1662
  }
763
1663
  handleSlotChange() {
764
1664
  const nodes = this.slotEl.assignedNodes({ flatten: true });