@italia/button 0.0.1-alpha.0 → 0.1.0-alpha.2
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/custom-elements.json +62 -24
- package/dist/src/it-button.d.ts +6 -4
- package/dist/src/it-button.d.ts.map +1 -1
- package/dist/src/it-button.js +994 -73
- package/dist/src/it-button.js.map +1 -1
- package/package.json +17 -14
- 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 { 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,29 +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 missing required value.
|
|
58
|
-
*/
|
|
59
|
-
VALIDATION_STATUS["ERROR_REQUIRED"] = "required";
|
|
60
|
-
})(VALIDATION_STATUS || (VALIDATION_STATUS = {}));
|
|
61
|
-
|
|
62
39
|
class SetAttributesDirective extends Directive {
|
|
63
40
|
update(part, [attributes]) {
|
|
64
41
|
const el = part.element;
|
|
@@ -81,19 +58,26 @@ class SetAttributesDirective extends Directive {
|
|
|
81
58
|
*/
|
|
82
59
|
const setAttributes = directive(SetAttributesDirective);
|
|
83
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
|
+
|
|
84
63
|
const connectedElements = new Set();
|
|
85
64
|
if (window && !window.translations) {
|
|
86
65
|
window.translations = new Map();
|
|
87
66
|
}
|
|
88
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';
|
|
89
73
|
const isClient = typeof MutationObserver !== 'undefined' &&
|
|
90
74
|
typeof document !== 'undefined' &&
|
|
91
75
|
typeof document.documentElement !== 'undefined';
|
|
92
76
|
/** Updates all localized elements that are currently connected */
|
|
93
77
|
function update() {
|
|
94
78
|
if (isClient) {
|
|
95
|
-
document.documentElement.dir || 'ltr';
|
|
96
|
-
document.documentElement.lang || navigator.language;
|
|
79
|
+
documentDirection = document.documentElement.dir || 'ltr';
|
|
80
|
+
documentLanguage = document.documentElement.lang || navigator.language;
|
|
97
81
|
}
|
|
98
82
|
[...connectedElements.keys()].forEach((el) => {
|
|
99
83
|
const litEl = el;
|
|
@@ -104,8 +88,8 @@ function update() {
|
|
|
104
88
|
}
|
|
105
89
|
if (isClient) {
|
|
106
90
|
const documentElementObserver = new MutationObserver(update);
|
|
107
|
-
document.documentElement.dir || 'ltr';
|
|
108
|
-
document.documentElement.lang || navigator.language;
|
|
91
|
+
documentDirection = document.documentElement.dir || 'ltr';
|
|
92
|
+
documentLanguage = document.documentElement.lang || navigator.language;
|
|
109
93
|
// Watch for changes on <html lang>
|
|
110
94
|
documentElementObserver.observe(document.documentElement, {
|
|
111
95
|
attributes: true,
|
|
@@ -123,10 +107,238 @@ function registerTranslation(...translation) {
|
|
|
123
107
|
else {
|
|
124
108
|
translations.set(code, t);
|
|
125
109
|
}
|
|
110
|
+
// The first translation that's registered is the fallback
|
|
111
|
+
if (!fallback) {
|
|
112
|
+
fallback = t;
|
|
113
|
+
}
|
|
126
114
|
});
|
|
127
115
|
update();
|
|
128
116
|
}
|
|
129
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
|
+
};
|
|
130
342
|
|
|
131
343
|
/* eslint-disable no-console */
|
|
132
344
|
class Logger {
|
|
@@ -154,9 +366,21 @@ class Logger {
|
|
|
154
366
|
class BaseComponent extends LitElement {
|
|
155
367
|
constructor() {
|
|
156
368
|
super();
|
|
157
|
-
this.
|
|
369
|
+
this.composeClass = clsx;
|
|
158
370
|
this.logger = new Logger(this.tagName.toLowerCase());
|
|
159
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
|
+
}
|
|
160
384
|
// eslint-disable-next-line class-methods-use-this
|
|
161
385
|
generateId(prefix) {
|
|
162
386
|
return `${prefix}-${Math.random().toString(36).slice(2)}`;
|
|
@@ -166,30 +390,647 @@ class BaseComponent extends LitElement {
|
|
|
166
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.
|
|
167
391
|
}
|
|
168
392
|
// eslint-disable-next-line class-methods-use-this
|
|
169
|
-
|
|
170
|
-
let
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
.forEach((newClass) => {
|
|
174
|
-
composedClass += ` ${newClass}`;
|
|
175
|
-
});
|
|
176
|
-
return composedClass.trim();
|
|
177
|
-
}
|
|
178
|
-
getAriaAttributes() {
|
|
179
|
-
for (const attr of this.getAttributeNames()) {
|
|
180
|
-
if (attr.startsWith('aria-')) {
|
|
181
|
-
this._ariaAttributes[attr] = this.getAttribute(attr);
|
|
182
|
-
}
|
|
393
|
+
getActiveElement() {
|
|
394
|
+
let active = document.activeElement;
|
|
395
|
+
while (active && active.shadowRoot && active.shadowRoot.activeElement) {
|
|
396
|
+
active = active.shadowRoot.activeElement;
|
|
183
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;
|
|
184
406
|
}
|
|
185
407
|
connectedCallback() {
|
|
186
|
-
super.connectedCallback
|
|
187
|
-
this.getAriaAttributes();
|
|
408
|
+
super.connectedCallback();
|
|
188
409
|
// generate internal _id
|
|
189
410
|
const prefix = this.id?.length > 0 ? this.id : this.tagName.toLowerCase();
|
|
190
411
|
this._id = this.generateId(prefix);
|
|
191
412
|
}
|
|
192
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.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
|
+
default:
|
|
462
|
+
if (Array.isArray(value)) {
|
|
463
|
+
value.forEach((val) => {
|
|
464
|
+
event.formData.append(name, val.toString());
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
else {
|
|
468
|
+
event.formData.append(name, value.toString());
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
this.handleFormSubmit = (event) => {
|
|
474
|
+
const disabled = this.options.disabled(this.host);
|
|
475
|
+
const reportValidity = this.options.reportValidity;
|
|
476
|
+
// Update the interacted state for all controls when the form is submitted
|
|
477
|
+
if (this.form && !this.form.noValidate) {
|
|
478
|
+
formCollections.get(this.form)?.forEach((control) => {
|
|
479
|
+
this.setUserInteracted(control, true);
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
if (this.form && !this.form.noValidate && !disabled && !reportValidity(this.host)) {
|
|
483
|
+
event.preventDefault();
|
|
484
|
+
// event.stopImmediatePropagation(); // se lo attiviamo, valida un campo alla volta
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
this.handleFormReset = () => {
|
|
488
|
+
this.options.setValue(this.host, '');
|
|
489
|
+
this.setUserInteracted(this.host, false);
|
|
490
|
+
interactions.set(this.host, []);
|
|
491
|
+
};
|
|
492
|
+
this.handleInteraction = (event) => {
|
|
493
|
+
const emittedEvents = interactions.get(this.host);
|
|
494
|
+
if (!emittedEvents.includes(event.type)) {
|
|
495
|
+
emittedEvents.push(event.type);
|
|
496
|
+
}
|
|
497
|
+
// Mark it as user-interacted as soon as all associated events have been emitted
|
|
498
|
+
if (emittedEvents.length === this.options.assumeInteractionOn.length) {
|
|
499
|
+
this.setUserInteracted(this.host, true);
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
this.checkFormValidity = () => {
|
|
503
|
+
// console.log('checkFormValidity');
|
|
504
|
+
//
|
|
505
|
+
// This is very similar to the `reportFormValidity` function, but it does not trigger native constraint validation
|
|
506
|
+
// Allow the user to simply check if the form is valid and handling validity in their own way.
|
|
507
|
+
//
|
|
508
|
+
// We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
|
|
509
|
+
// validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
|
|
510
|
+
// be necessary once we can use ElementInternals.
|
|
511
|
+
//
|
|
512
|
+
// Note that we're also honoring the form's novalidate attribute.
|
|
513
|
+
//
|
|
514
|
+
if (this.form && !this.form.noValidate) {
|
|
515
|
+
// This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
|
|
516
|
+
// elements that support the constraint validation API.
|
|
517
|
+
const elements = this.form.querySelectorAll('*');
|
|
518
|
+
for (const element of elements) {
|
|
519
|
+
if (typeof element.checkValidity === 'function') {
|
|
520
|
+
if (!element.checkValidity()) {
|
|
521
|
+
return false;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return true;
|
|
527
|
+
};
|
|
528
|
+
this.reportFormValidity = () => {
|
|
529
|
+
// console.log('reportFormValidity');
|
|
530
|
+
//
|
|
531
|
+
// FormControl work hard to act like regular form controls. They support the Constraint Validation API
|
|
532
|
+
// and its associated methods such as setCustomValidity() and reportValidity(). However, the HTMLFormElement also
|
|
533
|
+
// has a reportValidity() method that will trigger validation on all child controls. Since we're not yet using
|
|
534
|
+
// ElementInternals, we need to overload this method so it looks for any element with the reportValidity() method.
|
|
535
|
+
//
|
|
536
|
+
// We preserve the original method in a WeakMap, but we don't call it from the overload because that would trigger
|
|
537
|
+
// validations in an unexpected order. When the element disconnects, we revert to the original behavior. This won't
|
|
538
|
+
// be necessary once we can use ElementInternals.
|
|
539
|
+
//
|
|
540
|
+
// Note that we're also honoring the form's novalidate attribute.
|
|
541
|
+
//
|
|
542
|
+
if (this.form && !this.form.noValidate) {
|
|
543
|
+
// This seems sloppy, but checking all elements will cover native inputs, Shoelace inputs, and other custom
|
|
544
|
+
// elements that support the constraint validation API.
|
|
545
|
+
const elements = this.form.querySelectorAll('*');
|
|
546
|
+
for (const element of elements) {
|
|
547
|
+
if (typeof element.reportValidity === 'function') {
|
|
548
|
+
if (!element.reportValidity()) {
|
|
549
|
+
return false;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
return true;
|
|
555
|
+
};
|
|
556
|
+
(this.host = host).addController(this);
|
|
557
|
+
this.options = {
|
|
558
|
+
form: (input) => {
|
|
559
|
+
// If there's a form attribute, use it to find the target form by id
|
|
560
|
+
// Controls may not always reflect the 'form' property. For example, `<it-button>` doesn't reflect.
|
|
561
|
+
const formId = input.form;
|
|
562
|
+
if (formId) {
|
|
563
|
+
const root = input.getRootNode();
|
|
564
|
+
const form = root.querySelector(`#${formId}`);
|
|
565
|
+
if (form) {
|
|
566
|
+
return form;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return input.closest('form');
|
|
570
|
+
},
|
|
571
|
+
name: (input) => input.name,
|
|
572
|
+
value: (input) => input.value,
|
|
573
|
+
disabled: (input) => input.disabled ?? false,
|
|
574
|
+
reportValidity: (input) => typeof input.reportValidity === 'function' ? input.reportValidity() : true,
|
|
575
|
+
checkValidity: (input) => (typeof input.checkValidity === 'function' ? input.checkValidity() : true),
|
|
576
|
+
setValue: (input, value) => {
|
|
577
|
+
// eslint-disable-next-line no-param-reassign
|
|
578
|
+
input.value = value;
|
|
579
|
+
},
|
|
580
|
+
assumeInteractionOn: ['it-input'],
|
|
581
|
+
...options,
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
hostConnected() {
|
|
585
|
+
const form = this.options.form(this.host);
|
|
586
|
+
if (form) {
|
|
587
|
+
this.attachForm(form);
|
|
588
|
+
}
|
|
589
|
+
// Listen for interactions
|
|
590
|
+
interactions.set(this.host, []);
|
|
591
|
+
this.options.assumeInteractionOn.forEach((event) => {
|
|
592
|
+
this.host.addEventListener(event, this.handleInteraction);
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
hostDisconnected() {
|
|
596
|
+
this.detachForm();
|
|
597
|
+
// Clean up interactions
|
|
598
|
+
interactions.delete(this.host);
|
|
599
|
+
this.options.assumeInteractionOn.forEach((event) => {
|
|
600
|
+
this.host.removeEventListener(event, this.handleInteraction);
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
hostUpdated() {
|
|
604
|
+
const form = this.options.form(this.host);
|
|
605
|
+
// Detach if the form no longer exists
|
|
606
|
+
if (!form) {
|
|
607
|
+
this.detachForm();
|
|
608
|
+
}
|
|
609
|
+
// If the form has changed, reattach it
|
|
610
|
+
if (form && this.form !== form) {
|
|
611
|
+
this.detachForm();
|
|
612
|
+
this.attachForm(form);
|
|
613
|
+
}
|
|
614
|
+
if (this.host.hasUpdated) {
|
|
615
|
+
this.setValidity(this.host.validity.valid);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
attachForm(form) {
|
|
619
|
+
if (form) {
|
|
620
|
+
this.form = form;
|
|
621
|
+
// Add this element to the form's collection
|
|
622
|
+
if (formCollections.has(this.form)) {
|
|
623
|
+
formCollections.get(this.form).add(this.host);
|
|
624
|
+
}
|
|
625
|
+
else {
|
|
626
|
+
formCollections.set(this.form, new Set([this.host]));
|
|
627
|
+
}
|
|
628
|
+
this.form.addEventListener('formdata', this.handleFormData);
|
|
629
|
+
this.form.addEventListener('submit', this.handleFormSubmit);
|
|
630
|
+
this.form.addEventListener('reset', this.handleFormReset);
|
|
631
|
+
// Overload the form's reportValidity() method so it looks at FormControl
|
|
632
|
+
if (!reportValidityOverloads.has(this.form)) {
|
|
633
|
+
reportValidityOverloads.set(this.form, this.form.reportValidity);
|
|
634
|
+
this.form.reportValidity = () => this.reportFormValidity();
|
|
635
|
+
}
|
|
636
|
+
// Overload the form's checkValidity() method so it looks at FormControl
|
|
637
|
+
if (!checkValidityOverloads.has(this.form)) {
|
|
638
|
+
checkValidityOverloads.set(this.form, this.form.checkValidity);
|
|
639
|
+
this.form.checkValidity = () => this.checkFormValidity();
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
else {
|
|
643
|
+
this.form = undefined;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
detachForm() {
|
|
647
|
+
if (!this.form)
|
|
648
|
+
return;
|
|
649
|
+
const formCollection = formCollections.get(this.form);
|
|
650
|
+
if (!formCollection) {
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
// Remove this host from the form's collection
|
|
654
|
+
formCollection.delete(this.host);
|
|
655
|
+
// Check to make sure there's no other form controls in the collection. If we do this
|
|
656
|
+
// without checking if any other controls are still in the collection, then we will wipe out the
|
|
657
|
+
// validity checks for all other elements.
|
|
658
|
+
// see: https://github.com/shoelace-style/shoelace/issues/1703
|
|
659
|
+
if (formCollection.size <= 0) {
|
|
660
|
+
this.form.removeEventListener('formdata', this.handleFormData);
|
|
661
|
+
this.form.removeEventListener('submit', this.handleFormSubmit);
|
|
662
|
+
this.form.removeEventListener('reset', this.handleFormReset);
|
|
663
|
+
// Remove the overload and restore the original method
|
|
664
|
+
if (reportValidityOverloads.has(this.form)) {
|
|
665
|
+
this.form.reportValidity = reportValidityOverloads.get(this.form);
|
|
666
|
+
reportValidityOverloads.delete(this.form);
|
|
667
|
+
}
|
|
668
|
+
if (checkValidityOverloads.has(this.form)) {
|
|
669
|
+
this.form.checkValidity = checkValidityOverloads.get(this.form);
|
|
670
|
+
checkValidityOverloads.delete(this.form);
|
|
671
|
+
}
|
|
672
|
+
// So it looks weird here to not always set the form to undefined. But I _think_ if we unattach this.form here,
|
|
673
|
+
// we end up in this fun spot where future validity checks don't have a reference to the form validity handler.
|
|
674
|
+
// 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.
|
|
675
|
+
this.form = undefined;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
// eslint-disable-next-line class-methods-use-this
|
|
679
|
+
setUserInteracted(el, hasInteracted) {
|
|
680
|
+
if (hasInteracted) {
|
|
681
|
+
userInteractedControls.add(el);
|
|
682
|
+
}
|
|
683
|
+
else {
|
|
684
|
+
userInteractedControls.delete(el);
|
|
685
|
+
}
|
|
686
|
+
el.requestUpdate();
|
|
687
|
+
}
|
|
688
|
+
doAction(type, submitter) {
|
|
689
|
+
// console.log('doaction', type);
|
|
690
|
+
if (this.form) {
|
|
691
|
+
const button = document.createElement('button');
|
|
692
|
+
button.type = type;
|
|
693
|
+
button.style.position = 'absolute';
|
|
694
|
+
button.style.width = '0';
|
|
695
|
+
button.style.height = '0';
|
|
696
|
+
button.style.clipPath = 'inset(50%)';
|
|
697
|
+
button.style.overflow = 'hidden';
|
|
698
|
+
button.style.whiteSpace = 'nowrap';
|
|
699
|
+
// Pass name, value, and form attributes through to the temporary button
|
|
700
|
+
if (submitter) {
|
|
701
|
+
button.name = submitter.name;
|
|
702
|
+
button.value = submitter.value;
|
|
703
|
+
['formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget'].forEach((attr) => {
|
|
704
|
+
if (submitter.hasAttribute(attr)) {
|
|
705
|
+
button.setAttribute(attr, submitter.getAttribute(attr));
|
|
706
|
+
}
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
this.form.append(button);
|
|
710
|
+
button.click();
|
|
711
|
+
button.remove();
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
/** Returns the associated `<form>` element, if one exists. */
|
|
715
|
+
getForm() {
|
|
716
|
+
return this.form ?? null;
|
|
717
|
+
}
|
|
718
|
+
/** Resets the form, restoring all the control to their default value */
|
|
719
|
+
reset(submitter) {
|
|
720
|
+
this.doAction('reset', submitter);
|
|
721
|
+
}
|
|
722
|
+
/** Submits the form, triggering validation and form data injection. */
|
|
723
|
+
submit(submitter) {
|
|
724
|
+
// Calling form.submit() bypasses the submit event and constraint validation. To prevent this, we can inject a
|
|
725
|
+
// native submit button into the form, "click" it, then remove it to simulate a standard form submission.
|
|
726
|
+
this.doAction('submit', submitter);
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Synchronously sets the form control's validity. Call this when you know the future validity but need to update
|
|
730
|
+
* the host element immediately, i.e. before Lit updates the component in the next update.
|
|
731
|
+
*/
|
|
732
|
+
setValidity(isValid) {
|
|
733
|
+
const host = this.host;
|
|
734
|
+
const hasInteracted = Boolean(userInteractedControls.has(host));
|
|
735
|
+
const required = Boolean(host.required);
|
|
736
|
+
//
|
|
737
|
+
// We're mapping the following "states" to data attributes. In the future, we can use ElementInternals.states to
|
|
738
|
+
// create a similar mapping, but instead of [data-invalid] it will look like :--invalid.
|
|
739
|
+
//
|
|
740
|
+
// See this RFC for more details: https://github.com/shoelace-style/shoelace/issues/1011
|
|
741
|
+
//
|
|
742
|
+
host.toggleAttribute('data-required', required);
|
|
743
|
+
host.toggleAttribute('data-optional', !required);
|
|
744
|
+
host.toggleAttribute('data-invalid', !isValid);
|
|
745
|
+
host.toggleAttribute('data-valid', isValid);
|
|
746
|
+
host.toggleAttribute('data-user-invalid', !isValid && hasInteracted);
|
|
747
|
+
host.toggleAttribute('data-user-valid', isValid && hasInteracted);
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Updates the form control's validity based on the current value of `host.validity.valid`. Call this when anything
|
|
751
|
+
* that affects constraint validation changes so the component receives the correct validity states.
|
|
752
|
+
*/
|
|
753
|
+
updateValidity() {
|
|
754
|
+
const host = this.host;
|
|
755
|
+
this.setValidity(host.validity.valid);
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Dispatches a non-bubbling, cancelable custom event of type `it-invalid`.
|
|
759
|
+
* If the `it-invalid` event will be cancelled then the original `invalid`
|
|
760
|
+
* event (which may have been passed as argument) will also be cancelled.
|
|
761
|
+
* If no original `invalid` event has been passed then the `it-invalid`
|
|
762
|
+
* event will be cancelled before being dispatched.
|
|
763
|
+
*/
|
|
764
|
+
emitInvalidEvent(originalInvalidEvent) {
|
|
765
|
+
const itInvalidEvent = new CustomEvent('it-invalid', {
|
|
766
|
+
bubbles: false,
|
|
767
|
+
composed: false,
|
|
768
|
+
cancelable: true,
|
|
769
|
+
detail: {},
|
|
770
|
+
});
|
|
771
|
+
if (!originalInvalidEvent) {
|
|
772
|
+
itInvalidEvent.preventDefault();
|
|
773
|
+
}
|
|
774
|
+
if (!this.host.dispatchEvent(itInvalidEvent)) {
|
|
775
|
+
originalInvalidEvent?.preventDefault();
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
const translation = {
|
|
781
|
+
$code: 'it',
|
|
782
|
+
$name: 'Italiano',
|
|
783
|
+
$dir: 'ltr',
|
|
784
|
+
validityRequired: 'Questo campo è obbligatorio.',
|
|
785
|
+
validityPattern: 'Il valore non corrisponde al formato richiesto.',
|
|
786
|
+
validityMinlength: 'Il valore deve essere lungo almeno {minlength} caratteri.',
|
|
787
|
+
validityMaxlength: 'Il valore deve essere lungo al massimo {maxlength} caratteri.',
|
|
788
|
+
};
|
|
789
|
+
|
|
790
|
+
registerTranslation(translation);
|
|
791
|
+
class FormControl extends BaseLocalizedComponent {
|
|
792
|
+
constructor() {
|
|
793
|
+
super(...arguments);
|
|
794
|
+
this.formControlController = new FormControlController(this, {
|
|
795
|
+
assumeInteractionOn: ['it-input', 'it-blur', 'it-change'],
|
|
796
|
+
});
|
|
797
|
+
// TODO: verificare se serve davvero con il fatto che usiamo form-controller
|
|
798
|
+
// static formAssociated = true;
|
|
799
|
+
// @property()
|
|
800
|
+
// internals = this.attachInternals();
|
|
801
|
+
this._touched = false;
|
|
802
|
+
/** The name of the input, submitted as a name/value pair with form data. */
|
|
803
|
+
this.name = '';
|
|
804
|
+
/** The current value of the input, submitted as a name/value pair with form data. */
|
|
805
|
+
this.value = '';
|
|
806
|
+
/** If the input is disabled. */
|
|
807
|
+
this.disabled = false;
|
|
808
|
+
/**
|
|
809
|
+
* By default, form controls are associated with the nearest containing `<form>` element. This attribute allows you
|
|
810
|
+
* to place the form control outside of a form and associate it with the form that has this `id`. The form must be in
|
|
811
|
+
* the same document or shadow root for this to work.
|
|
812
|
+
*/
|
|
813
|
+
this.form = '';
|
|
814
|
+
/** If you implement your custom validation and you won't to trigger default validation */
|
|
815
|
+
this.customValidation = false;
|
|
816
|
+
/** If your input is invalid from your custom validition, set this attribute with message validation */
|
|
817
|
+
this.validationText = '';
|
|
818
|
+
/**
|
|
819
|
+
* Specifies the granularity that the value must adhere to, or the special value `any` which means no stepping is
|
|
820
|
+
* implied, allowing any numeric value. Only applies to date and number input types.
|
|
821
|
+
*/
|
|
822
|
+
this.step = 'any';
|
|
823
|
+
/** The input's minimum length. */
|
|
824
|
+
this.minlength = -1;
|
|
825
|
+
/** The input's maximum length. */
|
|
826
|
+
this.maxlength = -1;
|
|
827
|
+
/** If the input is required. */
|
|
828
|
+
this.required = false;
|
|
829
|
+
this.validationMessage = '';
|
|
830
|
+
}
|
|
831
|
+
/** Gets the validity state object */
|
|
832
|
+
get validity() {
|
|
833
|
+
return this.inputElement?.validity;
|
|
834
|
+
}
|
|
835
|
+
// Form validation methods
|
|
836
|
+
checkValidity() {
|
|
837
|
+
const inputValid = this.inputElement?.checkValidity() ?? true; // this.inputElement.checkValidity() è la validazione del browser
|
|
838
|
+
return inputValid;
|
|
839
|
+
}
|
|
840
|
+
/** Gets the associated form, if one exists. */
|
|
841
|
+
getForm() {
|
|
842
|
+
return this.formControlController.getForm();
|
|
843
|
+
}
|
|
844
|
+
/** Checks for validity and shows the browser's validation message if the control is invalid. */
|
|
845
|
+
reportValidity() {
|
|
846
|
+
const ret = this.inputElement.checkValidity();
|
|
847
|
+
this.handleValidationMessages();
|
|
848
|
+
return ret; // this.inputElement.reportValidity();
|
|
849
|
+
}
|
|
850
|
+
/** Sets a custom validation message. Pass an empty string to restore validity. */
|
|
851
|
+
setCustomValidity(message) {
|
|
852
|
+
this.inputElement.setCustomValidity(message);
|
|
853
|
+
this.validationMessage = this.inputElement.validationMessage;
|
|
854
|
+
this.formControlController.updateValidity();
|
|
855
|
+
}
|
|
856
|
+
// Handlers
|
|
857
|
+
_handleReady() {
|
|
858
|
+
requestAnimationFrame(() => {
|
|
859
|
+
this.dispatchEvent(new CustomEvent('it-input-ready', { bubbles: true, detail: { el: this.inputElement } }));
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
863
|
+
_handleInput(e) {
|
|
864
|
+
this.handleValidationMessages();
|
|
865
|
+
this.dispatchEvent(new CustomEvent('it-input', {
|
|
866
|
+
detail: { value: this.inputElement.value, el: this.inputElement },
|
|
867
|
+
bubbles: true,
|
|
868
|
+
composed: true,
|
|
869
|
+
}));
|
|
870
|
+
}
|
|
871
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
872
|
+
_handleBlur(e) {
|
|
873
|
+
this._touched = true;
|
|
874
|
+
this.handleValidationMessages();
|
|
875
|
+
this.dispatchEvent(new FocusEvent('it-blur', { bubbles: true, composed: true }));
|
|
876
|
+
}
|
|
877
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
878
|
+
_handleFocus(e) {
|
|
879
|
+
this.dispatchEvent(new FocusEvent('it-focus', { bubbles: true, composed: true }));
|
|
880
|
+
}
|
|
881
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
882
|
+
_handleClick(e) {
|
|
883
|
+
this.dispatchEvent(new MouseEvent('it-click', { bubbles: true, composed: true }));
|
|
884
|
+
}
|
|
885
|
+
/*
|
|
886
|
+
Override default browser validation messages
|
|
887
|
+
*/
|
|
888
|
+
handleValidationMessages() {
|
|
889
|
+
if (!this.customValidation) {
|
|
890
|
+
const _v = this.inputElement.validity;
|
|
891
|
+
if (_v.valueMissing) {
|
|
892
|
+
this.setCustomValidity(this.$t('validityRequired'));
|
|
893
|
+
}
|
|
894
|
+
else if (_v.patternMismatch) {
|
|
895
|
+
this.setCustomValidity(this.$t('validityPattern'));
|
|
896
|
+
}
|
|
897
|
+
else if (_v.tooShort) {
|
|
898
|
+
this.setCustomValidity(this.$t('validityMinlength').replace('{minlength}', this.minlength.toString()));
|
|
899
|
+
}
|
|
900
|
+
else if (_v.tooLong) {
|
|
901
|
+
this.setCustomValidity(this.$t('validityMaxlength').replace('{maxlength}', this.maxlength.toString()));
|
|
902
|
+
}
|
|
903
|
+
else {
|
|
904
|
+
/* nothing. Usa il messaggio di errore della validazione
|
|
905
|
+
di default del browser per altri errori di validità come:
|
|
906
|
+
- typeMismatch
|
|
907
|
+
- rangeUnderflow
|
|
908
|
+
- rangeOverflow
|
|
909
|
+
- stepMismatch
|
|
910
|
+
- badInput */
|
|
911
|
+
const otherConstraintErrors = _v.typeMismatch || _v.rangeUnderflow || _v.rangeOverflow || _v.stepMismatch || _v.badInput;
|
|
912
|
+
if (!otherConstraintErrors) {
|
|
913
|
+
this.setCustomValidity('');
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
this.validationMessage = this.inputElement.validationMessage;
|
|
918
|
+
}
|
|
919
|
+
_handleInvalid(event) {
|
|
920
|
+
this.formControlController.setValidity(false);
|
|
921
|
+
this.formControlController.emitInvalidEvent(event);
|
|
922
|
+
}
|
|
923
|
+
_handleChange(e) {
|
|
924
|
+
const target = e.target;
|
|
925
|
+
let value;
|
|
926
|
+
if (target instanceof HTMLInputElement) {
|
|
927
|
+
switch (target.type) {
|
|
928
|
+
case 'checkbox':
|
|
929
|
+
case 'radio':
|
|
930
|
+
value = target.checked;
|
|
931
|
+
break;
|
|
932
|
+
case 'file':
|
|
933
|
+
value = target.files; // FileList
|
|
934
|
+
break;
|
|
935
|
+
default:
|
|
936
|
+
value = target.value;
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
else if (target instanceof HTMLSelectElement) {
|
|
940
|
+
if (target.multiple) {
|
|
941
|
+
value = Array.from(target.selectedOptions).map((o) => o.value);
|
|
942
|
+
}
|
|
943
|
+
else {
|
|
944
|
+
value = target.value;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
else {
|
|
948
|
+
// textarea o altri input con value
|
|
949
|
+
value = target.value;
|
|
950
|
+
}
|
|
951
|
+
this.dispatchEvent(new CustomEvent('it-change', {
|
|
952
|
+
detail: { value, el: target },
|
|
953
|
+
bubbles: true,
|
|
954
|
+
composed: true,
|
|
955
|
+
}));
|
|
956
|
+
}
|
|
957
|
+
updated(changedProperties) {
|
|
958
|
+
super.updated?.(changedProperties);
|
|
959
|
+
if (this.customValidation) {
|
|
960
|
+
this.setCustomValidity(this.validationText ?? '');
|
|
961
|
+
}
|
|
962
|
+
else {
|
|
963
|
+
this.formControlController.updateValidity();
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
__decorate([
|
|
968
|
+
state(),
|
|
969
|
+
__metadata("design:type", Object)
|
|
970
|
+
], FormControl.prototype, "_touched", void 0);
|
|
971
|
+
__decorate([
|
|
972
|
+
query('.it-form__control'),
|
|
973
|
+
__metadata("design:type", HTMLInputElement)
|
|
974
|
+
], FormControl.prototype, "inputElement", void 0);
|
|
975
|
+
__decorate([
|
|
976
|
+
property({ type: String, reflect: true }) // from FormControl
|
|
977
|
+
,
|
|
978
|
+
__metadata("design:type", Object)
|
|
979
|
+
], FormControl.prototype, "name", void 0);
|
|
980
|
+
__decorate([
|
|
981
|
+
property({ reflect: true }),
|
|
982
|
+
__metadata("design:type", Object)
|
|
983
|
+
], FormControl.prototype, "value", void 0);
|
|
984
|
+
__decorate([
|
|
985
|
+
property({ type: Boolean, reflect: true }) // from FormControl
|
|
986
|
+
,
|
|
987
|
+
__metadata("design:type", Object)
|
|
988
|
+
], FormControl.prototype, "disabled", void 0);
|
|
989
|
+
__decorate([
|
|
990
|
+
property({ reflect: true, type: String }),
|
|
991
|
+
__metadata("design:type", Object)
|
|
992
|
+
], FormControl.prototype, "form", void 0);
|
|
993
|
+
__decorate([
|
|
994
|
+
property({ type: Boolean, reflect: true, attribute: 'custom-validation' }),
|
|
995
|
+
__metadata("design:type", Object)
|
|
996
|
+
], FormControl.prototype, "customValidation", void 0);
|
|
997
|
+
__decorate([
|
|
998
|
+
property({ attribute: 'validity-message', reflect: true }),
|
|
999
|
+
__metadata("design:type", String)
|
|
1000
|
+
], FormControl.prototype, "validationText", void 0);
|
|
1001
|
+
__decorate([
|
|
1002
|
+
property(),
|
|
1003
|
+
__metadata("design:type", String)
|
|
1004
|
+
], FormControl.prototype, "pattern", void 0);
|
|
1005
|
+
__decorate([
|
|
1006
|
+
property(),
|
|
1007
|
+
__metadata("design:type", Object)
|
|
1008
|
+
], FormControl.prototype, "min", void 0);
|
|
1009
|
+
__decorate([
|
|
1010
|
+
property(),
|
|
1011
|
+
__metadata("design:type", Object)
|
|
1012
|
+
], FormControl.prototype, "max", void 0);
|
|
1013
|
+
__decorate([
|
|
1014
|
+
property(),
|
|
1015
|
+
__metadata("design:type", Object)
|
|
1016
|
+
], FormControl.prototype, "step", void 0);
|
|
1017
|
+
__decorate([
|
|
1018
|
+
property({ type: Number }),
|
|
1019
|
+
__metadata("design:type", Object)
|
|
1020
|
+
], FormControl.prototype, "minlength", void 0);
|
|
1021
|
+
__decorate([
|
|
1022
|
+
property({ type: Number }),
|
|
1023
|
+
__metadata("design:type", Object)
|
|
1024
|
+
], FormControl.prototype, "maxlength", void 0);
|
|
1025
|
+
__decorate([
|
|
1026
|
+
property({ type: Boolean, reflect: true }) // from FormControl
|
|
1027
|
+
,
|
|
1028
|
+
__metadata("design:type", Object)
|
|
1029
|
+
], FormControl.prototype, "required", void 0);
|
|
1030
|
+
__decorate([
|
|
1031
|
+
state(),
|
|
1032
|
+
__metadata("design:type", Object)
|
|
1033
|
+
], FormControl.prototype, "validationMessage", void 0);
|
|
193
1034
|
|
|
194
1035
|
var styles = css`/***************************** 1 ****************************************/
|
|
195
1036
|
/***************************** 2 ****************************************/
|
|
@@ -530,13 +1371,51 @@ a.btn-outline-danger:active {
|
|
|
530
1371
|
.bg-dark .btn-link {
|
|
531
1372
|
--bs-btn-text-color: var(--bs-color-text-inverse);
|
|
532
1373
|
}
|
|
1374
|
+
.bg-dark a.btn-primary,
|
|
1375
|
+
.bg-dark .btn-primary {
|
|
1376
|
+
--bs-btn-text-color: var(--bs-color-text-primary);
|
|
1377
|
+
--bs-btn-background: var(--bs-color-background-inverse);
|
|
1378
|
+
}
|
|
1379
|
+
.bg-dark a.btn-primary:hover,
|
|
1380
|
+
.bg-dark .btn-primary:hover {
|
|
1381
|
+
--bs-btn-background: color-mix(in srgb, var(--bs-color-background-inverse) 85%, black);
|
|
1382
|
+
}
|
|
1383
|
+
.bg-dark a.btn-primary:active,
|
|
1384
|
+
.bg-dark .btn-primary:active {
|
|
1385
|
+
--bs-btn-background: color-mix(in srgb, var(--bs-color-background-inverse) 80%, black);
|
|
1386
|
+
}
|
|
1387
|
+
.bg-dark a.btn-secondary,
|
|
1388
|
+
.bg-dark .btn-secondary {
|
|
1389
|
+
--bs-btn-text-color: var(--bs-color-text-inverse);
|
|
1390
|
+
--bs-btn-background: var(--bs-color-background-secondary);
|
|
1391
|
+
}
|
|
1392
|
+
.bg-dark a.btn-secondary:hover, .bg-dark a.btn-secondary:active,
|
|
1393
|
+
.bg-dark .btn-secondary:hover,
|
|
1394
|
+
.bg-dark .btn-secondary:active {
|
|
1395
|
+
--bs-btn-background: color-mix(in srgb, var(--bs-color-background-secondary) 85%, black);
|
|
1396
|
+
}
|
|
533
1397
|
.bg-dark .btn-outline-primary,
|
|
534
|
-
.bg-dark a.btn-outline-primary
|
|
1398
|
+
.bg-dark a.btn-outline-primary {
|
|
1399
|
+
--bs-btn-outline-border-color: var(--bs-color-border-inverse);
|
|
1400
|
+
--bs-btn-text-color: var(--bs-color-text-inverse);
|
|
1401
|
+
}
|
|
1402
|
+
.bg-dark .btn-outline-primary:hover,
|
|
1403
|
+
.bg-dark a.btn-outline-primary:hover {
|
|
1404
|
+
--bs-btn-boxshadow-color-darken: color-mix(in srgb, var(--bs-color-border-inverse) 80%, black);
|
|
1405
|
+
--bs-btn-boxshadow-color-desaturated: color-mix(in srgb, var(--bs-btn-boxshadow-color-darken) 80%, gray);
|
|
1406
|
+
--bs-btn-outline-border-color: var(--bs-btn-boxshadow-color-desaturated);
|
|
1407
|
+
}
|
|
535
1408
|
.bg-dark .btn-outline-secondary,
|
|
536
1409
|
.bg-dark a.btn-outline-secondary {
|
|
537
|
-
--bs-btn-outline-border-color: var(--bs-color-border-inverse);
|
|
538
1410
|
--bs-btn-text-color: var(--bs-color-text-inverse);
|
|
539
1411
|
}
|
|
1412
|
+
.bg-dark .btn-outline-secondary:hover, .bg-dark .btn-outline-secondary:active,
|
|
1413
|
+
.bg-dark a.btn-outline-secondary:hover,
|
|
1414
|
+
.bg-dark a.btn-outline-secondary:active {
|
|
1415
|
+
--bs-btn-boxshadow-color-darken: color-mix(in srgb, var(--bs-color-background-secondary) 80%, black);
|
|
1416
|
+
--bs-btn-boxshadow-color-desaturated: color-mix(in srgb, var(--bs-btn-boxshadow-color-darken) 80%, gray);
|
|
1417
|
+
--bs-btn-outline-border-color: var(--bs-btn-boxshadow-color-desaturated);
|
|
1418
|
+
}
|
|
540
1419
|
|
|
541
1420
|
.btn-close {
|
|
542
1421
|
position: relative;
|
|
@@ -575,7 +1454,6 @@ a.btn-outline-danger:active {
|
|
|
575
1454
|
let ItButton = class ItButton extends BaseComponent {
|
|
576
1455
|
constructor() {
|
|
577
1456
|
super(...arguments);
|
|
578
|
-
this._buttonClasses = '';
|
|
579
1457
|
this.type = 'button';
|
|
580
1458
|
this.variant = '';
|
|
581
1459
|
this.size = '';
|
|
@@ -584,28 +1462,41 @@ let ItButton = class ItButton extends BaseComponent {
|
|
|
584
1462
|
this.icon = false;
|
|
585
1463
|
this.value = '';
|
|
586
1464
|
this.internals = this.attachInternals();
|
|
1465
|
+
this._onKeyDown = (e) => {
|
|
1466
|
+
if (e.key === 'Enter' || e.key === ' ') {
|
|
1467
|
+
e.preventDefault();
|
|
1468
|
+
this._nativeButton?.click();
|
|
1469
|
+
}
|
|
1470
|
+
};
|
|
587
1471
|
}
|
|
588
1472
|
static get formAssociated() {
|
|
589
1473
|
return true;
|
|
590
1474
|
}
|
|
591
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
592
|
-
firstUpdated(_changedProperties) {
|
|
593
|
-
const button = this.renderRoot.querySelector('button');
|
|
594
|
-
if (button) {
|
|
595
|
-
this.addFocus(button);
|
|
596
|
-
}
|
|
597
|
-
}
|
|
598
|
-
updated() {
|
|
599
|
-
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' : '');
|
|
600
|
-
}
|
|
601
1475
|
surfaceSubmitEvent(event) {
|
|
602
|
-
|
|
603
|
-
if (this.form && !disabled) {
|
|
1476
|
+
if (this.form && !this.disabled) {
|
|
604
1477
|
event.preventDefault();
|
|
605
1478
|
event.stopPropagation();
|
|
606
|
-
|
|
1479
|
+
let someInvalid = false;
|
|
1480
|
+
// valido ogni campo
|
|
1481
|
+
const itItems = Array.from(this.form.querySelectorAll('*')).filter((el) => el.tagName.toLowerCase().startsWith('it-'));
|
|
1482
|
+
itItems.forEach((itItem) => {
|
|
1483
|
+
// Accedi allo Shadow DOM del web component
|
|
1484
|
+
if (itItem.checkValidity) {
|
|
1485
|
+
itItem.checkValidity();
|
|
1486
|
+
}
|
|
1487
|
+
const isValid = itItem?.isValid ? itItem.isValid() : true;
|
|
1488
|
+
// Controlla se l'input interno esiste e se non è valido
|
|
1489
|
+
if (!isValid) {
|
|
1490
|
+
someInvalid = true;
|
|
1491
|
+
// eslint-disable-next-line no-console
|
|
1492
|
+
console.error(`Invalid field: [name]=${itItem.name}, [id]=${itItem.id}`);
|
|
1493
|
+
}
|
|
1494
|
+
});
|
|
1495
|
+
if (!someInvalid) {
|
|
1496
|
+
this.form.requestSubmit();
|
|
1497
|
+
}
|
|
607
1498
|
}
|
|
608
|
-
if (disabled) {
|
|
1499
|
+
if (this.disabled) {
|
|
609
1500
|
event.preventDefault();
|
|
610
1501
|
event.stopPropagation();
|
|
611
1502
|
}
|
|
@@ -613,23 +1504,45 @@ let ItButton = class ItButton extends BaseComponent {
|
|
|
613
1504
|
get form() {
|
|
614
1505
|
return this.internals ? this.internals.form : null;
|
|
615
1506
|
}
|
|
1507
|
+
focus() {
|
|
1508
|
+
this._nativeButton?.focus();
|
|
1509
|
+
}
|
|
616
1510
|
connectedCallback() {
|
|
617
1511
|
super.connectedCallback?.();
|
|
618
1512
|
if (this.block) {
|
|
619
1513
|
this.classList.add('d-block', 'w-100');
|
|
620
1514
|
}
|
|
1515
|
+
this.addEventListener('keydown', this._onKeyDown);
|
|
1516
|
+
}
|
|
1517
|
+
disconnectedCallback() {
|
|
1518
|
+
this.removeEventListener('keydown', this._onKeyDown);
|
|
1519
|
+
super.disconnectedCallback?.();
|
|
621
1520
|
}
|
|
622
1521
|
// Render the UI as a function of component state
|
|
623
1522
|
render() {
|
|
624
|
-
const
|
|
1523
|
+
const classes = this.composeClass('btn', this.className, {
|
|
1524
|
+
[`btn-${this.variant}`]: !!this.variant && !this.outline,
|
|
1525
|
+
[`btn-outline-${this.variant}`]: !!this.variant && this.outline,
|
|
1526
|
+
[`btn-${this.size}`]: !!this.size,
|
|
1527
|
+
disabled: this.disabled,
|
|
1528
|
+
'btn-icon': this.icon,
|
|
1529
|
+
'd-block w-100': this.block,
|
|
1530
|
+
});
|
|
1531
|
+
const part = this.composeClass('button', 'focusable', {
|
|
1532
|
+
[this.variant]: this.variant?.length > 0,
|
|
1533
|
+
outline: this.outline,
|
|
1534
|
+
});
|
|
625
1535
|
return html `
|
|
626
1536
|
<button
|
|
1537
|
+
id=${ifDefined(this.id || undefined)}
|
|
627
1538
|
part="${part}"
|
|
628
1539
|
type="${this.type}"
|
|
629
|
-
class="${
|
|
1540
|
+
class="${classes}"
|
|
630
1541
|
@click="${this.type === 'submit' ? this.surfaceSubmitEvent : undefined}"
|
|
631
1542
|
.value="${ifDefined(this.value ? this.value : undefined)}"
|
|
632
1543
|
${setAttributes(this._ariaAttributes)}
|
|
1544
|
+
aria-expanded="${ifDefined(this.expanded !== undefined ? this.expanded : undefined)}"
|
|
1545
|
+
aria-disabled="${ifDefined(this.disabled ? this.disabled : undefined)}"
|
|
633
1546
|
>
|
|
634
1547
|
<slot></slot>
|
|
635
1548
|
</button>
|
|
@@ -638,31 +1551,31 @@ let ItButton = class ItButton extends BaseComponent {
|
|
|
638
1551
|
};
|
|
639
1552
|
ItButton.styles = styles;
|
|
640
1553
|
__decorate([
|
|
641
|
-
|
|
642
|
-
__metadata("design:type",
|
|
643
|
-
], ItButton.prototype, "
|
|
1554
|
+
query('button'),
|
|
1555
|
+
__metadata("design:type", HTMLButtonElement)
|
|
1556
|
+
], ItButton.prototype, "_nativeButton", void 0);
|
|
644
1557
|
__decorate([
|
|
645
|
-
property({ type: String }),
|
|
1558
|
+
property({ type: String, reflect: true }),
|
|
646
1559
|
__metadata("design:type", Object)
|
|
647
1560
|
], ItButton.prototype, "type", void 0);
|
|
648
1561
|
__decorate([
|
|
649
|
-
property({ type: String }),
|
|
1562
|
+
property({ type: String, reflect: true }),
|
|
650
1563
|
__metadata("design:type", String)
|
|
651
1564
|
], ItButton.prototype, "variant", void 0);
|
|
652
1565
|
__decorate([
|
|
653
|
-
property({ type: String }),
|
|
1566
|
+
property({ type: String, reflect: true }),
|
|
654
1567
|
__metadata("design:type", String)
|
|
655
1568
|
], ItButton.prototype, "size", void 0);
|
|
656
1569
|
__decorate([
|
|
657
|
-
property({ type: Boolean }),
|
|
1570
|
+
property({ type: Boolean, reflect: true }),
|
|
658
1571
|
__metadata("design:type", Object)
|
|
659
1572
|
], ItButton.prototype, "outline", void 0);
|
|
660
1573
|
__decorate([
|
|
661
|
-
property({ type: Boolean }),
|
|
1574
|
+
property({ type: Boolean, reflect: true }),
|
|
662
1575
|
__metadata("design:type", Object)
|
|
663
1576
|
], ItButton.prototype, "block", void 0);
|
|
664
1577
|
__decorate([
|
|
665
|
-
property({ type: Boolean }),
|
|
1578
|
+
property({ type: Boolean, reflect: true }),
|
|
666
1579
|
__metadata("design:type", Object)
|
|
667
1580
|
], ItButton.prototype, "icon", void 0);
|
|
668
1581
|
__decorate([
|
|
@@ -673,6 +1586,14 @@ __decorate([
|
|
|
673
1586
|
property(),
|
|
674
1587
|
__metadata("design:type", Object)
|
|
675
1588
|
], ItButton.prototype, "internals", void 0);
|
|
1589
|
+
__decorate([
|
|
1590
|
+
property({ type: Boolean, reflect: true, attribute: 'it-aria-disabled' }),
|
|
1591
|
+
__metadata("design:type", Boolean)
|
|
1592
|
+
], ItButton.prototype, "disabled", void 0);
|
|
1593
|
+
__decorate([
|
|
1594
|
+
property({ type: Boolean, reflect: true, attribute: 'it-aria-expanded' }),
|
|
1595
|
+
__metadata("design:type", Boolean)
|
|
1596
|
+
], ItButton.prototype, "expanded", void 0);
|
|
676
1597
|
ItButton = __decorate([
|
|
677
1598
|
customElement('it-button')
|
|
678
1599
|
], ItButton);
|