main.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // log htmx on dev
  2. // htmx.logAll();
  3. // add text/html accept header to receive html instead of json for the requests
  4. document.body.addEventListener('htmx:configRequest', function(evt) {
  5. evt.detail.headers["Accept"] = "text/html,*/*";
  6. });
  7. // redirect to homepage
  8. document.body.addEventListener("redirectToHomepage", function() {
  9. setTimeout(() => {
  10. window.location.replace("/");
  11. }, 1500);
  12. });
  13. // reset form if event is sent from the backend
  14. function resetForm(id) {
  15. return function() {
  16. const form = document.getElementById(id);
  17. if (!form) return;
  18. form.reset();
  19. }
  20. }
  21. document.body.addEventListener('resetChangePasswordForm', resetForm("change-password"));
  22. document.body.addEventListener('resetChangeEmailForm', resetForm("change-email"));
  23. // an htmx extension to use the specifed params in the path instead of the query or body
  24. htmx.defineExtension("path-params", {
  25. onEvent: function(name, evt) {
  26. if (name === "htmx:configRequest") {
  27. evt.detail.path = evt.detail.path.replace(/{([^}]+)}/g, function(_, param) {
  28. var val = evt.detail.parameters[param]
  29. delete evt.detail.parameters[param]
  30. return val === undefined ? '{' + param + '}' : encodeURIComponent(val)
  31. })
  32. }
  33. }
  34. })
  35. // find closest element
  36. function closest(selector, elm) {
  37. let element = elm || this;
  38. while (element && element.nodeType === 1) {
  39. if (element.matches(selector)) {
  40. return element;
  41. }
  42. element = element.parentNode;
  43. }
  44. return null;
  45. };
  46. // get url query param
  47. function getQueryParams() {
  48. const search = window.location.search.replace("?", "");
  49. const query = {};
  50. search.split("&").map(q => {
  51. const keyvalue = q.split("=");
  52. query[keyvalue[0]] = keyvalue[1];
  53. });
  54. return query;
  55. }
  56. // trim text
  57. function trimText(selector, length) {
  58. const element = document.querySelector(selector);
  59. if (!element) return;
  60. let text = element.textContent;
  61. if (typeof text !== "string") return;
  62. text = text.trim();
  63. if (text.length > length) {
  64. element.textContent = text.split("").slice(0, length).join("") + "...";
  65. }
  66. }
  67. function formatDateHour(selector) {
  68. const element = document.querySelector(selector);
  69. if (!element) return;
  70. const dateString = element.dataset.date;
  71. if (!dateString) return;
  72. const date = new Date(dateString);
  73. element.textContent = date.getHours() + ":" + date.getMinutes();
  74. }
  75. // show QR code
  76. function handleQRCode(element, id) {
  77. const dialog = document.getElementById(id);
  78. const dialogContent = dialog.querySelector(".content-wrapper");
  79. if (!dialogContent) return;
  80. openDialog(id, "qrcode");
  81. dialogContent.textContent = "";
  82. const qrcode = new QRCode(dialogContent, {
  83. text: element.dataset.url,
  84. width: 200,
  85. height: 200,
  86. colorDark : "#000000",
  87. colorLight : "#ffffff",
  88. correctLevel : QRCode.CorrectLevel.H
  89. });
  90. }
  91. // copy the link to clipboard
  92. function handleCopyLink(element) {
  93. navigator.clipboard.writeText(element.dataset.url);
  94. }
  95. // copy the link and toggle copy button style
  96. function handleShortURLCopyLink(element) {
  97. handleCopyLink(element);
  98. const clipboard = element.parentNode.querySelector(".clipboard") || closest(".clipboard", element);
  99. if (!clipboard || clipboard.classList.contains("copied")) return;
  100. clipboard.classList.add("copied");
  101. setTimeout(function() {
  102. clipboard.classList.remove("copied");
  103. }, 1000);
  104. }
  105. // open and close dialog
  106. function openDialog(id, name) {
  107. const dialog = document.getElementById(id);
  108. if (!dialog) return;
  109. dialog.classList.add("open");
  110. if (name) {
  111. dialog.classList.add(name);
  112. }
  113. }
  114. function closeDialog() {
  115. const dialog = document.querySelector(".dialog");
  116. if (!dialog) return;
  117. while (dialog.classList.length > 0) {
  118. dialog.classList.remove(dialog.classList[0]);
  119. }
  120. dialog.classList.add("dialog");
  121. }
  122. window.addEventListener("click", function(event) {
  123. const dialog = document.querySelector(".dialog");
  124. if (dialog && event.target === dialog) {
  125. closeDialog();
  126. }
  127. });
  128. // handle navigation in the table of links
  129. function setLinksLimit(event) {
  130. const buttons = Array.from(document.querySelectorAll('table .nav .limit button'));
  131. const limitInput = document.querySelector('#limit');
  132. if (!limitInput || !buttons || !buttons.length) return;
  133. limitInput.value = event.target.textContent;
  134. buttons.forEach(b => {
  135. b.disabled = b.textContent === event.target.textContent;
  136. });
  137. }
  138. function setLinksSkip(event, action) {
  139. const buttons = Array.from(document.querySelectorAll('table .nav .pagination button'));
  140. const limitElm = document.querySelector('#limit');
  141. const totalElm = document.querySelector('#total');
  142. const skipElm = document.querySelector('#skip');
  143. if (!buttons || !limitElm || !totalElm || !skipElm) return;
  144. const skip = parseInt(skipElm.value);
  145. const limit = parseInt(limitElm.value);
  146. const total = parseInt(totalElm.value);
  147. skipElm.value = action === "next" ? skip + limit : Math.max(skip - limit, 0);
  148. document.querySelectorAll('.pagination .next').forEach(elm => {
  149. elm.disabled = total <= parseInt(skipElm.value) + limit;
  150. });
  151. document.querySelectorAll('.pagination .prev').forEach(elm => {
  152. elm.disabled = parseInt(skipElm.value) <= 0;
  153. });
  154. }
  155. function updateLinksNav() {
  156. const totalElm = document.querySelector('#total');
  157. const skipElm = document.querySelector('#skip');
  158. const limitElm = document.querySelector('#limit');
  159. if (!totalElm || !skipElm || !limitElm) return;
  160. const total = parseInt(totalElm.value);
  161. const skip = parseInt(skipElm.value);
  162. const limit = parseInt(limitElm.value);
  163. document.querySelectorAll('.pagination .next').forEach(elm => {
  164. elm.disabled = total <= skip + limit;
  165. });
  166. document.querySelectorAll('.pagination .prev').forEach(elm => {
  167. elm.disabled = skip <= 0;
  168. });
  169. }
  170. function resetTableNav() {
  171. const totalElm = document.querySelector('#total');
  172. const skipElm = document.querySelector('#skip');
  173. const limitElm = document.querySelector('#limit');
  174. if (!totalElm || !skipElm || !limitElm) return;
  175. skipElm.value = 0;
  176. limitElm.value = 10;
  177. const total = parseInt(totalElm.value);
  178. const skip = parseInt(skipElm.value);
  179. const limit = parseInt(limitElm.value);
  180. document.querySelectorAll('.pagination .next').forEach(elm => {
  181. elm.disabled = total <= skip + limit;
  182. });
  183. document.querySelectorAll('.pagination .prev').forEach(elm => {
  184. elm.disabled = skip <= 0;
  185. });
  186. document.querySelectorAll('table .nav .limit button').forEach(b => {
  187. b.disabled = b.textContent === limit.toString();
  188. });
  189. }
  190. // tab click
  191. function setTab(event, targetId) {
  192. const tabs = Array.from(closest("nav", event.target).children);
  193. tabs.forEach(function (tab) {
  194. tab.classList.remove("active");
  195. });
  196. if (targetId) {
  197. document.getElementById(targetId).classList.add("active");
  198. } else {
  199. event.target.classList.add("active");
  200. }
  201. }
  202. // show clear search button
  203. function onSearchChange(event) {
  204. const clearButton = event.target.parentElement.querySelector("button.clear");
  205. if (!clearButton) return;
  206. clearButton.style.display = event.target.value.length > 0 ? "block" : "none";
  207. }
  208. function clearSeachInput(event) {
  209. event.preventDefault();
  210. const button = closest("button", event.target);
  211. const input = button.parentElement.querySelector("input");
  212. if (!input) return;
  213. input.value = "";
  214. button.style.display = "none";
  215. htmx.trigger("body", "reloadMainTable");
  216. }
  217. // detect if search inputs have value on load to show clear button
  218. function onSearchInputLoad() {
  219. const linkSearchInput = document.getElementById("search");
  220. if (!linkSearchInput) return;
  221. const linkClearButton = linkSearchInput.parentElement.querySelector("button.clear")
  222. linkClearButton.style.display = linkSearchInput.value.length > 0 ? "block" : "none";
  223. const userSearchInput = document.getElementById("search_user");
  224. if (!userSearchInput) return;
  225. const userClearButton = userSearchInput.parentElement.querySelector("button.clear")
  226. userClearButton.style.display = userSearchInput.value.length > 0 ? "block" : "none";
  227. const domainSearchInput = document.getElementById("search_domain");
  228. if (!domainSearchInput) return;
  229. const domainClearButton = domainSearchInput.parentElement.querySelector("button.clear")
  230. domainClearButton.style.display = domainSearchInput.value.length > 0 ? "block" : "none";
  231. }
  232. onSearchInputLoad();
  233. // create user checkbox control
  234. function canSendVerificationEmail() {
  235. const canSendVerificationEmail = !document.getElementById('create-user-verified').checked && !document.getElementById('create-user-banned').checked;
  236. const checkbox = document.getElementById('send-email-label');
  237. if (canSendVerificationEmail)
  238. checkbox.classList.remove('hidden');
  239. if (!canSendVerificationEmail && !checkbox.classList.contains('hidden'))
  240. checkbox.classList.add('hidden');
  241. }
  242. // htmx prefetch extension
  243. // https://github.com/bigskysoftware/htmx-extensions/blob/main/src/preload/README.md
  244. htmx.defineExtension('preload', {
  245. onEvent: function(name, event) {
  246. if (name !== 'htmx:afterProcessNode') {
  247. return
  248. }
  249. var attr = function(node, property) {
  250. if (node == undefined) { return undefined }
  251. return node.getAttribute(property) || node.getAttribute('data-' + property) || attr(node.parentElement, property)
  252. }
  253. var load = function(node) {
  254. var done = function(html) {
  255. if (!node.preloadAlways) {
  256. node.preloadState = 'DONE'
  257. }
  258. if (attr(node, 'preload-images') == 'true') {
  259. document.createElement('div').innerHTML = html
  260. }
  261. }
  262. return function() {
  263. if (node.preloadState !== 'READY') {
  264. return
  265. }
  266. var hxGet = node.getAttribute('hx-get') || node.getAttribute('data-hx-get')
  267. if (hxGet) {
  268. htmx.ajax('GET', hxGet, {
  269. source: node,
  270. handler: function(elt, info) {
  271. done(info.xhr.responseText)
  272. }
  273. })
  274. return
  275. }
  276. if (node.getAttribute('href')) {
  277. var r = new XMLHttpRequest()
  278. r.open('GET', node.getAttribute('href'))
  279. r.onload = function() { done(r.responseText) }
  280. r.send()
  281. }
  282. }
  283. }
  284. var init = function(node) {
  285. if (node.getAttribute('href') + node.getAttribute('hx-get') + node.getAttribute('data-hx-get') == '') {
  286. return
  287. }
  288. if (node.preloadState !== undefined) {
  289. return
  290. }
  291. var on = attr(node, 'preload') || 'mousedown'
  292. const always = on.indexOf('always') !== -1
  293. if (always) {
  294. on = on.replace('always', '').trim()
  295. }
  296. node.addEventListener(on, function(evt) {
  297. if (node.preloadState === 'PAUSE') {
  298. node.preloadState = 'READY'
  299. if (on === 'mouseover') {
  300. window.setTimeout(load(node), 100)
  301. } else {
  302. load(node)()
  303. }
  304. }
  305. })
  306. switch (on) {
  307. case 'mouseover':
  308. node.addEventListener('touchstart', load(node))
  309. node.addEventListener('mouseout', function(evt) {
  310. if ((evt.target === node) && (node.preloadState === 'READY')) {
  311. node.preloadState = 'PAUSE'
  312. }
  313. })
  314. break
  315. case 'mousedown':
  316. node.addEventListener('touchstart', load(node))
  317. break
  318. }
  319. node.preloadState = 'PAUSE'
  320. node.preloadAlways = always
  321. htmx.trigger(node, 'preload:init')
  322. }
  323. const parent = event.target || event.detail.elt;
  324. parent.querySelectorAll("[preload]").forEach(function(node) {
  325. init(node)
  326. node.querySelectorAll('a,[hx-get],[data-hx-get]').forEach(init)
  327. })
  328. }
  329. })