UNPKG

simple-color-functions

Version:
2 lines (1 loc) 2.87 kB
"use strict";var t;!function(t){t[t.Kn=18]="Kn",t[t.Xn=.95047]="Xn",t[t.Yn=1]="Yn",t[t.Zn=1.08883]="Zn",t[t.t0=.137931034]="t0",t[t.t1=.206896552]="t1",t[t.t2=.12841855]="t2",t[t.t3=.008856452]="t3"}(t||(t={}));const r=(t,r=0,n=255)=>Math.min(Math.max(r,t),n),n=t=>{const n=t>.00304?1.055*Math.pow(t,1/2.4)-.055:12.92*t;return Math.round(255*r(n,0,1))},e=r=>r>t.t1?r*r*r:t.t2*(r-t.t0),s=({L:r,a:s,b:a})=>{let i,u,h;return u=(r+16)/116,i=isNaN(s)?u:u+s/500,h=isNaN(a)?u:u-a/200,u=t.Yn*e(u),i=t.Xn*e(i),h=t.Zn*e(h),{r:n(3.2404542*i-1.5371385*u-.4985314*h),g:n(-.969266*i+1.8760108*u+.041556*h),b:n(.0556434*i-.2040259*u+1.0572252*h),a:1}},a=t=>(t/=255)>.04045?Math.pow((t+.055)/1.055,2.4):t/12.92,i=r=>r>t.t3?Math.pow(r,1/3):r/t.t2+t.t0,u=r=>{const{x:n,y:e,z:s}=(({r:r,g:n,b:e})=>(r=a(r),n=a(n),e=a(e),{x:i((.4124564*r+.3575761*n+.1804375*e)/t.Xn),y:i((.2126729*r+.7151522*n+.072175*e)/t.Yn),z:i((.0193339*r+.119192*n+.9503041*e)/t.Zn)}))(r),u=116*e-16;return{L:u<0?0:u,a:500*(n-e),b:200*(e-s)}},h=t=>(t/=255)<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4),b=({r:t,g:r,b:n})=>{const e=h(t),s=h(r),a=h(n);return Math.sqrt(.299*e*e+.587*s*s+.114*a*a)},g=t=>{if(!t)throw"Color not passed";return(t=>/^#?([a-f\d]{1,2})([a-f\d]{1,2})([a-f\d]{1,2})$/i.test(t))(t)?(t=>{const r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec((t=>{if(4!==t.length)return t;return t.split("").slice(1).reduce((t,r)=>t+r+r,"#")})(t))||[];return{r:parseInt(r[1],16),g:parseInt(r[2],16),b:parseInt(r[3],16),a:1}})(t):(t=>{if(!t)return!1;const r=t.replace(/\s+/g,"").split(",");return 3===r.length&&r.every(t=>{const r=/^\+?(0|[1-9]\d*)$/.test(t),n=parseInt(t,10);return r&&n>=0&&n<=255})})(t)?(t=>{const r=t.replace(/\s+/g,"").split(",").map(t=>parseInt(t,10));return{r:r[0],g:r[1],b:r[2],a:1}})(t):{r:-1,g:-1,b:-1,a:1}},o=(t,n)=>{const{L:e,a:a,b:i}=u(t),h=r(e*(1+(t=>{if("string"==typeof t){const r="%"===t[t.length-1],n=/^0?\.\d+$/.test(t);return r&&!n?parseFloat(t.replace("%",""))/100:parseFloat(t)}if("number"==typeof t){if(Math.abs(t)<=1)return t;if(Math.abs(t)<=100)return t/100}return 0})(n)),0,100);return s({L:h,a:a,b:i})};class c{constructor(t){this._rgb=g(t)}rgb(){return this._rgb}css(){const{r:t,g:r,b:n,a:e}=this._rgb;return 1!==e&&e?e>0&&e<1&&`rgba(${t},${r},${n},${e})`:`rgb(${t},${r},${n})`}hex(){return(({r:t,g:r,b:n})=>[t,r,n].reduce((t,r)=>{const n=r.toString(16);return t+=n.length>1?n:`0${n}`},"#"))(this._rgb)}alpha(t){return this._rgb=Object.assign(Object.assign({},this._rgb),{a:t>=0&&t<=1?t:1}),this}darken(r=1){const{L:n,a:e,b:a}=u(this._rgb);return this._rgb=s({L:n-t.Kn*r,a:e,b:a}),this}brighten(t=1){return this.darken(-t)}brightness(t){return this._rgb=o(this._rgb,t),this}luminance(t){return b(t||this._rgb)}contrast(t){const r=b(this._rgb),n=b(g(t));return r>n?(r+.05)/(n+.05):(n+.05)/(r+.05)}toString(){return this.hex()}}module.exports=function(t){return new c(t)};