import { api } from '../../lib/api.mjs'; import './people-form.mjs'; class PeopleList extends HTMLElement { #people = []; #loading = true; #search = ''; connectedCallback() { if (!this.shadowRoot) this.attachShadow({ mode: 'open' }); this.#load(); } async #load() { this.#loading = true; this.#render(); try { this.#people = await api.get(`/registry/people?all=1${this.#search ? '&search=' + encodeURIComponent(this.#search) : ''}`) || []; } catch { this.#people = []; } this.#loading = false; this.#render(); } async #deactivate(id) { try { await api.delete(`/registry/people/${id}`); window.dispatchEvent(new CustomEvent('wo:toast', { detail: { message: 'Person deactivated', type: 'success' } })); await this.#load(); } catch (err) { window.dispatchEvent(new CustomEvent('wo:toast', { detail: { message: err.message, type: 'error' } })); } } #initials(name) { return (name || '?').split(' ').slice(0,2).map(w => w[0]).join('').toUpperCase(); } #avatarColor(name) { const colors = ['#0A7EA4','#8B5CF6','#E07B39','#1D9D6C','#D97706','#C0392B','#64748B']; let h = 0; for (const c of name || '') h = (h * 31 + c.charCodeAt(0)) & 0xffffffff; return colors[Math.abs(h) % colors.length]; } #render() { const s = this.shadowRoot; s.innerHTML = ` ${this.#loading ? '' : this.#people.length === 0 ? `
No people found
` : `
${this.#people.map(p => `
${this.#initials(p.name)}
${this.#esc(p.name)}
${p.role ? `${this.#esc(p.role)}` : ''} ${p.phone ? `${this.#esc(p.phone)}` : ''} ${p.email ? `${this.#esc(p.email)}` : ''}
${p.active ? 'Active' : 'Inactive'}
${p.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('#people-form').open(null, () => this.#load()); }); s.querySelectorAll('[data-edit]').forEach(btn => { const p = this.#people.find(x => x.id === +btn.dataset.edit); btn.addEventListener('click', () => s.querySelector('#people-form').open(p, () => 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('people-list', PeopleList);