2 * Returns a function, that, as long as it continues to be invoked, will not
3 * be triggered. The function will be called after it stops being called for
4 * N milliseconds. If `immediate` is passed, trigger the function on the
5 * leading edge, instead of the trailing.
6 * @attribution https://davidwalsh.name/javascript-debounce-function
7 * @param {Function} func
9 * @param {Boolean} immediate
12 export function debounce(func, wait, immediate) {
14 return function debouncedWrapper(...args) {
16 const later = function debouncedTimeout() {
18 if (!immediate) func.apply(context, args);
20 const callNow = immediate && !timeout;
21 clearTimeout(timeout);
22 timeout = setTimeout(later, wait);
23 if (callNow) func.apply(context, args);
28 * Scroll and highlight an element.
29 * @param {HTMLElement} element
31 export function scrollAndHighlightElement(element) {
33 element.scrollIntoView({behavior: 'smooth'});
35 const color = getComputedStyle(document.body).getPropertyValue('--color-primary-light');
36 const initColor = window.getComputedStyle(element).getPropertyValue('background-color');
37 element.style.backgroundColor = color;
39 element.classList.add('selectFade');
40 element.style.backgroundColor = initColor;
43 element.classList.remove('selectFade');
44 element.style.backgroundColor = '';
49 * Escape any HTML in the given 'unsafe' string.
50 * Take from https://stackoverflow.com/a/6234804.
51 * @param {String} unsafe
54 export function escapeHtml(unsafe) {
56 .replace(/&/g, '&')
57 .replace(/</g, '<')
58 .replace(/>/g, '>')
59 .replace(/"/g, '"')
60 .replace(/'/g, ''');
64 * Generate a random unique ID.
68 export function uniqueId() {
69 // eslint-disable-next-line no-bitwise
70 const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
71 return (`${S4() + S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`);
75 * Create a promise that resolves after the given time.
79 export function wait(timeMs) {
80 return new Promise(res => {
81 setTimeout(res, timeMs);