@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
123 lines • 2.68 kB
JavaScript
import { format } 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 {
pageYOffset,
pageXOffset
} = typeof window !== 'undefined' ? window : {
pageYOffset: 0,
pageXOffset: 0
};
const {
left,
top
} = node.getBoundingClientRect();
return {
top: top + pageYOffset,
left: left + pageXOffset
};
};
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 createMockDiv = ({
width,
height
}) => {
const div = document.createElement('div');
Object.assign(div.style, {
width: `${width}px`,
height: `${height}px`
});
div.getBoundingClientRect = () => ({
width,
height,
top: 0,
left: 0,
right: width,
bottom: height
});
return div;
};
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
};
}
return format(value, {
...(numberFormat || {}),
returnAria: true
});
}
return {
aria: null,
number: null
};
};
//# sourceMappingURL=SliderHelpers.js.map