@dile/ui 3.22.1 → 3.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/components/button/src/DileButton.js +3 -0
- package/components/checkbox/src/DileCheckbox.js +14 -5
- package/components/color-picker/src/DileColorPicker.js +6 -2
- package/components/drop-file/src/DileDropFile.js +7 -5
- package/components/form-group/form-group.js +5 -0
- package/components/form-group/index.js +1 -0
- package/components/form-group/src/DileFormGroup.js +188 -0
- package/components/input/index.js +1 -1
- package/components/input/src/DileInput.js +128 -31
- package/components/input/src/DileInputContact.js +38 -40
- package/components/input/src/DileInputIcon.js +7 -43
- package/components/input/src/DileInputInteger.js +8 -22
- package/components/input/src/DileInputMask.js +25 -15
- package/components/input/src/DileInputMoney.js +6 -23
- package/components/input/src/DileInputNumber.js +6 -12
- package/components/input/src/DileInputNumberMask.js +5 -12
- package/components/input/src/DileInputPercentage.js +8 -20
- package/components/input/src/DileInputSearch.js +7 -1
- package/components/input/src/label-styles.js +15 -0
- package/components/input-suggestions/src/DileInputSuggestionsBase.js +6 -3
- package/components/number-picker/src/DileNumberPicker.js +8 -4
- package/components/number-picker/src/DileNumberPickerElement.js +7 -0
- package/components/order-switch/src/DileOrderSwitch.js +18 -2
- package/components/otp-input/src/DileOtpInput.js +10 -4
- package/components/password/src/DilePassword.js +19 -42
- package/components/radio-group/src/DileRadioGroup.js +6 -3
- package/components/rating-scale-question/src/DileRatingScaleQuestion.js +35 -3
- package/components/select/src/DileSelect.js +12 -4
- package/components/select/src/DileSelectAjax.js +12 -5
- package/components/select/src/DileSelectBoolean.js +9 -2
- package/components/select/src/DileSelectOverlay.js +6 -3
- package/components/select/src/DileSelectSearchableBase.js +8 -3
- package/components/switch/src/DileSwitch.js +3 -1
- package/components/textarea/src/DileTextarea.js +7 -3
- package/components/time-picker/src/DileTimePicker.js +680 -123
- package/components/wheel-picker/src/DileWheelPicker.js +17 -2
- package/lib/time/time.js +171 -0
- package/lib/time/time.test.js +63 -0
- package/mixins/form/index.js +3 -2
- package/mixins/form/src/DileFieldMessage.js +4 -1
- package/mixins/form/src/DileForm.js +240 -1
- package/mixins/form/src/DileNativeValidity.js +195 -0
- package/mixins/overlay/src/DileOverlay.js +16 -0
- package/package.json +2 -2
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { LitElement, html, css } from 'lit';
|
|
2
|
-
import { DileEmmitChange } from '../../../mixins/form/index.js';
|
|
2
|
+
import { DileEmmitChange, DileNativeValidity } from '../../../mixins/form/index.js';
|
|
3
3
|
|
|
4
4
|
const supportsScrollEnd = typeof window !== 'undefined' && 'onscrollend' in window;
|
|
5
5
|
|
|
6
|
-
export class DileWheelPicker extends DileEmmitChange(LitElement) {
|
|
6
|
+
export class DileWheelPicker extends DileNativeValidity(DileEmmitChange(LitElement)) {
|
|
7
|
+
static get formAssociated() {
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
|
|
7
11
|
static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };
|
|
8
12
|
|
|
9
13
|
static styles = css`
|
|
@@ -105,6 +109,7 @@ export class DileWheelPicker extends DileEmmitChange(LitElement) {
|
|
|
105
109
|
this._normalizedItems = [];
|
|
106
110
|
this._scrollTimer = null;
|
|
107
111
|
this._lastItemHeight = 0;
|
|
112
|
+
this.internals = this.attachInternals();
|
|
108
113
|
}
|
|
109
114
|
|
|
110
115
|
get scroller() {
|
|
@@ -140,9 +145,19 @@ export class DileWheelPicker extends DileEmmitChange(LitElement) {
|
|
|
140
145
|
|
|
141
146
|
firstUpdated() {
|
|
142
147
|
this._resizeObserver.observe(this.scroller);
|
|
148
|
+
this._defaultValue = this.value;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Called by the browser when the owner form is reset: restores the initial value */
|
|
152
|
+
formResetCallback() {
|
|
153
|
+
super.formResetCallback?.();
|
|
154
|
+
this.value = this._defaultValue;
|
|
143
155
|
}
|
|
144
156
|
|
|
145
157
|
updated(changed) {
|
|
158
|
+
if (changed.has('value')) {
|
|
159
|
+
this.internals.setFormValue(this.value === undefined || this.value === null ? null : String(this.value));
|
|
160
|
+
}
|
|
146
161
|
if (changed.has('items') || changed.has('visibleItems')) {
|
|
147
162
|
this._scrollToIndex(this._indexOfValue(), 'instant');
|
|
148
163
|
} else if (changed.has('value')) {
|
package/lib/time/time.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Framework-agnostic helpers to parse, format and check times of day.
|
|
3
|
+
* A time is represented as { hours, minutes, seconds } in 24-hour notation.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const SECONDS_PER_DAY = 24 * 60 * 60;
|
|
7
|
+
|
|
8
|
+
export const pad = (n) => String(n).padStart(2, '0');
|
|
9
|
+
|
|
10
|
+
const MERIDIEM_REGEX = /\s*(a\.?\s?m\.?|p\.?\s?m\.?|a|p)$/i;
|
|
11
|
+
|
|
12
|
+
function escapeRegex(text) {
|
|
13
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Removes the AM/PM mark at the end of the text.
|
|
18
|
+
* Besides "am", "a.m.", "a", "pm", "p.m." and "p", accepts the given custom labels.
|
|
19
|
+
* @returns {{ text: string, meridiem: 'am'|'pm'|undefined }}
|
|
20
|
+
*/
|
|
21
|
+
function extractMeridiem(text, { amLabel, pmLabel } = {}) {
|
|
22
|
+
const custom = [[amLabel, 'am'], [pmLabel, 'pm']];
|
|
23
|
+
for (const [label, meridiem] of custom) {
|
|
24
|
+
if (label) {
|
|
25
|
+
const regex = new RegExp(`\\s*${escapeRegex(label.trim())}$`, 'i');
|
|
26
|
+
if (regex.test(text)) {
|
|
27
|
+
return { text: text.replace(regex, ''), meridiem };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const match = MERIDIEM_REGEX.exec(text);
|
|
32
|
+
if (match) {
|
|
33
|
+
return { text: text.slice(0, match.index), meridiem: match[1][0].toLowerCase() === 'a' ? 'am' : 'pm' };
|
|
34
|
+
}
|
|
35
|
+
return { text, meridiem: undefined };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Splits a run of digits without separators: "9" → 9, "930" → 9:30, "0930" → 09:30, "93015" → 9:30:15.
|
|
40
|
+
*/
|
|
41
|
+
function splitDigits(digits) {
|
|
42
|
+
switch (digits.length) {
|
|
43
|
+
case 1:
|
|
44
|
+
case 2:
|
|
45
|
+
return [digits];
|
|
46
|
+
case 3:
|
|
47
|
+
return [digits.slice(0, 1), digits.slice(1)];
|
|
48
|
+
case 4:
|
|
49
|
+
return [digits.slice(0, 2), digits.slice(2)];
|
|
50
|
+
case 5:
|
|
51
|
+
return [digits.slice(0, 1), digits.slice(1, 3), digits.slice(3)];
|
|
52
|
+
case 6:
|
|
53
|
+
return [digits.slice(0, 2), digits.slice(2, 4), digits.slice(4)];
|
|
54
|
+
default:
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Parses a time written by the user.
|
|
61
|
+
* Accepts "09:30", "9:30:15", "9.30", "9h30", "21h", "930", "0930", "9", "9:30 pm", "9pm"...
|
|
62
|
+
* @param {string} text
|
|
63
|
+
* @param {{ amLabel?: string, pmLabel?: string }} [options] custom AM/PM marks accepted besides the standard ones
|
|
64
|
+
* @returns {{ hours: number, minutes: number, seconds: number }|undefined} undefined when it is not a valid time
|
|
65
|
+
*/
|
|
66
|
+
export function parseTime(text, options) {
|
|
67
|
+
let source = String(text ?? '').trim();
|
|
68
|
+
if (!source) {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
const { text: withoutMeridiem, meridiem } = extractMeridiem(source, options);
|
|
72
|
+
source = withoutMeridiem.trim().replace(/[\s:.h]+$/i, '');
|
|
73
|
+
if (!source) {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
let parts;
|
|
77
|
+
if (/^\d+$/.test(source)) {
|
|
78
|
+
parts = splitDigits(source);
|
|
79
|
+
} else if (/^\d{1,2}(?:\s*[:.h\s]\s*\d{1,2}){1,2}$/i.test(source)) {
|
|
80
|
+
parts = source.split(/\s*[:.h\s]\s*/i);
|
|
81
|
+
}
|
|
82
|
+
if (!parts) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
let [hours, minutes = 0, seconds = 0] = parts.map(Number);
|
|
86
|
+
if (minutes > 59 || seconds > 59) {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
if (meridiem) {
|
|
90
|
+
if (hours < 1 || hours > 12) {
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
hours = (hours % 12) + (meridiem === 'pm' ? 12 : 0);
|
|
94
|
+
} else if (hours > 23) {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
return { hours, minutes, seconds };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Formats a time in 24-hour notation: "HH:mm" or "HH:mm:ss".
|
|
102
|
+
*/
|
|
103
|
+
export function formatTime(time, showSeconds = false) {
|
|
104
|
+
const base = `${pad(time.hours)}:${pad(time.minutes)}`;
|
|
105
|
+
return showSeconds ? `${base}:${pad(time.seconds)}` : base;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Formats a time in 12-hour notation: "hh:mm AM" or "hh:mm:ss PM".
|
|
110
|
+
*/
|
|
111
|
+
export function formatTime12(time, showSeconds = false, { amLabel = 'AM', pmLabel = 'PM' } = {}) {
|
|
112
|
+
const hours = time.hours % 12 === 0 ? 12 : time.hours % 12;
|
|
113
|
+
const base = formatTime({ ...time, hours }, showSeconds);
|
|
114
|
+
return `${base} ${time.hours < 12 ? amLabel : pmLabel}`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function toSeconds(time) {
|
|
118
|
+
return time.hours * 3600 + time.minutes * 60 + time.seconds;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function fromSeconds(totalSeconds) {
|
|
122
|
+
const value = ((Math.round(totalSeconds) % SECONDS_PER_DAY) + SECONDS_PER_DAY) % SECONDS_PER_DAY;
|
|
123
|
+
return {
|
|
124
|
+
hours: Math.floor(value / 3600),
|
|
125
|
+
minutes: Math.floor((value % 3600) / 60),
|
|
126
|
+
seconds: value % 60,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Checks if a time is inside the [min, max] range. Both limits are optional.
|
|
132
|
+
* When min is later than max the range goes through midnight (e.g. 22:00 to 02:00).
|
|
133
|
+
* @param {object} time
|
|
134
|
+
* @param {object} [min]
|
|
135
|
+
* @param {object} [max]
|
|
136
|
+
* @returns {true|'beforeMin'|'afterMax'|'outOfRange'}
|
|
137
|
+
*/
|
|
138
|
+
export function checkTimeRange(time, min, max) {
|
|
139
|
+
const value = toSeconds(time);
|
|
140
|
+
const minValue = min ? toSeconds(min) : undefined;
|
|
141
|
+
const maxValue = max ? toSeconds(max) : undefined;
|
|
142
|
+
if (minValue !== undefined && maxValue !== undefined && minValue > maxValue) {
|
|
143
|
+
return value >= minValue || value <= maxValue ? true : 'outOfRange';
|
|
144
|
+
}
|
|
145
|
+
if (minValue !== undefined && value < minValue) {
|
|
146
|
+
return 'beforeMin';
|
|
147
|
+
}
|
|
148
|
+
if (maxValue !== undefined && value > maxValue) {
|
|
149
|
+
return 'afterMax';
|
|
150
|
+
}
|
|
151
|
+
return true;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Normalizes a step for minutes or seconds to an integer between 1 and 59.
|
|
156
|
+
*/
|
|
157
|
+
export function validStep(step) {
|
|
158
|
+
const value = Math.round(Number(step));
|
|
159
|
+
return value >= 1 && value <= 59 ? value : 1;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Values from 0 to max with the given step.
|
|
164
|
+
*/
|
|
165
|
+
export function stepValues(max, step) {
|
|
166
|
+
const values = [];
|
|
167
|
+
for (let value = 0; value <= max; value += step) {
|
|
168
|
+
values.push(value);
|
|
169
|
+
}
|
|
170
|
+
return values;
|
|
171
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { parseTime, formatTime, formatTime12, checkTimeRange, fromSeconds, toSeconds } from './time.js';
|
|
4
|
+
|
|
5
|
+
const t = (hours, minutes = 0, seconds = 0) => ({ hours, minutes, seconds });
|
|
6
|
+
|
|
7
|
+
test('parseTime reads times with separators', () => {
|
|
8
|
+
assert.deepEqual(parseTime('09:30'), t(9, 30));
|
|
9
|
+
assert.deepEqual(parseTime('9:5'), t(9, 5));
|
|
10
|
+
assert.deepEqual(parseTime('9.30'), t(9, 30));
|
|
11
|
+
assert.deepEqual(parseTime('9h30'), t(9, 30));
|
|
12
|
+
assert.deepEqual(parseTime('21h'), t(21));
|
|
13
|
+
assert.deepEqual(parseTime('10:30:45'), t(10, 30, 45));
|
|
14
|
+
assert.deepEqual(parseTime(' 7 15 '), t(7, 15));
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('parseTime reads digits without separators', () => {
|
|
18
|
+
assert.deepEqual(parseTime('9'), t(9));
|
|
19
|
+
assert.deepEqual(parseTime('930'), t(9, 30));
|
|
20
|
+
assert.deepEqual(parseTime('0930'), t(9, 30));
|
|
21
|
+
assert.deepEqual(parseTime('2359'), t(23, 59));
|
|
22
|
+
assert.deepEqual(parseTime('93015'), t(9, 30, 15));
|
|
23
|
+
assert.deepEqual(parseTime('093015'), t(9, 30, 15));
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('parseTime reads the AM/PM notation', () => {
|
|
27
|
+
assert.deepEqual(parseTime('9:30 pm'), t(21, 30));
|
|
28
|
+
assert.deepEqual(parseTime('9pm'), t(21));
|
|
29
|
+
assert.deepEqual(parseTime('12:00 AM'), t(0));
|
|
30
|
+
assert.deepEqual(parseTime('12:15 p.m.'), t(12, 15));
|
|
31
|
+
assert.deepEqual(parseTime('7a'), t(7));
|
|
32
|
+
assert.deepEqual(parseTime('7:30 de la tarde', { pmLabel: 'de la tarde' }), t(19, 30));
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('parseTime rejects invalid times', () => {
|
|
36
|
+
for (const value of ['', ' ', 'abc', '24:00', '12:60', '10:30:60', '13 pm', '0 am', '1234567', '9:30 xx']) {
|
|
37
|
+
assert.equal(parseTime(value), undefined, value);
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('formatTime and formatTime12', () => {
|
|
42
|
+
assert.equal(formatTime(t(9, 5)), '09:05');
|
|
43
|
+
assert.equal(formatTime(t(9, 5, 7), true), '09:05:07');
|
|
44
|
+
assert.equal(formatTime12(t(0, 15)), '12:15 AM');
|
|
45
|
+
assert.equal(formatTime12(t(13, 0, 30), true), '01:00:30 PM');
|
|
46
|
+
assert.equal(formatTime12(t(12, 0), false, { amLabel: 'a. m.', pmLabel: 'p. m.' }), '12:00 p. m.');
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('checkTimeRange with normal and overnight ranges', () => {
|
|
50
|
+
assert.equal(checkTimeRange(t(10), t(9), t(18)), true);
|
|
51
|
+
assert.equal(checkTimeRange(t(8, 59), t(9), t(18)), 'beforeMin');
|
|
52
|
+
assert.equal(checkTimeRange(t(18, 1), t(9), t(18)), 'afterMax');
|
|
53
|
+
assert.equal(checkTimeRange(t(8), undefined, t(9)), true);
|
|
54
|
+
assert.equal(checkTimeRange(t(23), t(22), t(2)), true);
|
|
55
|
+
assert.equal(checkTimeRange(t(1), t(22), t(2)), true);
|
|
56
|
+
assert.equal(checkTimeRange(t(12), t(22), t(2)), 'outOfRange');
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('toSeconds and fromSeconds', () => {
|
|
60
|
+
assert.equal(toSeconds(t(1, 2, 3)), 3723);
|
|
61
|
+
assert.deepEqual(fromSeconds(3723), t(1, 2, 3));
|
|
62
|
+
assert.deepEqual(fromSeconds(-60), t(23, 59));
|
|
63
|
+
});
|
package/mixins/form/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export { DileForm } from "./src/DileForm.js";
|
|
1
|
+
export { DileForm, FORM_VALIDATION_MESSAGES, isEmptyValue } from "./src/DileForm.js";
|
|
2
2
|
export { DileFormChangeDetect } from "./src/DileFormChangeDetect.js";
|
|
3
3
|
export { DileEmmitChange } from "./src/DileEmmitChange.js";
|
|
4
|
-
export { DileFieldMessage } from "./src/DileFieldMessage.js";
|
|
4
|
+
export { DileFieldMessage, FIELD_MESSAGE_ID } from "./src/DileFieldMessage.js";
|
|
5
|
+
export { DileNativeValidity } from "./src/DileNativeValidity.js";
|
|
@@ -13,6 +13,9 @@ import { html } from 'lit';
|
|
|
13
13
|
*
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
+
/** Id of the element rendered by `messageTemplate`, to link it with aria-describedby */
|
|
17
|
+
export const FIELD_MESSAGE_ID = 'field-message';
|
|
18
|
+
|
|
16
19
|
export const DileFieldMessage = (superclass) => class extends superclass {
|
|
17
20
|
|
|
18
21
|
static get properties() {
|
|
@@ -28,7 +31,7 @@ export const DileFieldMessage = (superclass) => class extends superclass {
|
|
|
28
31
|
get messageTemplate() {
|
|
29
32
|
return html`
|
|
30
33
|
${this.message
|
|
31
|
-
? html`<div class="message ${this.errored ? 'errored-msg' : ''}"><span>${this.message}</span></div>`
|
|
34
|
+
? html`<div id="${FIELD_MESSAGE_ID}" class="message ${this.errored ? 'errored-msg' : ''}"><span>${this.message}</span></div>`
|
|
32
35
|
: ''
|
|
33
36
|
}
|
|
34
37
|
`
|
|
@@ -6,6 +6,55 @@
|
|
|
6
6
|
*
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
/** Default validation messages of DileForm, by language */
|
|
10
|
+
export const FORM_VALIDATION_MESSAGES = {
|
|
11
|
+
en: {
|
|
12
|
+
required: 'This field is required.',
|
|
13
|
+
},
|
|
14
|
+
es: {
|
|
15
|
+
required: 'Este campo es obligatorio.',
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const FOCUSABLE_SELECTOR = 'input:not([type="hidden"]):not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
|
|
20
|
+
|
|
21
|
+
/** First focusable element inside a node, looking into its shadow root, its light DOM and nested shadow roots */
|
|
22
|
+
function findFocusable(node) {
|
|
23
|
+
const roots = [node.shadowRoot, node].filter(Boolean);
|
|
24
|
+
for (const root of roots) {
|
|
25
|
+
for (const el of root.querySelectorAll('*')) {
|
|
26
|
+
if (el.matches(FOCUSABLE_SELECTOR)) {
|
|
27
|
+
return el;
|
|
28
|
+
}
|
|
29
|
+
if (el.shadowRoot) {
|
|
30
|
+
const nested = findFocusable(el);
|
|
31
|
+
if (nested) {
|
|
32
|
+
return nested;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Default emptiness criterion used by the required check.
|
|
42
|
+
* `undefined`, `null`, empty or whitespace-only strings and empty arrays are empty.
|
|
43
|
+
* `false` is a filled value: checkbox-like fields decide it with their own `isEmpty()`.
|
|
44
|
+
*/
|
|
45
|
+
export function isEmptyValue(value) {
|
|
46
|
+
if (value === undefined || value === null) {
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
if (typeof value === 'string') {
|
|
50
|
+
return value.trim() === '';
|
|
51
|
+
}
|
|
52
|
+
if (Array.isArray(value)) {
|
|
53
|
+
return value.length === 0;
|
|
54
|
+
}
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
9
58
|
export const DileForm = (superclass) => class extends superclass {
|
|
10
59
|
|
|
11
60
|
|
|
@@ -16,7 +65,16 @@ export const DileForm = (superclass) => class extends superclass {
|
|
|
16
65
|
|
|
17
66
|
static get properties() {
|
|
18
67
|
return {
|
|
19
|
-
setOnInit: { type: Object }
|
|
68
|
+
setOnInit: { type: Object },
|
|
69
|
+
|
|
70
|
+
/** Disables the validation: validate() always returns a valid result */
|
|
71
|
+
novalidate: { type: Boolean },
|
|
72
|
+
|
|
73
|
+
/** Messages overriding the default validation messages, e.g. `{ required: 'Mandatory' }` */
|
|
74
|
+
validationMessages: { type: Object },
|
|
75
|
+
|
|
76
|
+
/** Language of the default validation messages. Falls back to the lang attribute of the document */
|
|
77
|
+
language: { type: String },
|
|
20
78
|
};
|
|
21
79
|
}
|
|
22
80
|
|
|
@@ -219,6 +277,187 @@ export const DileForm = (superclass) => class extends superclass {
|
|
|
219
277
|
return false;
|
|
220
278
|
}
|
|
221
279
|
|
|
280
|
+
// ---- Validation ----
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Validates every field of the form: the required check, then the field's own validation
|
|
284
|
+
* (`getValidationError()`), then the rules of the installed validator, if any.
|
|
285
|
+
* Shows the errors in the fields, moves the focus to the first invalid one and
|
|
286
|
+
* dispatches `dile-form-validated`.
|
|
287
|
+
* @param {{ showErrors?: boolean, focus?: boolean }} [options]
|
|
288
|
+
* @returns {Promise<{ valid: boolean, errors: Object<string, string> }>} errors use the same
|
|
289
|
+
* shape as `showErrors()`: `{ fieldName: message }` (`items.0` for `items[]` fields).
|
|
290
|
+
*/
|
|
291
|
+
async validate({ showErrors = true, focus = true } = {}) {
|
|
292
|
+
if (this.novalidate) {
|
|
293
|
+
return { valid: true, errors: {} };
|
|
294
|
+
}
|
|
295
|
+
await this.updateComplete;
|
|
296
|
+
const errors = {};
|
|
297
|
+
let firstInvalid = null;
|
|
298
|
+
for (const { node, key } of this._validatableFields()) {
|
|
299
|
+
const error = await this.getFieldError(node, key);
|
|
300
|
+
if (error) {
|
|
301
|
+
errors[key] = error;
|
|
302
|
+
firstInvalid = firstInvalid ?? node;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const valid = Object.keys(errors).length === 0;
|
|
306
|
+
if (showErrors) {
|
|
307
|
+
this.clearErrors();
|
|
308
|
+
this.showErrors(errors);
|
|
309
|
+
if (focus && firstInvalid) {
|
|
310
|
+
this.focusField(firstInvalid);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
this.dispatchEvent(new CustomEvent('dile-form-validated', {
|
|
314
|
+
bubbles: true,
|
|
315
|
+
composed: true,
|
|
316
|
+
detail: { valid, errors },
|
|
317
|
+
}));
|
|
318
|
+
return { valid, errors };
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Validates a single field, showing or clearing its error.
|
|
323
|
+
* @param {string} name - field name, or `items.0` for an element of an `items[]` field
|
|
324
|
+
* @returns {Promise<string>} the error message, or '' when the field is valid
|
|
325
|
+
*/
|
|
326
|
+
async validateField(name) {
|
|
327
|
+
if (this.novalidate) {
|
|
328
|
+
return '';
|
|
329
|
+
}
|
|
330
|
+
const node = this.getNodeElement(name);
|
|
331
|
+
if (!node) {
|
|
332
|
+
return '';
|
|
333
|
+
}
|
|
334
|
+
const error = this._isValidatable(node) ? await this.getFieldError(node, name) : '';
|
|
335
|
+
if (error) {
|
|
336
|
+
this.showError(name, error);
|
|
337
|
+
} else {
|
|
338
|
+
this._clearNodeError(node);
|
|
339
|
+
}
|
|
340
|
+
return error;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Error of a field, without changing the UI.
|
|
345
|
+
* Order: required → field's own `getValidationError()` → validator rules. The first error wins.
|
|
346
|
+
* @param {Element} node
|
|
347
|
+
* @param {string} [key] - name used for the field in the errors object
|
|
348
|
+
* @returns {Promise<string>} the error message, or ''
|
|
349
|
+
*/
|
|
350
|
+
async getFieldError(node, key = node.getAttribute('name')) {
|
|
351
|
+
if (this.isFieldRequired(node) && this.isFieldEmpty(node)) {
|
|
352
|
+
return this.getValidationMessage('required', node);
|
|
353
|
+
}
|
|
354
|
+
if (typeof node.getValidationError === 'function') {
|
|
355
|
+
const ownError = await node.getValidationError();
|
|
356
|
+
if (ownError) {
|
|
357
|
+
return ownError;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (this.validator && typeof this.validator.validateField === 'function') {
|
|
361
|
+
const ruleError = await this.validator.validateField(node, {
|
|
362
|
+
name: key,
|
|
363
|
+
value: node.value,
|
|
364
|
+
form: this,
|
|
365
|
+
});
|
|
366
|
+
if (ruleError) {
|
|
367
|
+
return ruleError;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return '';
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** True when the field has the required property or attribute */
|
|
374
|
+
isFieldRequired(node) {
|
|
375
|
+
return node.required === true || node.hasAttribute('required');
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* True when the field has no value. Uses the field's `isEmpty()` when it exists,
|
|
380
|
+
* the checked state for native checkboxes and radios, or `isEmptyValue()`.
|
|
381
|
+
*/
|
|
382
|
+
isFieldEmpty(node) {
|
|
383
|
+
if (typeof node.isEmpty === 'function') {
|
|
384
|
+
return node.isEmpty();
|
|
385
|
+
}
|
|
386
|
+
if (node instanceof HTMLInputElement && (node.type === 'checkbox' || node.type === 'radio')) {
|
|
387
|
+
return !node.checked;
|
|
388
|
+
}
|
|
389
|
+
return isEmptyValue(node.value);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Message of a validation error. Uses validationMessages, then the default messages
|
|
394
|
+
* in the form language (or the document language), then English.
|
|
395
|
+
*/
|
|
396
|
+
getValidationMessage(key, node) {
|
|
397
|
+
if (this.validationMessages && this.validationMessages[key]) {
|
|
398
|
+
return this.validationMessages[key];
|
|
399
|
+
}
|
|
400
|
+
const language = (this.language || document.documentElement.lang || 'en').slice(0, 2).toLowerCase();
|
|
401
|
+
const messages = FORM_VALIDATION_MESSAGES[language] || FORM_VALIDATION_MESSAGES.en;
|
|
402
|
+
return messages[key] || FORM_VALIDATION_MESSAGES.en[key] || '';
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Moves the focus to a field. Uses its focus() method and, if the field does not take
|
|
407
|
+
* the focus that way, the first focusable element inside it (shadow DOM included).
|
|
408
|
+
*/
|
|
409
|
+
focusField(node) {
|
|
410
|
+
node.focus?.();
|
|
411
|
+
if (node.matches(':focus-within')) {
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
findFocusable(node)?.focus();
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Disabled and readonly fields are not validated, as in native forms */
|
|
418
|
+
_isValidatable(node) {
|
|
419
|
+
if (node.disabled || node.isDisabled || node.readonly || node.readOnly) {
|
|
420
|
+
return false;
|
|
421
|
+
}
|
|
422
|
+
try {
|
|
423
|
+
if (node.matches(':disabled')) {
|
|
424
|
+
return false;
|
|
425
|
+
}
|
|
426
|
+
} catch (e) {
|
|
427
|
+
// :disabled not supported for this element
|
|
428
|
+
}
|
|
429
|
+
return true;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Fields to validate, with the key used for each one in the errors object */
|
|
433
|
+
_validatableFields() {
|
|
434
|
+
const fields = [];
|
|
435
|
+
const arrayIndexes = {};
|
|
436
|
+
this.allNodeElements.forEach(node => {
|
|
437
|
+
const name = node.getAttribute('name');
|
|
438
|
+
if (!name) return;
|
|
439
|
+
let key = name;
|
|
440
|
+
if (name.endsWith('[]')) {
|
|
441
|
+
const fieldName = name.slice(0, -2);
|
|
442
|
+
arrayIndexes[fieldName] = arrayIndexes[fieldName] ?? 0;
|
|
443
|
+
key = `${fieldName}.${arrayIndexes[fieldName]++}`;
|
|
444
|
+
}
|
|
445
|
+
if (this._isValidatable(node)) {
|
|
446
|
+
fields.push({ node, key });
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
return fields;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
_clearNodeError(node) {
|
|
453
|
+
if (typeof node.clearError === 'function') {
|
|
454
|
+
node.clearError();
|
|
455
|
+
} else {
|
|
456
|
+
node.errored = false;
|
|
457
|
+
node.message = '';
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
222
461
|
/**
|
|
223
462
|
* Template method: Adapt data before it's returned from getData()
|
|
224
463
|
* Override this method in your component to transform the structure of outgoing data
|