templates/js/library/data_table_wrapper/data_table_wrapper.js line 1

Open in your IDE?
  1. class DataTableWrapper {
  2.     options = {};
  3.     selector = null;
  4.     table = null;
  5.     eventDispatcher = null;
  6.     columnIds = {};
  7.     searchStringHandlerRegistry = null;
  8.     static EVENTS = {
  9.         ON_TABLE_FILTERED: 'tableFiltered'
  10.     };
  11.     constructor(selector, options = {}) {
  12.         this.selector = selector;
  13.         this.options = {
  14.             dom: 'i lfrtip',   // i = info сверху
  15.             "lengthMenu": [[10, 20, 30, 50, 100, 200, 300, 500, 700, -1], [10, 20, 30, 50, 100, 200, 300, 500, 700, "Все"]],
  16.             language: {
  17.                 url: '/js/vendor/datatables/ru.json'
  18.             },
  19.             drawRowNumbersForColIndex: undefined,
  20.             searchPrehandler: null, // Function to preprocess search terms before applying search
  21.             ...options
  22.         };
  23.         this.eventDispatcher = new EventDispatcher();
  24.         let $head = $(this.selector).find('thead');
  25.         let i = -1;
  26.         const me = this;
  27.         $head.find('th').each(function (){
  28.             i++;
  29.             let colId = $(this).data('table-col-id');
  30.             me.columnIds[i] = colId;
  31.         });
  32.     }
  33.     static getOptionsExample() {
  34.         return {
  35.             "lengthMenu": [[10, 20, 50, 100, 200, 300, 500, 700, -1], [10, 20, 50, 100, 200, 300, 500, 700, "Все"]],
  36.             "pageLength": 10, // Number of rows to display by default
  37.             "columnDefs": [ // Columns definitions
  38.                 {
  39.                     "targets": 0,
  40.                     "type": "num",
  41.                     "visible": false,
  42.                 },
  43.                 {
  44.                     "targets": 1,
  45.                     "type": "date-d-m-Y"
  46.                 },
  47.             ],
  48.             drawRowNumbersForColIndex: 0,
  49.             "searchPrehandler": (searchTerm) => {
  50.                 // Example: if user enters "111", search for both "111" and "222"
  51.                 if (searchTerm === '111') {
  52.                     return '111|222';
  53.                 }
  54.                 return searchTerm;
  55.             },
  56.             "dropdownFiltersConfig": {
  57.                 "elementsData": [
  58.                     {
  59.                         "columnIndex": 2, //3th column
  60.                         "dropdownId": "departmentDropdown", // Dropdown button ID
  61.                         "badgeId": "departmentBadge", // Badge ID to show filter status (optional)
  62.                         "textForAll": "All" // Text to show when 'all' is selected (optional)
  63.                     },
  64.                 ]
  65.             },
  66.         }
  67.     }
  68.     getColumnIndexByColumnId(colId) {
  69.         for (let index in this.columnIds) {
  70.             if (this.columnIds[index] === colId) {
  71.                 return parseInt(index);
  72.             }
  73.         }
  74.         return -1;
  75.     }
  76.     getAllFilteredTableData() {
  77.         let allData = [];
  78.         this.table.rows({ search: 'applied' }).every((rowIdx) => {
  79.             let row = this.table.row(rowIdx);
  80.             allData.push(row.data());
  81.         });
  82.         return allData;
  83.     }
  84.     getFilteredData() {
  85.         return this.table.rows({ search: 'applied', order: 'applied' }).data().toArray();
  86.     }
  87.     getHeadElement() {
  88.         return $(this.table.table().header());
  89.     }
  90.     downloadCsv(filename = 'data_table_export.csv') {
  91.         const delimiter = ';';
  92.         const rows = [];
  93.         // collect headers and escape
  94.         const headers = [];
  95.         this.table.columns().every((index) => {
  96.             const $header = $(this.table.column(index).header());
  97.             if ($header.is('[data-export-exclude-col]')) return;
  98.             const raw = $header.text();
  99.             const safe = String(raw).replace(/"/g, '""');
  100.             headers.push(`"${safe}"`);
  101.         });
  102.         rows.push(headers.join(delimiter));
  103.         // collect rows (respect search: 'applied')
  104.         let number = 0;
  105.         this.table.rows({ search: 'applied' }).every((rowIdx) => {
  106.             const row = this.table.row(rowIdx);
  107.             const rowData = [];
  108.             row.columns().every((colIdx) => {
  109.                 const $header = $(this.table.column(colIdx).header());
  110.                 if ($header.is('[data-export-exclude-col]')) return;
  111.                 let cell = row.data()[colIdx];
  112.                 if (this.options.drawRowNumbersForColIndex === colIdx) {
  113.                     cell = ++number;
  114.                 }
  115.                 const raw = cell === null || cell === undefined ? '' : String(cell);
  116.                 const safe = raw.replace(/"/g, '""');
  117.                 rowData.push(`"${safe}"`);
  118.             });
  119.             rows.push(rowData.join(delimiter));
  120.         });
  121.         // Join with CRLF for Windows compatibility and prefix with UTF-8 BOM
  122.         const csvString = '\uFEFF' + rows.join('\r\n');
  123.         const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
  124.         const link = document.createElement('a');
  125.         if (link.download !== undefined) {
  126.             const url = URL.createObjectURL(blob);
  127.             link.setAttribute('href', url);
  128.             link.setAttribute('download', filename);
  129.             link.style.visibility = 'hidden';
  130.             document.body.appendChild(link);
  131.             link.click();
  132.             document.body.removeChild(link);
  133.         }
  134.     }
  135.     initDataTable() {
  136.         let columnDefs = [];
  137.         let dropdownFiltersConfig = {
  138.             elementsData: []
  139.         };
  140.         const me = this;
  141.         $(`${this.selector} th`).each(function(index) {
  142.             let hideCol = $(this).is('[data-table-hide-col]');
  143.             let tableType = $(this).data('table-type');
  144.             let sortOff = $(this).is('[data-table-sort-off]');
  145.             if ($(this).is('[data-table-default-sort-col]') && (!me.options.order || me.options.order.length === 0) && !sortOff) {
  146.                 me.options.order = [[index, 'asc']];
  147.             }
  148.             let optionsItem = {
  149.                 "targets": index,
  150.             };
  151.             if (hideCol) {
  152.                 optionsItem['visible'] = false;
  153.             }
  154.             if (tableType) {
  155.                 optionsItem['type'] = tableType;
  156.             }
  157.             if (sortOff) {
  158.                 optionsItem['orderable'] = false;
  159.             }
  160.             if (Object.keys(optionsItem).length > 1) {
  161.                 columnDefs.push(optionsItem);
  162.             }
  163.             let dropdownFilterConfig_elementsDataItem = {};
  164.             let dropdownId = $(this).data('table-dropdown-id');
  165.             if (dropdownId) {
  166.                 dropdownFilterConfig_elementsDataItem['columnIndex'] = index;
  167.                 dropdownFilterConfig_elementsDataItem['dropdownId'] = dropdownId;
  168.                 let badgeId = $(this).data('table-badge-id');
  169.                 if (badgeId) {
  170.                     dropdownFilterConfig_elementsDataItem['badgeId'] = badgeId;
  171.                 }
  172.                 let textForAll = $(this).data('table-dropdown-text-for-all');
  173.                 if (textForAll) {
  174.                     dropdownFilterConfig_elementsDataItem['textForAll'] = textForAll;
  175.                 }
  176.                 dropdownFiltersConfig.elementsData.push(dropdownFilterConfig_elementsDataItem);
  177.             }
  178.             let uniqueValues = $(this).data('table-dropdown-values');
  179.             if (uniqueValues) {
  180.                 uniqueValues = uniqueValues.split('|').map(v => v.trim());
  181.                 dropdownFilterConfig_elementsDataItem['uniqueValues'] = uniqueValues;
  182.             }
  183.         });
  184.         if (!this.options.columnDefs || this.options.columnDefs.length === 0) {
  185.             console.log(columnDefs)
  186.             this.options.columnDefs = columnDefs;
  187.         }
  188.         if (dropdownFiltersConfig && (!this.options.dropdownFiltersConfig
  189.             || !this.options.dropdownFiltersConfig.elementsData
  190.             || this.options.dropdownFiltersConfig.elementsData.length === 0)) {
  191.             this.options.dropdownFiltersConfig = dropdownFiltersConfig;
  192.         }
  193.         const originalInitComplete = this.options.initComplete;
  194.         this.options.initComplete = function(settings, json) {
  195.             if (originalInitComplete) {
  196.                 originalInitComplete.call(this, settings, json);
  197.             }
  198.             me.overrideSearchEngine(settings);
  199.         };
  200.         this.table = $(this.selector).DataTable(this.options);
  201.         $(document).ready(() => {
  202.             this.populateDropdowns();
  203.             this.table.on('draw', () => {
  204.                 this.populateDropdowns();
  205.             });
  206.         });
  207.         this.eventDispatcher.addEventListener(DataTableWrapper.EVENTS.ON_TABLE_FILTERED, () => {
  208.             if (this.options.drawRowNumbersForColIndex !== null && this.options.drawRowNumbersForColIndex !== undefined) {
  209.                 this.drawRowNumbers();
  210.             }
  211.         });
  212.         return this.table;
  213.     }
  214.     overrideSearchEngine(settings) {
  215.         const dataTableApi = new DataTableApi(settings);
  216.         this.searchStringHandlerRegistry = new SearchStringHandlerRegistry(dataTableApi);
  217.         this.enableEngToRuKeyboardLayoutSearch();
  218.         if (this.options.searchPrehandler) {
  219.             this.addSearchTextCallbackHandler(this.options.searchPrehandler);
  220.         }
  221.     }
  222.     enableEngToRuKeyboardLayoutSearch() {
  223.         new EnableEngToRuKeyboardLayoutSearchHandler(
  224.             this.searchStringHandlerRegistry
  225.         ).handle();
  226.         return this;
  227.     }
  228.     addSearchTextCallbackHandler(searchPrehandler) {
  229.         new AddSearchTextCallbackHandler(
  230.             this.searchStringHandlerRegistry,
  231.             searchPrehandler
  232.         ).handle();
  233.         return this;
  234.     }
  235.     drawRowNumbers() {
  236.         this.table.column(this.options.drawRowNumbersForColIndex, { search: 'applied' }).nodes().each(function(cell, i) {
  237.             cell.innerHTML = i + 1;
  238.         });
  239.     }
  240.     populateDropdowns() {
  241.         if (this.options.dropdownFiltersConfig && this.options.dropdownFiltersConfig.elementsData) {
  242.             this.options.dropdownFiltersConfig.elementsData.forEach((options) => {
  243.                 this.populateDropdown(options);
  244.             });
  245.         }
  246.     }
  247.     populateDropdown(options) {
  248.         const me = this;
  249.         options = {
  250.             columnIndex: null,
  251.             dropdownId: null,
  252.             badgeId: null,
  253.             textForAll: 'Все',
  254.             uniqueValues: null,
  255.             ...options
  256.         };
  257.         var dropdownButton = $("#" + options.dropdownId);
  258.         var dropdownMenu = dropdownButton.next('.dropdown-menu');
  259.         // Read multiple flag from data attribute on button (template sets data-multiple)
  260.         var isMultiple = false;
  261.         try {
  262.             var dataMultiple = dropdownButton.data('multiple');
  263.             if (typeof dataMultiple === 'boolean') {
  264.                 isMultiple = dataMultiple;
  265.             } else if (typeof dataMultiple === 'string') {
  266.                 isMultiple = dataMultiple === 'true';
  267.             }
  268.         } catch (e) {
  269.             isMultiple = false;
  270.         }
  271.         // Get unique values from column
  272.         if (!options.uniqueValues) {
  273.             options.uniqueValues = this.table
  274.                 .column(options.columnIndex)
  275.                 .data()
  276.                 .unique()
  277.                 .sort()
  278.                 .toArray();
  279.         }
  280.         // Remove previously generated non-all items
  281.         dropdownMenu.find('.dropdown-item:not([data-filter="all"])').remove();
  282.         // Append new items (галочка вместо checkbox)
  283.         options.uniqueValues.forEach(function(value) {
  284.             var item = $('<a class="dropdown-item d-flex align-items-center" href="#" role="menuitem" aria-pressed="false"></a>');
  285.             item.attr('data-filter', value);
  286.             // Общий контейнер с галочкой (скрыт до выбора)
  287.             var checkWrap = $('<span class="filter-check me-2" style="visibility:hidden;"></span>');
  288.             var checkIcon = $('<i class="fas fa-check text-white"></i>');
  289.             checkWrap.append(checkIcon);
  290.             var textSpan = $('<span class="filter-text"></span>').text(value);
  291.             item.append(checkWrap).append(textSpan);
  292.             dropdownMenu.append(item);
  293.         });
  294.         // Ensure no duplicate handlers
  295.         dropdownMenu.find('.dropdown-item').off('click');
  296.         var selectedValues = dropdownButton.data('selectedValues') || [];
  297.         function updateCheckMark($el, selected) {
  298.             var wrap = $el.find('.filter-check');
  299.             if (!wrap.length) return;
  300.             if (selected) {
  301.                 wrap.css('visibility', 'visible');
  302.                 $el.addClass('active').attr('aria-pressed', 'true');
  303.             } else {
  304.                 wrap.css('visibility', 'hidden');
  305.                 $el.removeClass('active').attr('aria-pressed', 'false');
  306.             }
  307.         }
  308.         // Initialize existing selections
  309.         if (selectedValues && selectedValues.length > 0) {
  310.             dropdownMenu.find('.dropdown-item:not([data-filter="all"])').each(function() {
  311.                 var $it = $(this);
  312.                 var val = $it.data('filter');
  313.                 updateCheckMark($it, selectedValues.indexOf(val) !== -1);
  314.             });
  315.             if (selectedValues.length === 1) {
  316.                 dropdownButton.text(selectedValues[0]);
  317.                 if (options.badgeId) $(options.badgeId).removeClass('d-none').text('Filter: ' + selectedValues[0]);
  318.             } else {
  319.                 dropdownButton.text(selectedValues.length + ' выбрано');
  320.                 if (options.badgeId) $(options.badgeId).removeClass('d-none').text('Filter: ' + selectedValues.length);
  321.             }
  322.         } else {
  323.             dropdownButton.text(options.textForAll || 'Все');
  324.             if (options.badgeId) $(options.badgeId).addClass('d-none');
  325.         }
  326.         dropdownMenu.find('.dropdown-item').on('click', function(e) {
  327.             e.preventDefault();
  328.             var $el = $(this);
  329.             var filterValue = $el.data('filter');
  330.             if (!isMultiple) {
  331.                 if (filterValue === 'all') {
  332.                     dropdownButton.data('selectedValues', []);
  333.                     dropdownMenu.find('.dropdown-item:not([data-filter="all"])').each(function(){ updateCheckMark($(this), false); });
  334.                     dropdownButton.text(options.textForAll || 'Все');
  335.                     if (options.badgeId) $(options.badgeId).addClass('d-none');
  336.                     me.table.column(options.columnIndex).search('').draw();
  337.                 } else {
  338.                     dropdownButton.data('selectedValues', [filterValue]);
  339.                     dropdownMenu.find('.dropdown-item:not([data-filter="all"])').each(function(){
  340.                         var $other = $(this);
  341.                         updateCheckMark($other, $other.data('filter') === filterValue);
  342.                     });
  343.                     dropdownButton.text(filterValue);
  344.                     if (options.badgeId) $(options.badgeId).removeClass('d-none').text('Filter: ' + filterValue);
  345.                     let esc = StringUtils.escapeRegex(filterValue);
  346.                     me.table.column(options.columnIndex).search('^' + esc + '$', true, false).draw();
  347.                 }
  348.             } else {
  349.                 if (filterValue === 'all') {
  350.                     selectedValues = [];
  351.                     dropdownButton.data('selectedValues', selectedValues);
  352.                     dropdownMenu.find('.dropdown-item:not([data-filter="all"])').each(function(){ updateCheckMark($(this), false); });
  353.                     dropdownButton.text(options.textForAll || 'Все');
  354.                     if (options.badgeId) $(options.badgeId).addClass('d-none');
  355.                     me.table.column(options.columnIndex).search('').draw();
  356.                 } else {
  357.                     var idx = selectedValues.indexOf(filterValue);
  358.                     if (idx === -1) {
  359.                         selectedValues.push(filterValue);
  360.                         updateCheckMark($el, true);
  361.                     } else {
  362.                         selectedValues.splice(idx, 1);
  363.                         updateCheckMark($el, false);
  364.                     }
  365.                     if (selectedValues.length === 0) {
  366.                         dropdownButton.text(options.textForAll || 'Все');
  367.                         if (options.badgeId) $(options.badgeId).addClass('d-none');
  368.                         dropdownButton.data('selectedValues', selectedValues);
  369.                         me.table.column(options.columnIndex).search('').draw();
  370.                     } else {
  371.                         if (selectedValues.length === 1) {
  372.                             dropdownButton.text(selectedValues[0]);
  373.                             if (options.badgeId) $(options.badgeId).removeClass('d-none').text('Filter: ' + selectedValues[0]);
  374.                         } else {
  375.                             dropdownButton.text(selectedValues.length + ' выбрано');
  376.                             if (options.badgeId) $(options.badgeId).removeClass('d-none').text('Filter: ' + selectedValues.length);
  377.                         }
  378.                         var escaped = selectedValues.map(function(v){ return StringUtils.escapeRegex(v); });
  379.                         var regex = '^(' + escaped.join('|') + ')$';
  380.                         dropdownButton.data('selectedValues', selectedValues);
  381.                         me.table.column(options.columnIndex).search(regex, true, false).draw();
  382.                     }
  383.                 }
  384.             }
  385.             me.eventDispatcher.emit(DataTableWrapper.EVENTS.ON_TABLE_FILTERED);
  386.         });
  387.     }
  388. }