Files
basecoat/src/js/select.js
T

432 lines
14 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]');
2026-01-04 14:39:32 +08:00
const listbox = popover ? popover.querySelector('[role="listbox"]') : null;
2025-06-12 18:44:17 +08:00
const input = selectComponent.querySelector(':scope > input[type="hidden"]');
const filter = selectComponent.querySelector('header input[type="text"]');
2026-01-04 14:39:32 +08:00
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');
2026-01-04 14:39:32 +08:00
if (!input) missing.push('input');
2025-06-18 19:42:26 +08:00
console.error(`Select component initialisation failed. Missing element(s): ${missing.join(', ')}`, selectComponent);
return;
}
2026-01-04 14:39:32 +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;
2026-01-04 14:39:32 +08:00
const isMultiple = listbox.getAttribute('aria-multiselectable') === 'true';
let selectedValues = isMultiple ? new Set() : null;
let placeholder = null;
if (isMultiple) {
placeholder = selectComponent.dataset.placeholder || '';
}
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;
};
2026-01-04 14:39:32 +08:00
const syncMultipleInputs = () => {
if (!isMultiple) return;
const values = Array.from(selectedValues);
const inputs = Array.from(selectComponent.querySelectorAll(':scope > input[type="hidden"]'));
inputs.slice(1).forEach(inp => inp.remove());
if (values.length === 0) {
input.value = '';
} else {
input.value = values[0];
let insertAfter = input;
for (let i = 1; i < values.length; i++) {
const clone = input.cloneNode(true);
clone.removeAttribute('id');
clone.value = values[i];
insertAfter.after(clone);
insertAfter = clone;
}
}
};
const updateMultipleLabel = () => {
if (!isMultiple) return;
const selected = options.filter(opt => selectedValues.has(opt.dataset.value));
if (selected.length === 0) {
selectedLabel.textContent = placeholder;
selectedLabel.classList.add('text-muted-foreground');
} else {
selectedLabel.textContent = selected.map(opt => opt.dataset.label || opt.textContent.trim()).join(', ');
selectedLabel.classList.remove('text-muted-foreground');
}
};
2026-01-04 19:21:07 +08:00
const updateValue = (optionOrOptions, triggerEvent = true) => {
let value;
if (isMultiple) {
const opts = Array.isArray(optionOrOptions) ? optionOrOptions : [];
selectedValues = new Set(opts.map(opt => opt.dataset.value));
options.forEach(opt => {
if (selectedValues.has(opt.dataset.value)) {
opt.setAttribute('aria-selected', 'true');
} else {
opt.removeAttribute('aria-selected');
}
});
updateMultipleLabel();
syncMultipleInputs();
value = Array.from(selectedValues);
} else {
const option = optionOrOptions;
if (!option) return;
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;
2026-01-04 19:21:07 +08:00
options.forEach(opt => {
if (opt === option) {
opt.setAttribute('aria-selected', 'true');
} else {
opt.removeAttribute('aria-selected');
}
});
value = option.dataset.value;
}
2026-01-04 14:39:32 +08:00
2026-01-04 19:21:07 +08:00
if (triggerEvent) {
selectComponent.dispatchEvent(new CustomEvent('change', {
detail: { value },
bubbles: true
}));
2025-05-01 20:53:03 +08:00
}
2025-06-12 10:37:19 +08:00
};
2025-05-01 20:53:03 +08:00
2026-01-04 14:39:32 +08:00
const toggleMultipleValue = (value, triggerEvent = true) => {
if (!isMultiple || value == null) return;
2026-01-04 19:21:07 +08:00
const newValues = new Set(selectedValues);
if (newValues.has(value)) {
newValues.delete(value);
2026-01-04 14:39:32 +08:00
} else {
2026-01-04 19:21:07 +08:00
newValues.add(value);
2026-01-04 14:39:32 +08:00
}
2026-01-04 19:21:07 +08:00
const selectedOptions = options.filter(opt => newValues.has(opt.dataset.value));
updateValue(selectedOptions, triggerEvent);
2026-01-04 14:39:32 +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);
2026-01-04 14:39:32 +08:00
if (isMultiple) {
2026-01-04 19:21:07 +08:00
if (value != null && selectedValues.has(value)) return;
2026-01-04 14:39:32 +08:00
if (option && value != null) {
2026-01-04 19:21:07 +08:00
const newValues = new Set(selectedValues);
newValues.add(value);
const selectedOptions = options.filter(opt => newValues.has(opt.dataset.value));
updateValue(selectedOptions);
2026-01-04 14:39:32 +08:00
}
} else {
selectOption(option);
}
};
const selectAll = () => {
if (!isMultiple) return;
2026-01-04 19:21:07 +08:00
updateValue(options.filter(opt => opt.dataset.value != null));
2026-01-04 14:39:32 +08:00
};
const selectNone = () => {
if (!isMultiple) return;
2026-01-04 19:21:07 +08:00
updateValue([]);
};
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 keywordList = (option.dataset.keywords || '')
.toLowerCase()
.split(/[\s,]+/)
.filter(Boolean);
const matchesKeyword = keywordList.some(keyword => keyword.includes(searchTerm));
const matches = optionText.includes(searchTerm) || matchesKeyword;
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);
}
2026-01-04 14:39:32 +08:00
if (isMultiple) {
const validValues = new Set(options.map(opt => opt.dataset.value).filter(v => v != null));
const inputs = Array.from(selectComponent.querySelectorAll(':scope > input[type="hidden"]'));
const initialValues = inputs
.map(inp => inp.value)
.filter(v => v != null && validValues.has(v));
2026-01-04 19:21:07 +08:00
let initialOptions;
2026-01-04 14:39:32 +08:00
if (initialValues.length > 0) {
2026-01-04 19:21:07 +08:00
initialOptions = options.filter(opt => initialValues.includes(opt.dataset.value));
2026-01-04 14:39:32 +08:00
} else {
2026-01-04 19:21:07 +08:00
initialOptions = options.filter(opt => opt.getAttribute('aria-selected') === 'true');
2026-01-04 14:39:32 +08:00
}
2026-01-04 19:21:07 +08:00
updateValue(initialOptions, false);
2026-01-04 14:39:32 +08:00
} else {
let initialOption = options.find(opt => opt.dataset.value === input.value);
2025-06-12 10:37:19 +08:00
2026-01-04 14:39:32 +08:00
if (!initialOption) {
initialOption = options.find(opt => opt.dataset.value !== undefined) ?? options[0];
}
if (initialOption) {
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) {
2026-01-04 14:39:32 +08:00
if (isMultiple) {
toggleMultipleValue(options[activeIndex].dataset.value);
} else {
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) {
2026-01-04 14:39:32 +08:00
if (isMultiple) {
toggleMultipleValue(clickedOption.dataset.value);
2026-01-04 19:21:07 +08:00
setActiveOption(options.indexOf(clickedOption));
if (filter) {
filter.focus();
} else {
trigger.focus();
}
2026-01-04 14:39:32 +08:00
} else {
selectOption(clickedOption);
}
2025-06-12 18:44:17 +08:00
}
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');
2026-01-04 14:39:32 +08:00
2025-06-19 15:21:12 +08:00
selectComponent.selectByValue = selectByValue;
2026-01-04 14:39:32 +08:00
if (isMultiple) {
selectComponent.selectAll = selectAll;
selectComponent.selectNone = selectNone;
}
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);
}
})();