@nafr/echo-ui
Version:
A UI library born for WAA
55 lines (54 loc) • 1.97 kB
JavaScript
import { clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs) {
return twMerge(clsx(inputs));
}
export const validValue = (value, min, max) => {
if (value < min)
return min;
if (value > max)
return max;
return value;
};
export const halfRange = (min, max) => {
return (max - Math.abs(min)) / 2;
};
export const fixTo = (n, fix = 2) => {
return Number(n.toFixed(fix));
};
export const formatTime = (seconds) => {
const pad = (num) => (num < 10 ? '0' + num : num.toString());
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return pad(minutes) + ':' + pad(remainingSeconds);
};
/**
* Returns a valid scaled value for a given scale and data point.
*/
export const validScaledNaN = (scale, data, specify) => {
let v = scale(data);
if (Number.isNaN(v))
v = specify;
return v;
};
/**
* Converts any color string to an RGBA string with the specified opacity.
* @param {string} color - The color string (hex, rgb, rgba, hsl, etc.)
* @param {number} opacity - The opacity value (0 to 1).
* @returns {string} - The resulting RGBA color string.
*/
export function convertColorToRGBA(color, opacity) {
// Create a temporary element to apply the style and read the computed color
const dummyElement = document.createElement('div');
dummyElement.style.display = 'none';
document.body.appendChild(dummyElement);
dummyElement.style.color = color;
const computedColor = window.getComputedStyle(dummyElement).color;
document.body.removeChild(dummyElement);
// Convert the computed color to rgba with the desired opacity
const rgbaMatch = computedColor.match(/^rgba?\((\d+), (\d+), (\d+)(?:, (\d+))?\)$/);
if (!rgbaMatch)
return color; // Fallback to the original color if parsing fails
const [, r, g, b] = rgbaMatch.map(Number);
return `rgba(${r}, ${g}, ${b}, ${opacity})`;
}