Files
basecoat/src/js/select.js
T

293 lines
9.1 KiB
JavaScript
Raw Normal View History

2025-06-12 10:37:19 +08:00
(() => {
2025-06-12 18:44:17 +08:00
const initSelect = (selectComponent) => {
const trigger = selectComponent.querySelector(':scope > button');
const selectedLabel = trigger.querySelector(':scope > span');
const popover = selectComponent.querySelector(':scope > [data-popover]');
2025-06-12 10:37:19 +08:00
const listbox = popover.querySelector('[role="listbox"]');
2025-06-12 18:44:17 +08:00
const input = selectComponent.querySelector(':scope > input[type="hidden"]');
const filter = selectComponent.querySelector('header input[type="text"]');
2025-06-18 19:42:26 +08:00
if (!trigger || !popover || !listbox || !input) {
const missing = [];
if (!trigger) missing.push('trigger');
if (!popover) missing.push('popover');
if (!listbox) missing.push('listbox');
if (!input) missing.push('input');
console.error(`Select component initialisation failed. Missing element(s): ${missing.join(', ')}`, selectComponent);
return;
}
2025-05-01 20:53:03 +08:00
const allOptions = Array.from(listbox.querySelectorAll('[role="option"]'));
const options = allOptions.filter(opt => opt.getAttribute('aria-disabled') !== 'true');
2025-06-12 18:44:17 +08:00
let visibleOptions = [...options];
2025-06-12 10:37:19 +08:00
let activeIndex = -1;
2025-05-01 20:53:03 +08:00
const setActiveOption = (index) => {
if (activeIndex > -1 && options[activeIndex]) {
options[activeIndex].classList.remove('active');
}
activeIndex = index;
if (activeIndex > -1) {
const activeOption = options[activeIndex];
activeOption.classList.add('active');
if (activeOption.id) {
trigger.setAttribute('aria-activedescendant', activeOption.id);
} else {
trigger.removeAttribute('aria-activedescendant');
}
} else {
trigger.removeAttribute('aria-activedescendant');
}
};
2025-06-18 19:42:26 +08:00
const hasTransition = () => {
const style = getComputedStyle(popover);
return parseFloat(style.transitionDuration) > 0 || parseFloat(style.transitionDelay) > 0;
};
const updateValue = (option, triggerEvent = true) => {
2025-06-08 12:32:52 +08:00
if (option) {
2025-11-17 10:45:39 +08:00
selectedLabel.innerHTML = option.innerHTML;
2025-06-12 10:37:19 +08:00
input.value = option.dataset.value;
listbox.querySelector('[role="option"][aria-selected="true"]')?.removeAttribute('aria-selected');
option.setAttribute('aria-selected', 'true');
if (triggerEvent) {
const event = new CustomEvent('change', {
detail: { value: option.dataset.value },
bubbles: true
});
selectComponent.dispatchEvent(event);
}
2025-05-01 20:53:03 +08:00
}
2025-06-12 10:37:19 +08:00
};
2025-05-01 20:53:03 +08:00
2025-06-18 19:42:26 +08:00
const closePopover = (focusOnTrigger = true) => {
if (popover.getAttribute('aria-hidden') === 'true') return;
if (filter) {
const resetFilter = () => {
filter.value = '';
visibleOptions = [...options];
allOptions.forEach(opt => opt.setAttribute('aria-hidden', 'false'));
2025-06-18 19:42:26 +08:00
};
if (hasTransition()) {
popover.addEventListener('transitionend', resetFilter, { once: true });
} else {
resetFilter();
}
}
if (focusOnTrigger) trigger.focus();
popover.setAttribute('aria-hidden', 'true');
trigger.setAttribute('aria-expanded', 'false');
setActiveOption(-1);
}
2025-06-12 10:37:19 +08:00
const selectOption = (option) => {
if (!option) return;
const oldValue = input.value;
const newValue = option.dataset.value;
if (newValue != null && newValue !== oldValue) {
updateValue(option);
}
2025-06-18 19:42:26 +08:00
closePopover();
2025-06-19 15:21:12 +08:00
};
const selectByValue = (value) => {
const option = options.find(opt => opt.dataset.value === value);
selectOption(option);
};
2025-06-12 18:44:17 +08:00
if (filter) {
const filterOptions = () => {
const searchTerm = filter.value.trim().toLowerCase();
setActiveOption(-1);
2025-06-12 18:44:17 +08:00
visibleOptions = [];
allOptions.forEach(option => {
2025-11-17 10:45:39 +08:00
if (option.hasAttribute('data-force')) {
option.setAttribute('aria-hidden', 'false');
if (options.includes(option)) {
visibleOptions.push(option);
}
return;
}
const optionText = (option.dataset.filter || option.textContent).trim().toLowerCase();
const keywords = (option.dataset.keywords || '').toLowerCase();
const matches = optionText.includes(searchTerm) || keywords.includes(searchTerm);
2025-06-12 18:44:17 +08:00
option.setAttribute('aria-hidden', String(!matches));
if (matches && options.includes(option)) {
2025-06-12 18:44:17 +08:00
visibleOptions.push(option);
}
});
};
filter.addEventListener('input', filterOptions);
}
2025-06-18 19:42:26 +08:00
let initialOption = options.find(opt => opt.dataset.value === input.value);
2025-08-18 09:52:09 +08:00
if (!initialOption) {
initialOption = options.find(opt => opt.dataset.value !== undefined) ?? options[0];
}
2025-06-12 10:37:19 +08:00
updateValue(initialOption, false);
2025-06-12 10:37:19 +08:00
2025-06-18 19:42:26 +08:00
const handleKeyNavigation = (event) => {
const isPopoverOpen = popover.getAttribute('aria-hidden') === 'false';
2025-06-18 19:42:26 +08:00
if (!['ArrowDown', 'ArrowUp', 'Enter', 'Home', 'End', 'Escape'].includes(event.key)) {
2025-06-12 18:44:17 +08:00
return;
2025-05-01 20:53:03 +08:00
}
2025-06-12 18:44:17 +08:00
if (!isPopoverOpen) {
2025-06-18 19:42:26 +08:00
if (event.key !== 'Enter' && event.key !== 'Escape') {
event.preventDefault();
2025-06-12 18:44:17 +08:00
trigger.click();
}
return;
}
2025-06-18 19:42:26 +08:00
event.preventDefault();
2025-06-12 18:44:17 +08:00
2025-06-18 19:42:26 +08:00
if (event.key === 'Escape') {
closePopover();
return;
}
2025-06-18 19:42:26 +08:00
if (event.key === 'Enter') {
2025-06-12 18:44:17 +08:00
if (activeIndex > -1) {
2025-06-18 19:42:26 +08:00
selectOption(options[activeIndex]);
2025-06-12 18:44:17 +08:00
}
return;
}
if (visibleOptions.length === 0) return;
const currentVisibleIndex = activeIndex > -1 ? visibleOptions.indexOf(options[activeIndex]) : -1;
let nextVisibleIndex = currentVisibleIndex;
2025-06-18 19:42:26 +08:00
switch (event.key) {
2025-06-12 18:44:17 +08:00
case 'ArrowDown':
if (currentVisibleIndex < visibleOptions.length - 1) {
nextVisibleIndex = currentVisibleIndex + 1;
}
break;
case 'ArrowUp':
if (currentVisibleIndex > 0) {
nextVisibleIndex = currentVisibleIndex - 1;
} else if (currentVisibleIndex === -1) {
2025-06-18 20:55:32 +08:00
nextVisibleIndex = 0;
2025-06-12 18:44:17 +08:00
}
break;
case 'Home':
nextVisibleIndex = 0;
break;
case 'End':
nextVisibleIndex = visibleOptions.length - 1;
break;
}
if (nextVisibleIndex !== currentVisibleIndex) {
const newActiveOption = visibleOptions[nextVisibleIndex];
setActiveOption(options.indexOf(newActiveOption));
2025-06-12 18:44:17 +08:00
newActiveOption.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
};
listbox.addEventListener('mousemove', (event) => {
const option = event.target.closest('[role="option"]');
if (option && visibleOptions.includes(option)) {
const index = options.indexOf(option);
if (index !== activeIndex) {
setActiveOption(index);
}
}
});
listbox.addEventListener('mouseleave', () => {
const selectedOption = listbox.querySelector('[role="option"][aria-selected="true"]');
if (selectedOption) {
setActiveOption(options.indexOf(selectedOption));
} else {
setActiveOption(-1);
}
});
2025-06-12 18:44:17 +08:00
trigger.addEventListener('keydown', handleKeyNavigation);
if (filter) {
filter.addEventListener('keydown', handleKeyNavigation);
}
2025-06-12 10:37:19 +08:00
2025-06-18 20:55:32 +08:00
const openPopover = () => {
document.dispatchEvent(new CustomEvent('basecoat:popover', {
detail: { source: selectComponent }
}));
if (filter) {
if (hasTransition()) {
popover.addEventListener('transitionend', () => {
filter.focus();
}, { once: true });
} else {
filter.focus();
}
}
popover.setAttribute('aria-hidden', 'false');
trigger.setAttribute('aria-expanded', 'true');
const selectedOption = listbox.querySelector('[role="option"][aria-selected="true"]');
if (selectedOption) {
setActiveOption(options.indexOf(selectedOption));
2025-06-18 20:55:32 +08:00
selectedOption.scrollIntoView({ block: 'nearest' });
}
};
trigger.addEventListener('click', () => {
const isExpanded = trigger.getAttribute('aria-expanded') === 'true';
if (isExpanded) {
closePopover();
} else {
2025-06-18 20:55:32 +08:00
openPopover();
}
});
2025-06-18 19:42:26 +08:00
listbox.addEventListener('click', (event) => {
const clickedOption = event.target.closest('[role="option"]');
2025-06-12 18:44:17 +08:00
if (clickedOption) {
selectOption(clickedOption);
}
2025-06-12 10:37:19 +08:00
});
2025-06-18 19:42:26 +08:00
document.addEventListener('click', (event) => {
if (!selectComponent.contains(event.target)) {
closePopover(false);
2025-05-01 20:53:03 +08:00
}
2025-06-12 10:37:19 +08:00
});
2025-06-18 20:55:32 +08:00
document.addEventListener('basecoat:popover', (event) => {
if (event.detail.source !== selectComponent) {
closePopover(false);
}
});
popover.setAttribute('aria-hidden', 'true');
2025-06-19 15:21:12 +08:00
selectComponent.selectByValue = selectByValue;
2025-06-12 18:44:17 +08:00
selectComponent.dataset.selectInitialized = true;
2025-06-19 15:21:12 +08:00
selectComponent.dispatchEvent(new CustomEvent('basecoat:initialized'));
2025-06-12 10:37:19 +08:00
};
if (window.basecoat) {
window.basecoat.register('select', 'div.select:not([data-select-initialized])', initSelect);
}
2025-06-12 10:37:19 +08:00
})();