Debian Codegraph @

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

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