PluginProbe
ElasticPress / 5.3.5
ElasticPress v5.3.5
5.3.5 5.3.4 3.6.5 3.6.6 4.0.0 4.0.1 4.1.0 4.2.0 4.2.1 4.2.2 4.3.0 4.3.1 4.4.0 4.4.1 4.5.0 4.5.1 4.5.2 4.6.0 4.6.1 4.7.0 4.7.1 4.7.2 5.0.0 5.0.1 5.0.2 All 108 releases
elasticpress / assets / js / utils / helpers.js

helpers.js in ElasticPress 5.3.5, at assets/js/utils/helpers.js

192 lines 5.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /**
2 * WordPress dependencies.
3 */
4 import { applyFilters } from '@wordpress/hooks';
5
6 /**
7 * External dependencies.
8 */
9 import { v4 as uuidv4 } from 'uuid';
10
11 /**
12 * Simple throttling function for waiting a set amount of time after the last keypress
13 * So we don't overload the server with too many requests at once
14 *
15 * @param {Function} fn - function to be debounced
16 * @param {number} delay - integer
17 * @returns {Function} - new function, with the provided function wrapped in a timeout
18 */
19 export const debounce = (fn, delay) => {
20 let timer = null;
21
22 // don't use a fat arrow in order to preserve the proper context
23 return function debouncedFunction(...args) {
24 const context = this;
25 window.clearTimeout(timer);
26
27 timer = window.setTimeout(() => {
28 fn.apply(context, args);
29 }, delay);
30 };
31 };
32
33 /**
34 * Helper function to escape input to be treated as a literal string with a RegEx
35 *
36 * @param {string} string - string to be escaped
37 * @returns {string} escaped string
38 */
39 export const escapeRegExp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
40
41 /**
42 * Helper function to escape input to be treated as a literal string with a RegEx
43 *
44 * @param {string} string - string to replace
45 * @param {string} term - tearm to search for
46 * @param {string} replacement replace value to use
47 * @returns {string} replaced string
48 */
49 export const replaceGlobally = (string, term, replacement) => {
50 return string.replace(
51 new RegExp(escapeRegExp(term), 'g'),
52 JSON.stringify(replacement).slice(1, -1), // Escapes especial chars and remove quotes added by JSON.stringify
53 );
54 };
55
56 /**
57 * Escapes double quotes for specific data-attr
58 *
59 * @param {string} str The provided string containing double quotes
60 * @returns {string} The escaped string
61 */
62 export const escapeDoubleQuotes = (str) => str.replace(/\\([\s\S])|(")/g, '"');
63
64 /**
65 * Finds parent node with the provided class param
66 *
67 * @param {*} el - node to search for its ancestor
68 * @param {*} className - class attribute to search for
69 * @returns {Element} - ancestor element of provided el
70 */
71 export const findAncestorByClass = (el, className) => {
72 // eslint-disable-next-line
73 while ( ( el = el.parentElement ) && !el.classList.contains( className ) );
74 return el;
75 };
76
77 /**
78 * Array pluck
79 *
80 * @param {Array} array - array to search
81 * @param {string} key - array to search
82 * @returns {Array} - new array
83 */
84 export const pluck = (array, key) => {
85 return array.map((o) => o[key]);
86 };
87
88 /**
89 * Formats object like a url query string, which is how ajax methods
90 * in PHP expect to receive the data, e.g. action_wp_ajax_ep_save_feature
91 * from dashboard.php
92 *
93 * @param {object} obj - js object
94 * @returns {string} urlencoded string for POST ajax request
95 */
96 export const formatPostBody = (obj) => {
97 return Object.keys(obj)
98 .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
99 .join('&')
100 .replace(/%20/g, '+');
101 };
102
103 /**
104 * Helper method to wrap show/hide elements. Not exported.
105 *
106 * @param {Array} els - could possibly be a single node, or an array of nodes
107 * @param {string} display - css display property to set
108 */
109 const showOrHideNodes = (els, display) => {
110 let nodes = [];
111
112 // convert nodelist to array
113 // eslint-disable-next-line no-prototype-builtins
114 if (NodeList.prototype.isPrototypeOf(els)) {
115 nodes = Array.from(els);
116 }
117
118 // if not converted, then it was a single node,
119 // so create an array
120 if (!nodes.length) {
121 if (Array.isArray(els)) {
122 nodes = [...els, ...nodes];
123 } else {
124 nodes.push(els);
125 }
126 }
127
128 nodes.forEach((el) => {
129 el.style.display = display; // eslint-disable-line no-param-reassign
130 });
131 };
132
133 /**
134 * Decorated helper function to show node/NodeList/array of nodes
135 *
136 * @param {Array} els - Nodelist/array of Nodes to show
137 * @returns {Function} - showOrHideNodes
138 */
139 export const showElements = (els) => showOrHideNodes(els, 'inline-block');
140
141 /**
142 * Decorated helper function to hide node/NodeList/array of nodes
143 *
144 * @param {Array} els - Nodelist/array of Nodes to show
145 * @returns {Function} - showOrHideNodes
146 */
147 export const hideElements = (els) => showOrHideNodes(els, 'none');
148
149 /**
150 * Specify a function to execute when the DOM is fully loaded.
151 *
152 * @param {Function} callback A function to execute after the DOM is ready.
153 * @returns {void}
154 */
155 export const domReady = (callback) => {
156 if (typeof document === 'undefined') {
157 return;
158 }
159
160 if (
161 document.readyState === 'complete' || // DOMContentLoaded + Images/Styles/etc loaded, so we call directly.
162 document.readyState === 'interactive' // DOMContentLoaded fires at this point, so we call directly.
163 ) {
164 callback();
165 return;
166 }
167
168 // DOMContentLoaded has not fired yet, delay callback until then.
169 document.addEventListener('DOMContentLoaded', callback);
170 };
171
172 /**
173 * Generate a Request ID for autosuggest
174 *
175 * @param {string} requestIdBase - base for request ID generation
176 * @returns {string} Request ID
177 */
178 export const generateRequestId = (requestIdBase) => {
179 const uuid = uuidv4().replaceAll('-', '');
180
181 /**
182 * Filter the request ID used for an autosuggest request.
183 *
184 * @filter ep.Autosuggest.requestId
185 * @since 4.5.0
186 *
187 * @param {string} requestId The Request ID.
188 * @returns {string} New Request ID.
189 */
190 return applyFilters('ep.requestId', requestIdBase + uuid);
191 };
192