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