index.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import TableHeader from './components/TableHeader.js';
  2. import TableBody from './components/TableBody.js';
  3. import Pagination from './components/pagination/Pagination.js';
  4. import ToolBar from './components/toolbar/ToolBar.js';
  5. export default class DataTable {
  6. constructor(tableElement, options = {}) {
  7. if (typeof tableElement === 'string') {
  8. this.tableElement = document.getElementById(tableElement);
  9. } else {
  10. this.tableElement = tableElement;
  11. }
  12. this.page = 1;
  13. this.options = options;
  14. this.perPage = 25;
  15. this.getData();
  16. }
  17. render(data) {
  18. const { actions, rowActions, columns, rows, total } = data;
  19. this.table = document.createElement('table');
  20. this.table.classList.add('table', 'table-responsive');
  21. this.searchBar = new ToolBar((searchText) => {
  22. this.getData(searchText);
  23. }, actions, this.options);
  24. this.pagination = new Pagination((page, perPage) => {
  25. this.page = page--;
  26. //this.perPage = perPage;
  27. this.getData();
  28. }, total, this.perPage);
  29. this.headerElement = new TableHeader(columns);
  30. const tableHeader = this.headerElement.render();
  31. this.table.appendChild(tableHeader.colgroup);
  32. this.table.appendChild(tableHeader.thead);
  33. this.bodyElement = new TableBody(rows, columns, rowActions, this.options);
  34. this.table.appendChild(this.bodyElement.render());
  35. // #ToDo Convert table to div
  36. if (this.tableElement.tagName === 'TABLE') {
  37. const divContainer = document.createElement('div');
  38. while (this.tableElement.firstChild) {
  39. divContainer.appendChild(this.tableElement.firstChild);
  40. }
  41. this.tableElement.parentNode.replaceChild(divContainer, this.tableElement);
  42. }
  43. this.tableElement.appendChild(this.searchBar.render());
  44. this.tableElement.appendChild(this.pagination.render());
  45. this.tableElement.appendChild(this.table);
  46. }
  47. rerender(data) {
  48. const { columns, rows, rowActions, total } = data;
  49. if (!this.table) {
  50. this.render(data);
  51. return;
  52. }
  53. const content = new TableBody(rows, columns, rowActions, this.options).render();
  54. this.table.querySelector('tbody').innerHTML = content.innerHTML;
  55. }
  56. async getData() {
  57. let requestBody = {
  58. 'page': this.page - 1,
  59. 'pageSize': this.perPage
  60. }
  61. if(this.searchBar){
  62. requestBody.search = this.searchBar.getSearch();
  63. }
  64. const params = new URLSearchParams(requestBody).toString();
  65. const response = await fetch(this.options.url + '?' + params);
  66. const data = await response.json();
  67. this.rerender(data);
  68. }
  69. }