Volsatik

Untitled

May 14th, 2023
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.43 KB | None | 0 0
  1. document.addEventListener("DOMContentLoaded", function () {
  2. const inputFields = document.querySelectorAll("input[data-input-filter][data-err-msg]");
  3. inputFields.forEach(function (inputField) {
  4. setInputFilter(inputField);
  5. });
  6. });
  7.  
  8. function setTableScrollableHeight() {
  9. var windowHeight = window.innerHeight;
  10. var pageTopbarHeight = $('#page-topbar').height();
  11. $('.table-scrollable').css('height', windowHeight - 80 - pageTopbarHeight + 'px');
  12. }
  13.  
  14. window.onload = function () {
  15. setTableScrollableHeight();
  16. };
  17.  
  18. window.onresize = function () {
  19. setTableScrollableHeight();
  20. };
  21.  
  22. function scrollTopTable() {
  23. $('#lazy-table').find('tbody').scrollTop(0);
  24. }
  25.  
  26. var defaultSettings = {
  27. resource: "base/items",
  28. SELECT: "getData",
  29. sortBy: "id",
  30. sortDirection: "asc",
  31. searchString: "",
  32. has_img: "",
  33. id: "",
  34. img_md5: "",
  35. itemLabel: "",
  36. itemName: "",
  37. itemDamage: "",
  38. nbt_hash: "",
  39. itemmaxSize: "",
  40. offset: 0,
  41. limit: 50,
  42. isLoading: false,
  43. isEndOfList: false,
  44. totalRows: 0,
  45. searchReturnEmpty: false
  46. }
  47.  
  48. var settings = Object.assign({}, defaultSettings);
  49.  
  50. // функция для обновления списка товаров на странице
  51. function updateItemList(data) {
  52. var tbody = $('tbody')
  53. tbody.html(data);
  54. }
  55.  
  56.  
  57. function clearInputsValues() {
  58. // Отчистка всех поисковых полей при загрузки страницы
  59. var list = document.getElementsByClassName('input_search');
  60. var n;
  61. for (n = 0; n < list.length; ++n) {
  62. list[n].value = '';
  63. }
  64.  
  65. // Получаем все элементы select, содержащие 'select_search_' в своем class
  66. var selects = document.querySelectorAll('select[class*="select_search_"]');
  67. // Перебираем все полученные элементы select и сбрасываем их в стандартное значение
  68. for (var i = 0; i < selects.length; i++) {
  69. selects[i].value = ""; //ставлю пустое значение или же что значит NaN
  70. }
  71. }
  72.  
  73. clearInputsValues()
  74.  
  75. // выполнение запроса при загрузке страницы
  76. sendHttpRequest('GET', settings, null, function (status, data) {
  77. if (status === 'ERROR') {
  78. console.error(data);
  79. } else {
  80. updateItemList(data.html)
  81. }
  82. });
  83.  
  84. function clearAllFilters() {
  85. clearInputsValues()
  86. settings = Object.assign({}, defaultSettings);
  87. // Удаляем классы arrow-up и arrow-down у всех заголовков столбцов
  88. $(".sortable i").removeClass("mdi-arrow-up-bold mdi-arrow-down-bold test-success");
  89. sendHttpRequest('GET', settings, null, function (status, data) {
  90. if (status === 'ERROR') {
  91. console.error(data);
  92. } else {
  93. updateItemList(data.html);
  94. scrollTopTable()
  95. settings.totalRows = parseInt(data.totalRows);
  96. settings.offset += settings.limit;
  97. if (settings.offset >= settings.totalRows) {
  98. settings.isEndOfList = true;
  99. }
  100. }
  101. });
  102. }
  103.  
  104.  
  105. $('.input_search, .select_search').on('keydown change', function (event) {
  106. // Проверяем, была ли нажата клавиша Enter
  107. if (event.type === 'keydown' && event.keyCode !== 13) {
  108. return;
  109. }
  110. // Отменяем стандартное поведение браузера при нажатии Enter в поле ввода
  111. event.preventDefault();
  112.  
  113. // Получаем класс текущего элемента и извлекаем тип настройки из класса
  114. var className = $(this).attr('class');
  115. var settingType = className.substring(className.indexOf('_search_') + '_search_'.length);
  116.  
  117. // Обновляем значение свойства объекта settings соответствующее типу настройки
  118. var selectedValue = $(this).val();
  119. settings[settingType] = selectedValue;
  120.  
  121. // Сброс параметров поиска и выполнение запроса на сервер
  122. settings.offset = 0;
  123. settings.limit = 50;
  124. settings.isLoading = false;
  125. settings.isEndOfList = false;
  126. settings.totalRows = 0;
  127.  
  128. sendHttpRequest('GET', settings, null, function (status, data) {
  129. if (status === 'ERROR') {
  130. console.error(data);
  131. } else {
  132. if (data.totalRows === 0 && data.html === "") {
  133. settings.searchReturnEmpty = true
  134. var messageRow = `
  135. <tr class="td-search404" style = "background-color: inherit; pointer-events: none;">
  136. <td colspan="8" style="pointer-events: none; border:0;">
  137. <span class="warning fs-4 fw-light text-muted d-flex justify-content-center mt-5 h-100">
  138. <i class="fa fa-exclamation-triangle mt-2 me-2"></i> Ничего не найдено!
  139. </span>
  140. </td>
  141. </tr>`;
  142. $('tbody').html(messageRow);
  143. } else {
  144. settings.searchReturnEmpty = false
  145. updateItemList(data.html);
  146. settings.totalRows = parseInt(data.totalRows);
  147. settings.offset += settings.limit;
  148. if (settings.offset >= settings.totalRows) {
  149. settings.isEndOfList = true;
  150. }
  151. }
  152. }
  153. });
  154. });
  155.  
  156.  
  157. $('#lazy-table').find('tbody').on('scroll', function () {
  158. var containerHeight = $(this).height();
  159. var scrollTop = $(this).scrollTop();
  160. var contentHeight = $(this).find('tr').length * $(this).find('tr:first').height();
  161.  
  162. // Если пользователь долистал до конца контента и запрос не отправляется в текущий момент
  163. if (containerHeight + scrollTop >= contentHeight && !settings.isLoading && !settings.isEndOfList) {
  164. settings.isLoading = true; // Устанавливаем флаг isLoading в значение true
  165.  
  166. settings.offset += settings.limit; // Корректируем значение offset
  167. settings.limit = defaultSettings.limit; // Задаем новое значение limit
  168.  
  169. // Отправляем запрос на сервер
  170. sendHttpRequest('GET', settings, null, function (status, data) {
  171. settings.isLoading = false; // Сбрасываем флаг isLoading в значение false после получения ответа от сервера
  172.  
  173. if (status === 'ERROR') {
  174. console.error(data);
  175. } else {
  176. // Добавляем полученные данные в таблицу
  177. $('#lazy-table tbody').append(data.html);
  178.  
  179. // Обновляем значение totalRows
  180. settings.totalRows = parseInt(data.totalRows);
  181.  
  182. // Проверяем, что были добавлены новые элементы и не достигнут конец списка
  183. if ($('#lazy-table tbody tr').length === 0 || settings.offset >= settings.totalRows) {
  184. settings.isEndOfList = true; // Устанавливаем флаг isEndOfList в значение true, если все данные уже были получены
  185. }
  186. }
  187. });
  188. }
  189. });
  190.  
  191. function sendSortRequest(sortBy, element) {
  192. if (settings.searchReturnEmpty) {
  193. return
  194. }
  195.  
  196. settings.offset = 0;
  197. settings.limit = 50;
  198. settings.isLoading = false;
  199. settings.isEndOfList = false;
  200. settings.totalRows = 0;
  201.  
  202. // Определяем направление сортировки
  203. var sortDirection = "asc";
  204. if (sortBy === settings.sortBy && settings.sortDirection === "asc") {
  205. sortDirection = "desc";
  206. }
  207.  
  208. // Обновляем значения параметров settings перед отправкой запроса на сервер
  209. settings.sortBy = sortBy;
  210. settings.sortDirection = sortDirection;
  211.  
  212. // Удаляем классы arrow-up и arrow-down у всех заголовков столбцов
  213. $(".sortable i").removeClass("mdi-arrow-up-bold mdi-arrow-down-bold test-success");
  214.  
  215. // Добавляем или обновляем иконку внутри i-элемента для текущего заголовка столбца
  216. var icon = $(element).find("i");
  217.  
  218. if (sortDirection === "asc") {
  219. icon.attr("class", "mdi mdi-arrow-up-bold");
  220. } else {
  221. icon.attr("class", "mdi mdi-arrow-down-bold");
  222. }
  223.  
  224. sendHttpRequest('GET', settings, null, function (status, data) {
  225. if (status === 'ERROR') {
  226. console.error(data);
  227. } else {
  228. updateItemList(data.html);
  229.  
  230. // Обновляем значения параметров settings после получения новых данных
  231. settings.totalRows = parseInt(data.totalRows);
  232. settings.offset += settings.limit;
  233. if (settings.offset >= settings.totalRows) {
  234. settings.isEndOfList = true;
  235. }
  236. // Устанавливаем скролл в самый верх
  237. scrollTopTable()
  238. }
  239. });
  240. }
  241.  
  242.  
  243. function editRow(button) {
  244. const row = button.closest('tr[id*="row-"]');
  245. const id = row.id.split('-')[1];
  246.  
  247. const modal = document.createElement('div');
  248. modal.classList.add('modal', 'fade');
  249. modal.setAttribute('tabindex', '-1');
  250. modal.setAttribute('role', 'dialog');
  251. modal.setAttribute('aria-hidden', 'true');
  252.  
  253. const modalContent = document.createElement('div');
  254. modalContent.classList.add('modal-dialog', 'modal-dialog-centered');
  255. modalContent.setAttribute('role', 'document');
  256.  
  257. const modalContentWrapper = document.createElement('div');
  258. modalContentWrapper.classList.add('modal-content');
  259.  
  260. const modalHeader = document.createElement('div');
  261. modalHeader.classList.add('modal-header');
  262. const modalTitle = document.createElement('h5');
  263. modalTitle.classList.add('modal-title');
  264. modalTitle.textContent = 'Редактирование строки';
  265. modalHeader.appendChild(modalTitle);
  266. const closeButton = document.createElement('button');
  267. closeButton.classList.add('btn-close');
  268. closeButton.setAttribute('type', 'button');
  269. closeButton.setAttribute('data-bs-dismiss', 'modal');
  270. closeButton.setAttribute('aria-label', 'Close');
  271. modalHeader.appendChild(closeButton);
  272.  
  273. modalContentWrapper.appendChild(modalHeader);
  274. const modalBody = document.createElement('div');
  275. modalBody.classList.add('modal-body');
  276.  
  277. const thead = document.querySelector('thead');
  278. const inputsRow = thead.querySelector('tr:nth-child(2)');
  279. Array.from(row.cells).forEach((cell, index) => {
  280. const inputCell = inputsRow.cells[index];
  281. const inputElement = inputCell.querySelector('input,select');
  282. if (inputElement && !inputElement.hasAttribute('data-editor-disable')) {
  283. const inputType = inputElement.classList.toString().split(' ').filter(className => className.startsWith('input_search_') || className.startsWith('select_search_')).map(className => className.replace('input_search_', 'input_edit_').replace('select_search_', 'select_edit_')).join(' ');
  284. const label = thead.querySelector(`tr:first-child th:nth-child(${index + 1})`).textContent;
  285. const inputValue = inputElement.tagName === 'SELECT' ? inputElement.value : cell.textContent.trim();
  286.  
  287. const formGroup = document.createElement('div');
  288. formGroup.classList.add('mb-3');
  289. const inputLabel = document.createElement('label');
  290. inputLabel.classList.add('form-label');
  291. inputLabel.textContent = label;
  292. let input;
  293. if (inputElement.tagName === 'SELECT') {
  294. input = document.createElement('select');
  295. Array.from(inputElement.options).forEach((option) => {
  296. const newOption = document.createElement('option');
  297. newOption.value = option.value;
  298. newOption.text = option.text;
  299. if (option.value === inputValue) {
  300. newOption.selected = true;
  301. }
  302. input.appendChild(newOption);
  303. });
  304. } else {
  305. input = document.createElement('input');
  306. input.setAttribute('type', 'text');
  307. input.setAttribute('value', inputValue);
  308. // Set data attributes
  309. input.setAttribute('data-input-filter', inputElement.getAttribute('data-input-filter'));
  310. input.setAttribute('data-err-msg', inputElement.getAttribute('data-err-msg'));
  311. // Apply input filter
  312. setInputFilter(input);
  313. }
  314. input.classList.add('form-control', inputType);
  315.  
  316. formGroup.appendChild(inputLabel);
  317. formGroup.appendChild(input);
  318. modalBody.appendChild(formGroup);
  319. }
  320. });
  321.  
  322. modalContentWrapper.appendChild(modalBody);
  323.  
  324. const modalFooter = document.createElement('div');
  325. modalFooter.classList.add('modal-footer');
  326. const saveButton = document.createElement('button');
  327. saveButton.classList.add('btn', 'btn-primary');
  328. saveButton.textContent = 'Сохранить';
  329.  
  330. saveButton.addEventListener('click', () => {
  331. const rowData = {};
  332. Array.from(modal.querySelectorAll('input,select')).forEach((input) => {
  333. const inputType = input.classList.toString().split(' ').find((className) => className.startsWith('input_edit_') || className.startsWith('select_edit_'));
  334. if (inputType) {
  335. const key = inputType.replace('input_edit_', '').replace('select_edit_', '');
  336. rowData[key] = input.tagName === 'SELECT' ? input.value : input.value.trim();
  337. }
  338. });
  339. sendHttpRequest(
  340. 'UPDATE',
  341. `/api/?resource=${settings.resource}&id=${id}`,
  342. rowData,
  343. function (status, data) {
  344. if (status === 'ERROR') {
  345. console.error(data);
  346. } else {
  347. row.outerHTML = data;
  348.  
  349. // addRow(parseInt(id))
  350. modal.remove();
  351. bootstrapModal.hide();
  352. }
  353. }
  354. );
  355. });
  356. modalFooter.appendChild(saveButton);
  357.  
  358. const cancelButton = document.createElement('button');
  359. cancelButton.classList.add('btn', 'btn-secondary');
  360. cancelButton.textContent = 'Отмена';
  361. cancelButton.setAttribute('type', 'button');
  362. cancelButton.setAttribute('data-bs-dismiss', 'modal');
  363. modalFooter.appendChild(cancelButton);
  364.  
  365. modalContentWrapper.appendChild(modalFooter);
  366. modalContent.appendChild(modalContentWrapper);
  367. modal.appendChild(modalContent);
  368. document.body.appendChild(modal);
  369.  
  370. const bootstrapModal = new bootstrap.Modal(modal);
  371. $(modal).on('hidden.bs.modal', function () {
  372. addRow(parseInt(id));
  373. });
  374. bootstrapModal.show();
  375.  
  376. }
  377.  
  378. function addRow(element) {
  379. if (window.innerWidth > 600) { // добавляем проверку на ширину экрана
  380. return;
  381. }
  382. let rowId;
  383. var isObj = true;
  384.  
  385. if (typeof element === 'object') {
  386. rowId = element.parentNode.id;
  387. var newRowId = `rowM-${rowId.slice(4)}`;
  388. const existingRow = document.getElementById(newRowId);
  389. if (existingRow) {
  390. existingRow.parentNode.removeChild(existingRow);
  391. return;
  392. }
  393. var trInnerHTML = element.parentNode.innerHTML;
  394. } else {
  395. isObj = false
  396. rowId = element;
  397. var newRowId = `rowM-${rowId}`;
  398. element = document.getElementById(`row-${rowId}`);
  399. var trInnerHTML = document.querySelector(`#row-${rowId}`).innerHTML;
  400. }
  401.  
  402. const newRow = document.createElement('tr');
  403. newRow.id = newRowId;
  404. newRow.innerHTML = trInnerHTML;
  405.  
  406. newRow.style.display = 'block';
  407. const newTds = newRow.querySelectorAll('td');
  408. const ths = document.getElementsByTagName('thead')[0].querySelectorAll('th');
  409. for (let i = 0; i < newTds.length; i++) {
  410. newTds[i].classList.add('td');
  411.  
  412. const content = document.createTextNode(ths[i].textContent);
  413. const beforeElem = document.createElement('div');
  414. beforeElem.classList.add('th-content');
  415. beforeElem.appendChild(content);
  416. newTds[i].insertBefore(beforeElem, newTds[i].firstChild);
  417.  
  418. newTds[i].style.display = 'block';
  419. }
  420.  
  421. const tds = newRow.querySelectorAll('td.m-transform');
  422. for (let i = 0; i < tds.length; i++) {
  423. tds[i].parentNode.removeChild(tds[i]);
  424. }
  425.  
  426. if (isObj) {
  427. element.parentNode.parentNode.insertBefore(newRow, element.parentNode.nextSibling);
  428. } else {
  429. const existingRow = document.getElementById(`rowM-${rowId}`);
  430. // Если существующий элемент найден, заменяем его на новый элемент
  431. if (existingRow) {
  432. existingRow.replaceWith(newRow);
  433. }
  434. }
  435. }
  436.  
  437.  
  438.  
Advertisement
Add Comment
Please, Sign In to add comment