Fix: some random frontend fixes and coverage

This commit is contained in:
shamoon
2024-12-04 16:31:16 -08:00
parent df2c139721
commit 0c883d064e
7 changed files with 49 additions and 18 deletions

View File

@@ -1,8 +1,10 @@
import {
BRIGHTNESS,
componentToHex,
computeLuminance,
estimateBrightnessForColor,
hexToHsl,
hslToRgb,
randomColor,
rgbToHsl,
} from './color'
@@ -44,7 +46,21 @@ describe('Color Utils', () => {
expect(hsl).toEqual([0, 0, 0.5019607843137255])
})
it('should convert hsl to rgb', () => {
let rgb = hslToRgb(0, 0, 0.5)
expect(rgb).toEqual([127.5, 127.5, 127.5])
expect(hslToRgb(0, 0, 0)).toEqual([0, 0, 0])
expect(hslToRgb(0, 0, 1)).toEqual([255, 255, 255])
})
it('should return a random color', () => {
expect(randomColor()).not.toBeNull()
})
it('should convert component to hex', () => {
expect(componentToHex(0)).toEqual('00')
expect(componentToHex(255)).toEqual('ff')
expect(componentToHex(128)).toEqual('80')
expect(componentToHex(15)).toEqual('0f')
})
})

View File

@@ -5,7 +5,7 @@ export const BRIGHTNESS = {
DARK: 'dark',
}
function componentToHex(c) {
export function componentToHex(c) {
var hex = Math.floor(c).toString(16)
return hex.length == 1 ? '0' + hex : hex
}
@@ -23,21 +23,22 @@ function componentToHex(c) {
* @param Number l The lightness
* @return Array The RGB representation
*/
function hslToRgb(h, s, l) {
function hue2rgb(p, q, t) {
if (t < 0) t += 1
if (t > 1) t -= 1
if (t < 1 / 6) return p + (q - p) * 6 * t
if (t < 1 / 2) return q
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6
return p
}
export function hslToRgb(h, s, l) {
var r, g, b
if (s == 0) {
r = g = b = l // achromatic
} else {
function hue2rgb(p, q, t) {
if (t < 0) t += 1
if (t > 1) t -= 1
if (t < 1 / 6) return p + (q - p) * 6 * t
if (t < 1 / 2) return q
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6
return p
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s
var p = 2 * l - q
r = hue2rgb(p, q, h + 1 / 3)