Choices/src/scripts/components/wrapped-select.ts

58 lines
1.6 KiB
TypeScript
Raw Normal View History

import WrappedElement from './wrapped-element';
2019-12-14 15:43:51 +01:00
import { ClassNames, Item, Choice } from '../interfaces';
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 });
this.template = template;
}
2019-12-14 15:43:51 +01:00
get placeholderOption(): HTMLOptionElement | null {
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
}
2019-12-14 15:43:51 +01:00
set options(options: Item[] | Choice[]): void {
const fragment = document.createDocumentFragment();
2019-12-14 17:40:15 +01:00
const addOptionToFragment = (data): void => {
// Create a standard select option
const option = this.template(data);
// Append it to fragment
fragment.appendChild(option);
};
// 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 {
this.element.innerHTML = '';
this.element.appendChild(fragment);
}
}