@italia/skiplinks 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.
@@ -0,0 +1,1173 @@
1
+ import { LitElement, css, html } from 'lit';
2
+ import { state, query, property, customElement } from 'lit/decorators.js';
3
+ import { directive, Directive } from 'lit/directive.js';
4
+
5
+ /******************************************************************************
6
+ Copyright (c) Microsoft Corporation.
7
+
8
+ Permission to use, copy, modify, and/or distribute this software for any
9
+ purpose with or without fee is hereby granted.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
+ PERFORMANCE OF THIS SOFTWARE.
18
+ ***************************************************************************** */
19
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
20
+
21
+
22
+ function __decorate(decorators, target, key, desc) {
23
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
24
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
25
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
26
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
27
+ }
28
+
29
+ function __metadata(metadataKey, metadataValue) {
30
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
31
+ }
32
+
33
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
34
+ var e = new Error(message);
35
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
36
+ };
37
+
38
+ class SetAttributesDirective extends Directive {
39
+ update(part, [attributes]) {
40
+ const el = part.element;
41
+ for (const [name, value] of Object.entries(attributes)) {
42
+ if (value != null)
43
+ el.setAttribute(name, value);
44
+ else
45
+ el.removeAttribute(name);
46
+ }
47
+ return null;
48
+ }
49
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
50
+ render(_attributes) {
51
+ return null;
52
+ }
53
+ }
54
+ /* How to use:
55
+
56
+ <textarea ${setAttributes(this._ariaAttributes)} ... />
57
+ */
58
+ const setAttributes = directive(SetAttributesDirective);
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
+
62
+ const connectedElements = new Set();
63
+ if (window && !window.translations) {
64
+ window.translations = new Map();
65
+ }
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';
72
+ const isClient = typeof MutationObserver !== 'undefined' &&
73
+ typeof document !== 'undefined' &&
74
+ typeof document.documentElement !== 'undefined';
75
+ /** Updates all localized elements that are currently connected */
76
+ function update() {
77
+ if (isClient) {
78
+ documentDirection = document.documentElement.dir || 'ltr';
79
+ documentLanguage = document.documentElement.lang || navigator.language;
80
+ }
81
+ [...connectedElements.keys()].forEach((el) => {
82
+ const litEl = el;
83
+ if (typeof litEl.requestUpdate === 'function') {
84
+ litEl.requestUpdate();
85
+ }
86
+ });
87
+ }
88
+ if (isClient) {
89
+ const documentElementObserver = new MutationObserver(update);
90
+ documentDirection = document.documentElement.dir || 'ltr';
91
+ documentLanguage = document.documentElement.lang || navigator.language;
92
+ // Watch for changes on <html lang>
93
+ documentElementObserver.observe(document.documentElement, {
94
+ attributes: true,
95
+ attributeFilter: ['dir', 'lang'],
96
+ });
97
+ }
98
+ /** Registers one or more translations */
99
+ function registerTranslation(...translation) {
100
+ translation.forEach((t) => {
101
+ const code = t.$code.toLowerCase();
102
+ if (translations.has(code)) {
103
+ // Merge translations that share the same language code
104
+ translations.set(code, { ...translations.get(code), ...t });
105
+ }
106
+ else {
107
+ translations.set(code, t);
108
+ }
109
+ // The first translation that's registered is the fallback
110
+ if (!fallback) {
111
+ fallback = t;
112
+ }
113
+ });
114
+ update();
115
+ }
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
+ };
341
+
342
+ /* eslint-disable no-console */
343
+ class Logger {
344
+ constructor(tag) {
345
+ this.tag = tag;
346
+ }
347
+ format(level, msg) {
348
+ return [`[${this.tag}] ${msg}`];
349
+ }
350
+ warn(msg) {
351
+ console.warn(...this.format('warn', msg));
352
+ }
353
+ error(msg) {
354
+ console.error(...this.format('error', msg));
355
+ }
356
+ info(msg) {
357
+ console.info(...this.format('info', msg));
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Factory function per creare una base class estendibile
363
+ * con stili personalizzati.
364
+ */
365
+ class BaseComponent extends LitElement {
366
+ constructor() {
367
+ super();
368
+ this.composeClass = clsx;
369
+ this.logger = new Logger(this.tagName.toLowerCase());
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
+ }
383
+ // eslint-disable-next-line class-methods-use-this
384
+ generateId(prefix) {
385
+ return `${prefix}-${Math.random().toString(36).slice(2)}`;
386
+ }
387
+ // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars
388
+ addFocus(element) {
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.
390
+ }
391
+ // eslint-disable-next-line class-methods-use-this
392
+ getActiveElement() {
393
+ let active = document.activeElement;
394
+ while (active && active.shadowRoot && active.shadowRoot.activeElement) {
395
+ active = active.shadowRoot.activeElement;
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;
405
+ }
406
+ connectedCallback() {
407
+ super.connectedCallback();
408
+ // generate internal _id
409
+ const prefix = this.id?.length > 0 ? this.id : this.tagName.toLowerCase();
410
+ this._id = this.generateId(prefix);
411
+ }
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
+ }
1084
+
1085
+ var styles = css`/***************************** 1 ****************************************/
1086
+ /***************************** 2 ****************************************/
1087
+ /***************************** 1 ****************************************/
1088
+ /***************************** 2 ****************************************/
1089
+ /***************************** 1 ****************************************/
1090
+ /***************************** 2 ****************************************/
1091
+ /***************************** 3 ****************************************/
1092
+ /***************************** 1 ****************************************/
1093
+ /***************************** 2 ****************************************/
1094
+ /***************************** 3 ****************************************/
1095
+ /***************************** NEUTRAL 1 ****************************************/
1096
+ /***************************** NEUTRAL 2 ****************************************/
1097
+ /***************************** NEUTRAL 2 / 3 ****************************************/
1098
+ .skiplinks {
1099
+ background-color: hsl(210, 62%, 97%);
1100
+ text-align: center;
1101
+ }
1102
+ .skiplinks a {
1103
+ padding: 0.5rem 0.5rem;
1104
+ display: block;
1105
+ font-weight: 600;
1106
+ color: hsl(210, 100%, 40%);
1107
+ text-decoration: underline;
1108
+ }
1109
+ .skiplinks ul {
1110
+ list-style: none;
1111
+ padding: 0;
1112
+ font-size: 1rem;
1113
+ line-height: 1.5rem;
1114
+ margin-bottom: 0;
1115
+ }
1116
+
1117
+ .visually-hidden,
1118
+ .visually-hidden-focusable:not(:focus):not(:focus-within) {
1119
+ position: absolute !important;
1120
+ width: 1px !important;
1121
+ height: 1px !important;
1122
+ padding: 0 !important;
1123
+ margin: -1px !important;
1124
+ overflow: hidden !important;
1125
+ clip: rect(0, 0, 0, 0) !important;
1126
+ white-space: nowrap !important;
1127
+ border: 0 !important;
1128
+ }`;
1129
+
1130
+ let ItSkiplinks = class ItSkiplinks extends BaseComponent {
1131
+ constructor() {
1132
+ super(...arguments);
1133
+ this.links = [];
1134
+ }
1135
+ _onSlotChange(e) {
1136
+ const slot = e.target;
1137
+ const assigned = slot?.assignedElements({ flatten: true });
1138
+ this.links = assigned
1139
+ .filter((el) => el.tagName === 'A')
1140
+ .map((a) => ({
1141
+ href: a.getAttribute('href'),
1142
+ text: a.textContent?.trim(),
1143
+ }));
1144
+ this.requestUpdate(); // aggiorna la UI
1145
+ }
1146
+ render() {
1147
+ return html `
1148
+ <slot @slotchange=${this._onSlotChange}></slot>
1149
+ ${this.links.length > 2
1150
+ ? html `
1151
+ <nav class="skiplinks" role="navigation" ${setAttributes(this._ariaAttributes)}>
1152
+ <ul part="skiplinks-list">
1153
+ ${this.links.map((link) => html `
1154
+ <li class="visually-hidden-focusable">
1155
+ <a href=${link.href}>${link.text}</a>
1156
+ </li>
1157
+ `)}
1158
+ </ul>
1159
+ </nav>
1160
+ `
1161
+ : html `<div class="skiplinks">
1162
+ ${this.links.map((link) => html ` <a href=${link.href} class="visually-hidden-focusable">${link.text}</a> `)}
1163
+ </div>`}
1164
+ `;
1165
+ }
1166
+ };
1167
+ ItSkiplinks.styles = styles;
1168
+ ItSkiplinks = __decorate([
1169
+ customElement('it-skiplinks')
1170
+ ], ItSkiplinks);
1171
+
1172
+ export { ItSkiplinks };
1173
+ //# sourceMappingURL=it-skiplinks.js.map