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 Cursor = { next?: string; self?: string; }; export type LoadDataResult = { cursor?: Cursor; data: T[]; }; export class DialogTable { private readonly prevPageId: string; private readonly nextPageId: string; private readonly prevCursors: Cursor[] = []; constructor( private readonly id: string, private readonly columns: DialogTableColumn[], private readonly limit: number, private readonly loadData: ( cursor: string | undefined, limit: number ) => Promise> ) { this.prevPageId = `${this.id}_page_prev`; this.nextPageId = `${this.id}_page_next`; } public async render() { await this.renderPage(); } private async renderPage(pageCursor?: string) { window.Dialog.show(this.id, `

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

`); try { const { data, cursor } = await this.loadData(pageCursor, this.limit); window.Dialog.show( this.id, ` ${this.buildPagination(cursor)} ${this.buildTable(data)} ` ); this.addEventListeners(cursor); } catch (err) { console.error(err); window.Dialog.close(); window.UI.ErrorMessage(t('Something went wrong while loading the data')); } } private buildPagination(cursor?: Cursor): string { 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(cursor?: Cursor) { document .querySelector('#' + this.prevPageId) ?.addEventListener('click', () => { const prev = this.prevCursors.pop(); if (!prev) { return; } this.renderPage(prev.self); }); document .querySelector('#' + this.nextPageId) ?.addEventListener('click', () => { if (!cursor) { return; } this.prevCursors.push(cursor); this.renderPage(cursor.next); }); } }