import { createTranslationFunc } from '../utils'; const t = createTranslationFunc({ pl_PL: { Loading: 'Wczytywanie', 'Previous page': 'Poprzednia strona', 'Next page': 'Następna strona', 'Something went wrong while loading the data': 'Coś poszło nie tak podczas wczytywania danych', }, }); export type DialogTableColumn = { header: string; accessor: (row: T, index: number, rows: T[]) => string; }; export type LoadDataResult = { data: T[]; total: number; }; export class DialogTable { prevPageId: string; selectId: string; nextPageId: string; constructor( private readonly id: string, private readonly columns: DialogTableColumn[], private readonly limit: number, private readonly loadData: ( page: number, limit: number ) => Promise> ) { this.prevPageId = `${this.id}_page_prev`; this.selectId = `${this.id}_page_select`; this.nextPageId = `${this.id}_page_next`; } public async render() { await this.renderPage(1); } private async renderPage(page: number) { window.Dialog.show(`${this.id}_loading`, `

${t('Loading')}...

`); try { const { data, total } = await this.loadData(page, this.limit); window.Dialog.show( this.id, ` ${this.buildPagination(page, total)} ${this.buildTable(data)} ` ); this.addEventListeners(page); } catch (err) { console.error(err); window.Dialog.close(); window.UI.ErrorMessage(t('Something went wrong while loading the data')); } } private buildPagination(page: number, total: number): string { const maxPage = Math.ceil(total / this.limit); const pageOpts = []; for (let i = 1; i <= (page > maxPage ? page : maxPage); i++) { pageOpts.push( `${i}` ); } return `
`; } private buildTable(data: T[]) { return ` ${this.columns.map((col) => ``).join('')} ${data .map( (r, index) => ` ${this.columns .map((col) => ``) .join('')} ` ) .join('')}
${col.header}
${col.accessor(r, index, data)}
`; } private addEventListeners(page: number) { document .querySelector('#' + this.prevPageId) ?.addEventListener('click', () => { this.renderPage(page - 1); }); document .querySelector('#' + this.selectId) ?.addEventListener('change', (e: Event) => { if (!(e.currentTarget instanceof HTMLSelectElement)) { return; } this.renderPage(parseInt(e.currentTarget.value)); }); document .querySelector('#' + this.nextPageId) ?.addEventListener('click', () => { this.renderPage(page + 1); }); } }