2017-10-13 14:43:58 +02:00
|
|
|
import WrappedElement from './wrapped-element';
|
|
|
|
|
2019-11-03 14:18:16 +01:00
|
|
|
/**
|
|
|
|
* @typedef {import('../../../types/index').Choices.ClassNames} ClassNames
|
|
|
|
* @typedef {import('../../../types/index').Choices.Item} Item
|
|
|
|
* @typedef {import('../../../types/index').Choices.Choice} Choice
|
|
|
|
*/
|
|
|
|
|
2017-10-13 14:43:58 +02:00
|
|
|
export default class WrappedSelect extends WrappedElement {
|
2019-11-03 14:18:16 +01:00
|
|
|
/**
|
|
|
|
* @param {{
|
|
|
|
* element: HTMLSelectElement,
|
|
|
|
* classNames: ClassNames,
|
|
|
|
* delimiter: string
|
|
|
|
* template: function
|
|
|
|
* }} args
|
|
|
|
*/
|
2019-10-21 11:48:49 +02:00
|
|
|
constructor({ element, classNames, template }) {
|
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
|
|
|
}
|
|
|
|
|
2018-04-24 13:54:45 +02:00
|
|
|
get placeholderOption() {
|
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-11-03 14:18:16 +01:00
|
|
|
/**
|
|
|
|
* @returns {Element[]}
|
|
|
|
*/
|
2018-04-24 13:54:45 +02:00
|
|
|
get optionGroups() {
|
|
|
|
return Array.from(this.element.getElementsByTagName('OPTGROUP'));
|
2017-10-18 09:43:56 +02:00
|
|
|
}
|
|
|
|
|
2019-11-03 14:18:16 +01:00
|
|
|
/**
|
|
|
|
* @returns {Item[] | Choice[]}
|
|
|
|
*/
|
2018-04-24 13:54:45 +02:00
|
|
|
get options() {
|
|
|
|
return Array.from(this.element.options);
|
2017-10-18 09:43:56 +02:00
|
|
|
}
|
2017-12-18 13:06:38 +01:00
|
|
|
|
2019-11-03 14:18:16 +01:00
|
|
|
/**
|
|
|
|
* @param {Item[] | Choice[]} options
|
|
|
|
*/
|
2018-04-24 13:54:45 +02:00
|
|
|
set options(options) {
|
2017-12-18 13:06:38 +01:00
|
|
|
const fragment = document.createDocumentFragment();
|
2018-05-28 14:55:44 +02:00
|
|
|
const addOptionToFragment = data => {
|
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-11-03 14:18:16 +01:00
|
|
|
/**
|
|
|
|
* @param {DocumentFragment} fragment
|
|
|
|
*/
|
2017-12-18 13:06:38 +01:00
|
|
|
appendDocFragment(fragment) {
|
|
|
|
this.element.innerHTML = '';
|
|
|
|
this.element.appendChild(fragment);
|
|
|
|
}
|
2017-10-13 14:43:58 +02:00
|
|
|
}
|