script.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. const webroot = document.querySelector("meta[name='webroot']").content;
  2. const fileInput = document.querySelector('input[type="file"]');
  3. const dropZone = document.getElementById("dropzone");
  4. const convertButton = document.querySelector("input[type='submit']");
  5. const fileNames = [];
  6. let fileType;
  7. dropZone.addEventListener("dragover", () => {
  8. dropZone.classList.add("dragover");
  9. });
  10. dropZone.addEventListener("dragleave", () => {
  11. dropZone.classList.remove("dragover");
  12. });
  13. dropZone.addEventListener("drop", () => {
  14. dropZone.classList.remove("dragover");
  15. });
  16. const selectContainer = document.querySelector("form .select_container");
  17. const updateSearchBar = () => {
  18. const convertToInput = document.querySelector(
  19. "input[name='convert_to_search']",
  20. );
  21. const convertToPopup = document.querySelector(".convert_to_popup");
  22. const convertToGroupElements = document.querySelectorAll(".convert_to_group");
  23. const convertToGroups = {};
  24. const convertToElement = document.querySelector("select[name='convert_to']");
  25. const showMatching = (search) => {
  26. for (const [targets, groupElement] of Object.values(convertToGroups)) {
  27. let matchingTargetsFound = 0;
  28. for (const target of targets) {
  29. if (target.dataset.target.includes(search)) {
  30. matchingTargetsFound++;
  31. target.classList.remove("hidden");
  32. target.classList.add("flex");
  33. } else {
  34. target.classList.add("hidden");
  35. target.classList.remove("flex");
  36. }
  37. }
  38. if (matchingTargetsFound === 0) {
  39. groupElement.classList.add("hidden");
  40. groupElement.classList.remove("flex");
  41. } else {
  42. groupElement.classList.remove("hidden");
  43. groupElement.classList.add("flex");
  44. }
  45. }
  46. };
  47. for (const groupElement of convertToGroupElements) {
  48. const groupName = groupElement.dataset.converter;
  49. const targetElements = groupElement.querySelectorAll(".target");
  50. const targets = Array.from(targetElements);
  51. for (const target of targets) {
  52. target.onmousedown = () => {
  53. convertToElement.value = target.dataset.value;
  54. convertToInput.value = `${target.dataset.target} using ${target.dataset.converter}`;
  55. convertButton.disabled = false;
  56. showMatching("");
  57. };
  58. }
  59. convertToGroups[groupName] = [targets, groupElement];
  60. }
  61. convertToInput.addEventListener("input", (e) => {
  62. showMatching(e.target.value.toLowerCase());
  63. });
  64. convertToInput.addEventListener("search", () => {
  65. // when the user clears the search bar using the 'x' button
  66. convertButton.disabled = true;
  67. });
  68. convertToInput.addEventListener("blur", (e) => {
  69. // Keep the popup open even when clicking on a target button
  70. // for a split second to allow the click to go through
  71. if (e?.relatedTarget?.classList?.contains("target")) {
  72. convertToPopup.classList.add("hidden");
  73. convertToPopup.classList.remove("flex");
  74. return;
  75. }
  76. convertToPopup.classList.add("hidden");
  77. convertToPopup.classList.remove("flex");
  78. });
  79. convertToInput.addEventListener("focus", () => {
  80. convertToPopup.classList.remove("hidden");
  81. convertToPopup.classList.add("flex");
  82. });
  83. };
  84. // Add a 'change' event listener to the file input element
  85. fileInput.addEventListener("change", (e) => {
  86. // Get the selected files from the event target
  87. const files = e.target.files;
  88. // Select the file-list table
  89. const fileList = document.querySelector("#file-list");
  90. // Loop through the selected files
  91. for (const file of files) {
  92. // Create a new table row for each file
  93. const row = document.createElement("tr");
  94. row.innerHTML = `
  95. <td>${file.name}</td>
  96. <td>${(file.size / 1024).toFixed(2)} kB</td>
  97. <td><a onclick="deleteRow(this)">Remove</a></td>
  98. `;
  99. if (!fileType) {
  100. fileType = file.name.split(".").pop();
  101. fileInput.setAttribute("accept", `.${fileType}`);
  102. setTitle();
  103. // choose the option that matches the file type
  104. // for (const option of convertFromSelect.children) {
  105. // console.log(option.value);
  106. // if (option.value === fileType) {
  107. // option.selected = true;
  108. // }
  109. // }
  110. fetch(`${webroot}/conversions`, {
  111. method: "POST",
  112. body: JSON.stringify({ fileType: fileType }),
  113. headers: {
  114. "Content-Type": "application/json",
  115. },
  116. })
  117. .then((res) => res.text())
  118. .then((html) => {
  119. selectContainer.innerHTML = html;
  120. updateSearchBar();
  121. })
  122. .catch((err) => console.log(err));
  123. }
  124. // Append the row to the file-list table
  125. fileList.appendChild(row);
  126. // Append the file to the hidden input
  127. fileNames.push(file.name);
  128. }
  129. uploadFiles(files);
  130. });
  131. const setTitle = () => {
  132. const title = document.querySelector("h1");
  133. title.textContent = `Convert ${fileType ? `.${fileType}` : ""}`;
  134. };
  135. // Add a onclick for the delete button
  136. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  137. const deleteRow = (target) => {
  138. const filename = target.parentElement.parentElement.children[0].textContent;
  139. const row = target.parentElement.parentElement;
  140. row.remove();
  141. // remove from fileNames
  142. const index = fileNames.indexOf(filename);
  143. fileNames.splice(index, 1);
  144. // if fileNames is empty, reset fileType
  145. if (fileNames.length === 0) {
  146. fileType = null;
  147. fileInput.removeAttribute("accept");
  148. setTitle();
  149. }
  150. fetch(`${webroot}/delete`, {
  151. method: "POST",
  152. body: JSON.stringify({ filename: filename }),
  153. headers: {
  154. "Content-Type": "application/json",
  155. },
  156. })
  157. .then((res) => res.json())
  158. .then((data) => {
  159. console.log(data);
  160. })
  161. .catch((err) => console.log(err));
  162. };
  163. const uploadFiles = (files) => {
  164. convertButton.disabled = true;
  165. convertButton.textContent = "Uploading...";
  166. const formData = new FormData();
  167. for (const file of files) {
  168. formData.append("file", file, file.name);
  169. }
  170. fetch(`${webroot}/upload`, {
  171. method: "POST",
  172. body: formData,
  173. })
  174. .then((res) => res.json())
  175. .then((data) => {
  176. convertButton.disabled = false;
  177. convertButton.textContent = "Convert";
  178. console.log(data);
  179. })
  180. .catch((err) => console.log(err));
  181. };
  182. const formConvert = document.querySelector(`form[action='${webroot}/convert']`);
  183. formConvert.addEventListener("submit", () => {
  184. const hiddenInput = document.querySelector("input[name='file_names']");
  185. hiddenInput.value = JSON.stringify(fileNames);
  186. });
  187. updateSearchBar();