ave / ave-select.js
sylvance's picture
Upload 33 files
dfb04cf verified
Raw History Blame Contribute Delete
14.3 kB
import { BaseComponent } from "./ave-base-component.js";
class AveSelect extends BaseComponent {
static get observedAttributes() {
return ['value', 'placeholder', 'disabled', 'name', 'simple', 'options'];
}
constructor() {
super();
this._selectId = `select-${Math.random().toString(36).substr(2, 9)}`;
this._trigger = null;
this._popover = null;
this._listbox = null;
this._options = [];
this._activeIndex = -1;
this._handleTriggerClick = this._handleTriggerClick.bind(this);
this._handleKeydown = this._handleKeydown.bind(this);
this._handleOptionClick = this._handleOptionClick.bind(this);
this._handleDocumentClick = this._handleDocumentClick.bind(this);
this._handleNativeChange = this._handleNativeChange.bind(this);
}
// Property getters/setters
get value() {
return this._currentValue || this.getAttribute('value') || '';
}
set value(value) {
this._currentValue = value;
this.setAttribute('value', value);
this._updateSelectedOption();
}
get placeholder() { return this.getAttribute('placeholder') || 'Select an option'; }
set placeholder(value) { this.setAttribute('placeholder', value); }
get disabled() { return this.hasAttribute('disabled'); }
set disabled(value) {
if (value === true || value === 'true' || value === '') {
this.setAttribute('disabled', '');
} else {
this.removeAttribute('disabled');
}
}
get name() { return this.getAttribute('name') || ''; }
set name(value) { this.setAttribute('name', value); }
get simple() { return this.hasAttribute('simple'); }
set simple(value) {
if (value === true || value === 'true' || value === '') {
this.setAttribute('simple', '');
} else {
this.removeAttribute('simple');
}
}
get options() {
const optionsAttr = this.getAttribute('options');
if (optionsAttr && typeof optionsAttr === 'string') {
try {
return JSON.parse(optionsAttr);
} catch (e) {
console.warn('Invalid JSON in options attribute:', optionsAttr);
return null;
}
}
return null;
}
set options(value) {
if (Array.isArray(value)) {
this.setAttribute('options', JSON.stringify(value));
} else {
this.setAttribute('options', value);
}
}
setupEventListeners() {
if (this.simple) {
// Native select element
const selectElement = this.shadowRoot.querySelector('select');
if (selectElement) {
selectElement.addEventListener('change', this._handleNativeChange);
}
} else {
// Custom select implementation
this._trigger = this.shadowRoot.querySelector('.select-trigger');
this._popover = this.shadowRoot.querySelector('[popover]');
this._listbox = this.shadowRoot.querySelector('[role="listbox"]');
if (this._trigger && this._popover && this._listbox) {
this._trigger.addEventListener('click', this._handleTriggerClick);
this.addEventListener('keydown', this._handleKeydown);
this._listbox.addEventListener('click', this._handleOptionClick);
document.addEventListener('click', this._handleDocumentClick);
this._updateOptions();
}
}
}
_handleNativeChange(e) {
this._currentValue = e.target.value;
this._dispatch('ave-select-change', {
value: this._currentValue,
name: this.name
});
}
_handleTriggerClick() {
if (this.disabled) return;
const isOpen = this._popover.matches(':popover-open');
if (isOpen) {
this._popover.hidePopover();
} else {
this._popover.showPopover();
this._updateOptions();
if (this._options.length > 0) {
this._setActiveOption(0);
}
}
}
_handleKeydown(e) {
const isOpen = this._popover?.matches(':popover-open');
if (e.key === 'Escape') {
if (isOpen) {
this._popover.hidePopover();
this._trigger.focus();
}
return;
}
if (!isOpen) {
if (['ArrowDown', 'ArrowUp', 'Enter', ' '].includes(e.key)) {
e.preventDefault();
this._popover.showPopover();
this._updateOptions();
if (this._options.length > 0) {
this._setActiveOption(0);
}
}
return;
}
if (this._options.length === 0) return;
let nextIndex = this._activeIndex;
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
nextIndex = this._activeIndex < this._options.length - 1 ? this._activeIndex + 1 : 0;
break;
case 'ArrowUp':
e.preventDefault();
nextIndex = this._activeIndex > 0 ? this._activeIndex - 1 : this._options.length - 1;
break;
case 'Home':
e.preventDefault();
nextIndex = 0;
break;
case 'End':
e.preventDefault();
nextIndex = this._options.length - 1;
break;
case 'Enter':
case ' ':
e.preventDefault();
if (this._activeIndex > -1) {
const activeOption = this._options[this._activeIndex];
this._selectOption(activeOption);
}
this._popover.hidePopover();
return;
}
if (nextIndex !== this._activeIndex) {
this._setActiveOption(nextIndex);
}
}
_handleOptionClick(e) {
const option = e.target.closest('[role="option"]');
if (option) {
this._selectOption(option);
this._popover.hidePopover();
}
}
_handleDocumentClick(e) {
if (!this.contains(e.target)) {
this._popover?.hidePopover();
}
}
_updateOptions() {
if (!this._listbox) return;
this._options = Array.from(this._listbox.querySelectorAll('[role="option"]'));
}
_setActiveOption(index) {
// Remove previous active state
if (this._activeIndex > -1 && this._options[this._activeIndex]) {
this._options[this._activeIndex].classList.remove('active');
}
this._activeIndex = index;
if (this._activeIndex > -1 && this._options[this._activeIndex]) {
const activeOption = this._options[this._activeIndex];
activeOption.classList.add('active');
activeOption.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
}
_selectOption(option) {
const value = option.getAttribute('data-value');
this._currentValue = value;
// Update visual state
this._updateSelectedOption();
// Update hidden input if present
const hiddenInput = this.shadowRoot.querySelector('input[type="hidden"]');
if (hiddenInput) {
hiddenInput.value = value;
}
// Dispatch change event
this._dispatch('ave-select-change', {
value: value,
text: option.textContent.trim(),
name: this.name
});
}
_updateSelectedOption() {
if (!this._listbox) return;
// Update aria-selected attributes
const options = this._listbox.querySelectorAll('[role="option"]');
options.forEach(option => {
const isSelected = option.getAttribute('data-value') === this.value;
option.setAttribute('aria-selected', isSelected.toString());
});
// Update trigger text
if (this._trigger) {
const triggerText = this._trigger.querySelector('span');
if (triggerText) {
triggerText.textContent = this.value ? this._getSelectedText() : this.placeholder;
}
}
}
// Get current value
getCurrentValue() {
return this.value;
}
render() {
if (this.simple) {
// Simple native select
this.shadowRoot.innerHTML = `
<style>
:host {
display: inline-block;
}
select {
flex: 1;
height: 2.5rem;
width: 100%;
border-radius: 0.375rem;
border: 1px solid var(--input);
background-color: var(--background);
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
ring-offset-background: var(--background);
transition: all 0.2s;
}
select:focus {
outline: none;
box-shadow: 0 0 0 2px var(--ring);
ring-offset: 2px;
}
select:disabled {
cursor: not-allowed;
opacity: 0.5;
}
</style>
<select class="select" ${this.disabled ? 'disabled' : ''} ${this.name ? `name="${this.name}"` : ''}>
<slot>${this._getDefaultOptions()}</slot>
</select>
`;
} else {
// Complex popover-based select
const slotContent = this.innerHTML;
const triggerId = `${this._selectId}-trigger`;
const listboxId = `${this._selectId}-listbox`;
this.shadowRoot.innerHTML = `
<style>
:host {
display: inline-block;
}
.chevron-icon {
transition: transform 0.2s ease;
}
.select-trigger[aria-expanded="true"] .chevron-icon {
transform: rotate(180deg);
}
[role="option"] {
cursor: pointer;
}
[role="option"]:hover,
[role="option"].active {
background-color: var(--accent);
color: var(--accent-foreground);
}
[role="option"][aria-selected="true"] {
background-color: var(--accent);
color: var(--accent-foreground);
}
.truncate {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
<div class="relative">
<button
type="button"
class="flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 min-w-[180px] select-trigger"
id="${triggerId}"
popovertarget="${this._selectId}"
aria-haspopup="listbox"
aria-expanded="false"
aria-controls="${listboxId}"
${this.disabled ? 'disabled' : ''}
>
<span class="flex-1 text-left truncate">${this.value ? this._getSelectedText() : this.placeholder}</span>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="chevron-icon text-muted-foreground opacity-50 shrink-0 h-4 w-4">
<path d="m7 15 5 5 5-5" />
<path d="m7 9 5-5 5 5" />
</svg>
</button>
<div popover id="${this._selectId}" class="z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2">
<div role="listbox" id="${listboxId}" aria-orientation="vertical" aria-labelledby="${triggerId}" class="max-h-60 overflow-auto p-1">
${slotContent || this._getDefaultOptions()}
</div>
</div>
${this.name ? `<input type="hidden" name="${this.name}" value="${this.value}" />` : ''}
</div>
`;
}
this.setupEventListeners();
// Set initial value if provided
if (this.value) {
this._updateSelectedOption();
}
}
disconnectedCallback() {
// Remove event listeners
if (this.simple) {
const selectElement = this.shadowRoot?.querySelector('select');
if (selectElement) {
selectElement.removeEventListener('change', this._handleNativeChange);
}
} else {
if (this._trigger) {
this._trigger.removeEventListener('click', this._handleTriggerClick);
}
this.removeEventListener('keydown', this._handleKeydown);
if (this._listbox) {
this._listbox.removeEventListener('click', this._handleOptionClick);
}
document.removeEventListener('click', this._handleDocumentClick);
}
}
_getSelectedText() {
// Try to find the selected option text
const options = this.querySelectorAll('[data-value]');
for (const option of options) {
if (option.getAttribute('data-value') === this.value) {
return option.textContent.trim();
}
}
return this.value;
}
_getDefaultOptions() {
const options = this.options || [
{
group: 'Fruits',
items: [
{ value: 'apple', label: 'Apple' },
{ value: 'banana', label: 'Banana' },
{ value: 'blueberry', label: 'Blueberry' },
{ value: 'grapes', label: 'Grapes' },
{ value: 'pineapple', label: 'Pineapple' }
]
}
];
return options.map(group => {
if (group.group) {
// Grouped options
const groupId = `group-label-${group.group.toLowerCase().replace(/\s+/g, '-')}`;
const items = group.items.map(item =>
`<div role="option" data-value="${item.value}" aria-selected="false" class="relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50">${item.label}</div>`
).join('');
return `
<div role="group" aria-labelledby="${groupId}">
<div role="heading" id="${groupId}" class="px-2 py-1.5 text-sm font-semibold text-foreground">${group.group}</div>
${items}
</div>
`;
} else {
// Simple option
return `<div role="option" data-value="${group.value}" aria-selected="false" class="relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50">${group.label}</div>`;
}
}).join('');
}
}
customElements.define('ave-select', AveSelect);