This repository has been archived by the owner on Sep 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
select.control.ts
55 lines (52 loc) · 1.64 KB
/
select.control.ts
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
import { itsEach, itsElements, reverseArray, valueArray } from '@proc7ts/push-iterator';
import { InConverter } from '../converter';
import { InElement } from '../element.control';
import { AbstractInElement } from './abstract-element.control';
/**
* Select input control.
*
* @category Control
*/
export type InSelect = InElement<readonly string[], HTMLSelectElement>;
/**
* Creates input control for the given select element.
*
* The value of this control is an array of selected option values. This is particularly useful for `<select multiple>`
* elements. Consider to use `inText()` for single-selects.
*
* @category Control
* @param element - Target select element.
* @param aspects - Input aspects applied by default. These are aspect converters to constructed control
* from the {@link inValueOf same-valued one}.
*
* @return New select input control instance.
*/
export function inSelect(
element: HTMLSelectElement,
{
aspects,
}: {
readonly aspects?:
| InConverter.Aspect<readonly string[]>
| readonly InConverter.Aspect<readonly string[]>[]
| undefined;
} = {},
): InSelect {
return new AbstractInElement(element, {
aspects,
get(): string[] {
return itsElements(
valueArray(this.element.options, option => option.selected && option.value),
);
},
set(value) {
const selected = new Set(value);
// Iterate in reverse order to ensure the first matching option is selected
// when `multiple` attribute isn't set.
itsEach(
reverseArray(this.element.options),
option => (option.selected = selected.has(option.value)),
);
},
});
}