@italia/sticky 1.0.0-alpha.8 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1433 +1,5 @@
1
- import { state, query, property, customElement } from 'lit/decorators.js';
2
- import { directive, Directive } from 'lit/directive.js';
3
- import { LitElement } from 'lit';
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
- 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
- case 'it-toggle':
463
- if (this.host.checked) {
464
- if (event.formData.getAll(name).indexOf(value) < 0) {
465
- // handle group checkbox
466
- event.formData.append(name, value);
467
- }
468
- }
469
- break;
470
- case 'it-checkbox-group':
471
- case 'it-toggle-group':
472
- // non settare valori in formData, perchè ogni singola checkbox setta il suo valore
473
- break;
474
- default:
475
- if (Array.isArray(value)) {
476
- value.forEach((val) => {
477
- event.formData.append(name, val.toString());
478
- });
479
- }
480
- else {
481
- event.formData.append(name, value.toString());
482
- }
483
- }
484
- }
485
- };
486
- this.handleFormSubmit = (event) => {
487
- const disabled = this.options.disabled(this.host);
488
- const reportValidity = this.options.reportValidity;
489
- // Update the interacted state for all controls when the form is submitted
490
- if (this.form && !this.form.noValidate) {
491
- formCollections.get(this.form)?.forEach((control) => {
492
- this.setUserInteracted(control, true);
493
- });
494
- }
495
- const resReportValidity = reportValidity(this.host);
496
- if (this.form && !this.form.noValidate && !disabled && !resReportValidity) {
497
- event.preventDefault();
498
- // event.stopImmediatePropagation(); // se lo attiviamo, valida un campo alla volta
499
- // Scroll al primo controllo non valido
500
- const formControls = formCollections.get(this.form);
501
- if (formControls) {
502
- for (const control of formControls) {
503
- if (!control.validity?.valid) {
504
- // Scroll smooth verso il controllo non valido
505
- control.scrollIntoView({
506
- behavior: 'smooth',
507
- block: 'center',
508
- });
509
- break;
510
- }
511
- }
512
- }
513
- }
514
- this.submittedOnce = true;
515
- };
516
- this.handleFormReset = () => {
517
- this.options.setValue(this.host, '');
518
- this.submittedOnce = false;
519
- this.setUserInteracted(this.host, false);
520
- interactions.set(this.host, []);
521
- };
522
- this.handleInteraction = (event) => {
523
- const emittedEvents = interactions.get(this.host);
524
- if (!emittedEvents.includes(event.type)) {
525
- emittedEvents.push(event.type);
526
- }
527
- // Mark it as user-interacted as soon as all associated events have been emitted
528
- if (emittedEvents.length === this.options.assumeInteractionOn.length) {
529
- this.setUserInteracted(this.host, true);
530
- }
531
- };
532
- this.checkFormValidity = () => {
533
- // console.log('checkFormValidity');
534
- //
535
- // This is very similar to the `reportFormValidity` function, but it does not trigger native constraint validation
536
- // Allow the user to simply check if the form is valid and handling validity in their own way.
537
- //
538
- // We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
539
- // validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
540
- // be necessary once we can use ElementInternals.
541
- //
542
- // Note that we're also honoring the form's novalidate attribute.
543
- //
544
- if (this.form && !this.form.noValidate) {
545
- // This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
546
- // elements that support the constraint validation API.
547
- const elements = this.form.querySelectorAll('*');
548
- for (const element of elements) {
549
- if (typeof element.checkValidity === 'function') {
550
- if (!element.checkValidity()) {
551
- return false;
552
- }
553
- }
554
- }
555
- }
556
- return true;
557
- };
558
- this.reportFormValidity = () => {
559
- // console.log('reportFormValidity');
560
- //
561
- // FormControl work hard to act like regular form controls. They support the Constraint Validation API
562
- // and its associated methods such as setCustomValidity() and reportValidity(). However, the HTMLFormElement also
563
- // has a reportValidity() method that will trigger validation on all child controls. Since we're not yet using
564
- // ElementInternals, we need to overload this method so it looks for any element with the reportValidity() method.
565
- //
566
- // We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
567
- // validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
568
- // be necessary once we can use ElementInternals.
569
- //
570
- // Note that we're also honoring the form's novalidate attribute.
571
- //
572
- if (this.form && !this.form.noValidate) {
573
- // This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
574
- // elements that support the constraint validation API.
575
- const elements = this.form.querySelectorAll('*');
576
- for (const element of elements) {
577
- if (typeof element.reportValidity === 'function') {
578
- if (!element.reportValidity()) {
579
- return false;
580
- }
581
- }
582
- }
583
- }
584
- return true;
585
- };
586
- (this.host = host).addController(this);
587
- this.options = {
588
- form: (input) => {
589
- // If there's a form attribute, use it to find the target form by id
590
- // Controls may not always reflect the 'form' property. For example, `<it-button>` doesn't reflect.
591
- const formId = input.form;
592
- if (formId) {
593
- const root = input.getRootNode();
594
- const form = root.querySelector(`#${formId}`);
595
- if (form) {
596
- return form;
597
- }
598
- }
599
- return input.closest('form');
600
- },
601
- name: (input) => input.name,
602
- value: (input) => input.value,
603
- disabled: (input) => input.disabled ?? false,
604
- reportValidity: (input) => typeof input.reportValidity === 'function' ? input.reportValidity() : true,
605
- checkValidity: (input) => (typeof input.checkValidity === 'function' ? input.checkValidity() : true),
606
- setValue: (input, value) => {
607
- // eslint-disable-next-line no-param-reassign
608
- input.value = value;
609
- },
610
- assumeInteractionOn: ['it-input'],
611
- ...options,
612
- };
613
- }
614
- hostConnected() {
615
- const form = this.options.form(this.host);
616
- if (form) {
617
- this.attachForm(form);
618
- }
619
- // Listen for interactions
620
- interactions.set(this.host, []);
621
- this.options.assumeInteractionOn.forEach((event) => {
622
- this.host.addEventListener(event, this.handleInteraction);
623
- });
624
- }
625
- hostDisconnected() {
626
- this.detachForm();
627
- // Clean up interactions
628
- interactions.delete(this.host);
629
- this.options.assumeInteractionOn.forEach((event) => {
630
- this.host.removeEventListener(event, this.handleInteraction);
631
- });
632
- }
633
- hostUpdated() {
634
- const form = this.options.form(this.host);
635
- // Detach if the form no longer exists
636
- if (!form) {
637
- this.detachForm();
638
- }
639
- // If the form has changed, reattach it
640
- if (form && this.form !== form) {
641
- this.detachForm();
642
- this.attachForm(form);
643
- }
644
- if (this.host.hasUpdated) {
645
- this.setValidity(this.host.validity.valid);
646
- }
647
- }
648
- attachForm(form) {
649
- if (form) {
650
- this.form = form;
651
- // Add this element to the form's collection
652
- if (formCollections.has(this.form)) {
653
- formCollections.get(this.form).add(this.host);
654
- }
655
- else {
656
- formCollections.set(this.form, new Set([this.host]));
657
- }
658
- this.form.addEventListener('formdata', this.handleFormData);
659
- this.form.addEventListener('submit', this.handleFormSubmit);
660
- this.form.addEventListener('reset', this.handleFormReset);
661
- // Overload the form's reportValidity() method so it looks at FormControl
662
- if (!reportValidityOverloads.has(this.form)) {
663
- reportValidityOverloads.set(this.form, this.form.reportValidity);
664
- this.form.reportValidity = () => this.reportFormValidity();
665
- }
666
- // Overload the form's checkValidity() method so it looks at FormControl
667
- if (!checkValidityOverloads.has(this.form)) {
668
- checkValidityOverloads.set(this.form, this.form.checkValidity);
669
- this.form.checkValidity = () => this.checkFormValidity();
670
- }
671
- }
672
- else {
673
- this.form = undefined;
674
- }
675
- }
676
- detachForm() {
677
- if (!this.form)
678
- return;
679
- const formCollection = formCollections.get(this.form);
680
- if (!formCollection) {
681
- return;
682
- }
683
- this.submittedOnce = false;
684
- // Remove this host from the form's collection
685
- formCollection.delete(this.host);
686
- // Check to make sure there's no other form controls in the collection. If we do this
687
- // without checking if any other controls are still in the collection, then we will wipe out the
688
- // validity checks for all other elements.
689
- // see: https://github.com/shoelace-style/shoelace/issues/1703
690
- if (formCollection.size <= 0) {
691
- this.form.removeEventListener('formdata', this.handleFormData);
692
- this.form.removeEventListener('submit', this.handleFormSubmit);
693
- this.form.removeEventListener('reset', this.handleFormReset);
694
- // Remove the overload and restore the original method
695
- if (reportValidityOverloads.has(this.form)) {
696
- this.form.reportValidity = reportValidityOverloads.get(this.form);
697
- reportValidityOverloads.delete(this.form);
698
- }
699
- if (checkValidityOverloads.has(this.form)) {
700
- this.form.checkValidity = checkValidityOverloads.get(this.form);
701
- checkValidityOverloads.delete(this.form);
702
- }
703
- // So it looks weird here to not always set the form to undefined. But I _think_ if we unattach this.form here,
704
- // we end up in this fun spot where future validity checks don't have a reference to the form validity handler.
705
- // 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.
706
- this.form = undefined;
707
- }
708
- }
709
- // eslint-disable-next-line class-methods-use-this
710
- setUserInteracted(el, hasInteracted) {
711
- if (hasInteracted) {
712
- userInteractedControls.add(el);
713
- }
714
- else {
715
- userInteractedControls.delete(el);
716
- }
717
- el.requestUpdate();
718
- }
719
- doAction(type, submitter) {
720
- // console.log('doaction', type);
721
- if (this.form) {
722
- const button = document.createElement('button');
723
- button.type = type;
724
- button.style.position = 'absolute';
725
- button.style.width = '0';
726
- button.style.height = '0';
727
- button.style.clipPath = 'inset(50%)';
728
- button.style.overflow = 'hidden';
729
- button.style.whiteSpace = 'nowrap';
730
- // Pass name, value, and form attributes through to the temporary button
731
- if (submitter) {
732
- button.name = submitter.name;
733
- button.value = submitter.value;
734
- ['formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget'].forEach((attr) => {
735
- if (submitter.hasAttribute(attr)) {
736
- button.setAttribute(attr, submitter.getAttribute(attr));
737
- }
738
- });
739
- }
740
- this.form.append(button);
741
- button.click();
742
- button.remove();
743
- }
744
- }
745
- /** Returns the associated `<form>` element, if one exists. */
746
- getForm() {
747
- return this.form ?? null;
748
- }
749
- /** Resets the form, restoring all the control to their default value */
750
- reset(submitter) {
751
- this.doAction('reset', submitter);
752
- }
753
- /** Submits the form, triggering validation and form data injection. */
754
- submit(submitter) {
755
- // Calling form.submit() bypasses the submit event and constraint validation. To prevent this, we can inject a
756
- // native submit button into the form, "click" it, then remove it to simulate a standard form submission.
757
- this.doAction('submit', submitter);
758
- }
759
- /**
760
- * Synchronously sets the form control's validity. Call this when you know the future validity but need to update
761
- * the host element immediately, i.e. before Lit updates the component in the next update.
762
- */
763
- setValidity(isValid) {
764
- const host = this.host;
765
- const hasInteracted = Boolean(userInteractedControls.has(host));
766
- const required = Boolean(host.required);
767
- //
768
- // We're mapping the following "states" to data attributes. In the future, we can use ElementInternals.states to
769
- // create a similar mapping, but instead of [data-invalid] it will look like :--invalid.
770
- //
771
- // See this RFC for more details: https://github.com/shoelace-style/shoelace/issues/1011
772
- //
773
- host.toggleAttribute('data-required', required);
774
- host.toggleAttribute('data-optional', !required);
775
- host.toggleAttribute('data-invalid', !isValid);
776
- host.toggleAttribute('data-valid', isValid);
777
- host.toggleAttribute('data-user-invalid', !isValid && hasInteracted);
778
- host.toggleAttribute('data-user-valid', isValid && hasInteracted);
779
- }
780
- userInteracted() {
781
- const hasInteracted = Boolean(userInteractedControls.has(this.host));
782
- return hasInteracted;
783
- }
784
- /**
785
- * Updates the form control's validity based on the current value of `host.validity.valid`. Call this when anything
786
- * that affects constraint validation changes so the component receives the correct validity states.
787
- */
788
- updateValidity() {
789
- const host = this.host;
790
- this.setValidity(host.validity.valid);
791
- }
792
- /**
793
- * Dispatches a non-bubbling, cancelable custom event of type `it-invalid`.
794
- * If the `it-invalid` event will be cancelled then the original `invalid`
795
- * event (which may have been passed as argument) will also be cancelled.
796
- * If no original `invalid` event has been passed then the `it-invalid`
797
- * event will be cancelled before being dispatched.
798
- */
799
- emitInvalidEvent(originalInvalidEvent) {
800
- const itInvalidEvent = new CustomEvent('it-invalid', {
801
- bubbles: false,
802
- composed: false,
803
- cancelable: true,
804
- detail: {},
805
- });
806
- if (!originalInvalidEvent) {
807
- itInvalidEvent.preventDefault();
808
- }
809
- if (!this.host.dispatchEvent(itInvalidEvent)) {
810
- originalInvalidEvent?.preventDefault();
811
- }
812
- }
813
- }
814
-
815
- const translation = {
816
- $code: 'it',
817
- $name: 'Italiano',
818
- $dir: 'ltr',
819
- validityRequired: 'Questo campo è obbligatorio.',
820
- validityGroupRequired: "Scegli almeno un'opzione",
821
- validityPattern: 'Il valore non corrisponde al formato richiesto.',
822
- validityMinlength: 'Il valore deve essere lungo almeno {minlength} caratteri.',
823
- validityMaxlength: 'Il valore deve essere lungo al massimo {maxlength} caratteri.',
824
- };
825
-
826
- registerTranslation(translation);
827
- class FormControl extends BaseLocalizedComponent {
828
- constructor() {
829
- super(...arguments);
830
- this.formControlController = new FormControlController(this, {
831
- assumeInteractionOn: ['it-input', 'it-blur', 'it-change'],
832
- });
833
- // TODO: verificare se serve davvero con il fatto che usiamo form-controller
834
- // static formAssociated = true;
835
- // @property()
836
- // internals = this.attachInternals();
837
- this._touched = false;
838
- /** The name of the input, submitted as a name/value pair with form data. */
839
- this.name = '';
840
- /** The current value of the input, submitted as a name/value pair with form data. */
841
- this.value = '';
842
- /** If the input is disabled. */
843
- this.disabled = false;
844
- /**
845
- * By default, form controls are associated with the nearest containing `<form>` element. This attribute allows you
846
- * to place the form control outside of a form and associate it with the form that has this `id`. The form must be in
847
- * the same document or shadow root for this to work.
848
- */
849
- this.form = '';
850
- /** If you implement your custom validation and you won't to trigger default validation */
851
- this.customValidation = false;
852
- /** If your input is invalid from your custom validition, set this attribute with message validation */
853
- this.validationText = '';
854
- /**
855
- * Specifies the granularity that the value must adhere to, or the special value `any` which means no stepping is
856
- * implied, allowing any numeric value. Only applies to date and number input types.
857
- */
858
- this.step = 'any';
859
- /** The input's minimum length. */
860
- this.minlength = -1;
861
- /** The input's maximum length. */
862
- this.maxlength = -1;
863
- /** If the input is required. */
864
- this.required = false;
865
- /* For grouped input, like checkbox-group */
866
- this.isInGroup = false;
867
- this.validationMessage = '';
868
- }
869
- /** Gets the validity state object */
870
- get validity() {
871
- return this.inputElement?.validity;
872
- }
873
- /** Gets the associated form, if one exists. */
874
- getForm() {
875
- return this.formControlController.getForm();
876
- }
877
- // Form validation methods
878
- checkValidity() {
879
- const inputValid = this.inputElement?.checkValidity() ?? true; // this.inputElement.checkValidity() è la validazione del browser
880
- return inputValid;
881
- }
882
- /** Checks for validity and shows the browser's validation message if the control is invalid. */
883
- reportValidity() {
884
- // const ret = this.inputElement.checkValidity();
885
- const ret = this.checkValidity(); // chiama la checkValidity, che se è stata overridata chiama quella
886
- this.handleValidationMessages();
887
- return ret; // this.inputElement.reportValidity();
888
- }
889
- /** Sets a custom validation message. Pass an empty string to restore validity. */
890
- setCustomValidity(message) {
891
- this.inputElement.setCustomValidity(message);
892
- this.validationMessage = this.inputElement.validationMessage;
893
- this.formControlController.updateValidity();
894
- }
895
- // Handlers
896
- _handleReady() {
897
- requestAnimationFrame(() => {
898
- this.dispatchEvent(new CustomEvent('it-input-ready', { bubbles: true, detail: { el: this.inputElement } }));
899
- });
900
- }
901
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
902
- _handleInput(e) {
903
- this.handleValidationMessages();
904
- this.dispatchEvent(new CustomEvent('it-input', {
905
- detail: { value: this.inputElement.value, el: this.inputElement },
906
- bubbles: true,
907
- composed: true,
908
- }));
909
- }
910
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
911
- _handleBlur(e) {
912
- this._touched = true;
913
- this.handleValidationMessages();
914
- this.dispatchEvent(new FocusEvent('it-blur', { bubbles: true, composed: true }));
915
- }
916
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
917
- _handleFocus(e) {
918
- this.dispatchEvent(new FocusEvent('it-focus', { bubbles: true, composed: true }));
919
- }
920
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
921
- _handleClick(e) {
922
- this.dispatchEvent(new MouseEvent('it-click', { bubbles: true, composed: true }));
923
- }
924
- /*
925
- Override default browser validation messages
926
- */
927
- handleValidationMessages() {
928
- if (!this.customValidation) {
929
- const _v = this.inputElement.validity;
930
- const isRequiredHandledByGroup = this.isInGroup === true;
931
- if (_v.valueMissing && !isRequiredHandledByGroup) {
932
- this.setCustomValidity(this.$t('validityRequired'));
933
- }
934
- else if (_v.patternMismatch) {
935
- this.setCustomValidity(this.$t('validityPattern'));
936
- }
937
- else if (_v.tooShort) {
938
- this.setCustomValidity(this.$t('validityMinlength').replace('{minlength}', this.minlength.toString()));
939
- }
940
- else if (_v.tooLong) {
941
- this.setCustomValidity(this.$t('validityMaxlength').replace('{maxlength}', this.maxlength.toString()));
942
- }
943
- else {
944
- /* nothing. Usa il messaggio di errore della validazione
945
- di default del browser per altri errori di validità come:
946
- - typeMismatch
947
- - rangeUnderflow
948
- - rangeOverflow
949
- - stepMismatch
950
- - badInput */
951
- const otherConstraintErrors = _v.typeMismatch || _v.rangeUnderflow || _v.rangeOverflow || _v.stepMismatch || _v.badInput;
952
- if (!otherConstraintErrors) {
953
- this.setCustomValidity('');
954
- }
955
- }
956
- }
957
- this.validationMessage = this.inputElement.validationMessage;
958
- }
959
- _handleInvalid(event) {
960
- this.formControlController.setValidity(false);
961
- this.formControlController.emitInvalidEvent(event);
962
- }
963
- _handleChange(e) {
964
- const target = e.target;
965
- let value;
966
- if (target instanceof HTMLInputElement) {
967
- switch (target.type) {
968
- case 'checkbox':
969
- case 'radio':
970
- value = target.checked;
971
- break;
972
- case 'file':
973
- value = target.files; // FileList
974
- break;
975
- default:
976
- value = target.value;
977
- }
978
- }
979
- else if (target instanceof HTMLSelectElement) {
980
- if (target.multiple) {
981
- value = Array.from(target.selectedOptions).map((o) => o.value);
982
- }
983
- else {
984
- value = target.value;
985
- }
986
- }
987
- else {
988
- // textarea o altri input con value
989
- value = target.value;
990
- }
991
- this.dispatchEvent(new CustomEvent('it-change', {
992
- detail: { value, el: target },
993
- bubbles: true,
994
- composed: true,
995
- }));
996
- }
997
- updated(changedProperties) {
998
- super.updated?.(changedProperties);
999
- if (this.customValidation) {
1000
- this.setCustomValidity(this.validationText ?? '');
1001
- }
1002
- else if (this.formControlController.userInteracted()) {
1003
- this.formControlController.updateValidity();
1004
- }
1005
- }
1006
- }
1007
- __decorate([
1008
- state(),
1009
- __metadata("design:type", Object)
1010
- ], FormControl.prototype, "_touched", void 0);
1011
- __decorate([
1012
- query('.it-form__control'),
1013
- __metadata("design:type", HTMLInputElement)
1014
- ], FormControl.prototype, "inputElement", void 0);
1015
- __decorate([
1016
- property({ type: String, reflect: true }) // from FormControl
1017
- ,
1018
- __metadata("design:type", Object)
1019
- ], FormControl.prototype, "name", void 0);
1020
- __decorate([
1021
- property({ reflect: true }),
1022
- __metadata("design:type", Object)
1023
- ], FormControl.prototype, "value", void 0);
1024
- __decorate([
1025
- property({ type: Boolean, reflect: true }) // from FormControl
1026
- ,
1027
- __metadata("design:type", Object)
1028
- ], FormControl.prototype, "disabled", void 0);
1029
- __decorate([
1030
- property({ reflect: true, type: String }),
1031
- __metadata("design:type", Object)
1032
- ], FormControl.prototype, "form", void 0);
1033
- __decorate([
1034
- property({ type: Boolean, reflect: true, attribute: 'custom-validation' }),
1035
- __metadata("design:type", Object)
1036
- ], FormControl.prototype, "customValidation", void 0);
1037
- __decorate([
1038
- property({ attribute: 'validity-message', reflect: true }),
1039
- __metadata("design:type", String)
1040
- ], FormControl.prototype, "validationText", void 0);
1041
- __decorate([
1042
- property(),
1043
- __metadata("design:type", String)
1044
- ], FormControl.prototype, "pattern", void 0);
1045
- __decorate([
1046
- property(),
1047
- __metadata("design:type", Object)
1048
- ], FormControl.prototype, "min", void 0);
1049
- __decorate([
1050
- property(),
1051
- __metadata("design:type", Object)
1052
- ], FormControl.prototype, "max", void 0);
1053
- __decorate([
1054
- property(),
1055
- __metadata("design:type", Object)
1056
- ], FormControl.prototype, "step", void 0);
1057
- __decorate([
1058
- property({ type: Number }),
1059
- __metadata("design:type", Object)
1060
- ], FormControl.prototype, "minlength", void 0);
1061
- __decorate([
1062
- property({ type: Number }),
1063
- __metadata("design:type", Object)
1064
- ], FormControl.prototype, "maxlength", void 0);
1065
- __decorate([
1066
- property({ type: Boolean, reflect: true }) // from FormControl
1067
- ,
1068
- __metadata("design:type", Object)
1069
- ], FormControl.prototype, "required", void 0);
1070
- __decorate([
1071
- property({ type: Boolean }),
1072
- __metadata("design:type", Object)
1073
- ], FormControl.prototype, "isInGroup", void 0);
1074
- __decorate([
1075
- state(),
1076
- __metadata("design:type", Object)
1077
- ], FormControl.prototype, "validationMessage", void 0);
1078
-
1079
- class WindowManager {
1080
- static init() {
1081
- if (this.initialized)
1082
- return;
1083
- this.lastScrollY = window.scrollY;
1084
- this.lastWidth = window.innerWidth;
1085
- this.lastHeight = window.innerHeight;
1086
- window.addEventListener('scroll', () => {
1087
- this.lastScrollY = window.scrollY;
1088
- this.requestTick();
1089
- });
1090
- window.addEventListener('resize', () => {
1091
- this.lastWidth = window.innerWidth;
1092
- this.lastHeight = window.innerHeight;
1093
- this.requestTick(true); // force recalculation
1094
- });
1095
- this.initialized = true;
1096
- }
1097
- static requestTick(forceRecalc = false) {
1098
- if (!this.ticking) {
1099
- requestAnimationFrame(() => this.tick(forceRecalc));
1100
- this.ticking = true;
1101
- }
1102
- }
1103
- static tick(forceRecalc) {
1104
- this.ticking = false;
1105
- const state = {
1106
- scrollY: this.lastScrollY,
1107
- width: this.lastWidth,
1108
- height: this.lastHeight,
1109
- };
1110
- this.subscribers.forEach((cb) => cb(state, forceRecalc));
1111
- }
1112
- static subscribe(cb) {
1113
- this.subscribers.add(cb);
1114
- }
1115
- static unsubscribe(cb) {
1116
- this.subscribers.delete(cb);
1117
- }
1118
- /**
1119
- * Blocca lo scroll del body. Usa ref counting per gestire modal nested.
1120
- * Chiamare unlockBodyScroll() per ogni lockBodyScroll().
1121
- */
1122
- static lockBodyScroll() {
1123
- this.scrollLockCount += 1;
1124
- if (this.scrollLockCount === 1) {
1125
- this.scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
1126
- document.body.classList.add('modal-open');
1127
- document.body.style.overflow = 'hidden';
1128
- document.body.style.paddingRight = `${this.scrollbarWidth}px`;
1129
- }
1130
- }
1131
- /**
1132
- * Sblocca lo scroll del body. Rimuove il lock solo quando tutti i consumer hanno chiamato unlock.
1133
- */
1134
- static unlockBodyScroll() {
1135
- this.scrollLockCount = Math.max(0, this.scrollLockCount - 1);
1136
- if (this.scrollLockCount === 0) {
1137
- document.body.classList.remove('modal-open');
1138
- document.body.style.overflow = '';
1139
- document.body.style.paddingRight = '';
1140
- }
1141
- }
1142
- /** Ritorna la larghezza della scrollbar (utile per compensazioni) */
1143
- static getScrollbarWidth() {
1144
- return this.scrollbarWidth || window.innerWidth - document.documentElement.clientWidth;
1145
- }
1146
- }
1147
- WindowManager.initialized = false;
1148
- WindowManager.subscribers = new Set();
1149
- WindowManager.lastScrollY = 0;
1150
- WindowManager.lastWidth = 0;
1151
- WindowManager.lastHeight = 0;
1152
- WindowManager.ticking = false;
1153
- // Body scroll lock (ref counting per modal nested)
1154
- WindowManager.scrollLockCount = 0;
1155
- WindowManager.scrollbarWidth = 0;
1156
-
1157
- if (typeof window !== 'undefined') {
1158
- window._itAnalytics = window._itAnalytics || {};
1159
- window._itAnalytics = {
1160
- ...window._itAnalytics,
1161
- version: '1.0.0-alpha.8',
1162
- };
1163
- }
1164
-
1165
- // Shared global array to avoid duplicate instances when the module is
1166
- // loaded multiple times
1167
- const GLOBAL_ACTIVE_FIXED_KEY = '__it_sticky_active_fixed_stickies_v1__';
1168
- const activeFixedStickies = globalThis[GLOBAL_ACTIVE_FIXED_KEY] ?? (globalThis[GLOBAL_ACTIVE_FIXED_KEY] = []);
1169
- class StickyController {
1170
- setVisualOrder(order) {
1171
- this.visualOrder = order;
1172
- }
1173
- get isSticky() {
1174
- return this._isSticky;
1175
- }
1176
- constructor(host, hostElement) {
1177
- this.visualOrder = 0;
1178
- this.limit = 0;
1179
- this.originalLimit = 0;
1180
- this.height = 0;
1181
- this.prevHeight = 0;
1182
- this._isSticky = false;
1183
- this.host = host;
1184
- this.hostElement = hostElement;
1185
- host.addController(this);
1186
- }
1187
- hostConnected() {
1188
- WindowManager.init();
1189
- this.computeLimit();
1190
- this.originalLimit = this.hostElement.offsetTop;
1191
- WindowManager.subscribe(this.onWindowUpdate.bind(this));
1192
- // Setup ResizeObserver
1193
- if (this.hostElement.firstElementChild) {
1194
- const content = this.hostElement.firstElementChild;
1195
- this.resizeObserver = new ResizeObserver(() => {
1196
- const currentHeight = this.hostElement.getBoundingClientRect().height + Number(this.hostElement.paddingTop || 0);
1197
- if (currentHeight !== this.height) {
1198
- this.height = currentHeight;
1199
- this.computeLimit();
1200
- if (this.hostElement.stackable && this._isSticky) {
1201
- const offset = this.computeOffset();
1202
- this.hostElement.style.top = `${offset + Number(this.hostElement.paddingTop || 0)}px`;
1203
- }
1204
- }
1205
- });
1206
- this.resizeObserver.observe(content);
1207
- }
1208
- }
1209
- hostDisconnected() {
1210
- WindowManager.unsubscribe(this.onWindowUpdate.bind(this));
1211
- this.host.removeController(this);
1212
- this.resizeObserver?.disconnect();
1213
- }
1214
- hostUpdate() {
1215
- // Compute limit on every update
1216
- this.computeLimit();
1217
- this.prevHeight = this.hostElement.getBoundingClientRect().height + Number(this.hostElement.paddingTop || 0);
1218
- // If sticky, recalculate position
1219
- if (this._isSticky) {
1220
- const offset = this.hostElement.stackable ? this.computeOffset() : 0;
1221
- this.hostElement.style.top = `${offset + Number(this.hostElement.paddingTop || 0)}px`;
1222
- }
1223
- else {
1224
- this.hostElement.style.top = `${Number(this.hostElement.paddingTop || 0)}px`;
1225
- }
1226
- }
1227
- computeLimit() {
1228
- if (this._isSticky) {
1229
- // If sticky, keep original limit, getBoundingClientRect is expensive
1230
- this.limit = this.originalLimit;
1231
- }
1232
- else {
1233
- const rect = this.hostElement.getBoundingClientRect();
1234
- const { scrollY } = window;
1235
- this.limit = rect.top + scrollY;
1236
- this.height = rect.height + Number(this.hostElement.paddingTop || 0);
1237
- }
1238
- }
1239
- // eslint-disable-next-line class-methods-use-this
1240
- isBeforeInDOM(a, b) {
1241
- // https:// developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
1242
- // this is a bitmask operation
1243
- // eslint-disable-next-line no-bitwise
1244
- return !!(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING);
1245
- }
1246
- getPreviousActiveStickies() {
1247
- const allActiveStickies = Array.from(document.querySelectorAll('it-sticky[stackable].bs-is-sticky, it-sticky[stackable].bs-is-fixed'));
1248
- return allActiveStickies.filter((sticky) => {
1249
- if (sticky === this.hostElement)
1250
- return false;
1251
- return this.isBeforeInDOM(sticky, this.hostElement);
1252
- });
1253
- }
1254
- getPreviousFixedStickiesHeight() {
1255
- const allFixedStickies = Array.from(document.querySelectorAll('it-sticky[stackable][position-type="fixed"]'));
1256
- return allFixedStickies
1257
- .filter((sticky) => sticky !== this.hostElement && this.isBeforeInDOM(sticky, this.hostElement))
1258
- .reduce((acc, sticky) => {
1259
- const rect = sticky.getBoundingClientRect();
1260
- return acc + rect.height + Number(sticky.paddingTop || 0);
1261
- }, 0);
1262
- }
1263
- computeOffset() {
1264
- // Get all stickies to determine visual order
1265
- // 1. Get all stickies
1266
- // 2. Active fixed first (in order of activation), then normal in DOM order
1267
- // 3. Set visualOrder on all
1268
- // 4. Find all with visualOrder < mine
1269
- // 5. Sum their heights
1270
- if (!this.hostElement.stackable) {
1271
- return 0;
1272
- }
1273
- const allStickies = Array.from(document.querySelectorAll('it-sticky[stackable]'));
1274
- const visualOrderList = [
1275
- ...activeFixedStickies,
1276
- ...allStickies.filter((el) => el.positionType !== 'fixed' && !activeFixedStickies.includes(el)),
1277
- ];
1278
- visualOrderList.forEach((el, idx) => {
1279
- if (el._stickyController)
1280
- el._stickyController.setVisualOrder(idx);
1281
- });
1282
- const myOrder = this.visualOrder;
1283
- const relevantStickies = visualOrderList.filter((el) => el !== this.hostElement && el._stickyController && el._stickyController.visualOrder < myOrder);
1284
- return relevantStickies.reduce((acc, sticky) => {
1285
- const rect = sticky.getBoundingClientRect();
1286
- // For all elements (fixed and sticky) we need to add paddingTop
1287
- // it creates visual space that must be considered
1288
- const addPad = Number(sticky.paddingTop || 0);
1289
- return acc + rect.height + addPad;
1290
- }, 0);
1291
- }
1292
- getClasses() {
1293
- if (!this.hostElement.stickyClassName)
1294
- return [];
1295
- const stickyClasses = this.hostElement.stickyClassName.split(' ').filter((c) => c.trim());
1296
- return stickyClasses.length ? [...new Set(stickyClasses)] : [this.hostElement.stickyClassName];
1297
- }
1298
- onWindowUpdate(state, forceRecalc) {
1299
- const currentHeight = this.hostElement.getBoundingClientRect().height;
1300
- if (forceRecalc && currentHeight !== this.prevHeight) {
1301
- this.computeLimit();
1302
- this.prevHeight = currentHeight;
1303
- }
1304
- let offset = 0;
1305
- if (this.hostElement.stackable) {
1306
- offset = this.computeOffset();
1307
- }
1308
- let triggerPoint = this.limit;
1309
- if (this.hostElement.stackable && this.hostElement.positionType !== 'fixed') {
1310
- // Consider previous fixed stickies height and anticipate trigger
1311
- const prevFixedHeight = this.getPreviousFixedStickiesHeight();
1312
- // Anticipate trigger with larger buffer to avoid overlaps
1313
- triggerPoint = this.limit - prevFixedHeight - 40;
1314
- }
1315
- const shouldBeSticky = state.scrollY > triggerPoint - (offset + Number(this.hostElement.paddingTop || 0));
1316
- if (shouldBeSticky && !this._isSticky) {
1317
- this.applySticky(offset);
1318
- this._isSticky = true;
1319
- }
1320
- else if (!shouldBeSticky && this._isSticky) {
1321
- this.resetSticky();
1322
- this._isSticky = false;
1323
- }
1324
- else if (this._isSticky && this.hostElement.stackable) {
1325
- // If still sticky and stackable, update position in case of other stickies changing
1326
- const newOffset = this.computeOffset();
1327
- this.hostElement.style.top = `${newOffset + Number(this.hostElement.paddingTop || 0)}px`;
1328
- }
1329
- }
1330
- applySticky(offset = 0) {
1331
- const classes = this.getClasses();
1332
- if (this.hostElement.positionType === 'fixed') {
1333
- this.hostElement.classList.add(...classes, 'bs-is-fixed');
1334
- // Add to active fixed stickies list if not already present
1335
- if (!activeFixedStickies.includes(this.hostElement)) {
1336
- activeFixedStickies.push(this.hostElement);
1337
- }
1338
- // Update position of all active fixed after applying classes
1339
- // so getBoundingClientRect() returns correct dimensions
1340
- this.updateAllActiveFixedPositions();
1341
- }
1342
- else {
1343
- this.hostElement.classList.add(...classes, 'bs-is-sticky');
1344
- this.hostElement.style.top = `${offset + Number(this.hostElement.paddingTop || 0)}px`;
1345
- }
1346
- this.hostElement.dispatchEvent(new CustomEvent('it-sticky-on', {
1347
- bubbles: true,
1348
- composed: true,
1349
- cancelable: true,
1350
- detail: { id: this.hostElement.id },
1351
- }));
1352
- }
1353
- resetSticky() {
1354
- const classes = this.getClasses();
1355
- if (this.hostElement.positionType === 'fixed') {
1356
- this.hostElement.classList.remove(...classes, 'bs-is-fixed');
1357
- // Remove from active fixed stickies list
1358
- const idx = activeFixedStickies.indexOf(this.hostElement);
1359
- if (idx !== -1)
1360
- activeFixedStickies.splice(idx, 1);
1361
- // Update the position of all active fixed after removal
1362
- this.updateAllActiveFixedPositions();
1363
- }
1364
- else {
1365
- this.hostElement.classList.remove(...classes, 'bs-is-sticky');
1366
- }
1367
- this.hostElement.style.top = '';
1368
- this.hostElement.dispatchEvent(new CustomEvent('it-sticky-off', {
1369
- bubbles: true,
1370
- composed: true,
1371
- cancelable: true,
1372
- detail: { id: this.hostElement.id },
1373
- }));
1374
- }
1375
- // eslint-disable-next-line class-methods-use-this
1376
- updateAllActiveFixedPositions() {
1377
- let offset = 0;
1378
- activeFixedStickies.forEach((elParam) => {
1379
- const el = elParam;
1380
- const ctrl = el._stickyController;
1381
- if (ctrl) {
1382
- const paddingTop = Number(el.paddingTop || 0);
1383
- el.style.top = `${offset + paddingTop}px`;
1384
- const rect = el.getBoundingClientRect();
1385
- offset += rect.height + paddingTop;
1386
- }
1387
- });
1388
- }
1389
- }
1390
-
1391
- let ItSticky = class ItSticky extends BaseComponent {
1392
- constructor() {
1393
- super(...arguments);
1394
- this.paddingTop = 0;
1395
- this.positionType = 'sticky';
1396
- this.stackable = false;
1397
- this._stickyController = new StickyController(this, this);
1398
- }
1399
- updated() {
1400
- if (this.id === '') {
1401
- this.id = this._id;
1402
- }
1403
- if (this.positionType !== 'fixed' && this.positionType !== 'sticky') {
1404
- // eslint-disable-next-line no-console
1405
- console.warn("The supported values for the 'position-type' property are 'fixed' or 'sticky'.");
1406
- }
1407
- }
1408
- createRenderRoot() {
1409
- return this;
1410
- }
1411
- };
1412
- __decorate([
1413
- property({ reflect: true, attribute: 'padding-top' }),
1414
- __metadata("design:type", Object)
1415
- ], ItSticky.prototype, "paddingTop", void 0);
1416
- __decorate([
1417
- property({ reflect: true, attribute: 'sticky-class-name' }),
1418
- __metadata("design:type", Object)
1419
- ], ItSticky.prototype, "stickyClassName", void 0);
1420
- __decorate([
1421
- property({ reflect: true, attribute: 'position-type' }),
1422
- __metadata("design:type", Object)
1423
- ], ItSticky.prototype, "positionType", void 0);
1424
- __decorate([
1425
- property({ reflect: true, type: Boolean }),
1426
- __metadata("design:type", Object)
1427
- ], ItSticky.prototype, "stackable", void 0);
1428
- ItSticky = __decorate([
1429
- customElement('it-sticky')
1430
- ], ItSticky);
1431
-
1432
- export { ItSticky };
1
+ export { I as ItSticky } from '../it-sticky-CV97i_DL.js';
2
+ import 'lit/decorators.js';
3
+ import 'lit/directive.js';
4
+ import 'lit';
1433
5
  //# sourceMappingURL=it-sticky.js.map