Files
basecoat/src/js/select.js
T

381 lines
12 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"]');
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';
2026-01-05 11:28:05 +08:00
const selectedOptions = isMultiple ? new Set() : null;
const placeholder = isMultiple ? (selectComponent.dataset.placeholder || '') : null;
2026-01-13 19:33:59 +08:00
const closeOnSelect = selectComponent.dataset.closeOnSelect === 'true';
2025-05-01 20:53:03 +08:00
2026-01-05 12:15:43 +08:00
const getValue = (opt) => opt.dataset.value ?? opt.textContent.trim();
2026-06-03 23:08:41 +08:00
const scrollOptionIntoListbox = (option) => {
const optionRect = option.getBoundingClientRect();
const listboxRect = listbox.getBoundingClientRect();
if (optionRect.top < listboxRect.top) {
listbox.scrollTop -= listboxRect.top - optionRect.top;
} else if (optionRect.bottom > listboxRect.bottom) {
listbox.scrollTop += optionRect.bottom - listboxRect.bottom;
}
};
const setActiveOption = (index) => {
if (activeIndex > -1 && options[activeIndex]) {
options[activeIndex].classList.remove('active');
}
2026-01-05 11:28:05 +08:00
activeIndex = index;
2026-01-05 11:28:05 +08:00
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');
}
};
2026-01-04 19:21:07 +08:00
const updateValue = (optionOrOptions, triggerEvent = true) => {
let value;
if (isMultiple) {
const opts = Array.isArray(optionOrOptions) ? optionOrOptions : [];
2026-01-05 11:28:05 +08:00
selectedOptions.clear();
opts.forEach(opt => selectedOptions.add(opt));
// Get selected options in DOM order
const selected = options.filter(opt => selectedOptions.has(opt));
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-05 12:15:43 +08:00
value = selected.map(getValue);
2026-01-05 11:28:05 +08:00
input.value = JSON.stringify(value);
2026-01-04 19:21:07 +08:00
} else {
const option = optionOrOptions;
if (!option) return;
2025-11-17 10:45:39 +08:00
selectedLabel.innerHTML = option.innerHTML;
2026-01-05 12:15:43 +08:00
value = getValue(option);
2026-01-05 11:28:05 +08:00
input.value = value;
2026-01-04 19:21:07 +08:00
}
2026-01-04 14:39:32 +08:00
2026-01-05 11:28:05 +08:00
options.forEach(opt => {
const isSelected = isMultiple ? selectedOptions.has(opt) : opt === optionOrOptions;
if (isSelected) {
opt.setAttribute('aria-selected', 'true');
} else {
opt.removeAttribute('aria-selected');
}
});
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
2025-06-18 19:42:26 +08:00
const closePopover = (focusOnTrigger = true) => {
if (popover.getAttribute('aria-hidden') === 'true') return;
2026-01-05 11:28:05 +08:00
2025-06-18 19:42:26 +08:00
if (focusOnTrigger) trigger.focus();
popover.setAttribute('aria-hidden', 'true');
trigger.setAttribute('aria-expanded', 'false');
setActiveOption(-1);
2025-06-19 15:21:12 +08:00
};
2026-01-05 11:28:05 +08:00
const toggleMultipleValue = (option) => {
if (selectedOptions.has(option)) {
selectedOptions.delete(option);
2026-01-04 14:39:32 +08:00
} else {
2026-01-05 11:28:05 +08:00
selectedOptions.add(option);
}
updateValue(options.filter(opt => selectedOptions.has(opt)));
};
const select = (value) => {
if (isMultiple) {
2026-01-05 12:15:43 +08:00
const option = options.find(opt => getValue(opt) === value && !selectedOptions.has(opt));
2026-01-05 11:28:05 +08:00
if (!option) return;
selectedOptions.add(option);
updateValue(options.filter(opt => selectedOptions.has(opt)));
} else {
2026-01-05 12:15:43 +08:00
const option = options.find(opt => getValue(opt) === value);
2026-01-05 11:28:05 +08:00
if (!option) return;
if (input.value !== value) {
updateValue(option);
}
closePopover();
2026-01-04 14:39:32 +08:00
}
};
2026-01-05 11:28:05 +08:00
const deselect = (value) => {
2026-01-04 14:39:32 +08:00
if (!isMultiple) return;
2026-01-05 12:15:43 +08:00
const option = options.find(opt => getValue(opt) === value && selectedOptions.has(opt));
2026-01-05 11:28:05 +08:00
if (!option) return;
selectedOptions.delete(option);
updateValue(options.filter(opt => selectedOptions.has(opt)));
2026-01-04 14:39:32 +08:00
};
2026-01-05 11:28:05 +08:00
const toggle = (value) => {
2026-01-04 14:39:32 +08:00
if (!isMultiple) return;
2026-01-05 12:15:43 +08:00
const option = options.find(opt => getValue(opt) === value);
2026-01-05 11:28:05 +08:00
if (!option) return;
toggleMultipleValue(option);
};
2026-01-05 11:28:05 +08:00
// Initialization
2026-01-04 14:39:32 +08:00
if (isMultiple) {
2026-01-05 11:28:05 +08:00
const ariaSelected = options.filter(opt => opt.getAttribute('aria-selected') === 'true');
try {
const parsed = JSON.parse(input.value || '[]');
2026-01-05 12:15:43 +08:00
const validValues = new Set(options.map(getValue));
2026-01-05 11:28:05 +08:00
const initialValues = Array.isArray(parsed) ? parsed.filter(v => validValues.has(v)) : [];
2026-01-04 19:21:07 +08:00
2026-01-05 11:28:05 +08:00
const initialOptions = [];
if (initialValues.length > 0) {
// Match values to options in order, allowing duplicates
initialValues.forEach(val => {
2026-01-05 12:15:43 +08:00
const opt = options.find(o => getValue(o) === val && !initialOptions.includes(o));
2026-01-05 11:28:05 +08:00
if (opt) initialOptions.push(opt);
});
} else {
initialOptions.push(...ariaSelected);
}
updateValue(initialOptions, false);
} catch (e) {
updateValue(ariaSelected, false);
2026-01-04 14:39:32 +08:00
}
} else {
2026-01-05 12:15:43 +08:00
const initialOption = options.find(opt => getValue(opt) === input.value) || options[0];
2026-01-05 11:28:05 +08:00
if (initialOption) updateValue(initialOption, false);
2026-01-04 14:39:32 +08:00
}
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;
}
2026-01-05 11:28:05 +08:00
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;
}
2026-01-05 11:28:05 +08:00
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-05 11:28:05 +08:00
const option = options[activeIndex];
2026-01-04 14:39:32 +08:00
if (isMultiple) {
2026-01-05 11:28:05 +08:00
toggleMultipleValue(option);
2026-01-13 19:33:59 +08:00
if (closeOnSelect) {
closePopover();
}
2026-01-04 14:39:32 +08:00
} else {
2026-01-05 12:15:43 +08:00
if (input.value !== getValue(option)) {
2026-01-05 11:28:05 +08:00
updateValue(option);
}
closePopover();
2026-01-04 14:39:32 +08:00
}
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));
2026-06-03 23:08:41 +08:00
scrollOptionIntoListbox(newActiveOption);
2025-06-12 18:44:17 +08:00
}
};
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);
2025-06-18 20:55:32 +08:00
const openPopover = () => {
document.dispatchEvent(new CustomEvent('basecoat:popover', {
detail: { source: selectComponent }
}));
2026-01-05 11:28:05 +08:00
2025-06-18 20:55:32 +08:00
popover.setAttribute('aria-hidden', 'false');
trigger.setAttribute('aria-expanded', 'true');
2026-01-05 11:28:05 +08:00
2025-06-18 20:55:32 +08:00
const selectedOption = listbox.querySelector('[role="option"][aria-selected="true"]');
if (selectedOption) {
setActiveOption(options.indexOf(selectedOption));
2026-06-03 23:08:41 +08:00
scrollOptionIntoListbox(selectedOption);
2025-06-18 20:55:32 +08:00
}
};
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"]');
2026-01-05 11:28:05 +08:00
if (!clickedOption) return;
const option = options.find(opt => opt === clickedOption);
if (!option) return;
if (isMultiple) {
toggleMultipleValue(option);
2026-01-13 19:33:59 +08:00
if (closeOnSelect) {
closePopover();
2026-01-04 14:39:32 +08:00
} else {
2026-01-13 19:33:59 +08:00
setActiveOption(options.indexOf(option));
trigger.focus();
2026-01-04 14:39:32 +08:00
}
2026-01-05 11:28:05 +08:00
} else {
2026-01-05 12:15:43 +08:00
if (input.value !== getValue(option)) {
2026-01-05 11:28:05 +08:00
updateValue(option);
}
closePopover();
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
2026-01-05 11:28:05 +08:00
// Public API
Object.defineProperty(selectComponent, 'value', {
get: () => {
if (isMultiple) {
2026-01-05 12:15:43 +08:00
return options.filter(opt => selectedOptions.has(opt)).map(getValue);
2026-01-05 11:28:05 +08:00
} else {
return input.value;
}
},
set: (val) => {
if (isMultiple) {
const values = Array.isArray(val) ? val : (val != null ? [val] : []);
const opts = [];
values.forEach(v => {
2026-01-05 12:15:43 +08:00
const opt = options.find(o => getValue(o) === v && !opts.includes(o));
2026-01-05 11:28:05 +08:00
if (opt) opts.push(opt);
});
updateValue(opts);
} else {
2026-01-05 12:15:43 +08:00
const option = options.find(opt => getValue(opt) === val);
2026-01-05 11:28:05 +08:00
if (option) {
updateValue(option);
closePopover();
}
}
}
});
selectComponent.select = select;
selectComponent.selectByValue = select; // Backward compatibility alias
2026-01-04 14:39:32 +08:00
if (isMultiple) {
2026-01-05 11:28:05 +08:00
selectComponent.deselect = deselect;
selectComponent.toggle = toggle;
2026-01-05 12:15:43 +08:00
selectComponent.selectAll = () => updateValue(options);
2026-01-05 11:28:05 +08:00
selectComponent.selectNone = () => updateValue([]);
2026-01-04 14:39:32 +08:00
}
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);
}
})();