feat(ui-lib): demo pages for c-lib components

This commit is contained in:
Corentin Thomasset 2023-04-23 22:26:32 +02:00 committed by Corentin THOMASSET
parent e88c1d5f2c
commit 92bd83536f
14 changed files with 294 additions and 248 deletions

View file

@ -0,0 +1,40 @@
import { describe, test, expect } from 'vitest';
import { darken, lighten, setOpacity } from './color.models';
describe('color models', () => {
describe('lighten', () => {
test('lightens a color', () => {
expect(lighten('#000000', 10)).toBe('#0a0a0a');
expect(lighten('#000000', 20)).toBe('#141414');
expect(lighten('#ffffff', 30)).toBe('#ffffff');
});
test('lightens a color with alpha', () => {
expect(lighten('#00000080', 10)).toBe('#0a0a0a80');
expect(lighten('#00000080', 20)).toBe('#14141480');
expect(lighten('#ffffff80', 30)).toBe('#ffffff80');
});
});
describe('darken', () => {
test('darkens a color', () => {
expect(darken('#ffffff', 10)).toBe('#f5f5f5');
expect(darken('#ffffff', 20)).toBe('#ebebeb');
expect(darken('#000000', 30)).toBe('#000000');
});
test('darkens a color with alpha', () => {
expect(darken('#ffffff80', 10)).toBe('#f5f5f580');
});
});
describe('setOpacity', () => {
test('sets the opacity of a color', () => {
expect(setOpacity('#000000', 0.5)).toBe('#00000080');
});
test('sets the opacity of a color with alpha', () => {
expect(setOpacity('#00000000', 0.5)).toBe('#00000080');
});
});
});

View file

@ -0,0 +1,33 @@
export { lighten, darken, setOpacity };
const clampHex = (value: number) => Math.max(0, Math.min(255, Math.round(value)));
function lighten(color: string, amount: number): string {
const alpha = color.length === 9 ? color.slice(7) : '';
const num = parseInt(color.slice(1, 7), 16);
const r = clampHex(((num >> 16) & 255) + amount);
const g = clampHex(((num >> 8) & 255) + amount);
const b = clampHex((num & 255) + amount);
return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, '0')}${alpha}`;
}
function darken(color: string, amount: number): string {
return lighten(color, -amount);
}
function setOpacity(color: string, opacity: number): string {
const alpha = clampHex(Math.round(opacity * 255))
.toString(16)
.padStart(2, '0');
if (color.length === 7) {
return `${color}${alpha}`;
}
if (color.length === 9) {
return `${color.slice(0, 7)}${alpha}`;
}
throw new Error('Invalid hex color');
}