Debian Codegraph @

node/@patternfly/react-core/src/helpers/util.ts

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