PluginProbe
ElasticPress / 5.0.1
ElasticPress v5.0.1
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.0.1, at assets/js/utils/helpers.js

189 lines 5.1 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(new RegExp(escapeRegExp(term), 'g'), replacement);
51 };
52
53 /**
54 * Escapes double quotes for specific data-attr
55 *
56 * @param {string} str The provided string containing double quotes
57 * @returns {string} The escaped string
58 */
59 export const escapeDoubleQuotes = (str) => str.replace(/\\([\s\S])|(")/g, '"');
60
61 /**
62 * Finds parent node with the provided class param
63 *
64 * @param {*} el - node to search for its ancestor
65 * @param {*} className - class attribute to search for
66 * @returns {Element} - ancestor element of provided el
67 */
68 export const findAncestorByClass = (el, className) => {
69 // eslint-disable-next-line
70 while ( ( el = el.parentElement ) && !el.classList.contains( className ) );
71 return el;
72 };
73
74 /**
75 * Array pluck
76 *
77 * @param {Array} array - array to search
78 * @param {string} key - array to search
79 * @returns {Array} - new array
80 */
81 export const pluck = (array, key) => {
82 return array.map((o) => o[key]);
83 };
84
85 /**
86 * Formats object like a url query string, which is how ajax methods
87 * in PHP expect to receive the data, e.g. action_wp_ajax_ep_save_feature
88 * from dashboard.php
89 *
90 * @param {object} obj - js object
91 * @returns {string} urlencoded string for POST ajax request
92 */
93 export const formatPostBody = (obj) => {
94 return Object.keys(obj)
95 .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
96 .join('&')
97 .replace(/%20/g, '+');
98 };
99
100 /**
101 * Helper method to wrap show/hide elements. Not exported.
102 *
103 * @param {Array} els - could possibly be a single node, or an array of nodes
104 * @param {string} display - css display property to set
105 */
106 const showOrHideNodes = (els, display) => {
107 let nodes = [];
108
109 // convert nodelist to array
110 // eslint-disable-next-line no-prototype-builtins
111 if (NodeList.prototype.isPrototypeOf(els)) {
112 nodes = Array.from(els);
113 }
114
115 // if not converted, then it was a single node,
116 // so create an array
117 if (!nodes.length) {
118 if (Array.isArray(els)) {
119 nodes = [...els, ...nodes];
120 } else {
121 nodes.push(els);
122 }
123 }
124
125 nodes.forEach((el) => {
126 el.style.display = display; // eslint-disable-line no-param-reassign
127 });
128 };
129
130 /**
131 * Decorated helper function to show node/NodeList/array of nodes
132 *
133 * @param {Array} els - Nodelist/array of Nodes to show
134 * @returns {Function} - showOrHideNodes
135 */
136 export const showElements = (els) => showOrHideNodes(els, 'inline-block');
137
138 /**
139 * Decorated helper function to hide node/NodeList/array of nodes
140 *
141 * @param {Array} els - Nodelist/array of Nodes to show
142 * @returns {Function} - showOrHideNodes
143 */
144 export const hideElements = (els) => showOrHideNodes(els, 'none');
145
146 /**
147 * Specify a function to execute when the DOM is fully loaded.
148 *
149 * @param {Function} callback A function to execute after the DOM is ready.
150 * @returns {void}
151 */
152 export const domReady = (callback) => {
153 if (typeof document === 'undefined') {
154 return;
155 }
156
157 if (
158 document.readyState === 'complete' || // DOMContentLoaded + Images/Styles/etc loaded, so we call directly.
159 document.readyState === 'interactive' // DOMContentLoaded fires at this point, so we call directly.
160 ) {
161 callback();
162 return;
163 }
164
165 // DOMContentLoaded has not fired yet, delay callback until then.
166 document.addEventListener('DOMContentLoaded', callback);
167 };
168
169 /**
170 * Generate a Request ID for autosuggest
171 *
172 * @param {string} requestIdBase - base for request ID generation
173 * @returns {string} Request ID
174 */
175 export const generateRequestId = (requestIdBase) => {
176 const uuid = uuidv4().replaceAll('-', '');
177
178 /**
179 * Filter the request ID used for an autosuggest request.
180 *
181 * @filter ep.Autosuggest.requestId
182 * @since 4.5.0
183 *
184 * @param {string} requestId The Request ID.
185 * @returns {string} New Request ID.
186 */
187 return applyFilters('ep.requestId', requestIdBase + uuid);
188 };
189