script.js 7.0 KB

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