frontend for xcvr appview
1export function ansiToHex(ansiCode: number) {
2 const rgb = ansiToRgb(ansiCode)
3 return rgbToHex(rgb)
4}
5
6export type ColorSet = {
7 theme: string
8 themetransparent: string
9 themecontrast: string
10 themecontrasttransparent: string
11}
12
13export function colorSetFromTheme(theme: number): ColorSet {
14 const color = numToHex(theme);
15 const cpartial = hexToTransparent(color);
16 const contrast = hexToContrast(color);
17 const partial = hexToTransparent(contrast);
18
19 return {
20 theme: color,
21 themetransparent: cpartial,
22 themecontrast: contrast,
23 themecontrasttransparent: partial,
24 }
25}
26
27
28export function numToHex(num: number) {
29 const int = Math.max(Math.min(16777215, Math.floor(num)), 0)
30 return "#" + int.toString(16).padStart(6, '0')
31}
32
33export function hexToNum(hex: string) {
34 return Number("0x" + hex.slice(1))
35}
36export function hexToContrast(hex: string) {
37 const r = Number("0x" + hex.slice(1, 3))
38 const g = Number("0x" + hex.slice(3, 5))
39 const b = Number("0x" + hex.slice(5))
40 const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
41 return luminance > 0.5 ? "#000000" : "#ffffff"
42}
43export function hexToTransparent(hex: string) {
44 return hex + "80"
45}
46
47function ansiToRgb(ansiCode: number): [number, number, number] {
48 // Define the standard and high-intensity colors
49 const colors: Array<[number, number, number]> = [
50 [0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],
51 [0, 0, 128], [128, 0, 128], [0, 128, 128], [192, 192, 192],
52 [128, 128, 128], [255, 0, 0], [0, 255, 0], [255, 255, 0],
53 [0, 0, 255], [255, 0, 255], [0, 255, 255], [255, 255, 255]
54 ];
55
56 if (ansiCode >= 0 && ansiCode <= 15) {
57 return colors[ansiCode];
58 } else if (ansiCode >= 16 && ansiCode <= 231) {
59 ansiCode -= 16;
60 const r = Math.floor(ansiCode / 36) * 51;
61 const g = Math.floor((ansiCode % 36) / 6) * 51;
62 const b = (ansiCode % 6) * 51;
63 return [r, g, b];
64 } else if (ansiCode >= 232 && ansiCode <= 255) {
65 const gray = (ansiCode - 232) * 10 + 8;
66 return [gray, gray, gray];
67 } else {
68 return [255, 255, 255]
69 }
70}
71
72// Function to convert RGB to Hex
73function rgbToHex([r, g, b]: [number, number, number]) {
74 return `#${((1 << 24) | (r << 16) | (g << 8) | b).toString(16).slice(1).toUpperCase()}`;
75}