UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

106 lines 2.49 kB
import { formatCurrency, formatNumber } from "../number-format/NumberUtils.js"; import { clamp } from "../../shared/helpers/clamp.js"; export const percentToValue = (percent, min, max, isReverse) => { let num = (max - min) * percent / 100 + min; if (isReverse) { num = max + min - num; } return num; }; export const getOffset = node => { const { scrollY, scrollX } = typeof window !== 'undefined' ? window : { scrollY: 0, scrollX: 0 }; const { left, top } = node.getBoundingClientRect(); return { top: top + scrollY, left: left + scrollX }; }; export const getMousePosition = event => { if (event.changedTouches && event.changedTouches[0]) { return { x: event.changedTouches[0].pageX, y: event.changedTouches[0].pageY }; } return { x: event.pageX, y: event.pageY }; }; export const calculatePercent = (node, event, isVertical) => { const { width, height } = node.getBoundingClientRect(); const { top, left } = getOffset(node); const { x, y } = getMousePosition(event); const value = isVertical ? y - top : x - left; const onePercent = (isVertical ? height : width) / 100; return Math.abs(clamp(value / onePercent)); }; export { clamp }; export const roundValue = (value, { step, min, max }) => { if (step > 0) { if (value >= max) { return max; } if (value <= min) { return min; } return Math.round(value / step) * step; } return parseFloat(parseFloat(String(value)).toFixed(3)); }; export const getUpdatedValues = (value, index, newValue) => { return value.map((val, i) => { if (i === index) { val = newValue; } return val; }); }; export const closestIndex = (goal, array) => { const res = [...array].sort((a, b) => Math.abs(goal - a) - Math.abs(goal - b))[0]; return array.findIndex(num => num === res); }; export const getFormattedNumber = (value, numberFormat) => { if (numberFormat) { if (typeof numberFormat === 'function') { const number = numberFormat(value); return { number, aria: number }; } const options = { ...(numberFormat || {}), returnAria: true }; const formatter = options.currency === true || typeof options.currency === 'string' ? formatCurrency : formatNumber; return formatter(value, options); } return { aria: null, number: null }; }; //# sourceMappingURL=SliderHelpers.js.map