utils.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // wrapper around addEventListener with optional event type at the end
  2. // addEvent() usage: addEvent(element, handler, eventType)
  3. export const addEvent = (element, handler, eventType = "click") => {
  4. element.addEventListener(eventType, handler);
  5. };
  6. // debounce() usage: const debouncedMyFunc = debounce(myFunc, 200);
  7. // or function debouncedMyFunc() { return debounce(myFunc, 200); }
  8. export const debounce = (callback, wait = 200) => {
  9. let timeoutId = null;
  10. return function (...args) {
  11. window.clearTimeout(timeoutId);
  12. timeoutId = window.setTimeout(() => {
  13. callback.apply(null, args);
  14. }, wait);
  15. };
  16. };
  17. // addBrackets() usage: addBrackets(element)
  18. export const addBrackets = (element) => {
  19. let trimmedValue = element.value.trim();
  20. if (!trimmedValue.startsWith('[')) {
  21. trimmedValue = '[' + trimmedValue;
  22. }
  23. if (!trimmedValue.endsWith(']')) {
  24. trimmedValue = trimmedValue + ']';
  25. }
  26. element.value = trimmedValue;
  27. };
  28. // wrapper around querySelector
  29. // select() usage: const [sel1, sel2] = select(".class1", ".class2")
  30. // [repeaterForm, repeaterOutput, addItemButton] = select( ".repeater-form", "output", ".add-btn");
  31. export const select = (...selectors) => selectors.map(selector => document.querySelector(selector));
  32. // selectAll() usage: const [sel1, sel2] = selectAll(".class1", ".class2")
  33. // wrapper around querySelectorAll
  34. export const selectAll = (...selectors) => selectors.map(selector => document.querySelectorAll(selector));
  35. // Shortcodes
  36. export function doShortcodes(shortcodes, contentString) {
  37. // Replace names with values in the provided string
  38. shortcodes.forEach(item => {
  39. const namePattern = new RegExp(escapeRegExp(item.name), 'g');
  40. contentString = contentString.replace(namePattern, item.value);
  41. });
  42. return contentString;
  43. }
  44. export function doShortcodesFromLocalstorage(main) {
  45. // localStorage.setItem('repeaterData', jsonString);
  46. // localStorage.removeItem('repeaterData');
  47. const shortcodesJsonString = localStorage.getItem('repeaterData');
  48. if (shortcodesJsonString) {
  49. const shortcodes = JSON.parse(shortcodesJsonString);
  50. if (shortcodes[0]) { // console.log(shortcodes[0].name);
  51. return doShortcodes(shortcodes, main)
  52. }
  53. }
  54. return main;
  55. }
  56. // Function to escape special characters in a string for regex
  57. export function escapeRegExp(string) {
  58. return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  59. }