import { api } from '../../lib/api.mjs'; import './vehicle-form.mjs'; class VehicleList extends HTMLElement { #vehicles = []; #loading = true; #search = ''; connectedCallback() { if (!this.shadowRoot) this.attachShadow({ mode: 'open' }); this.#load(); } async #load() { this.#loading = true; this.#render(); try { this.#vehicles = await api.get(`/registry/vehicles?all=1${this.#search ? '&search=' + encodeURIComponent(this.#search) : ''}`) || []; } catch { this.#vehicles = []; } this.#loading = false; this.#render(); } async #deactivate(id) { try { await api.delete(`/registry/vehicles/${id}`); window.dispatchEvent(new CustomEvent('wo:toast', { detail: { message: 'Vehicle deactivated', type: 'success' } })); await this.#load(); } catch (err) { window.dispatchEvent(new CustomEvent('wo:toast', { detail: { message: err.message, type: 'error' } })); } } #render() { const s = this.shadowRoot; s.innerHTML = ` ${this.#loading ? '' : this.#vehicles.length === 0 ? `
No vehicles found
` : `
${this.#vehicles.map(v => `
${this.#esc(v.unit_number)}
${v.description ? `${this.#esc(v.description)}` : ''} ${v.vehicle_type ? `${this.#esc(v.vehicle_type)}` : ''}
${v.active ? 'Active' : 'Inactive'}
${v.active ? `` : ''}
`).join('')}
`} `; if (window.lucide) lucide.createIcons({ root: s }); const searchEl = s.querySelector('#search'); let debounce; searchEl.addEventListener('input', () => { clearTimeout(debounce); debounce = setTimeout(() => { this.#search = searchEl.value; this.#load(); }, 350); }); s.querySelector('#new-btn').addEventListener('click', () => s.querySelector('#vehicle-form').open(null, () => this.#load())); s.querySelectorAll('[data-edit]').forEach(btn => { const v = this.#vehicles.find(x => x.id === +btn.dataset.edit); btn.addEventListener('click', () => s.querySelector('#vehicle-form').open(v, () => this.#load())); }); s.querySelectorAll('[data-deactivate]').forEach(btn => btn.addEventListener('click', () => this.#deactivate(+btn.dataset.deactivate))); } #esc(s) { return (s || '').replace(/&/g,'&').replace(//g,'>'); } } customElements.define('vehicle-list', VehicleList);