2017-10-13 14:43:58 +02:00
|
|
|
import WrappedElement from './wrapped-element';
|
2019-12-14 15:43:51 +01:00
|
|
|
import { ClassNames, Item, Choice } from '../interfaces';
|
2019-11-03 14:18:16 +01:00
|
|
|
|
2017-10-13 14:43:58 +02:00
|
|
|
export default class WrappedSelect extends WrappedElement {
|
2019-12-14 17:08:15 +01:00
|
|
|
element: HTMLSelectElement;
|
2019-12-14 15:43:51 +01:00
|
|
|
classNames: ClassNames;
|
2019-12-14 17:40:15 +01:00
|
|
|
template: (data: object) => HTMLOptionElement;
|
2019-12-14 15:43:51 +01:00
|
|
|
|
|
|
|
constructor({
|
|
|
|
element,
|
|
|
|
classNames,
|
|
|
|
template,
|
|
|
|
}: {
|
2019-12-14 17:08:15 +01:00
|
|
|
element: HTMLSelectElement;
|
2019-12-14 15:43:51 +01:00
|
|
|
classNames: ClassNames;
|
2019-12-14 17:40:15 +01:00
|
|
|
template: (data: object) => HTMLOptionElement;
|
2019-12-14 15:43:51 +01:00
|
|
|
}) {
|
2018-05-21 18:01:03 +02:00
|
|
|
super({ element, classNames });
|
2019-10-21 11:48:49 +02:00
|
|
|
this.template = template;
|
2017-10-13 14:43:58 +02:00
|
|
|
}
|
|
|
|
|
2019-12-14 15:43:51 +01:00
|
|
|
get placeholderOption(): HTMLOptionElement | null {
|
2019-10-22 12:25:36 +02:00
|
|
|
return (
|
|
|
|
this.element.querySelector('option[value=""]') ||
|
|
|
|
// Backward compatibility layer for the non-standard placeholder attribute supported in older versions.
|
|
|
|
this.element.querySelector('option[placeholder]')
|
|
|
|
);
|
2017-10-18 09:43:56 +02:00
|
|
|
}
|
|
|
|
|
2019-12-14 15:43:51 +01:00
|
|
|
get optionGroups(): Element[] {
|
2018-04-24 13:54:45 +02:00
|
|
|
return Array.from(this.element.getElementsByTagName('OPTGROUP'));
|
2017-10-18 09:43:56 +02:00
|
|
|
}
|
|
|
|
|
2019-12-14 15:43:51 +01:00
|
|
|
get options(): HTMLOptionElement[] {
|
2018-04-24 13:54:45 +02:00
|
|
|
return Array.from(this.element.options);
|
2017-10-18 09:43:56 +02:00
|
|
|
}
|
2017-12-18 13:06:38 +01:00
|
|
|
|
2019-12-14 15:43:51 +01:00
|
|
|
set options(options: Item[] | Choice[]): void {
|
2017-12-18 13:06:38 +01:00
|
|
|
const fragment = document.createDocumentFragment();
|
2019-12-14 17:40:15 +01:00
|
|
|
const addOptionToFragment = (data): void => {
|
2017-12-18 13:06:38 +01:00
|
|
|
// Create a standard select option
|
2019-10-21 11:48:49 +02:00
|
|
|
const option = this.template(data);
|
2017-12-18 13:06:38 +01:00
|
|
|
// Append it to fragment
|
2019-10-21 11:48:49 +02:00
|
|
|
fragment.appendChild(option);
|
2017-12-18 13:06:38 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
// Add each list item to list
|
|
|
|
options.forEach(optionData => addOptionToFragment(optionData));
|
|
|
|
|
|
|
|
this.appendDocFragment(fragment);
|
|
|
|
}
|
|
|
|
|
2019-12-14 15:43:51 +01:00
|
|
|
appendDocFragment(fragment: DocumentFragment): void {
|
2017-12-18 13:06:38 +01:00
|
|
|
this.element.innerHTML = '';
|
|
|
|
this.element.appendChild(fragment);
|
|
|
|
}
|
2017-10-13 14:43:58 +02:00
|
|
|
}
|