]> BookStack Code Mirror - bookstack/blob - resources/js/services/util.js
Ran eslint fix on existing codebase
[bookstack] / resources / js / services / util.js
1 /**
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
8  * @param {Number} wait
9  * @param {Boolean} immediate
10  * @returns {Function}
11  */
12 export function debounce(func, wait, immediate) {
13     let timeout;
14     return function() {
15         const context = this; const
16             args = arguments;
17         const later = function() {
18             timeout = null;
19             if (!immediate) func.apply(context, args);
20         };
21         const callNow = immediate && !timeout;
22         clearTimeout(timeout);
23         timeout = setTimeout(later, wait);
24         if (callNow) func.apply(context, args);
25     };
26 }
27
28 /**
29  * Scroll and highlight an element.
30  * @param {HTMLElement} element
31  */
32 export function scrollAndHighlightElement(element) {
33     if (!element) return;
34     element.scrollIntoView({behavior: 'smooth'});
35
36     const color = getComputedStyle(document.body).getPropertyValue('--color-primary-light');
37     const initColor = window.getComputedStyle(element).getPropertyValue('background-color');
38     element.style.backgroundColor = color;
39     setTimeout(() => {
40         element.classList.add('selectFade');
41         element.style.backgroundColor = initColor;
42     }, 10);
43     setTimeout(() => {
44         element.classList.remove('selectFade');
45         element.style.backgroundColor = '';
46     }, 3000);
47 }
48
49 /**
50  * Escape any HTML in the given 'unsafe' string.
51  * Take from https://stackoverflow.com/a/6234804.
52  * @param {String} unsafe
53  * @returns {string}
54  */
55 export function escapeHtml(unsafe) {
56     return unsafe
57         .replace(/&/g, '&')
58         .replace(/</g, '&lt;')
59         .replace(/>/g, '&gt;')
60         .replace(/"/g, '&quot;')
61         .replace(/'/g, '&#039;');
62 }
63
64 /**
65  * Generate a random unique ID.
66  *
67  * @returns {string}
68  */
69 export function uniqueId() {
70     const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
71     return (`${S4() + S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`);
72 }