import { gettext } from "django"; import { CSSResult, html, LitElement, property, TemplateResult } from "lit-element"; import { PBResponse } from "../../api/Client"; import { COMMON_STYLES } from "../../common/styles"; import "./TablePagination"; import "../EmptyState"; export abstract class Table extends LitElement { abstract apiEndpoint(page: number): Promise>; abstract columns(): Array; abstract row(item: T): Array; // eslint-disable-next-line @typescript-eslint/no-unused-vars renderExpanded(item: T): TemplateResult { if (this.expandable) { throw new Error("Expandable is enabled but renderExpanded is not overridden!"); } return html``; } @property({attribute: false}) data?: PBResponse; @property({type: Number}) page = 1; @property({type: Boolean}) expandable = false; @property({attribute: false}) expandedRows: boolean[] = []; static get styles(): CSSResult[] { return COMMON_STYLES; } constructor() { super(); this.addEventListener("ak-refresh", () => { this.fetch(); }); } public fetch(): void { this.apiEndpoint(this.page).then((r) => { this.data = r; this.page = r.pagination.current; }); } private renderLoading(): TemplateResult { return html`

${gettext("Loading")}

`; } renderEmpty(inner?: TemplateResult): TemplateResult { return html`
${inner ? inner : html``}
`; } private renderRows(): TemplateResult[] | undefined { if (!this.data) { return; } if (this.data.pagination.count === 0) { return [this.renderEmpty()]; } return this.data.results.map((item: T, idx: number) => { if ((this.expandedRows.length - 1) < idx) { this.expandedRows[idx] = false; } return html` ${this.expandable ? html` ` : html``} ${this.row(item).map((col) => { return html`${col}`; })} ${this.renderExpanded(item)} `; }); } renderToolbar(): TemplateResult { return html` `; } renderTable(): TemplateResult { if (!this.data) { this.fetch(); } return html`
${this.renderToolbar()}
{this.page = page; }}>
${this.expandable ? html``)} ${this.data ? this.renderRows() : this.renderLoading()}
` : html``} ${this.columns().map((col) => html`${gettext(col)}
{ this.page = page; }}>
`; } render(): TemplateResult { return this.renderTable(); } }