@italia/navscroll 1.0.0-alpha.10

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,1549 @@
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
+ 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
+ if (typeof window !== 'undefined') {
117
+ window.registerTranslation = registerTranslation;
118
+ }
119
+ /**
120
+ * Localize Reactive Controller for components built with Lit
121
+ *
122
+ * To use this controller, import the class and instantiate it in a custom element constructor:
123
+ *
124
+ * private localize = new LocalizeController(this);
125
+ *
126
+ * This will add the element to the set and make it respond to changes to <html dir|lang> automatically. To make it
127
+ * respond to changes to its own dir|lang properties, make it a property:
128
+ *
129
+ * @property() dir: string;
130
+ * @property() lang: string;
131
+ *
132
+ * To use a translation method, call it like this:
133
+ *
134
+ * ${this.localize.term('term_key_here')}
135
+ * ${this.localize.date('2021-12-03')}
136
+ * ${this.localize.number(1000000)}
137
+ */
138
+ class LocalizeController {
139
+ constructor(host) {
140
+ this.host = host;
141
+ this.host.addController(this);
142
+ }
143
+ hostConnected() {
144
+ connectedElements.add(this.host);
145
+ }
146
+ hostDisconnected() {
147
+ connectedElements.delete(this.host);
148
+ }
149
+ /**
150
+ * Gets the host element's directionality as determined by the `dir` attribute. The return value is transformed to
151
+ * lowercase.
152
+ */
153
+ dir() {
154
+ return `${this.host.dir || documentDirection}`.toLowerCase();
155
+ }
156
+ /**
157
+ * Gets the host element's language as determined by the `lang` attribute. The return value is transformed to
158
+ * lowercase.
159
+ */
160
+ lang() {
161
+ return `${this.host.lang || documentLanguage}`.toLowerCase();
162
+ }
163
+ // eslint-disable-next-line class-methods-use-this
164
+ getTranslationData(lang) {
165
+ // Convert "en_US" to "en-US". Note that both underscores and dashes are allowed per spec, but underscores result in
166
+ // a RangeError by the call to `new Intl.Locale()`. See: https://unicode.org/reports/tr35/#unicode-locale-identifier
167
+ const locale = new Intl.Locale(lang.replace(/_/g, '-'));
168
+ const language = locale?.language.toLowerCase();
169
+ const region = locale?.region?.toLowerCase() ?? '';
170
+ const primary = translations.get(`${language}-${region}`);
171
+ const secondary = translations.get(language);
172
+ return { locale, language, region, primary, secondary };
173
+ }
174
+ /** Determines if the specified term exists, optionally checking the fallback translation. */
175
+ exists(key, options) {
176
+ const { primary, secondary } = this.getTranslationData(options.lang ?? this.lang());
177
+ const mergedOptions = {
178
+ includeFallback: false,
179
+ ...options,
180
+ };
181
+ if ((primary && primary[key]) ||
182
+ (secondary && secondary[key]) ||
183
+ (mergedOptions.includeFallback && fallback && fallback[key])) {
184
+ return true;
185
+ }
186
+ return false;
187
+ }
188
+ /** Outputs a translated term. */
189
+ term(key, ...args) {
190
+ const { primary, secondary } = this.getTranslationData(this.lang());
191
+ let term;
192
+ // Look for a matching term using regionCode, code, then the fallback
193
+ if (primary && primary[key]) {
194
+ term = primary[key];
195
+ }
196
+ else if (secondary && secondary[key]) {
197
+ term = secondary[key];
198
+ }
199
+ else if (fallback && fallback[key]) {
200
+ term = fallback[key];
201
+ }
202
+ else {
203
+ // eslint-disable-next-line no-console
204
+ console.error(`No translation found for: ${String(key)}`);
205
+ return String(key);
206
+ }
207
+ if (typeof term === 'function') {
208
+ return term(...args);
209
+ }
210
+ return term;
211
+ }
212
+ /** Outputs a localized date in the specified format. */
213
+ date(dateToFormat, options) {
214
+ const date = new Date(dateToFormat);
215
+ return new Intl.DateTimeFormat(this.lang(), options).format(date);
216
+ }
217
+ /** Outputs a localized number in the specified format. */
218
+ number(numberToFormat, options) {
219
+ const num = Number(numberToFormat);
220
+ return Number.isNaN(num) ? '' : new Intl.NumberFormat(this.lang(), options).format(num);
221
+ }
222
+ /** Outputs a localized time in relative format. */
223
+ relativeTime(value, unit, options) {
224
+ return new Intl.RelativeTimeFormat(this.lang(), options).format(value, unit);
225
+ }
226
+ }
227
+
228
+ /**
229
+ * @param Base The base class.
230
+ * @returns A mix-in implementing `localizations` method.
231
+ *
232
+ *@example
233
+ * <!-- Terms -->
234
+ ${this.$localize.term('hello')}
235
+ or
236
+ ${this.$t('hello')}
237
+
238
+ <!-- Dates -->
239
+ ${this.$localize.date('2021-09-15 14:00:00 ET', { month: 'long', day: 'numeric', year: 'numeric' })}
240
+ or
241
+ ${this.$d('2021-09-15 14:00:00 ET', { month: 'long', day: 'numeric', year: 'numeric' })}
242
+
243
+ <!-- Numbers/currency -->
244
+ ${this.$localize.number(1000, { style: 'currency', currency: 'USD'})}
245
+ or
246
+ ${this.$n(1000,{ style: 'currency', currency: 'USD'})}
247
+
248
+ <!-- Determining language -->
249
+ ${this.$localize.lang()}
250
+
251
+ <!-- Determining directionality, e.g. 'ltr' or 'rtl' -->
252
+ ${this.$localize.dir()}
253
+
254
+
255
+ *** HOW TO DEFINE TRANSLATIONS: ***
256
+ // Simple terms
257
+ upload: 'Upload',
258
+
259
+ // Terms with placeholders
260
+ greetUser: (name: string) => `Hello, ${name}!`,
261
+
262
+ // Plurals
263
+ numFilesSelected: (count: number) => {
264
+ if (count === 0) return 'No files selected';
265
+ if (count === 1) return '1 file selected';
266
+ return `${count} files selected`;
267
+ }
268
+ */
269
+ const LocalizeMixin = (Base) => class extends Base {
270
+ constructor() {
271
+ super(...arguments);
272
+ this.localize = new LocalizeController(this);
273
+ }
274
+ // Provide default values to avoid definite assignment errors and avoid decorators
275
+ // commentati perchè danno problemi su React.js. Sono attributi nativi, e assegnare un valore di default a react da fastidio
276
+ // dir: string = '';
277
+ // lang: string = '';
278
+ /**
279
+ * Restituisce tutta l'utility di traduzione
280
+ *
281
+
282
+ *
283
+ * @returns tutta l'utility di traduzione
284
+ *
285
+ * @example
286
+ * this.$localize.lang() -> ritorna la lingua corrente
287
+ * this.$localize.dir() -> ritorna la direzione della lingua corrente
288
+ */
289
+ get $localize() {
290
+ return this.localize;
291
+ }
292
+ /**
293
+ * Restituisce una stringa localizzata a partire da una chiave di termine.
294
+ *
295
+ * Utilizza il `LocalizeController` per accedere al dizionario corrente e
296
+ * tradurre la chiave fornita secondo la lingua attiva.
297
+ *
298
+ * @param t - La chiave del termine da localizzare (es. 'hello', 'submit', ecc.).
299
+ * @returns La stringa tradotta in base alla lingua attiva. Se la chiave non è trovata, restituisce la chiave stessa.
300
+ *
301
+ * @example
302
+ * this.$t('hello'); // → "Ciao" (in locale it-IT)
303
+ */
304
+ $t(t) {
305
+ // format term
306
+ return this.localize.term(t);
307
+ }
308
+ /**
309
+ * Formatta una data in base alla localizzazione attiva.
310
+ *
311
+ * Utilizza il `LocalizeController` per restituire una stringa localizzata
312
+ * secondo le opzioni fornite (es. mese esteso, anno, ecc.).
313
+ *
314
+ * @param n - La data da formattare come stringa compatibile (es. ISO o con timezone, es. '2021-09-15 14:00:00 ET').
315
+ * @param p - Le opzioni di formattazione per `Intl.DateTimeFormat` (es. { year: 'numeric', month: 'long', day: 'numeric' }).
316
+ * @returns Una stringa rappresentante la data formattata secondo la localizzazione attiva.
317
+ *
318
+ * @example
319
+ * this.$d('2021-09-15 14:00:00 ET', { year: 'numeric', month: 'long', day: 'numeric' });
320
+ * // → "15 settembre 2021" (in locale it-IT)
321
+ */
322
+ $d(d, p) {
323
+ // format date
324
+ return this.localize.date(d, p);
325
+ }
326
+ /**
327
+ * Formatta un numero secondo le impostazioni locali dell'utente corrente.
328
+ *
329
+ * Utilizza il `LocalizeController` per applicare formattazione numerica,
330
+ * incluse opzioni come separatori, decimali, valute, ecc.
331
+ *
332
+ * @param d - Il numero da formattare.
333
+ * @param p - Le opzioni di formattazione (es. { style: 'currency', currency: 'EUR' }).
334
+ * @returns Una stringa rappresentante il numero formattato secondo la localizzazione attiva.
335
+ *
336
+ * @example
337
+ * this.$n(1234.56, { style: 'currency', currency: 'USD' }); // → "$1,234.56" (in locale en-US)
338
+ */
339
+ $n(d, p) {
340
+ return this.localize.number(d, p);
341
+ }
342
+ };
343
+
344
+ /* eslint-disable no-console */
345
+ class Logger {
346
+ constructor(tag) {
347
+ this.tag = tag;
348
+ }
349
+ format(level, msg) {
350
+ return [`[${this.tag}] ${msg}`];
351
+ }
352
+ warn(msg) {
353
+ console.warn(...this.format('warn', msg));
354
+ }
355
+ error(msg) {
356
+ console.error(...this.format('error', msg));
357
+ }
358
+ info(msg) {
359
+ console.info(...this.format('info', msg));
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Factory function per creare una base class estendibile
365
+ * con stili personalizzati.
366
+ */
367
+ class BaseComponent extends LitElement {
368
+ constructor() {
369
+ super();
370
+ this.composeClass = clsx;
371
+ this.logger = new Logger(this.tagName.toLowerCase());
372
+ }
373
+ get _ariaAttributes() {
374
+ const attributes = {};
375
+ for (const attr of this.getAttributeNames()) {
376
+ if (attr === 'it-role') {
377
+ attributes.role = this.getAttribute(attr);
378
+ }
379
+ else if (attr.startsWith('it-aria-')) {
380
+ attributes[attr.replace(/^it-/, '')] = this.getAttribute(attr);
381
+ }
382
+ }
383
+ return attributes;
384
+ }
385
+ // eslint-disable-next-line class-methods-use-this
386
+ generateId(prefix) {
387
+ return `${prefix}-${Math.random().toString(36).slice(2)}`;
388
+ }
389
+ // eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars
390
+ addFocus(element) {
391
+ // new TrackFocus(element); // per il momento è stato disattivato perchè ci sono le pseudo classi ::focus-visible per fare quello che fa TrackFocus. Si possono aggiungere regole css in bsi-italia 3 dato che stiamo facendo una breaking release di bsi.
392
+ }
393
+ // eslint-disable-next-line class-methods-use-this
394
+ getActiveElement() {
395
+ let active = document.activeElement;
396
+ while (active && active.shadowRoot && active.shadowRoot.activeElement) {
397
+ active = active.shadowRoot.activeElement;
398
+ }
399
+ return active;
400
+ }
401
+ get focusElement() {
402
+ return this;
403
+ }
404
+ // eslint-disable-next-line class-methods-use-this
405
+ get prefersReducedMotion() {
406
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
407
+ }
408
+ connectedCallback() {
409
+ super.connectedCallback();
410
+ // generate internal _id
411
+ const prefix = this.id?.length > 0 ? this.id : this.tagName.toLowerCase();
412
+ this._id = this.generateId(prefix);
413
+ }
414
+ }
415
+ const BaseLocalizedComponent = LocalizeMixin(BaseComponent);
416
+
417
+ //
418
+ // We store a WeakMap of forms + controls so we can keep references to all FormControl within a given form. As
419
+ // elements connect and disconnect to/from the DOM, their containing form is used as the key and the form control is
420
+ // added and removed from the form's set, respectively.
421
+ //
422
+ const formCollections = new WeakMap();
423
+ //
424
+ // We store a WeakMap of reportValidity() overloads so we can override it when form controls connect to the DOM and
425
+ // restore the original behavior when they disconnect.
426
+ //
427
+ const reportValidityOverloads = new WeakMap();
428
+ const checkValidityOverloads = new WeakMap();
429
+ //
430
+ // We store a Set of controls that users have interacted with. This allows us to determine the interaction state
431
+ // without littering the DOM with additional data attributes.
432
+ //
433
+ const userInteractedControls = new WeakSet();
434
+ //
435
+ // We store a WeakMap of interactions for each form control so we can track when all conditions are met for validation.
436
+ //
437
+ const interactions = new WeakMap();
438
+ /** A reactive controller to allow form controls to participate in form submission, validation, etc. */
439
+ class FormControlController {
440
+ constructor(host, options) {
441
+ this.submittedOnce = false;
442
+ this.handleFormData = (event) => {
443
+ // console.log('handleFormData');
444
+ const disabled = this.options.disabled(this.host);
445
+ const name = this.options.name(this.host);
446
+ const value = this.options.value(this.host);
447
+ const tagName = this.host.tagName.toLowerCase();
448
+ // For buttons, we only submit the value if they were the submitter. This is currently done in doAction() by
449
+ // injecting the name/value on a temporary button, so we can just skip them here.
450
+ const isButton = tagName === 'it-button';
451
+ if (this.host.isConnected &&
452
+ !disabled &&
453
+ !isButton &&
454
+ typeof name === 'string' &&
455
+ name.length > 0 &&
456
+ typeof value !== 'undefined') {
457
+ switch (tagName) {
458
+ case 'it-radio':
459
+ if (this.host.checked) {
460
+ event.formData.append(name, value);
461
+ }
462
+ break;
463
+ case 'it-checkbox':
464
+ case 'it-toggle':
465
+ if (this.host.checked) {
466
+ if (event.formData.getAll(name).indexOf(value) < 0) {
467
+ // handle group checkbox
468
+ event.formData.append(name, value);
469
+ }
470
+ }
471
+ break;
472
+ case 'it-checkbox-group':
473
+ case 'it-toggle-group':
474
+ // non settare valori in formData, perchè ogni singola checkbox setta il suo valore
475
+ break;
476
+ case 'it-upload':
477
+ // value is File[] — append each File object directly (not as string)
478
+ if (Array.isArray(value)) {
479
+ value.forEach((file) => {
480
+ event.formData.append(name, file);
481
+ });
482
+ }
483
+ break;
484
+ default:
485
+ if (Array.isArray(value)) {
486
+ value.forEach((val) => {
487
+ event.formData.append(name, val.toString());
488
+ });
489
+ }
490
+ else {
491
+ event.formData.append(name, value.toString());
492
+ }
493
+ }
494
+ }
495
+ };
496
+ this.handleFormSubmit = (event) => {
497
+ const disabled = this.options.disabled(this.host);
498
+ const reportValidity = this.options.reportValidity;
499
+ // Update the interacted state for all controls when the form is submitted
500
+ if (this.form && !this.form.noValidate) {
501
+ formCollections.get(this.form)?.forEach((control) => {
502
+ this.setUserInteracted(control, true);
503
+ });
504
+ }
505
+ const resReportValidity = reportValidity(this.host);
506
+ if (this.form && !this.form.noValidate && !disabled && !resReportValidity) {
507
+ event.preventDefault();
508
+ // event.stopImmediatePropagation(); // se lo attiviamo, valida un campo alla volta
509
+ // Scroll al primo controllo non valido
510
+ const formControls = formCollections.get(this.form);
511
+ if (formControls) {
512
+ for (const control of formControls) {
513
+ if (!control.validity?.valid) {
514
+ // Scroll smooth verso il controllo non valido
515
+ control.scrollIntoView({
516
+ behavior: 'smooth',
517
+ block: 'center',
518
+ });
519
+ break;
520
+ }
521
+ }
522
+ }
523
+ }
524
+ this.submittedOnce = true;
525
+ };
526
+ this.handleFormReset = () => {
527
+ this.options.setValue(this.host, '');
528
+ this.submittedOnce = false;
529
+ this.setUserInteracted(this.host, false);
530
+ interactions.set(this.host, []);
531
+ };
532
+ this.handleInteraction = (event) => {
533
+ const emittedEvents = interactions.get(this.host);
534
+ if (!emittedEvents.includes(event.type)) {
535
+ emittedEvents.push(event.type);
536
+ }
537
+ // Mark it as user-interacted as soon as all associated events have been emitted
538
+ if (emittedEvents.length === this.options.assumeInteractionOn.length) {
539
+ this.setUserInteracted(this.host, true);
540
+ }
541
+ };
542
+ this.checkFormValidity = () => {
543
+ // console.log('checkFormValidity');
544
+ //
545
+ // This is very similar to the `reportFormValidity` function, but it does not trigger native constraint validation
546
+ // Allow the user to simply check if the form is valid and handling validity in their own way.
547
+ //
548
+ // We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
549
+ // validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
550
+ // be necessary once we can use ElementInternals.
551
+ //
552
+ // Note that we're also honoring the form's novalidate attribute.
553
+ //
554
+ if (this.form && !this.form.noValidate) {
555
+ // This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
556
+ // elements that support the constraint validation API.
557
+ const elements = this.form.querySelectorAll('*');
558
+ for (const element of elements) {
559
+ if (typeof element.checkValidity === 'function') {
560
+ if (!element.checkValidity()) {
561
+ return false;
562
+ }
563
+ }
564
+ }
565
+ }
566
+ return true;
567
+ };
568
+ this.reportFormValidity = () => {
569
+ // console.log('reportFormValidity');
570
+ //
571
+ // FormControl work hard to act like regular form controls. They support the Constraint Validation API
572
+ // and its associated methods such as setCustomValidity() and reportValidity(). However, the HTMLFormElement also
573
+ // has a reportValidity() method that will trigger validation on all child controls. Since we're not yet using
574
+ // ElementInternals, we need to overload this method so it looks for any element with the reportValidity() method.
575
+ //
576
+ // We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
577
+ // validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
578
+ // be necessary once we can use ElementInternals.
579
+ //
580
+ // Note that we're also honoring the form's novalidate attribute.
581
+ //
582
+ if (this.form && !this.form.noValidate) {
583
+ // This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
584
+ // elements that support the constraint validation API.
585
+ const elements = this.form.querySelectorAll('*');
586
+ for (const element of elements) {
587
+ if (typeof element.reportValidity === 'function') {
588
+ if (!element.reportValidity()) {
589
+ return false;
590
+ }
591
+ }
592
+ }
593
+ }
594
+ return true;
595
+ };
596
+ (this.host = host).addController(this);
597
+ this.options = {
598
+ form: (input) => {
599
+ // If there's a form attribute, use it to find the target form by id
600
+ // Controls may not always reflect the 'form' property. For example, `<it-button>` doesn't reflect.
601
+ const formId = input.form;
602
+ if (formId) {
603
+ const root = input.getRootNode();
604
+ const form = root.querySelector(`#${formId}`);
605
+ if (form) {
606
+ return form;
607
+ }
608
+ }
609
+ return input.closest('form');
610
+ },
611
+ name: (input) => input.name,
612
+ value: (input) => input.value,
613
+ disabled: (input) => input.disabled ?? false,
614
+ reportValidity: (input) => typeof input.reportValidity === 'function' ? input.reportValidity() : true,
615
+ checkValidity: (input) => (typeof input.checkValidity === 'function' ? input.checkValidity() : true),
616
+ setValue: (input, value) => {
617
+ // eslint-disable-next-line no-param-reassign
618
+ input.value = value;
619
+ },
620
+ assumeInteractionOn: ['it-input'],
621
+ ...options,
622
+ };
623
+ }
624
+ hostConnected() {
625
+ const form = this.options.form(this.host);
626
+ if (form) {
627
+ this.attachForm(form);
628
+ }
629
+ // Listen for interactions
630
+ interactions.set(this.host, []);
631
+ this.options.assumeInteractionOn.forEach((event) => {
632
+ this.host.addEventListener(event, this.handleInteraction);
633
+ });
634
+ }
635
+ hostDisconnected() {
636
+ this.detachForm();
637
+ // Clean up interactions
638
+ interactions.delete(this.host);
639
+ this.options.assumeInteractionOn.forEach((event) => {
640
+ this.host.removeEventListener(event, this.handleInteraction);
641
+ });
642
+ }
643
+ hostUpdated() {
644
+ const form = this.options.form(this.host);
645
+ // Detach if the form no longer exists
646
+ if (!form) {
647
+ this.detachForm();
648
+ }
649
+ // If the form has changed, reattach it
650
+ if (form && this.form !== form) {
651
+ this.detachForm();
652
+ this.attachForm(form);
653
+ }
654
+ if (this.host.hasUpdated) {
655
+ this.setValidity(this.host.validity.valid);
656
+ }
657
+ }
658
+ attachForm(form) {
659
+ if (form) {
660
+ this.form = form;
661
+ // Add this element to the form's collection
662
+ if (formCollections.has(this.form)) {
663
+ formCollections.get(this.form).add(this.host);
664
+ }
665
+ else {
666
+ formCollections.set(this.form, new Set([this.host]));
667
+ }
668
+ this.form.addEventListener('formdata', this.handleFormData);
669
+ this.form.addEventListener('submit', this.handleFormSubmit);
670
+ this.form.addEventListener('reset', this.handleFormReset);
671
+ // Overload the form's reportValidity() method so it looks at FormControl
672
+ if (!reportValidityOverloads.has(this.form)) {
673
+ reportValidityOverloads.set(this.form, this.form.reportValidity);
674
+ this.form.reportValidity = () => this.reportFormValidity();
675
+ }
676
+ // Overload the form's checkValidity() method so it looks at FormControl
677
+ if (!checkValidityOverloads.has(this.form)) {
678
+ checkValidityOverloads.set(this.form, this.form.checkValidity);
679
+ this.form.checkValidity = () => this.checkFormValidity();
680
+ }
681
+ }
682
+ else {
683
+ this.form = undefined;
684
+ }
685
+ }
686
+ detachForm() {
687
+ if (!this.form)
688
+ return;
689
+ const formCollection = formCollections.get(this.form);
690
+ if (!formCollection) {
691
+ return;
692
+ }
693
+ this.submittedOnce = false;
694
+ // Remove this host from the form's collection
695
+ formCollection.delete(this.host);
696
+ // Check to make sure there's no other form controls in the collection. If we do this
697
+ // without checking if any other controls are still in the collection, then we will wipe out the
698
+ // validity checks for all other elements.
699
+ // see: https://github.com/shoelace-style/shoelace/issues/1703
700
+ if (formCollection.size <= 0) {
701
+ this.form.removeEventListener('formdata', this.handleFormData);
702
+ this.form.removeEventListener('submit', this.handleFormSubmit);
703
+ this.form.removeEventListener('reset', this.handleFormReset);
704
+ // Remove the overload and restore the original method
705
+ if (reportValidityOverloads.has(this.form)) {
706
+ this.form.reportValidity = reportValidityOverloads.get(this.form);
707
+ reportValidityOverloads.delete(this.form);
708
+ }
709
+ if (checkValidityOverloads.has(this.form)) {
710
+ this.form.checkValidity = checkValidityOverloads.get(this.form);
711
+ checkValidityOverloads.delete(this.form);
712
+ }
713
+ // So it looks weird here to not always set the form to undefined. But I _think_ if we unattach this.form here,
714
+ // we end up in this fun spot where future validity checks don't have a reference to the form validity handler.
715
+ // 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.
716
+ this.form = undefined;
717
+ }
718
+ }
719
+ // eslint-disable-next-line class-methods-use-this
720
+ setUserInteracted(el, hasInteracted) {
721
+ if (hasInteracted) {
722
+ userInteractedControls.add(el);
723
+ }
724
+ else {
725
+ userInteractedControls.delete(el);
726
+ }
727
+ el.requestUpdate();
728
+ }
729
+ doAction(type, submitter) {
730
+ // console.log('doaction', type);
731
+ if (this.form) {
732
+ const button = document.createElement('button');
733
+ button.type = type;
734
+ button.style.position = 'absolute';
735
+ button.style.width = '0';
736
+ button.style.height = '0';
737
+ button.style.clipPath = 'inset(50%)';
738
+ button.style.overflow = 'hidden';
739
+ button.style.whiteSpace = 'nowrap';
740
+ // Pass name, value, and form attributes through to the temporary button
741
+ if (submitter) {
742
+ button.name = submitter.name;
743
+ button.value = submitter.value;
744
+ ['formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget'].forEach((attr) => {
745
+ if (submitter.hasAttribute(attr)) {
746
+ button.setAttribute(attr, submitter.getAttribute(attr));
747
+ }
748
+ });
749
+ }
750
+ this.form.append(button);
751
+ button.click();
752
+ button.remove();
753
+ }
754
+ }
755
+ /** Returns the associated `<form>` element, if one exists. */
756
+ getForm() {
757
+ return this.form ?? null;
758
+ }
759
+ /** Resets the form, restoring all the control to their default value */
760
+ reset(submitter) {
761
+ this.doAction('reset', submitter);
762
+ }
763
+ /** Submits the form, triggering validation and form data injection. */
764
+ submit(submitter) {
765
+ // Calling form.submit() bypasses the submit event and constraint validation. To prevent this, we can inject a
766
+ // native submit button into the form, "click" it, then remove it to simulate a standard form submission.
767
+ this.doAction('submit', submitter);
768
+ }
769
+ /**
770
+ * Synchronously sets the form control's validity. Call this when you know the future validity but need to update
771
+ * the host element immediately, i.e. before Lit updates the component in the next update.
772
+ */
773
+ setValidity(isValid) {
774
+ const host = this.host;
775
+ const hasInteracted = Boolean(userInteractedControls.has(host));
776
+ const required = Boolean(host.required);
777
+ //
778
+ // We're mapping the following "states" to data attributes. In the future, we can use ElementInternals.states to
779
+ // create a similar mapping, but instead of [data-invalid] it will look like :--invalid.
780
+ //
781
+ // See this RFC for more details: https://github.com/shoelace-style/shoelace/issues/1011
782
+ //
783
+ host.toggleAttribute('data-required', required);
784
+ host.toggleAttribute('data-optional', !required);
785
+ host.toggleAttribute('data-invalid', !isValid);
786
+ host.toggleAttribute('data-valid', isValid);
787
+ host.toggleAttribute('data-user-invalid', !isValid && hasInteracted);
788
+ host.toggleAttribute('data-user-valid', isValid && hasInteracted);
789
+ }
790
+ userInteracted() {
791
+ const hasInteracted = Boolean(userInteractedControls.has(this.host));
792
+ return hasInteracted;
793
+ }
794
+ /**
795
+ * Updates the form control's validity based on the current value of `host.validity.valid`. Call this when anything
796
+ * that affects constraint validation changes so the component receives the correct validity states.
797
+ */
798
+ updateValidity() {
799
+ const host = this.host;
800
+ this.setValidity(host.validity.valid);
801
+ }
802
+ /**
803
+ * Dispatches a non-bubbling, cancelable custom event of type `it-invalid`.
804
+ * If the `it-invalid` event will be cancelled then the original `invalid`
805
+ * event (which may have been passed as argument) will also be cancelled.
806
+ * If no original `invalid` event has been passed then the `it-invalid`
807
+ * event will be cancelled before being dispatched.
808
+ */
809
+ emitInvalidEvent(originalInvalidEvent) {
810
+ const itInvalidEvent = new CustomEvent('it-invalid', {
811
+ bubbles: false,
812
+ composed: false,
813
+ cancelable: true,
814
+ detail: {},
815
+ });
816
+ if (!originalInvalidEvent) {
817
+ itInvalidEvent.preventDefault();
818
+ }
819
+ if (!this.host.dispatchEvent(itInvalidEvent)) {
820
+ originalInvalidEvent?.preventDefault();
821
+ }
822
+ }
823
+ }
824
+
825
+ const translation = {
826
+ $code: 'it',
827
+ $name: 'Italiano',
828
+ $dir: 'ltr',
829
+ validityRequired: 'Questo campo è obbligatorio.',
830
+ validityGroupRequired: "Scegli almeno un'opzione",
831
+ validityPattern: 'Il valore non corrisponde al formato richiesto.',
832
+ validityMinlength: 'Il valore deve essere lungo almeno {minlength} caratteri.',
833
+ validityMaxlength: 'Il valore deve essere lungo al massimo {maxlength} caratteri.',
834
+ };
835
+
836
+ registerTranslation(translation);
837
+ class FormControl extends BaseLocalizedComponent {
838
+ constructor() {
839
+ super(...arguments);
840
+ this.formControlController = new FormControlController(this, {
841
+ assumeInteractionOn: ['it-input', 'it-blur', 'it-change'],
842
+ });
843
+ // TODO: verificare se serve davvero con il fatto che usiamo form-controller
844
+ // static formAssociated = true;
845
+ // @property()
846
+ // internals = this.attachInternals();
847
+ this._touched = false;
848
+ /** The name of the input, submitted as a name/value pair with form data. */
849
+ this.name = '';
850
+ /** The current value of the input, submitted as a name/value pair with form data. */
851
+ this.value = '';
852
+ /** If the input is disabled. */
853
+ this.disabled = false;
854
+ /**
855
+ * By default, form controls are associated with the nearest containing `<form>` element. This attribute allows you
856
+ * to place the form control outside of a form and associate it with the form that has this `id`. The form must be in
857
+ * the same document or shadow root for this to work.
858
+ */
859
+ this.form = '';
860
+ /** If you implement your custom validation and you won't to trigger default validation */
861
+ this.customValidation = false;
862
+ /** If your input is invalid from your custom validition, set this attribute with message validation */
863
+ this.validationText = '';
864
+ /**
865
+ * Specifies the granularity that the value must adhere to, or the special value `any` which means no stepping is
866
+ * implied, allowing any numeric value. Only applies to date and number input types.
867
+ */
868
+ this.step = 'any';
869
+ /** The input's minimum length. */
870
+ this.minlength = -1;
871
+ /** The input's maximum length. */
872
+ this.maxlength = -1;
873
+ /** If the input is required. */
874
+ this.required = false;
875
+ /* For grouped input, like checkbox-group */
876
+ this.isInGroup = false;
877
+ this.validationMessage = '';
878
+ }
879
+ /** Gets the validity state object */
880
+ get validity() {
881
+ return this.inputElement?.validity;
882
+ }
883
+ /** Gets the associated form, if one exists. */
884
+ getForm() {
885
+ return this.formControlController.getForm();
886
+ }
887
+ // Form validation methods
888
+ checkValidity() {
889
+ const inputValid = this.inputElement?.checkValidity() ?? true; // this.inputElement.checkValidity() è la validazione del browser
890
+ return inputValid;
891
+ }
892
+ /** Checks for validity and shows the browser's validation message if the control is invalid. */
893
+ reportValidity() {
894
+ // const ret = this.inputElement.checkValidity();
895
+ const ret = this.checkValidity(); // chiama la checkValidity, che se è stata overridata chiama quella
896
+ this.handleValidationMessages();
897
+ return ret; // this.inputElement.reportValidity();
898
+ }
899
+ /** Sets a custom validation message. Pass an empty string to restore validity. */
900
+ setCustomValidity(message) {
901
+ this.inputElement.setCustomValidity(message);
902
+ this.validationMessage = this.inputElement.validationMessage;
903
+ this.formControlController.updateValidity();
904
+ }
905
+ // Handlers
906
+ _handleReady() {
907
+ requestAnimationFrame(() => {
908
+ this.dispatchEvent(new CustomEvent('it-input-ready', { bubbles: true, detail: { el: this.inputElement } }));
909
+ });
910
+ }
911
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
912
+ _handleInput(e) {
913
+ this.handleValidationMessages();
914
+ this.dispatchEvent(new CustomEvent('it-input', {
915
+ detail: { value: this.inputElement.value, el: this.inputElement },
916
+ bubbles: true,
917
+ composed: true,
918
+ }));
919
+ }
920
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
921
+ _handleBlur(e) {
922
+ this._touched = true;
923
+ this.handleValidationMessages();
924
+ this.dispatchEvent(new FocusEvent('it-blur', { bubbles: true, composed: true }));
925
+ }
926
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
927
+ _handleFocus(e) {
928
+ this.dispatchEvent(new FocusEvent('it-focus', { bubbles: true, composed: true }));
929
+ }
930
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
931
+ _handleClick(e) {
932
+ this.dispatchEvent(new MouseEvent('it-click', { bubbles: true, composed: true }));
933
+ }
934
+ /*
935
+ Override default browser validation messages
936
+ */
937
+ handleValidationMessages() {
938
+ if (!this.customValidation) {
939
+ const _v = this.inputElement.validity;
940
+ const isRequiredHandledByGroup = this.isInGroup === true;
941
+ if (_v.valueMissing && !isRequiredHandledByGroup) {
942
+ this.setCustomValidity(this.$t('validityRequired'));
943
+ }
944
+ else if (_v.patternMismatch) {
945
+ this.setCustomValidity(this.$t('validityPattern'));
946
+ }
947
+ else if (_v.tooShort) {
948
+ this.setCustomValidity(this.$t('validityMinlength').replace('{minlength}', this.minlength.toString()));
949
+ }
950
+ else if (_v.tooLong) {
951
+ this.setCustomValidity(this.$t('validityMaxlength').replace('{maxlength}', this.maxlength.toString()));
952
+ }
953
+ else {
954
+ /* nothing. Usa il messaggio di errore della validazione
955
+ di default del browser per altri errori di validità come:
956
+ - typeMismatch
957
+ - rangeUnderflow
958
+ - rangeOverflow
959
+ - stepMismatch
960
+ - badInput */
961
+ const otherConstraintErrors = _v.typeMismatch || _v.rangeUnderflow || _v.rangeOverflow || _v.stepMismatch || _v.badInput;
962
+ if (!otherConstraintErrors) {
963
+ this.setCustomValidity('');
964
+ }
965
+ }
966
+ }
967
+ this.validationMessage = this.inputElement.validationMessage;
968
+ }
969
+ _handleInvalid(event) {
970
+ this.formControlController.setValidity(false);
971
+ this.formControlController.emitInvalidEvent(event);
972
+ }
973
+ _handleChange(e) {
974
+ const target = e.target;
975
+ let value;
976
+ if (target instanceof HTMLInputElement) {
977
+ switch (target.type) {
978
+ case 'checkbox':
979
+ case 'radio':
980
+ value = target.checked;
981
+ break;
982
+ case 'file':
983
+ value = target.files; // FileList
984
+ break;
985
+ default:
986
+ value = target.value;
987
+ }
988
+ }
989
+ else if (target instanceof HTMLSelectElement) {
990
+ if (target.multiple) {
991
+ value = Array.from(target.selectedOptions).map((o) => o.value);
992
+ }
993
+ else {
994
+ value = target.value;
995
+ }
996
+ }
997
+ else {
998
+ // textarea o altri input con value
999
+ value = target.value;
1000
+ }
1001
+ this.dispatchEvent(new CustomEvent('it-change', {
1002
+ detail: { value, el: target },
1003
+ bubbles: true,
1004
+ composed: true,
1005
+ }));
1006
+ }
1007
+ updated(changedProperties) {
1008
+ super.updated?.(changedProperties);
1009
+ if (this.customValidation) {
1010
+ this.setCustomValidity(this.validationText ?? '');
1011
+ }
1012
+ else if (this.formControlController.userInteracted()) {
1013
+ this.formControlController.updateValidity();
1014
+ }
1015
+ }
1016
+ }
1017
+ __decorate([
1018
+ state(),
1019
+ __metadata("design:type", Object)
1020
+ ], FormControl.prototype, "_touched", void 0);
1021
+ __decorate([
1022
+ query('.it-form__control'),
1023
+ __metadata("design:type", HTMLInputElement)
1024
+ ], FormControl.prototype, "inputElement", void 0);
1025
+ __decorate([
1026
+ property({ type: String, reflect: true }) // from FormControl
1027
+ ,
1028
+ __metadata("design:type", Object)
1029
+ ], FormControl.prototype, "name", void 0);
1030
+ __decorate([
1031
+ property({ reflect: true }),
1032
+ __metadata("design:type", Object)
1033
+ ], FormControl.prototype, "value", void 0);
1034
+ __decorate([
1035
+ property({ type: Boolean, reflect: true }) // from FormControl
1036
+ ,
1037
+ __metadata("design:type", Object)
1038
+ ], FormControl.prototype, "disabled", void 0);
1039
+ __decorate([
1040
+ property({ reflect: true, type: String }),
1041
+ __metadata("design:type", Object)
1042
+ ], FormControl.prototype, "form", void 0);
1043
+ __decorate([
1044
+ property({ type: Boolean, reflect: true, attribute: 'custom-validation' }),
1045
+ __metadata("design:type", Object)
1046
+ ], FormControl.prototype, "customValidation", void 0);
1047
+ __decorate([
1048
+ property({ attribute: 'validity-message', reflect: true }),
1049
+ __metadata("design:type", String)
1050
+ ], FormControl.prototype, "validationText", void 0);
1051
+ __decorate([
1052
+ property(),
1053
+ __metadata("design:type", String)
1054
+ ], FormControl.prototype, "pattern", void 0);
1055
+ __decorate([
1056
+ property(),
1057
+ __metadata("design:type", Object)
1058
+ ], FormControl.prototype, "min", void 0);
1059
+ __decorate([
1060
+ property(),
1061
+ __metadata("design:type", Object)
1062
+ ], FormControl.prototype, "max", void 0);
1063
+ __decorate([
1064
+ property(),
1065
+ __metadata("design:type", Object)
1066
+ ], FormControl.prototype, "step", void 0);
1067
+ __decorate([
1068
+ property({ type: Number }),
1069
+ __metadata("design:type", Object)
1070
+ ], FormControl.prototype, "minlength", void 0);
1071
+ __decorate([
1072
+ property({ type: Number }),
1073
+ __metadata("design:type", Object)
1074
+ ], FormControl.prototype, "maxlength", void 0);
1075
+ __decorate([
1076
+ property({ type: Boolean, reflect: true }) // from FormControl
1077
+ ,
1078
+ __metadata("design:type", Object)
1079
+ ], FormControl.prototype, "required", void 0);
1080
+ __decorate([
1081
+ property({ type: Boolean }),
1082
+ __metadata("design:type", Object)
1083
+ ], FormControl.prototype, "isInGroup", void 0);
1084
+ __decorate([
1085
+ state(),
1086
+ __metadata("design:type", Object)
1087
+ ], FormControl.prototype, "validationMessage", void 0);
1088
+
1089
+ if (typeof window !== 'undefined') {
1090
+ window._itAnalytics = window._itAnalytics || {};
1091
+ window._itAnalytics = {
1092
+ ...window._itAnalytics,
1093
+ version: '1.0.0-alpha.10',
1094
+ };
1095
+ }
1096
+
1097
+ var styles = css``;
1098
+
1099
+ let ItNavscroll = class ItNavscroll extends BaseComponent {
1100
+ constructor() {
1101
+ super(...arguments);
1102
+ /**
1103
+ * Breakpoint di usabilità (zoom-safe)
1104
+ */
1105
+ this.breakpoint = 991;
1106
+ /**
1107
+ * Label del trigger modale
1108
+ */
1109
+ this.openLabel = 'Indice di navigazione';
1110
+ /**
1111
+ * Aria-Label del trigger modale
1112
+ */
1113
+ this.openAriaLabel = 'Apri/Chiudi indice di navigazione';
1114
+ /**
1115
+ * Label per il pulsante di 'Torna indietro' nella modale
1116
+ */
1117
+ this.backLabel = 'Indietro';
1118
+ /**
1119
+ * Selettore del contenitore scrollabile da monitorare per la progress bar
1120
+ */
1121
+ this.for = null;
1122
+ /**
1123
+ * Posizione dello navscroll su mobile quando è chiuso
1124
+ * */
1125
+ this.position = 'bottom';
1126
+ /**
1127
+ * If on desktop you want navscroll to be sticky on top
1128
+ * */
1129
+ this.sticky = false;
1130
+ /** Where you want to display separation line on desktop */
1131
+ this.linePosition = null;
1132
+ /** If you want dark mode only on mobile or desktop, or both */
1133
+ this.darkMode = null;
1134
+ this.mode = 'inline'; // Modalità di visualizzazione corrente, a seconda che siamo su desktop o mobile
1135
+ this.activeTarget = null; // voce di menu attiva in questo momento
1136
+ this.onMediaChange = (e) => {
1137
+ this.updateMode(e.matches);
1138
+ };
1139
+ }
1140
+ createRenderRoot() {
1141
+ // nav deve restare nel light DOM
1142
+ return this;
1143
+ }
1144
+ connectedCallback() {
1145
+ super.connectedCallback?.();
1146
+ // nav deve esistere
1147
+ this.navEl = this.querySelector('nav');
1148
+ if (!this.navEl) {
1149
+ // eslint-disable-next-line no-console
1150
+ this.logger.error('<it-navscroll> requires a <nav> item as children.');
1151
+ return;
1152
+ }
1153
+ // media query per modalità modal / inline
1154
+ this.mql = window.matchMedia(this.mediaQuery);
1155
+ this.mql.addEventListener('change', this.onMediaChange);
1156
+ }
1157
+ firstUpdated() {
1158
+ // ora il DOM del render esiste
1159
+ this.wrapper = this.querySelector('.it-navscroll-wrapper');
1160
+ this.menuWrapper = this.querySelector('.menu-wrapper');
1161
+ if (!this.wrapper || !this.menuWrapper) {
1162
+ this.logger.error('Wrapper not found');
1163
+ return;
1164
+ }
1165
+ // prendi tutti i figli e spostali nel wrapper
1166
+ const children = Array.from(this.childNodes).filter((node) => node !== this.wrapper);
1167
+ children.forEach((child) => this.menuWrapper.appendChild(child));
1168
+ this.wrapper.appendChild(this.menuWrapper);
1169
+ // inizializzazioni che dipendono dal DOM
1170
+ this.initContainers();
1171
+ this.attachLinkListeners();
1172
+ // inizializza il mode corretto
1173
+ this.updateMode(this.mql.matches);
1174
+ }
1175
+ disconnectedCallback() {
1176
+ super.disconnectedCallback?.();
1177
+ this.mql.removeEventListener('change', this.onMediaChange);
1178
+ try {
1179
+ this.scrollContainer.removeEventListener('scroll', this.onScroll);
1180
+ window.removeEventListener('scroll', this.onScroll);
1181
+ }
1182
+ catch (e) {
1183
+ // do nothing. One of this.scrollContainer or window will not have this.onScroll on event scroll.
1184
+ }
1185
+ }
1186
+ /*
1187
+ * Gestione dimensione schermo
1188
+ */
1189
+ get mediaQuery() {
1190
+ return `(max-width: ${this.breakpoint}px)`;
1191
+ }
1192
+ /*
1193
+ * Gestione della modale
1194
+ */
1195
+ updateMode(isConstrained) {
1196
+ const nextMode = isConstrained ? 'modal' : 'inline';
1197
+ if (this.sticky) {
1198
+ if (nextMode === 'inline' && !this.wrapper.classList.contains('affix-top')) {
1199
+ this.wrapper.classList.add('affix-top');
1200
+ }
1201
+ if (nextMode === 'modal' && this.wrapper.classList.contains('affix-top')) {
1202
+ this.wrapper.classList.remove('affix-top');
1203
+ }
1204
+ }
1205
+ if (this.mode === nextMode)
1206
+ return;
1207
+ this.mode = nextMode;
1208
+ if (this.mode === 'modal') {
1209
+ this.enterModal();
1210
+ }
1211
+ else {
1212
+ this.exitModal();
1213
+ }
1214
+ }
1215
+ enterModal() {
1216
+ if (!this.modalEl) {
1217
+ this.modalEl = this.createModal();
1218
+ }
1219
+ if (!this.modalEl.contains(this.menuWrapper)) {
1220
+ this.menuWrapper.setAttribute('slot', 'content');
1221
+ this.modalEl.appendChild(this.menuWrapper);
1222
+ }
1223
+ if (!this.wrapper.contains(this.modalEl)) {
1224
+ this.wrapper.appendChild(this.modalEl);
1225
+ }
1226
+ // if (!this.shadowRoot?.contains(this.modalEl)) {
1227
+ // this.shadowRoot?.appendChild(this.modalEl);
1228
+ // }
1229
+ if (this.position === 'bottom') {
1230
+ document.body.classList.add('navscroll-on-bottom');
1231
+ }
1232
+ this.updateTriggerText();
1233
+ }
1234
+ exitModal() {
1235
+ if (this.modalEl?.contains(this.menuWrapper)) {
1236
+ this.wrapper.appendChild(this.menuWrapper);
1237
+ // this.shadowRoot?.appendChild(this.navEl);
1238
+ }
1239
+ if (this.position === 'bottom') {
1240
+ document.body.classList.remove('navscroll-on-bottom');
1241
+ }
1242
+ this.modalEl?.remove();
1243
+ this.modalEl = undefined;
1244
+ this.menuWrapper.removeAttribute('slot');
1245
+ }
1246
+ createModal() {
1247
+ const modal = document.createElement('it-modal');
1248
+ modal.setAttribute('position', 'left');
1249
+ modal.setAttribute('scrollable', 'true');
1250
+ modal.setAttribute('hide-close-button', 'true');
1251
+ // trigger modale
1252
+ const trigger = document.createElement('it-button');
1253
+ trigger.setAttribute('class', 'custom-navbar-toggler');
1254
+ trigger.setAttribute('aria-label', this.openAriaLabel);
1255
+ trigger.setAttribute('variant', 'link');
1256
+ trigger.setAttribute('slot', 'trigger');
1257
+ trigger.innerHTML = `<span>${this.openLabel}</span>`;
1258
+ // pulsante di back
1259
+ const backButton = document.createElement('it-button');
1260
+ backButton.setAttribute('slot', 'header');
1261
+ backButton.setAttribute('variant', 'link');
1262
+ backButton.setAttribute('block', '');
1263
+ backButton.innerHTML = `<it-icon name="it-chevron-left" size="sm" color="primary"></it-icon> <span>${this.backLabel}</span>`;
1264
+ backButton.addEventListener('click', () => {
1265
+ modal.hide?.();
1266
+ });
1267
+ modal.appendChild(trigger);
1268
+ modal.appendChild(backButton);
1269
+ modal.addEventListener('it-modal-open', () => {
1270
+ document.body.classList.add('navbar-open');
1271
+ });
1272
+ modal.addEventListener('it-modal-close', () => {
1273
+ document.body.classList.remove('navbar-open');
1274
+ });
1275
+ return modal;
1276
+ }
1277
+ /*
1278
+ * Gestione dei container
1279
+ */
1280
+ get scrollContainerTop() {
1281
+ return this.scrollContainer === document.documentElement ? window.scrollY : this.scrollContainer.scrollTop;
1282
+ }
1283
+ initContainers() {
1284
+ // Cerco il main referenziato
1285
+ const targetContainer = this.for ? document.querySelector(this.for) : document.scrollingElement;
1286
+ // Determino il container corretto
1287
+ const style = targetContainer ? getComputedStyle(targetContainer) : null;
1288
+ const overflowY = style?.overflowY;
1289
+ const isScrollableContainer = overflowY !== 'visible' && overflowY !== 'hidden';
1290
+ if (isScrollableContainer && targetContainer instanceof HTMLElement) {
1291
+ // container interno scrollabile
1292
+ this.scrollContainer = targetContainer;
1293
+ this.scrollContainer.addEventListener('scroll', () => this.onScroll());
1294
+ }
1295
+ else {
1296
+ // scroll della pagina → ascolto window
1297
+ this.scrollContainer = document.documentElement; // placeholder
1298
+ window.addEventListener('scroll', () => this.onScroll());
1299
+ }
1300
+ this.progressEl = this.querySelector('it-progress');
1301
+ if (!this.progressEl)
1302
+ return;
1303
+ // init a 0%
1304
+ this.updateProgress();
1305
+ }
1306
+ /*
1307
+ * Gestione della voce attiva
1308
+ */
1309
+ setCurrent(hash) {
1310
+ const links = this.navEl.querySelectorAll('a[href^="#"]');
1311
+ // 1️⃣ reset: rimuovo active da tutti
1312
+ links.forEach((link) => {
1313
+ link.classList.remove('active');
1314
+ link.removeAttribute('aria-current');
1315
+ });
1316
+ // 2️⃣ applico active solo al link corrente e ai suoi parent
1317
+ const currentLink = this.navEl.querySelector(`a[href="${hash}"]`);
1318
+ if (currentLink) {
1319
+ currentLink.classList.add('active');
1320
+ currentLink.setAttribute('aria-current', 'location');
1321
+ let parentLi = currentLink.parentElement?.parentElement?.closest('li');
1322
+ while (parentLi) {
1323
+ parentLi.querySelector('a[href^="#"]')?.classList.add('active');
1324
+ parentLi = parentLi.parentElement?.parentElement?.closest('li');
1325
+ }
1326
+ }
1327
+ // Aggiorna trigger testo
1328
+ if (this.mode === 'modal') {
1329
+ this.updateTriggerText();
1330
+ }
1331
+ }
1332
+ // aggiorna il testo del trigger della modale in base al link attivo
1333
+ updateTriggerText() {
1334
+ if (!this.modalEl)
1335
+ return;
1336
+ const trigger = this.modalEl.querySelector('[slot="trigger"]');
1337
+ if (!trigger)
1338
+ return;
1339
+ const activeLink = this.navEl.querySelector('a[aria-current="location"]');
1340
+ if (activeLink) {
1341
+ trigger.textContent = activeLink.textContent;
1342
+ }
1343
+ else {
1344
+ // fallback
1345
+ trigger.textContent = this.openLabel;
1346
+ }
1347
+ }
1348
+ /*
1349
+ * Gestione dello scroll e della progressbar
1350
+ */
1351
+ onScroll() {
1352
+ this.updateProgress();
1353
+ this.scrollHandler();
1354
+ }
1355
+ scrollHandler() {
1356
+ const links = Array.from(this.navEl.querySelectorAll('a[href^="#"]'));
1357
+ const sections = links
1358
+ .map((link) => document.getElementById(link.getAttribute('href').slice(1)))
1359
+ .filter(Boolean);
1360
+ if (!sections.length)
1361
+ return;
1362
+ const scrollTop = this.scrollContainer?.scrollTop;
1363
+ const viewportHeight = this.scrollContainer.clientHeight;
1364
+ let currentSection = null;
1365
+ for (const section of sections) {
1366
+ const sectionTop = section.offsetTop;
1367
+ // se la sezione supera il 25% del viewport del container
1368
+ // console.log(
1369
+ // { scrollTop, viewportHeight, sectionTop },
1370
+ // 'scrollTop + viewportHeight * 0.25 >= sectionTop=',
1371
+ // scrollTop + viewportHeight * 0.25 >= sectionTop,
1372
+ // );
1373
+ if (scrollTop + viewportHeight * 0.25 >= sectionTop) {
1374
+ currentSection = section;
1375
+ }
1376
+ else {
1377
+ break;
1378
+ }
1379
+ }
1380
+ if (currentSection) {
1381
+ const id = currentSection?.id;
1382
+ this.activeTarget = `#${id}`;
1383
+ this.setCurrent(this.activeTarget);
1384
+ }
1385
+ }
1386
+ updateProgress() {
1387
+ if (!this.progressEl || !this.scrollContainer)
1388
+ return;
1389
+ const isDocumentScroll = this.scrollContainer === document.documentElement;
1390
+ const scrollTop = this.scrollContainerTop;
1391
+ const clientHeight = isDocumentScroll ? window.innerHeight : this.scrollContainer.clientHeight;
1392
+ const scrollHeight = isDocumentScroll ? document.documentElement.scrollHeight : this.scrollContainer.scrollHeight;
1393
+ const maxScrollable = Math.max(scrollHeight - clientHeight, 1);
1394
+ let percent = (scrollTop / maxScrollable) * 100;
1395
+ percent = Math.min(100, Math.max(0, percent));
1396
+ this.progressEl.setAttribute('value', percent.toFixed(0));
1397
+ }
1398
+ /*
1399
+ * Gestione dello scroll alle sezioni
1400
+ */
1401
+ attachLinkListeners() {
1402
+ const links = this.navEl.querySelectorAll('a[href^="#"]');
1403
+ links.forEach((link) => {
1404
+ link.addEventListener('click', (event) => {
1405
+ event.preventDefault();
1406
+ const hash = link.getAttribute('href');
1407
+ const targetId = hash.slice(1);
1408
+ const targetEl = document.getElementById(targetId);
1409
+ if (!targetEl)
1410
+ return;
1411
+ this.activeTarget = `#${targetId}`;
1412
+ this.setCurrent(this.activeTarget);
1413
+ // scroll animato
1414
+ this.scrollToElement(targetEl, 700, 0, () => {
1415
+ // focus senza scroll jump
1416
+ targetEl.setAttribute('tabindex', '-1');
1417
+ targetEl.focus({ preventScroll: true });
1418
+ // aggiorna URL
1419
+ window.history.replaceState(null, '', `#${targetId}`);
1420
+ const announcer = document.getElementById('aria-navscroll-announcer');
1421
+ if (announcer) {
1422
+ announcer.textContent = `Sezione ${targetEl.textContent} selezionata`;
1423
+ }
1424
+ });
1425
+ // chiude il modal se siamo in modal mode
1426
+ if (this.mode === 'modal' && this.modalEl) {
1427
+ this.modalEl.hide?.();
1428
+ }
1429
+ });
1430
+ });
1431
+ }
1432
+ // eslint-disable-next-line class-methods-use-this
1433
+ scrollToElement(targetEl, duration = 700, offset = 0, callback) {
1434
+ const container = this.scrollContainer ?? null;
1435
+ const style = container ? getComputedStyle(container) : null;
1436
+ const overflowY = style?.overflowY;
1437
+ const isScrollableContainer = !!container && overflowY !== 'visible' && overflowY !== 'hidden';
1438
+ const startY = this.scrollContainerTop;
1439
+ // offset per posizionare la sezione al 25% della viewport
1440
+ const viewportHeight = isScrollableContainer ? this.scrollContainer.clientHeight : window.innerHeight;
1441
+ const sectionOffset = viewportHeight * 0.25 - 30;
1442
+ const targetOffset = startY - sectionOffset - offset;
1443
+ const targetY = isScrollableContainer
1444
+ ? (() => {
1445
+ const containerRect = container.getBoundingClientRect();
1446
+ const targetRect = targetEl.getBoundingClientRect();
1447
+ return targetRect.top - containerRect.top + targetOffset;
1448
+ })()
1449
+ : targetEl.getBoundingClientRect().top + targetOffset;
1450
+ const distance = targetY - startY;
1451
+ const startTime = performance.now();
1452
+ const easeInOutSine = (t) => -(Math.cos(Math.PI * t) - 1) / 2;
1453
+ const step = (currentTime) => {
1454
+ const elapsed = currentTime - startTime;
1455
+ const progress = Math.min(elapsed / duration, 1);
1456
+ const value = startY + distance * easeInOutSine(progress);
1457
+ if (isScrollableContainer) {
1458
+ container.scrollTop = value;
1459
+ }
1460
+ else {
1461
+ window.scrollTo(0, value);
1462
+ }
1463
+ if (progress < 1) {
1464
+ requestAnimationFrame(step);
1465
+ }
1466
+ else {
1467
+ callback?.();
1468
+ }
1469
+ };
1470
+ requestAnimationFrame(step);
1471
+ }
1472
+ render() {
1473
+ const positionClass = this.position === 'bottom' ? 'it-bottom-navscroll' : 'it-top-navscroll';
1474
+ let themeClass = '';
1475
+ switch (this.darkMode) {
1476
+ case 'mobile':
1477
+ themeClass = 'theme-dark-mobile';
1478
+ break;
1479
+ case 'desktop':
1480
+ themeClass = 'theme-dark-desk';
1481
+ break;
1482
+ case 'always':
1483
+ themeClass = 'theme-dark-mobile theme-dark-desk';
1484
+ break;
1485
+ default:
1486
+ themeClass = '';
1487
+ }
1488
+ let lineClass = '';
1489
+ switch (this.linePosition) {
1490
+ case 'left':
1491
+ lineClass = 'it-left-side';
1492
+ break;
1493
+ case 'right':
1494
+ lineClass = 'it-right-side';
1495
+ break;
1496
+ default:
1497
+ lineClass = '';
1498
+ }
1499
+ const wrapperClasses = ['it-navscroll-wrapper', 'navbar', positionClass, themeClass, lineClass].join(' ');
1500
+ return html `
1501
+ <div class="${wrapperClasses}">
1502
+ <div class="menu-wrapper" tabindex="-1"></div>
1503
+ </div>
1504
+ `;
1505
+ }
1506
+ };
1507
+ ItNavscroll.styles = styles;
1508
+ __decorate([
1509
+ property({ type: Number }),
1510
+ __metadata("design:type", Object)
1511
+ ], ItNavscroll.prototype, "breakpoint", void 0);
1512
+ __decorate([
1513
+ property({ type: String, attribute: 'open-label' }),
1514
+ __metadata("design:type", Object)
1515
+ ], ItNavscroll.prototype, "openLabel", void 0);
1516
+ __decorate([
1517
+ property({ type: String, attribute: 'open-aria-label' }),
1518
+ __metadata("design:type", Object)
1519
+ ], ItNavscroll.prototype, "openAriaLabel", void 0);
1520
+ __decorate([
1521
+ property({ type: String, attribute: 'back-label' }),
1522
+ __metadata("design:type", Object)
1523
+ ], ItNavscroll.prototype, "backLabel", void 0);
1524
+ __decorate([
1525
+ property({ type: String }),
1526
+ __metadata("design:type", Object)
1527
+ ], ItNavscroll.prototype, "for", void 0);
1528
+ __decorate([
1529
+ property({ type: String, attribute: 'position' }),
1530
+ __metadata("design:type", String)
1531
+ ], ItNavscroll.prototype, "position", void 0);
1532
+ __decorate([
1533
+ property({ type: Boolean, attribute: 'sticky' }),
1534
+ __metadata("design:type", Boolean)
1535
+ ], ItNavscroll.prototype, "sticky", void 0);
1536
+ __decorate([
1537
+ property({ type: String, attribute: 'line-position' }),
1538
+ __metadata("design:type", Object)
1539
+ ], ItNavscroll.prototype, "linePosition", void 0);
1540
+ __decorate([
1541
+ property({ type: String, attribute: 'dark-mode' }),
1542
+ __metadata("design:type", Object)
1543
+ ], ItNavscroll.prototype, "darkMode", void 0);
1544
+ ItNavscroll = __decorate([
1545
+ customElement('it-navscroll')
1546
+ ], ItNavscroll);
1547
+
1548
+ export { ItNavscroll };
1549
+ //# sourceMappingURL=it-navscroll.js.map