| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- import TableHeader from './components/TableHeader.js';
- import TableBody from './components/TableBody.js';
- import Pagination from './components/pagination/Pagination.js';
- import ToolBar from './components/toolbar/ToolBar.js';
- export default class DataTable {
- constructor(tableElement, options = {}) {
- if (typeof tableElement === 'string') {
- this.tableElement = document.getElementById(tableElement);
- } else {
- this.tableElement = tableElement;
- }
- this.page = 1;
- this.options = options;
- this.perPage = 25;
- this.getData();
- }
- render(data) {
- const { actions, rowActions, columns, rows, total } = data;
- this.table = document.createElement('table');
- this.table.classList.add('table');
- this.searchBar = new ToolBar((searchText) => {
- this.getData(searchText);
- }, actions, this.options);
- this.headerElement = new TableHeader(columns);
- const tableHeader = this.headerElement.render();
- this.table.appendChild(tableHeader.colgroup);
- this.table.appendChild(tableHeader.thead);
- this.pagination = new Pagination((page, perPage) => {
- this.page = page--;
- //this.perPage = perPage;
- this.getData();
- }, total, this.perPage);
- this.bodyElement = new TableBody(rows, columns, rowActions, this.options);
- this.table.appendChild(this.bodyElement.render());
- // #ToDo Convert table to div
- if (this.tableElement.tagName === 'TABLE') {
- const divContainer = document.createElement('div');
- while (this.tableElement.firstChild) {
- divContainer.appendChild(this.tableElement.firstChild);
- }
- this.tableElement.parentNode.replaceChild(divContainer, this.tableElement);
- }
- this.tableElement.appendChild(this.searchBar.render());
- this.tableElement.appendChild(this.pagination.render());
- this.tableElement.appendChild(this.table);
- }
- rerender(data) {
- const { columns, rows, rowActions, total } = data;
- if (!this.table) {
- this.render(data);
- return;
- }
- const content = new TableBody(rows, columns, rowActions, this.options).render();
- this.table.querySelector('tbody').innerHTML = content.innerHTML;
- }
- async getData() {
- let requestBody = {
- 'page': this.page - 1,
- 'pageSize': this.perPage
- }
- if(this.searchBar){
- requestBody.search = this.searchBar.getSearch();
- }
- const params = new URLSearchParams(requestBody).toString();
- const response = await fetch(this.options.url + '?' + params);
- const data = await response.json();
- this.rerender(data);
- }
- }
|