summaryrefslogtreecommitdiff
path: root/lib/colors.nix
blob: a653f115540d07b0030c155238f90844ea1dfb26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
{lib, ...}: let
  colorToInt = hex: let
    table = {
      "0" = 0;
      "1" = 1;
      "2" = 2;
      "3" = 3;
      "4" = 4;
      "5" = 5;
      "6" = 6;
      "7" = 7;
      "8" = 8;
      "9" = 9;
      "a" = 10;
      "b" = 11;
      "c" = 12;
      "d" = 13;
      "e" = 14;
      "f" = 15;
    };
  in
    builtins.foldl'
    (acc: c: acc * 16 + table.${c})
    0
    (lib.strings.stringToCharacters (lib.strings.toLower hex));

  colorToHex = n: let
    hexChars = "0123456789abcdef";
    hi = builtins.div n 16;
    lo = lib.trivial.mod n 16;
  in
    builtins.substring hi 1 hexChars
    + builtins.substring lo 1 hexChars;

  mapColor = f: hex: let
    r = colorToInt (builtins.substring 0 2 hex);
    g = colorToInt (builtins.substring 2 2 hex);
    b = colorToInt (builtins.substring 4 2 hex);
  in
    colorToHex (f r)
    + colorToHex (f g)
    + colorToHex (f b);

  darkenColor = factor: hex:
    mapColor (c: builtins.floor (c * (1 - factor))) hex;

  lightenColor = factor: hex:
    mapColor (c: builtins.floor (c + (255 - c) * factor)) hex;

  mixColor = factor: hex1: hex2: let
    r1 = colorToInt (builtins.substring 0 2 hex1);
    g1 = colorToInt (builtins.substring 2 2 hex1);
    b1 = colorToInt (builtins.substring 4 2 hex1);
    r2 = colorToInt (builtins.substring 0 2 hex2);
    g2 = colorToInt (builtins.substring 2 2 hex2);
    b2 = colorToInt (builtins.substring 4 2 hex2);
    r = builtins.floor (r1 * factor) + builtins.floor (r2 * (1 - factor));
    g = builtins.floor (g1 * factor) + builtins.floor (g2 * (1 - factor));
    b = builtins.floor (b1 * factor) + builtins.floor (b2 * (1 - factor));
  in
    colorToHex r
    + colorToHex g
    + colorToHex b;
in {
  inherit colorToInt colorToHex darkenColor lightenColor mixColor;
}