ngrandson's picture
document.querySelectorAll('.custom-select').forEach(initSelect);
3425d88 verified
Raw History Blame Contribute Delete
6.7 kB
/**
* Initialize custom select components
* @param {HTMLElement} select - The select container element
*/
function initSelect(select) {
const type = select.dataset.type;
const btn = select.querySelector('.select-btn');
const label = select.querySelector('.select-label');
const list = select.querySelector('.select-list');
const input = select.querySelector('input[type="hidden"]');
const arrow = btn.querySelector('svg');
const selectedValues = new Map();
let originalParent = list.parentNode;
let movedToBody = false;
let rafId = null;
let portal = null;
// Open/close functionality
btn.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = !list.classList.contains('pointer-events-none');
closeAllSelects();
if (!isOpen) openList();
});
function openList() {
if (!movedToBody) {
originalParent = list.parentNode;
portal = document.createElement('div');
portal.className = 'select-portal';
Object.assign(portal.style, {
position: 'fixed',
left: '0px',
top: '0px',
zIndex: '9999',
pointerEvents: 'none'
});
portal.appendChild(list);
document.body.appendChild(portal);
movedToBody = true;
}
const btnRect = btn.getBoundingClientRect();
const listRect = list.getBoundingClientRect();
const margin = 8;
const maxAllowed = Math.min((listRect.height + 12), 400);
const spaceBelow = window.innerHeight - btnRect.bottom;
const spaceAbove = btnRect.top;
const preferBelow = spaceBelow >= Math.min(maxAllowed, spaceAbove);
const availableSpace = preferBelow ? spaceBelow : spaceAbove;
const maxHeight = Math.max(0, Math.min(maxAllowed, Math.floor(availableSpace - margin)));
if (portal) {
Object.assign(portal.style, {
left: `${Math.round(btnRect.left)}px`,
top: preferBelow
? `${Math.round(btnRect.bottom)}px`
: `${Math.round(btnRect.top - maxHeight)}px`,
minWidth: `${Math.round(btnRect.width)}px`,
pointerEvents: 'auto'
});
}
if (maxHeight > 0) {
list.classList.remove('overflow-hidden');
list.style.maxHeight = `${maxHeight}px`;
list.style.overflowY = 'auto';
}
list.classList.remove('pointer-events-none', 'opacity-0', 'scale-95');
list.classList.add('opacity-100', 'scale-100');
if (arrow) arrow.classList.add('rotate-180');
window.addEventListener('resize', updatePosition);
window.addEventListener('scroll', updatePosition, true);
}
function updatePosition() {
if (rafId) return;
rafId = requestAnimationFrame(() => {
const btnRect = btn.getBoundingClientRect();
const listRect = list.getBoundingClientRect();
const margin = 8;
const maxAllowed = Math.min((listRect.height + 12), 400);
const spaceBelow = window.innerHeight - btnRect.bottom;
const spaceAbove = btnRect.top;
const preferBelow = spaceBelow >= Math.min(maxAllowed, spaceAbove);
const availableSpace = preferBelow ? spaceBelow : spaceAbove;
const maxHeight = Math.max(0, Math.min(maxAllowed, Math.floor(availableSpace - margin)));
if (portal) {
portal.style.left = `${Math.round(btnRect.left)}px`;
portal.style.top = preferBelow
? `${Math.round(btnRect.bottom)}px`
: `${Math.round(btnRect.top - maxHeight)}px`;
}
if (maxHeight > 0) {
list.style.maxHeight = `${maxHeight}px`;
}
rafId = null;
});
}
function closeList() {
list.classList.add('pointer-events-none', 'opacity-0', 'scale-95');
list.classList.remove('opacity-100', 'scale-100');
if (arrow) arrow.classList.remove('rotate-180');
window.removeEventListener('resize', updatePosition);
window.removeEventListener('scroll', updatePosition, true);
if (rafId) { cancelAnimationFrame(rafId); rafId = null; }
if (movedToBody) {
originalParent.appendChild(list);
if (portal && portal.parentNode) {
portal.parentNode.removeChild(portal);
}
portal = null;
movedToBody = false;
list.style.position = '';
list.style.left = '';
list.style.top = '';
list.style.minWidth = '';
list.style.zIndex = '';
list.style.maxHeight = '';
list.style.overflowY = '';
}
}
// Selection functionality
list.querySelectorAll('li').forEach(li => {
li.addEventListener('click', (e) => {
e.stopPropagation();
const value = li.dataset.value;
const text = li.dataset.label;
if (type === 'single') {
input.value = value;
label.textContent = text;
input.dispatchEvent(new Event('change'));
closeList();
}
if (type === 'multi') {
const checkbox = li.querySelector('input[type="checkbox"]');
checkbox.checked = !checkbox.checked;
checkbox.checked
? selectedValues.set(value, text)
: selectedValues.delete(value);
const selected = Array.from(selectedValues.entries());
input.value = selected.map(([v]) => v).join(',');
input.dispatchEvent(new Event('change'));
label.textContent = selected.length
? selected.map(([_, t]) => t).join(', ')
: 'Select options';
}
});
});
// Expose methods
select._list = list;
select.close = closeList;
select.reset = function() {
input.value = '';
label.textContent = type === 'single' ? 'Select an option' : 'Select options';
selectedValues.clear();
list.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.checked = false);
};
}
// Global close handler
window.addEventListener('click', (e) => {
document.querySelectorAll('.custom-select').forEach(select => {
const list = select._list || select.querySelector('.select-list');
if (!select.contains(e.target) && (!list || !list.contains(e.target))) {
if (typeof select.close === 'function') select.close();
}
});
});
function closeAllSelects() {
document.querySelectorAll('.custom-select').forEach(select => {
if (typeof select.close === 'function') {
select.close();
} else {
const list = select.querySelector('.select-list');
if (list) {
list.classList.add('pointer-events-none', 'opacity-0', 'scale-95');
list.classList.remove('opacity-100', 'scale-100');
}
const arrow = select.querySelector('svg');
if (arrow) arrow.classList.remove('rotate-180');
}
});
}
// Initialize all selects on page load
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.custom-select').forEach(initSelect);
});