Debian Codegraph @

node/@patternfly/react-core/dist/esm/helpers/util.js

raw
1 import { globalWidthBreakpoints, globalHeightBreakpoints, SIDE } from './constants';
2 /**
3 * @param {string} input - String to capitalize first letter
4 */
5 export function capitalize(input) {
6 return input[0].toUpperCase() + input.substring(1);
7 }
8 /**
9 * @param {string} prefix - String to prefix ID with
10 */
11 export function getUniqueId(prefix = 'pf') {
12 const uid = new Date().getTime() + Math.random().toString(36).slice(2);
13 return `${prefix}-${uid}`;
14 }
15 /**
16 * @param { any } this - "This" reference
17 * @param { Function } func - Function to debounce
18 * @param { number } wait - Debounce amount
19 */
20 export function debounce(func, wait) {
21 let timeout;
22 return (...args) => {
23 clearTimeout(timeout);
24 timeout = setTimeout(() => func.apply(this, args), wait);
25 };
26 }
27 /** This function returns whether or not an element is within the viewable area of a container. If partial is true,
28 * then this function will return true even if only part of the element is in view.
29 *
30 * @param {HTMLElement} container The container to check if the element is in view of.
31 * @param {HTMLElement} element The element to check if it is view
32 * @param {boolean} partial true if partial view is allowed
33 * @param {boolean} strict true if strict mode is set, never consider the container width and element width
34 *
35 * @returns { boolean } True if the component is in View.
36 */
37 export function isElementInView(container, element, partial, strict = false) {
38 if (!container || !element) {
39 return false;
40 }
41 const containerBounds = container.getBoundingClientRect();
42 const elementBounds = element.getBoundingClientRect();
43 const containerBoundsLeft = Math.ceil(containerBounds.left);
44 const containerBoundsRight = Math.floor(containerBounds.right);
45 const elementBoundsLeft = Math.ceil(elementBounds.left);
46 const elementBoundsRight = Math.floor(elementBounds.right);
47 // Check if in view
48 const isTotallyInView = elementBoundsLeft >= containerBoundsLeft && elementBoundsRight <= containerBoundsRight;
49 const isPartiallyInView = (partial || (!strict && containerBounds.width < elementBounds.width)) &&
50 ((elementBoundsLeft < containerBoundsLeft && elementBoundsRight > containerBoundsLeft) ||
51 (elementBoundsRight > containerBoundsRight && elementBoundsLeft < containerBoundsRight));
52 // Return outcome
53 return isTotallyInView || isPartiallyInView;
54 }
55 /** This function returns the side the element is out of view on (right, left or both)
56 *
57 * @param {HTMLElement} container The container to check if the element is in view of.
58 * @param {HTMLElement} element The element to check if it is view
59 *
60 * @returns {string} right if the element is of the right, left if element is off the left or both if it is off on both sides.
61 */
62 export function sideElementIsOutOfView(container, element) {
63 const containerBounds = container.getBoundingClientRect();
64 const elementBounds = element.getBoundingClientRect();
65 const containerBoundsLeft = Math.floor(containerBounds.left);
66 const containerBoundsRight = Math.floor(containerBounds.right);
67 const elementBoundsLeft = Math.floor(elementBounds.left);
68 const elementBoundsRight = Math.floor(elementBounds.right);
69 // Check if in view
70 const isOffLeft = elementBoundsLeft < containerBoundsLeft;
71 const isOffRight = elementBoundsRight > containerBoundsRight;
72 let side = SIDE.NONE;
73 if (isOffRight && isOffLeft) {
74 side = SIDE.BOTH;
75 }
76 else if (isOffRight) {
77 side = SIDE.RIGHT;
78 }
79 else if (isOffLeft) {
80 side = SIDE.LEFT;
81 }
82 // Return outcome
83 return side;
84 }
85 /** Interpolates a parameterized templateString using values from a templateVars object.
86 * The templateVars object should have keys and values which match the templateString's parameters.
87 * Example:
88 * const templateString: 'My name is ${firstName} ${lastName}';
89 * const templateVars: {
90 * firstName: 'Jon'
91 * lastName: 'Dough'
92 * };
93 * const result = fillTemplate(templateString, templateVars);
94 * // "My name is Jon Dough"
95 *
96 * @param {string} templateString The string passed by the consumer
97 * @param {object} templateVars The variables passed to the string
98 *
99 * @returns {string} The template string literal result
100 */
101 export function fillTemplate(templateString, templateVars) {
102 return templateString.replace(/\${(.*?)}/g, (_, match) => templateVars[match] || '');
103 }
104 /**
105 * This function allows for keyboard navigation through dropdowns. The custom argument is optional.
106 *
107 * @param {number} index The index of the element you're on
108 * @param {number} innerIndex Inner index number
109 * @param {string} position The orientation of the dropdown
110 * @param {string[]} refsCollection Array of refs to the items in the dropdown
111 * @param {object[]} kids Array of items in the dropdown
112 * @param {boolean} [custom] Allows for handling of flexible content
113 */
114 export function keyHandler(index, innerIndex, position, refsCollection, kids, custom = false) {
115 if (!Array.isArray(kids)) {
116 return;
117 }
118 const isMultiDimensional = refsCollection.filter((ref) => ref)[0].constructor === Array;
119 let nextIndex = index;
120 let nextInnerIndex = innerIndex;
121 if (position === 'up') {
122 if (index === 0) {
123 // loop back to end
124 nextIndex = kids.length - 1;
125 }
126 else {
127 nextIndex = index - 1;
128 }
129 }
130 else if (position === 'down') {
131 if (index === kids.length - 1) {
132 // loop back to beginning
133 nextIndex = 0;
134 }
135 else {
136 nextIndex = index + 1;
137 }
138 }
139 else if (position === 'left') {
140 if (innerIndex === 0) {
141 nextInnerIndex = refsCollection[index].length - 1;
142 }
143 else {
144 nextInnerIndex = innerIndex - 1;
145 }
146 }
147 else if (position === 'right') {
148 if (innerIndex === refsCollection[index].length - 1) {
149 nextInnerIndex = 0;
150 }
151 else {
152 nextInnerIndex = innerIndex + 1;
153 }
154 }
155 if (refsCollection[nextIndex] === null ||
156 refsCollection[nextIndex] === undefined ||
157 (isMultiDimensional &&
158 (refsCollection[nextIndex][nextInnerIndex] === null || refsCollection[nextIndex][nextInnerIndex] === undefined))) {
159 keyHandler(nextIndex, nextInnerIndex, position, refsCollection, kids, custom);
160 }
161 else if (custom) {
162 if (refsCollection[nextIndex].focus) {
163 refsCollection[nextIndex].focus();
164 }
165 const element = refsCollection[nextIndex];
166 element.focus();
167 }
168 else if (position !== 'tab') {
169 if (isMultiDimensional) {
170 refsCollection[nextIndex][nextInnerIndex].focus();
171 }
172 else {
173 refsCollection[nextIndex].focus();
174 }
175 }
176 }
177 /** This function returns a list of tabbable items in a container
178 *
179 * @param {any} containerRef to the container
180 * @param {string} tababbleSelectors CSS selector string of tabbable items
181 */
182 export function findTabbableElements(containerRef, tababbleSelectors) {
183 const tabbable = containerRef.current.querySelectorAll(tababbleSelectors);
184 const list = Array.prototype.filter.call(tabbable, function (item) {
185 return item.tabIndex >= '0';
186 });
187 return list;
188 }
189 /** This function is a helper for keyboard navigation through dropdowns.
190 *
191 * @param {number} index The index of the element you're on
192 * @param {string} position The orientation of the dropdown
193 * @param {string[]} collection Array of refs to the items in the dropdown
194 */
195 export function getNextIndex(index, position, collection) {
196 let nextIndex;
197 if (position === 'up') {
198 if (index === 0) {
199 // loop back to end
200 nextIndex = collection.length - 1;
201 }
202 else {
203 nextIndex = index - 1;
204 }
205 }
206 else if (index === collection.length - 1) {
207 // loop back to beginning
208 nextIndex = 0;
209 }
210 else {
211 nextIndex = index + 1;
212 }
213 if (collection[nextIndex] === undefined || collection[nextIndex][0] === null) {
214 return getNextIndex(nextIndex, position, collection);
215 }
216 else {
217 return nextIndex;
218 }
219 }
220 /** This function is a helper for pluralizing strings.
221 *
222 * @param {number} i The quantity of the string you want to pluralize
223 * @param {string} singular The singular version of the string
224 * @param {string} plural The change to the string that should occur if the quantity is not equal to 1.
225 * Defaults to adding an 's'.
226 */
227 export function pluralize(i, singular, plural) {
228 if (!plural) {
229 plural = `${singular}s`;
230 }
231 return `${i || 0} ${i === 1 ? singular : plural}`;
232 }
233 /**
234 * This function is a helper for turning arrays of breakpointMod objects for flex and grid into style object
235 *
236 * @param {object} mods The modifiers object
237 * @param {string} css-variable The appropriate css variable for the component
238 */
239 export const setBreakpointCssVars = (mods, cssVar) => Object.entries(mods || {}).reduce((acc, [breakpoint, value]) => breakpoint === 'default' ? Object.assign(Object.assign({}, acc), { [cssVar]: value }) : Object.assign(Object.assign({}, acc), { [`${cssVar}-on-${breakpoint}`]: value }), {});
240 /**
241 * This function is a helper for turning arrays of breakpointMod objects for data toolbar and flex into classes
242 *
243 * @param {object} mods The modifiers object
244 * @param {any} styles The appropriate styles object for the component
245 */
246 export const formatBreakpointMods = (mods, styles, stylePrefix = '', breakpoint, vertical) => {
247 if (!mods) {
248 return '';
249 }
250 if (breakpoint && !vertical) {
251 if (breakpoint in mods) {
252 return styles.modifiers[toCamel(`${stylePrefix}${mods[breakpoint]}`)];
253 }
254 // the current breakpoint is not specified in mods, so we try to find the next nearest
255 const breakpointsOrder = ['2xl', 'xl', 'lg', 'md', 'sm', 'default'];
256 const breakpointsIndex = breakpointsOrder.indexOf(breakpoint);
257 for (let i = breakpointsIndex; i < breakpointsOrder.length; i++) {
258 if (breakpointsOrder[i] in mods) {
259 return styles.modifiers[toCamel(`${stylePrefix}${mods[breakpointsOrder[i]]}`)];
260 }
261 }
262 return '';
263 }
264 return Object.entries(mods || {})
265 .map(([breakpoint, mod]) => `${stylePrefix}${mod}${breakpoint !== 'default' ? `-on-${breakpoint}` : ''}${vertical && breakpoint !== 'default' ? '-height' : ''}`)
266 .map(toCamel)
267 .map((mod) => mod.replace(/-?(\dxl)/gi, (_res, group) => `_${group}`))
268 .map((modifierKey) => styles.modifiers[modifierKey])
269 .filter(Boolean)
270 .join(' ');
271 };
272 /**
273 * Return the breakpoint for the given height
274 *
275 * @param {number | null} height The height to check
276 * @returns {'default' | 'sm' | 'md' | 'lg' | 'xl' | '2xl'} The breakpoint
277 */
278 export const getVerticalBreakpoint = (height) => {
279 if (height === null) {
280 return null;
281 }
282 if (height >= globalHeightBreakpoints['2xl']) {
283 return '2xl';
284 }
285 if (height >= globalHeightBreakpoints.xl) {
286 return 'xl';
287 }
288 if (height >= globalHeightBreakpoints.lg) {
289 return 'lg';
290 }
291 if (height >= globalHeightBreakpoints.md) {
292 return 'md';
293 }
294 if (height >= globalHeightBreakpoints.sm) {
295 return 'sm';
296 }
297 return 'default';
298 };
299 /**
300 * Return the breakpoint for the given width
301 *
302 * @param {number | null} width The width to check
303 * @returns {'default' | 'sm' | 'md' | 'lg' | 'xl' | '2xl'} The breakpoint
304 */
305 export const getBreakpoint = (width) => {
306 if (width === null) {
307 return null;
308 }
309 if (width >= globalWidthBreakpoints['2xl']) {
310 return '2xl';
311 }
312 if (width >= globalWidthBreakpoints.xl) {
313 return 'xl';
314 }
315 if (width >= globalWidthBreakpoints.lg) {
316 return 'lg';
317 }
318 if (width >= globalWidthBreakpoints.md) {
319 return 'md';
320 }
321 if (width >= globalWidthBreakpoints.sm) {
322 return 'sm';
323 }
324 return 'default';
325 };
326 const camelize = (s) => s.toUpperCase().replace('-', '').replace('_', '');
327 /**
328 *
329 * @param {string} s string to make camelCased
330 */
331 export const toCamel = (s) => s.replace(/([-_][a-z])/gi, camelize);
332 /**
333 * Copied from exenv
334 */
335 export const canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
336 /**
337 * Calculate the width of the text
338 * Example:
339 * getTextWidth('my text', node)
340 *
341 * @param {string} text The text to calculate the width for
342 * @param {HTMLElement} node The HTML element
343 */
344 export const getTextWidth = (text, node) => {
345 const computedStyle = getComputedStyle(node);
346 // Firefox returns the empty string for .font, so this function creates the .font property manually
347 const getFontFromComputedStyle = () => {
348 let computedFont = '';
349 // Firefox uses percentages for font-stretch, but Canvas does not accept percentages
350 // so convert to keywords, as listed at:
351 // https://developer.mozilla.org/en-US/docs/Web/CSS/font-stretch
352 const fontStretchLookupTable = {
353 '50%': 'ultra-condensed',
354 '62.5%': 'extra-condensed',
355 '75%': 'condensed',
356 '87.5%': 'semi-condensed',
357 '100%': 'normal',
358 '112.5%': 'semi-expanded',
359 '125%': 'expanded',
360 '150%': 'extra-expanded',
361 '200%': 'ultra-expanded'
362 };
363 // If the retrieved font-stretch percentage isn't found in the lookup table, use
364 // 'normal' as a last resort.
365 let fontStretch;
366 if (computedStyle.fontStretch in fontStretchLookupTable) {
367 fontStretch = fontStretchLookupTable[computedStyle.fontStretch];
368 }
369 else {
370 fontStretch = 'normal';
371 }
372 computedFont =
373 computedStyle.fontStyle +
374 ' ' +
375 computedStyle.fontVariant +
376 ' ' +
377 computedStyle.fontWeight +
378 ' ' +
379 fontStretch +
380 ' ' +
381 computedStyle.fontSize +
382 '/' +
383 computedStyle.lineHeight +
384 ' ' +
385 computedStyle.fontFamily;
386 return computedFont;
387 };
388 const canvas = document.createElement('canvas');
389 const context = canvas.getContext('2d');
390 context.font = computedStyle.font || getFontFromComputedStyle();
391 return context.measureText(text).width;
392 };
393 /**
394 * Get the inner dimensions of an element
395 *
396 * @param {HTMLElement} node HTML element to calculate the inner dimensions for
397 */
398 export const innerDimensions = (node) => {
399 const computedStyle = getComputedStyle(node);
400 let width = node.clientWidth; // width with padding
401 let height = node.clientHeight; // height with padding
402 height -= parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
403 width -= parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.paddingRight);
404 return { height, width };
405 };
406 /**
407 * This function is a helper for truncating text content on the left, leaving the right side of the content in view
408 *
409 * @param {HTMLElement} node HTML element
410 * @param {string} value The original text value
411 */
412 export const trimLeft = (node, value) => {
413 const availableWidth = innerDimensions(node).width;
414 let newValue = value;
415 if (getTextWidth(value, node) > availableWidth) {
416 // we have text overflow, trim the text to the left and add ... in the front until it fits
417 while (getTextWidth(`...${newValue}`, node) > availableWidth) {
418 newValue = newValue.substring(1);
419 }
420 // replace text with our truncated text
421 if (node.value) {
422 node.value = `...${newValue}`;
423 }
424 else {
425 node.innerText = `...${newValue}`;
426 }
427 }
428 else {
429 if (node.value) {
430 node.value = value;
431 }
432 else {
433 node.innerText = value;
434 }
435 }
436 };
437 /**
438 * @param {string[]} events - Operations to prevent when disabled
439 */
440 export const preventedEvents = (events) => events.reduce((handlers, eventToPrevent) => (Object.assign(Object.assign({}, handlers), { [eventToPrevent]: (event) => {
441 event.preventDefault();
442 } })), {});
443 /**
444 * @param {React.RefObject<any>[]} timeoutRefs - Timeout refs to clear
445 */
446 export const clearTimeouts = (timeoutRefs) => {
447 timeoutRefs.forEach((ref) => {
448 if (ref.current) {
449 clearTimeout(ref.current);
450 }
451 });
452 };
453 /**
454 * Helper function to get the language direction of a given element, useful for figuring out if left-to-right
455 * or right-to-left specific logic should be applied.
456 *
457 * @param {HTMLElement} targetElement - Element the helper will get the language direction of
458 * @param {'ltr' | 'rtl'} defaultDirection - Language direction to assume if one can't be determined, defaults to 'ltr'
459 * @returns {'ltr' | 'rtl'} - The language direction of the target element
460 */
461 export const getLanguageDirection = (targetElement, defaultDirection = 'ltr') => {
462 if (!targetElement) {
463 return defaultDirection;
464 }
465 const computedDirection = getComputedStyle(targetElement).getPropertyValue('direction');
466 if (['ltr', 'rtl'].includes(computedDirection)) {
467 return computedDirection;
468 }
469 return defaultDirection;
470 };
471 /**
472 * Gets a reference element based on a ref property, which can typically be 1 of several types.
473 *
474 * @param {HTMLElement | (() => HTMLElement) | React.RefObject<any>} refProp The ref property to get a reference element from.
475 * @returns The reference element if one is found.
476 */
477 export const getReferenceElement = (refProp) => {
478 if (refProp instanceof HTMLElement) {
479 return refProp;
480 }
481 if (typeof refProp === 'function') {
482 return refProp();
483 }
484 return refProp === null || refProp === void 0 ? void 0 : refProp.current;
485 };
486 /**
487 * Gets the [client|offset|scroll]Left property of an element, and determines whether it needs to be
488 * adjusted for an RTL direction.
489 *
490 * @param {HTMLElement} targetElement - Element to get the inline-start property of.
491 * @param {HTMLElement} ancestorElement - Ancestor element to base the inline-start calculation off of when the direction is RTL.
492 * @param {'client' | 'offset' | 'scroll'} inlineType - The inline-start property type to base calculations on.
493 * @returns {number} - The value of the inline-start property.
494 */
495 export const getInlineStartProperty = (targetElement, ancestorElement, inlineType = 'offset') => {
496 if (!targetElement) {
497 return;
498 }
499 const inlineProperty = `${inlineType}Left`;
500 const isRTL = getLanguageDirection(targetElement) === 'rtl';
501 if (!isRTL) {
502 return targetElement[inlineProperty];
503 }
504 const widthProperty = `${inlineType}Width`;
505 return ancestorElement[widthProperty] - (targetElement[inlineProperty] + targetElement[widthProperty]);
506 };
507 //# sourceMappingURL=util.js.map