logo

pleroma-fe

My custom branche(s) on git.pleroma.social/pleroma/pleroma-fe git clone https://hacktivis.me/git/pleroma-fe.git

color_convert.js (6636B)


  1. import { invertLightness, contrastRatio } from 'chromatism'
  2. // useful for visualizing color when debugging
  3. export const consoleColor = (color) => console.log('%c##########', 'background: ' + color + '; color: ' + color)
  4. /**
  5. * Convert r, g, b values into hex notation. All components are [0-255]
  6. *
  7. * @param {Number|String|Object} r - Either red component, {r,g,b} object, or hex string
  8. * @param {Number} [g] - Green component
  9. * @param {Number} [b] - Blue component
  10. */
  11. export const rgb2hex = (r, g, b) => {
  12. if (r === null || typeof r === 'undefined') {
  13. return undefined
  14. }
  15. // TODO: clean up this mess
  16. if (r[0] === '#' || r === 'transparent') {
  17. return r
  18. }
  19. if (typeof r === 'object') {
  20. ({ r, g, b } = r)
  21. }
  22. [r, g, b] = [r, g, b].map(val => {
  23. val = Math.ceil(val)
  24. val = val < 0 ? 0 : val
  25. val = val > 255 ? 255 : val
  26. return val
  27. })
  28. return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`
  29. }
  30. /**
  31. * Converts 8-bit RGB component into linear component
  32. * https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
  33. * https://www.w3.org/TR/2008/REC-WCAG20-20081211/relative-luminance.xml
  34. * https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation
  35. *
  36. * @param {Number} bit - color component [0..255]
  37. * @returns {Number} linear component [0..1]
  38. */
  39. const c2linear = (bit) => {
  40. // W3C gives 0.03928 while wikipedia states 0.04045
  41. // what those magical numbers mean - I don't know.
  42. // something about gamma-correction, i suppose.
  43. // Sticking with W3C example.
  44. const c = bit / 255
  45. if (c < 0.03928) {
  46. return c / 12.92
  47. } else {
  48. return Math.pow((c + 0.055) / 1.055, 2.4)
  49. }
  50. }
  51. /**
  52. * Converts sRGB into linear RGB
  53. * @param {Object} srgb - sRGB color
  54. * @returns {Object} linear rgb color
  55. */
  56. const srgbToLinear = (srgb) => {
  57. return 'rgb'.split('').reduce((acc, c) => { acc[c] = c2linear(srgb[c]); return acc }, {})
  58. }
  59. /**
  60. * Calculates relative luminance for given color
  61. * https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
  62. * https://www.w3.org/TR/2008/REC-WCAG20-20081211/relative-luminance.xml
  63. *
  64. * @param {Object} srgb - sRGB color
  65. * @returns {Number} relative luminance
  66. */
  67. export const relativeLuminance = (srgb) => {
  68. const { r, g, b } = srgbToLinear(srgb)
  69. return 0.2126 * r + 0.7152 * g + 0.0722 * b
  70. }
  71. /**
  72. * Generates color ratio between two colors. Order is unimporant
  73. * https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
  74. *
  75. * @param {Object} a - sRGB color
  76. * @param {Object} b - sRGB color
  77. * @returns {Number} color ratio
  78. */
  79. export const getContrastRatio = (a, b) => {
  80. const la = relativeLuminance(a)
  81. const lb = relativeLuminance(b)
  82. const [l1, l2] = la > lb ? [la, lb] : [lb, la]
  83. return (l1 + 0.05) / (l2 + 0.05)
  84. }
  85. /**
  86. * Same as `getContrastRatio` but for multiple layers in-between
  87. *
  88. * @param {Object} text - text color (topmost layer)
  89. * @param {[Object, Number]} layers[] - layers between text and bedrock
  90. * @param {Object} bedrock - layer at the very bottom
  91. */
  92. export const getContrastRatioLayers = (text, layers, bedrock) => {
  93. return getContrastRatio(alphaBlendLayers(bedrock, layers), text)
  94. }
  95. /**
  96. * This performs alpha blending between solid background and semi-transparent foreground
  97. *
  98. * @param {Object} fg - top layer color
  99. * @param {Number} fga - top layer's alpha
  100. * @param {Object} bg - bottom layer color
  101. * @returns {Object} sRGB of resulting color
  102. */
  103. export const alphaBlend = (fg, fga, bg) => {
  104. if (fga === 1 || typeof fga === 'undefined') return fg
  105. return 'rgb'.split('').reduce((acc, c) => {
  106. // Simplified https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
  107. // for opaque bg and transparent fg
  108. acc[c] = (fg[c] * fga + bg[c] * (1 - fga))
  109. return acc
  110. }, {})
  111. }
  112. /**
  113. * Same as `alphaBlend` but for multiple layers in-between
  114. *
  115. * @param {Object} bedrock - layer at the very bottom
  116. * @param {[Object, Number]} layers[] - layers between text and bedrock
  117. */
  118. export const alphaBlendLayers = (bedrock, layers) => layers.reduce((acc, [color, opacity]) => {
  119. return alphaBlend(color, opacity, acc)
  120. }, bedrock)
  121. export const invert = (rgb) => {
  122. return 'rgb'.split('').reduce((acc, c) => {
  123. acc[c] = 255 - rgb[c]
  124. return acc
  125. }, {})
  126. }
  127. /**
  128. * Converts #rrggbb hex notation into an {r, g, b} object
  129. *
  130. * @param {String} hex - #rrggbb string
  131. * @returns {Object} rgb representation of the color, values are 0-255
  132. */
  133. export const hex2rgb = (hex) => {
  134. const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  135. return result
  136. ? {
  137. r: parseInt(result[1], 16),
  138. g: parseInt(result[2], 16),
  139. b: parseInt(result[3], 16)
  140. }
  141. : null
  142. }
  143. /**
  144. * Old somewhat weird function for mixing two colors together
  145. *
  146. * @param {Object} a - one color (rgb)
  147. * @param {Object} b - other color (rgb)
  148. * @returns {Object} result
  149. */
  150. export const mixrgb = (a, b) => {
  151. return 'rgb'.split('').reduce((acc, k) => {
  152. acc[k] = (a[k] + b[k]) / 2
  153. return acc
  154. }, {})
  155. }
  156. /**
  157. * Converts rgb object into a CSS rgba() color
  158. *
  159. * @param {Object} color - rgb
  160. * @returns {String} CSS rgba() color
  161. */
  162. export const rgba2css = function (rgba) {
  163. return `rgba(${Math.floor(rgba.r)}, ${Math.floor(rgba.g)}, ${Math.floor(rgba.b)}, ${rgba.a ?? 1})`
  164. }
  165. /**
  166. * Get text color for given background color and intended text color
  167. * This checks if text and background don't have enough color and inverts
  168. * text color's lightness if needed. If text color is still not enough it
  169. * will fall back to black or white
  170. *
  171. * @param {Object} bg - background color
  172. * @param {Object} text - intended text color
  173. * @param {Boolean} preserve - try to preserve intended text color's hue/saturation (i.e. no BW)
  174. */
  175. export const getTextColor = function (bg, text, preserve) {
  176. const contrast = getContrastRatio(bg, text)
  177. if (contrast < 4.5) {
  178. const base = typeof text.a !== 'undefined' ? { a: text.a } : {}
  179. const result = Object.assign(base, invertLightness(text).rgb)
  180. if (!preserve && getContrastRatio(bg, result) < 4.5) {
  181. // B&W
  182. return contrastRatio(bg, text).rgb
  183. }
  184. // Inverted color
  185. return result
  186. }
  187. return text
  188. }
  189. /**
  190. * Converts color to CSS Color value
  191. *
  192. * @param {Object|String} input - color
  193. * @param {Number} [a] - alpha value
  194. * @returns {String} a CSS Color value
  195. */
  196. export const getCssColor = (input, a) => {
  197. let rgb = {}
  198. if (typeof input === 'object') {
  199. rgb = input
  200. } else if (typeof input === 'string') {
  201. if (input.startsWith('#')) {
  202. rgb = hex2rgb(input)
  203. } else {
  204. return input
  205. }
  206. }
  207. return rgba2css({ ...rgb, a })
  208. }