ave / ave-table.js
sylvance's picture
Upload 33 files
dfb04cf verified
Raw History Blame Contribute Delete
10.1 kB
import { BaseComponent } from "./ave-base-component.js";
class AveTable extends BaseComponent {
static get observedAttributes() {
return ['caption', 'sortable', 'striped', 'hover', 'data', 'columns'];
}
constructor() {
super();
this._handleSort = this._handleSort.bind(this);
this._handleRowClick = this._handleRowClick.bind(this);
this._sortColumn = null;
this._sortDirection = 'asc';
}
// Property getters/setters
get caption() { return this.getAttribute('caption') || ''; }
set caption(value) { this.setAttribute('caption', value); }
get sortable() { return this.getAttribute('sortable') !== 'false'; }
set sortable(value) { this.setAttribute('sortable', value); }
get striped() { return this._getBooleanAttribute('striped'); }
set striped(value) { this._setBooleanAttribute('striped', value); }
get hover() { return this._getBooleanAttribute('hover'); }
set hover(value) { this._setBooleanAttribute('hover', value); }
get data() {
const dataAttr = this.getAttribute('data');
if (dataAttr && typeof dataAttr === 'string') {
try {
return JSON.parse(dataAttr);
} catch (e) {
console.warn('Invalid JSON in data attribute:', dataAttr);
return null;
}
}
return null;
}
set data(value) {
if (Array.isArray(value)) {
this.setAttribute('data', JSON.stringify(value));
} else {
this.setAttribute('data', value);
}
}
get columns() {
const columnsAttr = this.getAttribute('columns');
if (columnsAttr && typeof columnsAttr === 'string') {
try {
return JSON.parse(columnsAttr);
} catch (e) {
console.warn('Invalid JSON in columns attribute:', columnsAttr);
return null;
}
}
return null;
}
set columns(value) {
if (Array.isArray(value)) {
this.setAttribute('columns', JSON.stringify(value));
} else {
this.setAttribute('columns', value);
}
}
setupEventListeners() {
if (this.sortable) {
this._registerEvent('th[data-sortable]', 'click', this._handleSort);
}
this._registerEvent('tbody tr', 'click', this._handleRowClick);
}
_handleSort(e) {
const th = e.target.closest('th');
if (!th || !th.dataset.sortable) return;
const column = th.dataset.sortable;
// Toggle sort direction if same column, otherwise start with asc
if (this._sortColumn === column) {
this._sortDirection = this._sortDirection === 'asc' ? 'desc' : 'asc';
} else {
this._sortColumn = column;
this._sortDirection = 'asc';
}
this._updateSortIndicators();
this._sortTable(column, this._sortDirection);
this._dispatch('ave-table-sort', {
column: column,
direction: this._sortDirection
});
}
_handleRowClick(e) {
const row = e.target.closest('tr');
if (!row) return;
const rowIndex = Array.from(row.parentNode.children).indexOf(row);
const rowData = this._getRowData(row);
this._dispatch('ave-table-row-click', {
rowIndex: rowIndex,
rowData: rowData,
row: row
});
}
_updateSortIndicators() {
// Remove all existing sort indicators
this.shadowRoot.querySelectorAll('th[data-sortable]').forEach(th => {
th.classList.remove('sort-asc', 'sort-desc');
const indicator = th.querySelector('.sort-indicator');
if (indicator) indicator.remove();
});
// Add indicator to current sort column
const currentTh = this.shadowRoot.querySelector(`th[data-sortable="${this._sortColumn}"]`);
if (currentTh) {
currentTh.classList.add(`sort-${this._sortDirection}`);
const indicator = document.createElement('span');
indicator.className = 'sort-indicator ml-1';
indicator.innerHTML = this._sortDirection === 'asc' ? '↑' : '↓';
currentTh.appendChild(indicator);
}
}
_sortTable(column, direction) {
const tbody = this.shadowRoot.querySelector('tbody');
if (!tbody) return;
const rows = Array.from(tbody.querySelectorAll('tr'));
const columnIndex = this._getColumnIndex(column);
if (columnIndex === -1) return;
rows.sort((a, b) => {
const aValue = a.cells[columnIndex]?.textContent.trim() || '';
const bValue = b.cells[columnIndex]?.textContent.trim() || '';
// Try to parse as numbers
const aNum = parseFloat(aValue.replace(/[^0-9.-]/g, ''));
const bNum = parseFloat(bValue.replace(/[^0-9.-]/g, ''));
let comparison = 0;
if (!isNaN(aNum) && !isNaN(bNum)) {
comparison = aNum - bNum;
} else {
comparison = aValue.localeCompare(bValue);
}
return direction === 'asc' ? comparison : -comparison;
});
// Re-append sorted rows
rows.forEach(row => tbody.appendChild(row));
}
_getColumnIndex(column) {
const headers = this.shadowRoot.querySelectorAll('th');
for (let i = 0; i < headers.length; i++) {
if (headers[i].dataset.sortable === column) {
return i;
}
}
return -1;
}
_getRowData(row) {
const data = {};
const headers = this.shadowRoot.querySelectorAll('th');
Array.from(row.cells).forEach((cell, index) => {
const header = headers[index];
const key = header?.dataset.sortable || header?.textContent.trim().toLowerCase() || `column_${index}`;
data[key] = cell.textContent.trim();
});
return data;
}
render() {
const slotContent = this.innerHTML;
const hasCustomContent = slotContent.trim().length > 0;
this.shadowRoot.innerHTML = `
<style>
:host {
display: block;
}
th[data-sortable] {
cursor: pointer;
user-select: none;
position: relative;
}
th[data-sortable]:hover {
background-color: color-mix(in srgb, var(--muted) 50%, transparent);
}
.sort-indicator {
font-size: 0.75rem;
opacity: 0.7;
}
tbody tr {
cursor: pointer;
}
tbody tr:hover {
background-color: color-mix(in srgb, var(--muted) 30%, transparent);
}
.striped tbody tr:nth-child(even) {
background-color: color-mix(in srgb, var(--muted) 10%, transparent);
}
caption {
margin-bottom: 0.75rem;
font-size: 0.875rem;
color: var(--muted-foreground);
}
</style>
<div class="relative w-full overflow-auto">
<table class="w-full caption-bottom text-sm">
${this.caption ? `<caption class="mt-4 text-sm text-muted-foreground">${this.caption}</caption>` : ''}
${hasCustomContent ? slotContent : this._getDefaultContent()}
</table>
</div>
`;
this.setupEventListeners();
}
_getDefaultContent() {
return `
<thead class="[&_tr]:border-b">
<tr class="border-b transition-colors hover:bg-muted/50">
<th data-sortable="invoice" class="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Invoice</th>
<th data-sortable="status" class="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Status</th>
<th data-sortable="method" class="h-12 px-4 text-left align-middle font-medium text-muted-foreground">Method</th>
<th data-sortable="amount" class="h-12 px-4 text-right align-middle font-medium text-muted-foreground">Amount</th>
</tr>
</thead>
<tbody class="[&_tr:last-child]:border-0">
<tr class="border-b transition-colors hover:bg-muted/50">
<td class="p-4 align-middle font-medium">INV001</td>
<td class="p-4 align-middle">Paid</td>
<td class="p-4 align-middle">Credit Card</td>
<td class="p-4 align-middle text-right">$250.00</td>
</tr>
<tr class="border-b transition-colors hover:bg-muted/50">
<td class="p-4 align-middle font-medium">INV002</td>
<td class="p-4 align-middle">Pending</td>
<td class="p-4 align-middle">PayPal</td>
<td class="p-4 align-middle text-right">$150.00</td>
</tr>
<tr class="border-b transition-colors hover:bg-muted/50">
<td class="p-4 align-middle font-medium">INV003</td>
<td class="p-4 align-middle">Unpaid</td>
<td class="p-4 align-middle">Bank Transfer</td>
<td class="p-4 align-middle text-right">$350.00</td>
</tr>
<tr class="border-b transition-colors hover:bg-muted/50">
<td class="p-4 align-middle font-medium">INV004</td>
<td class="p-4 align-middle">Paid</td>
<td class="p-4 align-middle">Credit Card</td>
<td class="p-4 align-middle text-right">$450.00</td>
</tr>
<tr class="border-b transition-colors hover:bg-muted/50">
<td class="p-4 align-middle font-medium">INV005</td>
<td class="p-4 align-middle">Paid</td>
<td class="p-4 align-middle">PayPal</td>
<td class="p-4 align-middle text-right">$550.00</td>
</tr>
<tr class="border-b transition-colors hover:bg-muted/50">
<td class="p-4 align-middle font-medium">INV006</td>
<td class="p-4 align-middle">Pending</td>
<td class="p-4 align-middle">Bank Transfer</td>
<td class="p-4 align-middle text-right">$200.00</td>
</tr>
<tr class="border-b transition-colors hover:bg-muted/50">
<td class="p-4 align-middle font-medium">INV007</td>
<td class="p-4 align-middle">Unpaid</td>
<td class="p-4 align-middle">Credit Card</td>
<td class="p-4 align-middle text-right">$300.00</td>
</tr>
</tbody>
<tfoot class="border-t bg-muted/50 font-medium [&>tr]:last:border-b-0">
<tr class="border-b transition-colors hover:bg-muted/50">
<td class="p-4 align-middle font-medium" colspan="3">Total</td>
<td class="p-4 align-middle text-right font-medium">$2,500.00</td>
</tr>
</tfoot>
`;
}
}
customElements.define('ave-table', AveTable);