generated from adobe/aem-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 174
/
formControls.js
92 lines (76 loc) · 2.4 KB
/
formControls.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { html, useEffect, useState } from '../../deps/htm-preact.js';
let checkboxIdx = 0;
const Select = ({
label, name, onChange, options, isRequired, value, sort = false, tooltip,
}) => {
const [isValid, setIsValid] = useState(true);
const validateInput = (val) => {
setIsValid(!(isRequired && val === ''));
};
useEffect(() => {
validateInput(value);
}, []);
const onSelectChange = (e) => {
validateInput(e.target.value);
onChange(e.target.value, e);
};
const entries = sort
? Object.entries(options).sort((a, b) => a[1].localeCompare(b[1]))
: Object.entries(options);
return html`
<div class="field ${isRequired ? 'required' : ''}">
<label for=${name}>${label}</label>
${tooltip && html`<i class="tooltip"></i>`}
<select id=${name} class=${!isValid && 'input-invalid'} value=${value} onChange=${onSelectChange}>
${entries.map(
([val, optionLabel]) => html`<option value="${val}">${optionLabel}</option>`,
)}
</select>
${tooltip && html`<span class="tooltip-text">${tooltip}</span>`}
</div>
`;
};
const Input = ({
label, name, onChange, onValidate, isRequired, type = 'text', value, title, tooltip,
}) => {
const [isValid, setIsValid] = useState(true);
const validateInput = (val) => {
if (typeof onValidate === 'function' && val !== '' && !onValidate(val)) {
setIsValid(false);
} else if (isRequired && val === '') {
setIsValid(false);
} else {
setIsValid(true);
}
};
useEffect(() => {
validateInput(value);
}, []);
const onInputChange = (e) => {
const inputVal = type === 'checkbox' ? e.target.checked : e.target.value;
validateInput(inputVal);
onChange(inputVal, e);
};
const isCheckbox = type === 'checkbox';
const computedValue = { [isCheckbox ? 'checked' : 'value']: value };
const id = isCheckbox
? `${name}${checkboxIdx++}`
: name;
return html`
<div class="field ${isCheckbox ? 'checkbox' : ''} ${isRequired ? 'required' : ''}">
<label for=${id}>${label}</label>
${tooltip && html`<i class="tooltip"></i>`}
<input
class=${!isValid && 'input-invalid'}
type=${type}
id=${id}
name=${name}
title=${title}
...${computedValue}
onChange=${onInputChange}
/>
${tooltip && html`<span class="tooltip-text">${tooltip}</span>`}
</div>
`;
};
export { Input, Select };