]> BookStack Code Mirror - bookstack/blob - resources/js/services/util.js
Added code editor changes mobile design handling
[bookstack] / resources / js / services / util.js
1
2
3 /**
4  * Returns a function, that, as long as it continues to be invoked, will not
5  * be triggered. The function will be called after it stops being called for
6  * N milliseconds. If `immediate` is passed, trigger the function on the
7  * leading edge, instead of the trailing.
8  * @attribution https://davidwalsh.name/javascript-debounce-function
9  * @param func
10  * @param wait
11  * @param immediate
12  * @returns {Function}
13  */
14 export function debounce(func, wait, immediate) {
15     let timeout;
16     return function() {
17         const context = this, args = arguments;
18         const later = function() {
19             timeout = null;
20             if (!immediate) func.apply(context, args);
21         };
22         const callNow = immediate && !timeout;
23         clearTimeout(timeout);
24         timeout = setTimeout(later, wait);
25         if (callNow) func.apply(context, args);
26     };
27 };
28
29 /**
30  * Scroll and highlight an element.
31  * @param {HTMLElement} element
32  */
33 export function scrollAndHighlightElement(element) {
34     if (!element) return;
35     element.scrollIntoView({behavior: 'smooth'});
36
37     const color = document.getElementById('custom-styles').getAttribute('data-color-light');
38     const initColor = window.getComputedStyle(element).getPropertyValue('background-color');
39     element.style.backgroundColor = color;
40     setTimeout(() => {
41         element.classList.add('selectFade');
42         element.style.backgroundColor = initColor;
43     }, 10);
44     setTimeout(() => {
45         element.classList.remove('selectFade');
46         element.style.backgroundColor = '';
47     }, 3000);
48 }
49
50 /**
51  * Escape any HTML in the given 'unsafe' string.
52  * Take from https://stackoverflow.com/a/6234804.
53  * @param {String} unsafe
54  * @returns {string}
55  */
56 export function escapeHtml(unsafe) {
57     return unsafe
58         .replace(/&/g, "&")
59         .replace(/</g, "&lt;")
60         .replace(/>/g, "&gt;")
61         .replace(/"/g, "&quot;")
62         .replace(/'/g, "&#039;");
63 }
64
65 /**
66  * Generate a random unique ID.
67  *
68  * @returns {string}
69  */
70 export function uniqueId() {
71     const S4 = () => (((1+Math.random())*0x10000)|0).toString(16).substring(1);
72     return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
73 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.