Debian Codegraph @

node/@xterm/xterm/src/common/input/XParseColor.ts

raw
1 /**
2 * Copyright (c) 2021 The xterm.js authors. All rights reserved.
3 * @license MIT
4 */
5
6
7 // 'rgb:' rule - matching: r/g/b | rr/gg/bb | rrr/ggg/bbb | rrrr/gggg/bbbb (hex digits)
8 const RGB_REX = /^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/;
9 // '#...' rule - matching any hex digits
10 const HASH_REX = /^[\da-f]+$/;
11
12 /**
13 * Parse color spec to RGB values (8 bit per channel).
14 * See `man xparsecolor` for details about certain format specifications.
15 *
16 * Supported formats:
17 * - rgb:<red>/<green>/<blue> with <red>, <green>, <blue> in h | hh | hhh | hhhh
18 * - #RGB, #RRGGBB, #RRRGGGBBB, #RRRRGGGGBBBB
19 *
20 * All other formats like rgbi: or device-independent string specifications
21 * with float numbering are not supported.
22 */
23 export function parseColor(data: string): [number, number, number] | undefined {
24 if (!data) return;
25 // also handle uppercases
26 let low = data.toLowerCase();
27 if (low.indexOf('rgb:') === 0) {
28 // 'rgb:' specifier
29 low = low.slice(4);
30 const m = RGB_REX.exec(low);
31 if (m) {
32 const base = m[1] ? 15 : m[4] ? 255 : m[7] ? 4095 : 65535;
33 return [
34 Math.round(parseInt(m[1] || m[4] || m[7] || m[10], 16) / base * 255),
35 Math.round(parseInt(m[2] || m[5] || m[8] || m[11], 16) / base * 255),
36 Math.round(parseInt(m[3] || m[6] || m[9] || m[12], 16) / base * 255)
37 ];
38 }
39 } else if (low.indexOf('#') === 0) {
40 // '#' specifier
41 low = low.slice(1);
42 if (HASH_REX.exec(low) && [3, 6, 9, 12].includes(low.length)) {
43 const adv = low.length / 3;
44 const result: [number, number, number] = [0, 0, 0];
45 for (let i = 0; i < 3; ++i) {
46 const c = parseInt(low.slice(adv * i, adv * i + adv), 16);
47 result[i] = adv === 1 ? c << 4 : adv === 2 ? c : adv === 3 ? c >> 4 : c >> 8;
48 }
49 return result;
50 }
51 }
52
53 // Named colors are currently not supported due to the large addition to the xterm.js bundle size
54 // they would add. In order to support named colors, we would need some way of optionally loading
55 // additional payloads so startup/download time is not bloated (see #3530).
56 }
57
58 // pad hex output to requested bit width
59 function pad(n: number, bits: number): string {
60 const s = n.toString(16);
61 const s2 = s.length < 2 ? '0' + s : s;
62 switch (bits) {
63 case 4:
64 return s[0];
65 case 8:
66 return s2;
67 case 12:
68 return (s2 + s2).slice(0, 3);
69 default:
70 return s2 + s2;
71 }
72 }
73
74 /**
75 * Convert a given color to rgb:../../.. string of `bits` depth.
76 */
77 export function toRgbString(color: [number, number, number], bits: number = 16): string {
78 const [r, g, b] = color;
79 return `rgb:${pad(r, bits)}/${pad(g, bits)}/${pad(b, bits)}`;
80 }