index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. const colorString = require('color-string');
  2. const convert = require('color-convert');
  3. const skippedModels = [
  4. // To be honest, I don't really feel like keyword belongs in color convert, but eh.
  5. 'keyword',
  6. // Gray conflicts with some method names, and has its own method defined.
  7. 'gray',
  8. // Shouldn't really be in color-convert either...
  9. 'hex',
  10. ];
  11. const hashedModelKeys = {};
  12. for (const model of Object.keys(convert)) {
  13. hashedModelKeys[[...convert[model].labels].sort().join('')] = model;
  14. }
  15. const limiters = {};
  16. function Color(object, model) {
  17. if (!(this instanceof Color)) {
  18. return new Color(object, model);
  19. }
  20. if (model && model in skippedModels) {
  21. model = null;
  22. }
  23. if (model && !(model in convert)) {
  24. throw new Error('Unknown model: ' + model);
  25. }
  26. let i;
  27. let channels;
  28. if (object == null) { // eslint-disable-line no-eq-null,eqeqeq
  29. this.model = 'rgb';
  30. this.color = [0, 0, 0];
  31. this.valpha = 1;
  32. } else if (object instanceof Color) {
  33. this.model = object.model;
  34. this.color = [...object.color];
  35. this.valpha = object.valpha;
  36. } else if (typeof object === 'string') {
  37. const result = colorString.get(object);
  38. if (result === null) {
  39. throw new Error('Unable to parse color from string: ' + object);
  40. }
  41. this.model = result.model;
  42. channels = convert[this.model].channels;
  43. this.color = result.value.slice(0, channels);
  44. this.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1;
  45. } else if (object.length > 0) {
  46. this.model = model || 'rgb';
  47. channels = convert[this.model].channels;
  48. const newArray = Array.prototype.slice.call(object, 0, channels);
  49. this.color = zeroArray(newArray, channels);
  50. this.valpha = typeof object[channels] === 'number' ? object[channels] : 1;
  51. } else if (typeof object === 'number') {
  52. // This is always RGB - can be converted later on.
  53. this.model = 'rgb';
  54. this.color = [
  55. (object >> 16) & 0xFF,
  56. (object >> 8) & 0xFF,
  57. object & 0xFF,
  58. ];
  59. this.valpha = 1;
  60. } else {
  61. this.valpha = 1;
  62. const keys = Object.keys(object);
  63. if ('alpha' in object) {
  64. keys.splice(keys.indexOf('alpha'), 1);
  65. this.valpha = typeof object.alpha === 'number' ? object.alpha : 0;
  66. }
  67. const hashedKeys = keys.sort().join('');
  68. if (!(hashedKeys in hashedModelKeys)) {
  69. throw new Error('Unable to parse color from object: ' + JSON.stringify(object));
  70. }
  71. this.model = hashedModelKeys[hashedKeys];
  72. const {labels} = convert[this.model];
  73. const color = [];
  74. for (i = 0; i < labels.length; i++) {
  75. color.push(object[labels[i]]);
  76. }
  77. this.color = zeroArray(color);
  78. }
  79. // Perform limitations (clamping, etc.)
  80. if (limiters[this.model]) {
  81. channels = convert[this.model].channels;
  82. for (i = 0; i < channels; i++) {
  83. const limit = limiters[this.model][i];
  84. if (limit) {
  85. this.color[i] = limit(this.color[i]);
  86. }
  87. }
  88. }
  89. this.valpha = Math.max(0, Math.min(1, this.valpha));
  90. if (Object.freeze) {
  91. Object.freeze(this);
  92. }
  93. }
  94. Color.prototype = {
  95. toString() {
  96. return this.string();
  97. },
  98. toJSON() {
  99. return this[this.model]();
  100. },
  101. string(places) {
  102. let self = this.model in colorString.to ? this : this.rgb();
  103. self = self.round(typeof places === 'number' ? places : 1);
  104. const args = self.valpha === 1 ? self.color : [...self.color, this.valpha];
  105. return colorString.to[self.model](args);
  106. },
  107. percentString(places) {
  108. const self = this.rgb().round(typeof places === 'number' ? places : 1);
  109. const args = self.valpha === 1 ? self.color : [...self.color, this.valpha];
  110. return colorString.to.rgb.percent(args);
  111. },
  112. array() {
  113. return this.valpha === 1 ? [...this.color] : [...this.color, this.valpha];
  114. },
  115. object() {
  116. const result = {};
  117. const {channels} = convert[this.model];
  118. const {labels} = convert[this.model];
  119. for (let i = 0; i < channels; i++) {
  120. result[labels[i]] = this.color[i];
  121. }
  122. if (this.valpha !== 1) {
  123. result.alpha = this.valpha;
  124. }
  125. return result;
  126. },
  127. unitArray() {
  128. const rgb = this.rgb().color;
  129. rgb[0] /= 255;
  130. rgb[1] /= 255;
  131. rgb[2] /= 255;
  132. if (this.valpha !== 1) {
  133. rgb.push(this.valpha);
  134. }
  135. return rgb;
  136. },
  137. unitObject() {
  138. const rgb = this.rgb().object();
  139. rgb.r /= 255;
  140. rgb.g /= 255;
  141. rgb.b /= 255;
  142. if (this.valpha !== 1) {
  143. rgb.alpha = this.valpha;
  144. }
  145. return rgb;
  146. },
  147. round(places) {
  148. places = Math.max(places || 0, 0);
  149. return new Color([...this.color.map(roundToPlace(places)), this.valpha], this.model);
  150. },
  151. alpha(value) {
  152. if (value !== undefined) {
  153. return new Color([...this.color, Math.max(0, Math.min(1, value))], this.model);
  154. }
  155. return this.valpha;
  156. },
  157. // Rgb
  158. red: getset('rgb', 0, maxfn(255)),
  159. green: getset('rgb', 1, maxfn(255)),
  160. blue: getset('rgb', 2, maxfn(255)),
  161. hue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, value => ((value % 360) + 360) % 360),
  162. saturationl: getset('hsl', 1, maxfn(100)),
  163. lightness: getset('hsl', 2, maxfn(100)),
  164. saturationv: getset('hsv', 1, maxfn(100)),
  165. value: getset('hsv', 2, maxfn(100)),
  166. chroma: getset('hcg', 1, maxfn(100)),
  167. gray: getset('hcg', 2, maxfn(100)),
  168. white: getset('hwb', 1, maxfn(100)),
  169. wblack: getset('hwb', 2, maxfn(100)),
  170. cyan: getset('cmyk', 0, maxfn(100)),
  171. magenta: getset('cmyk', 1, maxfn(100)),
  172. yellow: getset('cmyk', 2, maxfn(100)),
  173. black: getset('cmyk', 3, maxfn(100)),
  174. x: getset('xyz', 0, maxfn(95.047)),
  175. y: getset('xyz', 1, maxfn(100)),
  176. z: getset('xyz', 2, maxfn(108.833)),
  177. l: getset('lab', 0, maxfn(100)),
  178. a: getset('lab', 1),
  179. b: getset('lab', 2),
  180. keyword(value) {
  181. if (value !== undefined) {
  182. return new Color(value);
  183. }
  184. return convert[this.model].keyword(this.color);
  185. },
  186. hex(value) {
  187. if (value !== undefined) {
  188. return new Color(value);
  189. }
  190. return colorString.to.hex(this.rgb().round().color);
  191. },
  192. hexa(value) {
  193. if (value !== undefined) {
  194. return new Color(value);
  195. }
  196. const rgbArray = this.rgb().round().color;
  197. let alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase();
  198. if (alphaHex.length === 1) {
  199. alphaHex = '0' + alphaHex;
  200. }
  201. return colorString.to.hex(rgbArray) + alphaHex;
  202. },
  203. rgbNumber() {
  204. const rgb = this.rgb().color;
  205. return ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF);
  206. },
  207. luminosity() {
  208. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  209. const rgb = this.rgb().color;
  210. const lum = [];
  211. for (const [i, element] of rgb.entries()) {
  212. const chan = element / 255;
  213. lum[i] = (chan <= 0.04045) ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4;
  214. }
  215. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  216. },
  217. contrast(color2) {
  218. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  219. const lum1 = this.luminosity();
  220. const lum2 = color2.luminosity();
  221. if (lum1 > lum2) {
  222. return (lum1 + 0.05) / (lum2 + 0.05);
  223. }
  224. return (lum2 + 0.05) / (lum1 + 0.05);
  225. },
  226. level(color2) {
  227. // https://www.w3.org/TR/WCAG/#contrast-enhanced
  228. const contrastRatio = this.contrast(color2);
  229. if (contrastRatio >= 7) {
  230. return 'AAA';
  231. }
  232. return (contrastRatio >= 4.5) ? 'AA' : '';
  233. },
  234. isDark() {
  235. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  236. const rgb = this.rgb().color;
  237. const yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 10000;
  238. return yiq < 128;
  239. },
  240. isLight() {
  241. return !this.isDark();
  242. },
  243. negate() {
  244. const rgb = this.rgb();
  245. for (let i = 0; i < 3; i++) {
  246. rgb.color[i] = 255 - rgb.color[i];
  247. }
  248. return rgb;
  249. },
  250. lighten(ratio) {
  251. const hsl = this.hsl();
  252. hsl.color[2] += hsl.color[2] * ratio;
  253. return hsl;
  254. },
  255. darken(ratio) {
  256. const hsl = this.hsl();
  257. hsl.color[2] -= hsl.color[2] * ratio;
  258. return hsl;
  259. },
  260. saturate(ratio) {
  261. const hsl = this.hsl();
  262. hsl.color[1] += hsl.color[1] * ratio;
  263. return hsl;
  264. },
  265. desaturate(ratio) {
  266. const hsl = this.hsl();
  267. hsl.color[1] -= hsl.color[1] * ratio;
  268. return hsl;
  269. },
  270. whiten(ratio) {
  271. const hwb = this.hwb();
  272. hwb.color[1] += hwb.color[1] * ratio;
  273. return hwb;
  274. },
  275. blacken(ratio) {
  276. const hwb = this.hwb();
  277. hwb.color[2] += hwb.color[2] * ratio;
  278. return hwb;
  279. },
  280. grayscale() {
  281. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  282. const rgb = this.rgb().color;
  283. const value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  284. return Color.rgb(value, value, value);
  285. },
  286. fade(ratio) {
  287. return this.alpha(this.valpha - (this.valpha * ratio));
  288. },
  289. opaquer(ratio) {
  290. return this.alpha(this.valpha + (this.valpha * ratio));
  291. },
  292. rotate(degrees) {
  293. const hsl = this.hsl();
  294. let hue = hsl.color[0];
  295. hue = (hue + degrees) % 360;
  296. hue = hue < 0 ? 360 + hue : hue;
  297. hsl.color[0] = hue;
  298. return hsl;
  299. },
  300. mix(mixinColor, weight) {
  301. // Ported from sass implementation in C
  302. // https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  303. if (!mixinColor || !mixinColor.rgb) {
  304. throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor);
  305. }
  306. const color1 = mixinColor.rgb();
  307. const color2 = this.rgb();
  308. const p = weight === undefined ? 0.5 : weight;
  309. const w = 2 * p - 1;
  310. const a = color1.alpha() - color2.alpha();
  311. const w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2;
  312. const w2 = 1 - w1;
  313. return Color.rgb(
  314. w1 * color1.red() + w2 * color2.red(),
  315. w1 * color1.green() + w2 * color2.green(),
  316. w1 * color1.blue() + w2 * color2.blue(),
  317. color1.alpha() * p + color2.alpha() * (1 - p));
  318. },
  319. };
  320. // Model conversion methods and static constructors
  321. for (const model of Object.keys(convert)) {
  322. if (skippedModels.includes(model)) {
  323. continue;
  324. }
  325. const {channels} = convert[model];
  326. // Conversion methods
  327. Color.prototype[model] = function (...args) {
  328. if (this.model === model) {
  329. return new Color(this);
  330. }
  331. if (args.length > 0) {
  332. return new Color(args, model);
  333. }
  334. return new Color([...assertArray(convert[this.model][model].raw(this.color)), this.valpha], model);
  335. };
  336. // 'static' construction methods
  337. Color[model] = function (...args) {
  338. let color = args[0];
  339. if (typeof color === 'number') {
  340. color = zeroArray(args, channels);
  341. }
  342. return new Color(color, model);
  343. };
  344. }
  345. function roundTo(number, places) {
  346. return Number(number.toFixed(places));
  347. }
  348. function roundToPlace(places) {
  349. return function (number) {
  350. return roundTo(number, places);
  351. };
  352. }
  353. function getset(model, channel, modifier) {
  354. model = Array.isArray(model) ? model : [model];
  355. for (const m of model) {
  356. (limiters[m] || (limiters[m] = []))[channel] = modifier;
  357. }
  358. model = model[0];
  359. return function (value) {
  360. let result;
  361. if (value !== undefined) {
  362. if (modifier) {
  363. value = modifier(value);
  364. }
  365. result = this[model]();
  366. result.color[channel] = value;
  367. return result;
  368. }
  369. result = this[model]().color[channel];
  370. if (modifier) {
  371. result = modifier(result);
  372. }
  373. return result;
  374. };
  375. }
  376. function maxfn(max) {
  377. return function (v) {
  378. return Math.max(0, Math.min(max, v));
  379. };
  380. }
  381. function assertArray(value) {
  382. return Array.isArray(value) ? value : [value];
  383. }
  384. function zeroArray(array, length) {
  385. for (let i = 0; i < length; i++) {
  386. if (typeof array[i] !== 'number') {
  387. array[i] = 0;
  388. }
  389. }
  390. return array;
  391. }
  392. module.exports = Color;