css-color-parser-h 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.js ADDED
@@ -0,0 +1,36 @@
1
+ module.exports = {
2
+ settings: {
3
+ 'import/resolver': {
4
+ node: {
5
+ moduleDirectory: ['node_modules', 'src'],
6
+ extensions: ['.js', '.jsx', '.ts', '.tsx']
7
+ }
8
+ }
9
+ },
10
+ parser: '@typescript-eslint/parser',
11
+ plugins: ['@typescript-eslint'],
12
+ rules: {
13
+ 'no-console': 'off',
14
+ 'no-var': 'error', // 不能使用var声明变量
15
+ 'no-extra-semi': 'off',
16
+ '@typescript-eslint/indent': ['error', 2],
17
+ 'import/extensions': 'off',
18
+ 'linebreak-style': [0, 'error', 'windows'],
19
+ indent: ['error', 2, { SwitchCase: 1 }], // error类型,缩进2个空格
20
+ 'space-before-function-paren': 0, // 在函数左括号的前面是否有空格
21
+ 'eol-last': 0, // 不检测新文件末尾是否有空行
22
+ semi: ['error', 'never'], // 在语句后面加分号
23
+ quotes: ['error', 'single'], // 字符串使用单双引号,double,single
24
+ 'arrow-parens': 0,
25
+ 'no-new': 0, //允许使用 new 关键字
26
+ 'comma-dangle': [2, 'never'], // 数组和对象键值对最后一个逗号, never参数:不能带末尾的逗号, always参数:必须带末尾的逗号,always-multiline多行模式必须带逗号,单行模式不能带逗号
27
+ 'no-undef': 0
28
+ },
29
+ parserOptions: {
30
+ ecmaVersion: 6,
31
+ sourceType: 'module',
32
+ ecmaFeatures: {
33
+ modules: true
34
+ }
35
+ }
36
+ }
package/.prettierrc.js ADDED
@@ -0,0 +1,7 @@
1
+ module.exports = {
2
+ tabWidth: 2,
3
+ semi: false,
4
+ singleQuote: true,
5
+ trailingComma: 'none',
6
+ arrowParens: 'always'
7
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 roman_123
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ !function(r,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Parser=e():r.Parser=e()}(this,(function(){return function(){var r={168:function(r,e,t){const n=t(874),a={};for(const r of Object.keys(n))a[n[r]]=r;const o={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};r.exports=o;for(const r of Object.keys(o)){if(!("channels"in o[r]))throw new Error("missing channels property: "+r);if(!("labels"in o[r]))throw new Error("missing channel labels property: "+r);if(o[r].labels.length!==o[r].channels)throw new Error("channel and label counts mismatch: "+r);const{channels:e,labels:t}=o[r];delete o[r].channels,delete o[r].labels,Object.defineProperty(o[r],"channels",{value:e}),Object.defineProperty(o[r],"labels",{value:t})}o.rgb.hsl=function(r){const e=r[0]/255,t=r[1]/255,n=r[2]/255,a=Math.min(e,t,n),o=Math.max(e,t,n),s=o-a;let c,i;o===a?c=0:e===o?c=(t-n)/s:t===o?c=2+(n-e)/s:n===o&&(c=4+(e-t)/s),c=Math.min(60*c,360),c<0&&(c+=360);const l=(a+o)/2;return i=o===a?0:l<=.5?s/(o+a):s/(2-o-a),[c,100*i,100*l]},o.rgb.hsv=function(r){let e,t,n,a,o;const s=r[0]/255,c=r[1]/255,i=r[2]/255,l=Math.max(s,c,i),u=l-Math.min(s,c,i),h=function(r){return(l-r)/6/u+.5};return 0===u?(a=0,o=0):(o=u/l,e=h(s),t=h(c),n=h(i),s===l?a=n-t:c===l?a=1/3+e-n:i===l&&(a=2/3+t-e),a<0?a+=1:a>1&&(a-=1)),[360*a,100*o,100*l]},o.rgb.hwb=function(r){const e=r[0],t=r[1];let n=r[2];const a=o.rgb.hsl(r)[0],s=1/255*Math.min(e,Math.min(t,n));return n=1-1/255*Math.max(e,Math.max(t,n)),[a,100*s,100*n]},o.rgb.cmyk=function(r){const e=r[0]/255,t=r[1]/255,n=r[2]/255,a=Math.min(1-e,1-t,1-n);return[100*((1-e-a)/(1-a)||0),100*((1-t-a)/(1-a)||0),100*((1-n-a)/(1-a)||0),100*a]},o.rgb.keyword=function(r){const e=a[r];if(e)return e;let t,o=1/0;for(const e of Object.keys(n)){const a=(c=n[e],((s=r)[0]-c[0])**2+(s[1]-c[1])**2+(s[2]-c[2])**2);a<o&&(o=a,t=e)}var s,c;return t},o.keyword.rgb=function(r){return n[r]},o.rgb.xyz=function(r){let e=r[0]/255,t=r[1]/255,n=r[2]/255;return e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92,[100*(.4124*e+.3576*t+.1805*n),100*(.2126*e+.7152*t+.0722*n),100*(.0193*e+.1192*t+.9505*n)]},o.rgb.lab=function(r){const e=o.rgb.xyz(r);let t=e[0],n=e[1],a=e[2];return t/=95.047,n/=100,a/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,a=a>.008856?a**(1/3):7.787*a+16/116,[116*n-16,500*(t-n),200*(n-a)]},o.hsl.rgb=function(r){const e=r[0]/360,t=r[1]/100,n=r[2]/100;let a,o,s;if(0===t)return s=255*n,[s,s,s];a=n<.5?n*(1+t):n+t-n*t;const c=2*n-a,i=[0,0,0];for(let r=0;r<3;r++)o=e+1/3*-(r-1),o<0&&o++,o>1&&o--,s=6*o<1?c+6*(a-c)*o:2*o<1?a:3*o<2?c+(a-c)*(2/3-o)*6:c,i[r]=255*s;return i},o.hsl.hsv=function(r){const e=r[0];let t=r[1]/100,n=r[2]/100,a=t;const o=Math.max(n,.01);return n*=2,t*=n<=1?n:2-n,a*=o<=1?o:2-o,[e,100*(0===n?2*a/(o+a):2*t/(n+t)),(n+t)/2*100]},o.hsv.rgb=function(r){const e=r[0]/60,t=r[1]/100;let n=r[2]/100;const a=Math.floor(e)%6,o=e-Math.floor(e),s=255*n*(1-t),c=255*n*(1-t*o),i=255*n*(1-t*(1-o));switch(n*=255,a){case 0:return[n,i,s];case 1:return[c,n,s];case 2:return[s,n,i];case 3:return[s,c,n];case 4:return[i,s,n];case 5:return[n,s,c]}},o.hsv.hsl=function(r){const e=r[0],t=r[1]/100,n=r[2]/100,a=Math.max(n,.01);let o,s;s=(2-t)*n;const c=(2-t)*a;return o=t*a,o/=c<=1?c:2-c,o=o||0,s/=2,[e,100*o,100*s]},o.hwb.rgb=function(r){const e=r[0]/360;let t=r[1]/100,n=r[2]/100;const a=t+n;let o;a>1&&(t/=a,n/=a);const s=Math.floor(6*e),c=1-n;o=6*e-s,0!=(1&s)&&(o=1-o);const i=t+o*(c-t);let l,u,h;switch(s){default:case 6:case 0:l=c,u=i,h=t;break;case 1:l=i,u=c,h=t;break;case 2:l=t,u=c,h=i;break;case 3:l=t,u=i,h=c;break;case 4:l=i,u=t,h=c;break;case 5:l=c,u=t,h=i}return[255*l,255*u,255*h]},o.cmyk.rgb=function(r){const e=r[0]/100,t=r[1]/100,n=r[2]/100,a=r[3]/100;return[255*(1-Math.min(1,e*(1-a)+a)),255*(1-Math.min(1,t*(1-a)+a)),255*(1-Math.min(1,n*(1-a)+a))]},o.xyz.rgb=function(r){const e=r[0]/100,t=r[1]/100,n=r[2]/100;let a,o,s;return a=3.2406*e+-1.5372*t+-.4986*n,o=-.9689*e+1.8758*t+.0415*n,s=.0557*e+-.204*t+1.057*n,a=a>.0031308?1.055*a**(1/2.4)-.055:12.92*a,o=o>.0031308?1.055*o**(1/2.4)-.055:12.92*o,s=s>.0031308?1.055*s**(1/2.4)-.055:12.92*s,a=Math.min(Math.max(0,a),1),o=Math.min(Math.max(0,o),1),s=Math.min(Math.max(0,s),1),[255*a,255*o,255*s]},o.xyz.lab=function(r){let e=r[0],t=r[1],n=r[2];return e/=95.047,t/=100,n/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,[116*t-16,500*(e-t),200*(t-n)]},o.lab.xyz=function(r){let e,t,n;t=(r[0]+16)/116,e=r[1]/500+t,n=t-r[2]/200;const a=t**3,o=e**3,s=n**3;return t=a>.008856?a:(t-16/116)/7.787,e=o>.008856?o:(e-16/116)/7.787,n=s>.008856?s:(n-16/116)/7.787,e*=95.047,t*=100,n*=108.883,[e,t,n]},o.lab.lch=function(r){const e=r[0],t=r[1],n=r[2];let a;return a=360*Math.atan2(n,t)/2/Math.PI,a<0&&(a+=360),[e,Math.sqrt(t*t+n*n),a]},o.lch.lab=function(r){const e=r[0],t=r[1],n=r[2]/360*2*Math.PI;return[e,t*Math.cos(n),t*Math.sin(n)]},o.rgb.ansi16=function(r,e=null){const[t,n,a]=r;let s=null===e?o.rgb.hsv(r)[2]:e;if(s=Math.round(s/50),0===s)return 30;let c=30+(Math.round(a/255)<<2|Math.round(n/255)<<1|Math.round(t/255));return 2===s&&(c+=60),c},o.hsv.ansi16=function(r){return o.rgb.ansi16(o.hsv.rgb(r),r[2])},o.rgb.ansi256=function(r){const e=r[0],t=r[1],n=r[2];return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},o.ansi16.rgb=function(r){let e=r%10;if(0===e||7===e)return r>50&&(e+=3.5),e=e/10.5*255,[e,e,e];const t=.5*(1+~~(r>50));return[(1&e)*t*255,(e>>1&1)*t*255,(e>>2&1)*t*255]},o.ansi256.rgb=function(r){if(r>=232){const e=10*(r-232)+8;return[e,e,e]}let e;return r-=16,[Math.floor(r/36)/5*255,Math.floor((e=r%36)/6)/5*255,e%6/5*255]},o.rgb.hex=function(r){const e=(((255&Math.round(r[0]))<<16)+((255&Math.round(r[1]))<<8)+(255&Math.round(r[2]))).toString(16).toUpperCase();return"000000".substring(e.length)+e},o.hex.rgb=function(r){const e=r.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let t=e[0];3===e[0].length&&(t=t.split("").map((r=>r+r)).join(""));const n=parseInt(t,16);return[n>>16&255,n>>8&255,255&n]},o.rgb.hcg=function(r){const e=r[0]/255,t=r[1]/255,n=r[2]/255,a=Math.max(Math.max(e,t),n),o=Math.min(Math.min(e,t),n),s=a-o;let c,i;return c=s<1?o/(1-s):0,i=s<=0?0:a===e?(t-n)/s%6:a===t?2+(n-e)/s:4+(e-t)/s,i/=6,i%=1,[360*i,100*s,100*c]},o.hsl.hcg=function(r){const e=r[1]/100,t=r[2]/100,n=t<.5?2*e*t:2*e*(1-t);let a=0;return n<1&&(a=(t-.5*n)/(1-n)),[r[0],100*n,100*a]},o.hsv.hcg=function(r){const e=r[1]/100,t=r[2]/100,n=e*t;let a=0;return n<1&&(a=(t-n)/(1-n)),[r[0],100*n,100*a]},o.hcg.rgb=function(r){const e=r[0]/360,t=r[1]/100,n=r[2]/100;if(0===t)return[255*n,255*n,255*n];const a=[0,0,0],o=e%1*6,s=o%1,c=1-s;let i=0;switch(Math.floor(o)){case 0:a[0]=1,a[1]=s,a[2]=0;break;case 1:a[0]=c,a[1]=1,a[2]=0;break;case 2:a[0]=0,a[1]=1,a[2]=s;break;case 3:a[0]=0,a[1]=c,a[2]=1;break;case 4:a[0]=s,a[1]=0,a[2]=1;break;default:a[0]=1,a[1]=0,a[2]=c}return i=(1-t)*n,[255*(t*a[0]+i),255*(t*a[1]+i),255*(t*a[2]+i)]},o.hcg.hsv=function(r){const e=r[1]/100,t=e+r[2]/100*(1-e);let n=0;return t>0&&(n=e/t),[r[0],100*n,100*t]},o.hcg.hsl=function(r){const e=r[1]/100,t=r[2]/100*(1-e)+.5*e;let n=0;return t>0&&t<.5?n=e/(2*t):t>=.5&&t<1&&(n=e/(2*(1-t))),[r[0],100*n,100*t]},o.hcg.hwb=function(r){const e=r[1]/100,t=e+r[2]/100*(1-e);return[r[0],100*(t-e),100*(1-t)]},o.hwb.hcg=function(r){const e=r[1]/100,t=1-r[2]/100,n=t-e;let a=0;return n<1&&(a=(t-n)/(1-n)),[r[0],100*n,100*a]},o.apple.rgb=function(r){return[r[0]/65535*255,r[1]/65535*255,r[2]/65535*255]},o.rgb.apple=function(r){return[r[0]/255*65535,r[1]/255*65535,r[2]/255*65535]},o.gray.rgb=function(r){return[r[0]/100*255,r[0]/100*255,r[0]/100*255]},o.gray.hsl=function(r){return[0,0,r[0]]},o.gray.hsv=o.gray.hsl,o.gray.hwb=function(r){return[0,100,r[0]]},o.gray.cmyk=function(r){return[0,0,0,r[0]]},o.gray.lab=function(r){return[r[0],0,0]},o.gray.hex=function(r){const e=255&Math.round(r[0]/100*255),t=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(t.length)+t},o.rgb.gray=function(r){return[(r[0]+r[1]+r[2])/3/255*100]}},85:function(r,e,t){const n=t(168),a=t(111),o={};Object.keys(n).forEach((r=>{o[r]={},Object.defineProperty(o[r],"channels",{value:n[r].channels}),Object.defineProperty(o[r],"labels",{value:n[r].labels});const e=a(r);Object.keys(e).forEach((t=>{const n=e[t];o[r][t]=function(r){const e=function(...e){const t=e[0];if(null==t)return t;t.length>1&&(e=t);const n=r(e);if("object"==typeof n)for(let r=n.length,e=0;e<r;e++)n[e]=Math.round(n[e]);return n};return"conversion"in r&&(e.conversion=r.conversion),e}(n),o[r][t].raw=function(r){const e=function(...e){const t=e[0];return null==t?t:(t.length>1&&(e=t),r(e))};return"conversion"in r&&(e.conversion=r.conversion),e}(n)}))})),r.exports=o},111:function(r,e,t){const n=t(168);function a(r,e){return function(t){return e(r(t))}}function o(r,e){const t=[e[r].parent,r];let o=n[e[r].parent][r],s=e[r].parent;for(;e[s].parent;)t.unshift(e[s].parent),o=a(n[e[s].parent][s],o),s=e[s].parent;return o.conversion=t,o}r.exports=function(r){const e=function(r){const e=function(){const r={},e=Object.keys(n);for(let t=e.length,n=0;n<t;n++)r[e[n]]={distance:-1,parent:null};return r}(),t=[r];for(e[r].distance=0;t.length;){const r=t.pop(),a=Object.keys(n[r]);for(let n=a.length,o=0;o<n;o++){const n=a[o],s=e[n];-1===s.distance&&(s.distance=e[r].distance+1,s.parent=r,t.unshift(n))}}return e}(r),t={},a=Object.keys(e);for(let r=a.length,n=0;n<r;n++){const r=a[n];null!==e[r].parent&&(t[r]=o(r,e))}return t}},874:function(r){"use strict";r.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}}},e={};function t(n){var a=e[n];if(void 0!==a)return a.exports;var o=e[n]={exports:{}};return r[n](o,o.exports,t),o.exports}t.d=function(r,e){for(var n in e)t.o(e,n)&&!t.o(r,n)&&Object.defineProperty(r,n,{enumerable:!0,get:e[n]})},t.o=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},t.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})};var n={};return function(){"use strict";t.r(n),t.d(n,{ColorJson:function(){return i},CssColorParser:function(){return c}});var r=function(){function r(){}return r.type=function(r,e,t){var n=typeof t;if(n!==r)throw new Error("Expected ".concat(e," to be typeof ").concat(r,", actual typeof was ").concat(n))},r.types=function(r,e,t){var n=typeof t;if(!r.includes(n))throw new Error("Expected ".concat(e," to be typeof ").concat(r.join("|"),", actual typeof was ").concat(n))},r}();function e(r,e){return null==r||isNaN(r)&&"number"==typeof e?e:r}function a(r,e,t){return t>e?t=e:t<r&&(t=r),t}var o=function(){function r(){}return r.clearStrSpace=function(r){return r.replace(/\s/g,"")},r.trimStr=function(r){return(r=r.replace(/\s+/g," ")).trim()},r.parse3BitsHEX=function(t){var n=/^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/i.exec(t);if(n){var a=e(n[4],"f");return[r._parseResStrForRgb(parseInt(n[1]+n[1],16)),r._parseResStrForRgb(parseInt(n[2]+n[2],16)),r._parseResStrForRgb(parseInt(n[3]+n[3],16)),r._parsePercent(parseInt(a+a,16)/255)]}return null},r.parse6BitsHEX=function(t){var n=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i.exec(t);if(n){var a=e(n[4],"ff");return[r._parseResStrForRgb(parseInt(n[1],16)),r._parseResStrForRgb(parseInt(n[2],16)),r._parseResStrForRgb(parseInt(n[3],16)),r._parsePercent(parseInt(a,16)/255)]}return null},r.parseRGBA=function(e){var t=/^rgba?\(([0-9.]+%?),([0-9.]+%?),([0-9.]+%?)(?:,([0-9.]+%?))?\)$/i.exec(e);return t?[r._parseResStrForRgb(t[1]),r._parseResStrForRgb(t[2]),r._parseResStrForRgb(t[3]),r._parsePercent(t[4])]:null},r.parseHSLA=function(e){var t=/^hsla?\(([0-9.]+)(?:deg)?,([0-9.]+%?),([0-9.]+%?)(?:,([0-9.]+%?))?\)$/i.exec(e);return t?[r._parseResStrForHue(t[1]),r._parsePercent(t[2]),r._parsePercent(t[3]),r._parsePercent(t[4])]:null},r.parseHWB=function(e){var t=/^hwb\s?\(\s?([0-9.]+)(?:deg)?\s([0-9.]+%?)\s([0-9.]+%?)\s?(?:\/\s?([0-9.]+%?))?\s?\)$/i.exec(e);return t?[r._parseResStrForHue(t[1]),r._parsePercent(t[2]),r._parsePercent(t[3]),r._parsePercent(t[4])]:null},r.parseRGBA2=function(e){var t=/^rgba?\s?\(\s?([0-9.]+%?)\s?([0-9.]+%?)\s?([0-9.]+%?)(?:\s?\/\s?([0-9.]+%?))?\s?\)$/i.exec(e);return t?[r._parseResStrForRgb(t[1]),r._parseResStrForRgb(t[2]),r._parseResStrForRgb(t[3]),r._parsePercent(t[4])]:null},r.parseHSLA2=function(e){var t=/^hsla?\s?\(\s?([0-9.]+)(?:deg)?\s([0-9.]+%?)\s([0-9.]+%?)\s?(?:\/\s?([0-9.]+%?))?\s?\)$/i.exec(e);return t?[r._parseResStrForHue(t[1]),r._parsePercent(t[2]),r._parsePercent(t[3]),r._parsePercent(t[4])]:null},r._parseResStrForRgb=function(r){return"string"==typeof r&&(r=parseFloat(r)/("%"===r.substr(-1)?100/255:1)),isNaN(r)&&(r=1),a(0,255,r)},r._parseResStrForHue=function(r){return"string"==typeof r&&(r=parseFloat(r)),isNaN(r)&&(r=0),a(0,360,r)},r._parsePercent=function(r){return"string"==typeof r&&(r=parseFloat(r)/("%"===r.substr(-1)?100:1)),isNaN(r)&&(r=1),a(0,1,r)},r}(),s=t(85),c=function(){function t(r,e,t,n){this.r=255,this.g=255,this.b=255,this.a=1,this.setColor(r,e,t,n)}return t.prototype.setColor=function(r,t,n,o){this.r=a(0,255,e(Number(r),0)),this.g=a(0,255,e(Number(t),0)),this.b=a(0,255,e(Number(n),0)),this.a=a(0,1,e(Number(o),1))},t.parseKeyWord=function(r){var e=o.clearStrSpace(r),n=s.keyword.rgb(e);return n&&t.fromArray(n)},t.parseHEX=function(r){var e=o.clearStrSpace(r),n=o.parse3BitsHEX(e);return n||(n=o.parse6BitsHEX(e)),n&&t.fromArray(n)},t.parseRGBA=function(r){var e=o.clearStrSpace(r),n=o.parseRGBA(e);if(!n){var a=o.trimStr(r);n=o.parseRGBA2(a)}return n&&t.fromArray(n)},t.parseHSLA=function(r){var e=o.clearStrSpace(r),n=o.parseHSLA(e);if(!n){var a=o.trimStr(r);n=o.parseHSLA2(a)}return n&&t.fromHSL(n[0],n[1],n[2],n[3])},t.parseHWB=function(r){var e=o.trimStr(r),n=o.parseHWB(e);return n&&t.fromHWB(n[0],n[1],n[2],n[3])},t.parseCssColorString=function(e){return r.type("string","color",e),t.parseHEX(e)||t.parseRGBA(e)||t.parseKeyWord(e)||t.parseHSLA(e)||t.parseHWB(e)},t.fromHSL=function(r,n,o,c){var i=s.hsl.rgb(a(0,360,r),a(0,100,100*n),a(0,100,100*o));return new t(i[0],i[1],i[2],e(Number(c),1))},t.fromHWB=function(r,n,o,c){var i=s.hwb.rgb(a(0,360,r),a(0,100,100*n),a(0,100,100*o));return new t(i[0],i[1],i[2],e(Number(c),1))},t.fromRandom=function(r,e){if("string"==typeof r&&(r=t.parseCssColorString(r)),"string"==typeof e&&(e=t.parseCssColorString(e)),!r||!e)throw new Error("fail to create object from random");return new t(Math.random()*Math.abs(e.r-r.r)+Math.min(r.r,e.r),Math.random()*Math.abs(e.g-r.g)+Math.min(r.g,e.g),Math.random()*Math.abs(e.b-r.b)+Math.min(r.b,e.b),Math.random()*Math.abs(e.a-r.a)+Math.min(r.a,e.a))},t.fromJson=function(r){return new t(r.r,r.g,r.b,r.a)},t.fromArray=function(r){return new t(r[0],r[1],r[2],r[3])},t.prototype.toCssColorString=function(){var r=this.toJson();return 1===r.a?"rgb(".concat(r.r,",").concat(r.g,",").concat(r.b,")"):"rgba(".concat(r.r,",").concat(r.g,",").concat(r.b,",").concat(r.a,")")},t.prototype.toString=function(){return this.toCssColorString()},t.prototype.toNormalize=function(){return{r:parseFloat((this.r/255).toFixed(2)),g:parseFloat((this.g/255).toFixed(2)),b:parseFloat((this.b/255).toFixed(2)),a:parseFloat(this.a.toFixed(2))}},t.prototype.toCssHEXString=function(){var r=this.toJson(),e=r.r.toString(16);e.length<2&&(e="0".concat(e));var t=r.g.toString(16);t.length<2&&(t="0".concat(t));var n=r.b.toString(16);if(n.length<2&&(n="0".concat(n)),this.a<1){var a=parseInt((255*this.a).toFixed()).toString(16);return a.length<2&&(a="0".concat(a)),"#".concat(e).concat(t).concat(n).concat(a)}return"#".concat(e).concat(t).concat(n)},t.prototype.toArray=function(){var r=this.toJson();return[r.r,r.g,r.b,r.a]},t.prototype.toJson=function(){return{r:parseInt(this.r.toFixed()),g:parseInt(this.g.toFixed()),b:parseInt(this.b.toFixed()),a:parseFloat(this.a.toFixed(2))}},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.equals=function(r){return this===r||this.r===r.r&&this.g===r.g&&this.b===r.g&&this.a===r.a},t}(),i=function(){}}(),n}()}));
@@ -0,0 +1,123 @@
1
+ export declare class CssColorParser {
2
+ r: number;
3
+ g: number;
4
+ b: number;
5
+ a: number;
6
+ constructor(red?: number | string, green?: number | string, blue?: number | string, alpha?: number | string);
7
+ /**
8
+ * 设置颜色
9
+ * @param red
10
+ * @param green
11
+ * @param blue
12
+ * @param alpha
13
+ * @example: this.setColor(255,255,255,1)
14
+ */
15
+ setColor(red?: number | string, green?: number | string, blue?: number | string, alpha?: number | string): void;
16
+ static parseKeyWord(v: string): CssColorParser;
17
+ static parseHEX(v: string): CssColorParser;
18
+ static parseRGBA(v: string): CssColorParser;
19
+ static parseHSLA(v: string): CssColorParser;
20
+ static parseHWB(v: string): CssColorParser;
21
+ /**
22
+ * @description: 将css字符串转换为解析对象
23
+ * @param {string} v
24
+ * @return {CssColorParser}
25
+ * @example: CssColorParser.parseCssColorString('rgba(255,255,255,1)')
26
+ */
27
+ static parseCssColorString(v: string): CssColorParser;
28
+ /**
29
+ * @description: 将HSL色彩模式转换为解析对象
30
+ * @param {number} hue 色相
31
+ * @param {number} saturation 饱和度
32
+ * @param {number} lightness 亮度
33
+ * @param {number} alpha 不透明度
34
+ * @return {CssColorParser}
35
+ * @example: CssColorParser.fromHSL(0,1,1,1)
36
+ */
37
+ static fromHSL(h: number, s: number, l: number, a?: number): CssColorParser;
38
+ /**
39
+ * @description: 将HWB色彩模式转换为解析对象
40
+ * @param {number} h 色调
41
+ * @param {number} w 白度
42
+ * @param {number} b 黑度
43
+ * @param {number} a 不透明度
44
+ * @return {CssColorParser}
45
+ * @example: CssColorParser.fromHSL(0,1,1,1)
46
+ */
47
+ static fromHWB(h: number, w: number, b: number, a?: number): CssColorParser;
48
+ /**
49
+ * @description: 从解析器中产生随机颜色
50
+ * @return {CssColorParser}
51
+ * @author: roman_123
52
+ */
53
+ static fromRandom(color1: string | CssColorParser, color2: string | CssColorParser): CssColorParser;
54
+ /**
55
+ * @description: 将ColorJson格式的json数据转换为解析对象
56
+ * @param {ColorJson} json
57
+ * @return {CssColorParser}
58
+ * @author: roman_123
59
+ */
60
+ static fromJson(json: ColorJson): CssColorParser;
61
+ /**
62
+ * @description: 将rgba数组转换为解析对象
63
+ * @param {Array} color
64
+ * @return {CssColorParser}
65
+ * @author: roman_123
66
+ */
67
+ static fromArray(color: Array<number>): CssColorParser;
68
+ /**
69
+ * @description: 返回rgba格式的css字符串
70
+ * @return {*}
71
+ * @author: roman_123
72
+ */
73
+ toCssColorString(): string;
74
+ /**
75
+ * @description: 返回字符串
76
+ * @return {*}
77
+ * @author: roman_123
78
+ */
79
+ toString(): string;
80
+ /**
81
+ * @description: 归一化
82
+ * @return {*}
83
+ * @author: roman_123
84
+ */
85
+ toNormalize(): ColorJson;
86
+ /**
87
+ * @description: 返回16进制格式的css字符串
88
+ * @return {*}
89
+ * @author: roman_123
90
+ */
91
+ toCssHEXString(): string;
92
+ /**
93
+ * @description: 返回rgba数组
94
+ * @return {*}
95
+ * @author: roman_123
96
+ */
97
+ toArray(): number[];
98
+ /**
99
+ * @description: 返回ColorJson
100
+ * @return {*}
101
+ * @author: roman_123
102
+ */
103
+ toJson(): ColorJson;
104
+ /**
105
+ * @description: 拷贝
106
+ * @return {*}
107
+ * @author: roman_123
108
+ */
109
+ clone(): CssColorParser;
110
+ /**
111
+ * @description: 比较两个解析对象的数据是否相等
112
+ * @param {*} color
113
+ * @return {*}
114
+ * @author: roman_123
115
+ */
116
+ equals(color: any): boolean;
117
+ }
118
+ export declare class ColorJson {
119
+ r: number;
120
+ g: number;
121
+ b: number;
122
+ a: number;
123
+ }
package/example.html ADDED
@@ -0,0 +1,76 @@
1
+ <!--
2
+ * @Author: roman_123
3
+ * @Description:
4
+ * @Date: 2022-12-06 11:15:17
5
+ * @LastEditTime: 2022-12-06 17:51:18
6
+ -->
7
+ <!DOCTYPE html>
8
+ <html lang="en">
9
+ <head>
10
+ <meta charset="UTF-8" />
11
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
12
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
13
+ <meta
14
+ http-equiv="Cache-Control"
15
+ content="no-cache, no-store, must-revalidate"
16
+ />
17
+ <meta http-equiv="Pragma" content="no-cache" />
18
+ <meta http-equiv="Expires" content="0" />
19
+ <title>css-color-parser示例</title>
20
+ <script src="./dist/css-color-parser.min.js"></script>
21
+ </head>
22
+
23
+ <body>
24
+ <script>
25
+ const p = new Parser.CssColorParser(255, 255, 255, 1)
26
+ console.log(p)
27
+ const parser1 = Parser.CssColorParser.parseCssColorString('blue')
28
+ console.log(parser1)
29
+ const parser2 = Parser.CssColorParser.parseCssColorString('rgba(76,144,240,0.8)')
30
+ console.log(parser2)
31
+ const parser3 = Parser.CssColorParser.parseCssColorString('rgba(76 144 240 / 80%)')
32
+ console.log(parser3)
33
+ const parser4 = Parser.CssColorParser.parseCssColorString('rgb(76 144 240)')
34
+ console.log(parser4)
35
+ const parser5 = Parser.CssColorParser.parseCssColorString('rgb(76,144,240)')
36
+ console.log(parser5)
37
+ const parser6 = Parser.CssColorParser.parseCssColorString('#4c90f0')
38
+ console.log(parser6)
39
+ const parser7 = Parser.CssColorParser.parseCssColorString('#4c90f0cc')
40
+ console.log(parser7)
41
+ const parser8 = Parser.CssColorParser.parseCssColorString('#ccc')
42
+ console.log(parser8)
43
+ const parser9 = Parser.CssColorParser.parseCssColorString('hsl(215 85% 62% / 0.8)')
44
+ console.log(parser9)
45
+ const parser10 = Parser.CssColorParser.parseCssColorString('hsla(215,85%,62%,0.8)')
46
+ console.log(parser10)
47
+ const parser11 = Parser.CssColorParser.parseCssColorString('hwb(215deg 30% 6% / 80%)')
48
+ console.log(parser11)
49
+ // 随机生成颜色
50
+ const parser12 = Parser.CssColorParser.fromRandom('blue', 'red').toCssColorString()
51
+ console.log(parser12)
52
+ const parser13 = Parser.CssColorParser.fromRandom('blue', '#ccffbbaa').toCssColorString()
53
+ console.log(parser13)
54
+ const parser14 = Parser.CssColorParser.fromRandom(
55
+ new Parser.CssColorParser(205, 205, 100, 0.5),
56
+ '#ccffbbaa'
57
+ ).toCssColorString()
58
+ console.log(parser14)
59
+ const parser15 = Parser.CssColorParser.fromRandom(
60
+ Parser.CssColorParser.fromArray([205, 205, 100, 0.5]),
61
+ '#ccffbbaa'
62
+ ).toCssColorString()
63
+ console.log(parser15)
64
+ // 归一化
65
+ const parser16 = Parser.CssColorParser.fromJson({
66
+ r: 100,
67
+ g: 200,
68
+ b: 0,
69
+ a: 0.552
70
+ }).toNormalize()
71
+ console.log(parser16)
72
+ const parser17 = Parser.CssColorParser.parseRGBA('rgba(76 144 240 / 80%)')
73
+ console.log(parser17)
74
+ </script>
75
+ </body>
76
+ </html>
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "css-color-parser-h",
3
+ "version": "1.0.0",
4
+ "description": "A tool for parsing css color",
5
+ "main": "/dist/css-color-parser.min.js",
6
+ "scripts": {
7
+ "build": "webpack && node release.js"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://gitee.com/roman_123/css-color-parser.git"
12
+ },
13
+ "keywords": [
14
+ "html",
15
+ "css",
16
+ "color",
17
+ "parser",
18
+ "conversion"
19
+ ],
20
+ "author": "roman_123",
21
+ "license": "MIT",
22
+ "dependencies": {
23
+ "color-convert": "^2.0.1"
24
+ },
25
+ "devDependencies": {
26
+ "clean-webpack-plugin": "^4.0.0",
27
+ "fs-extra": "^11.1.0",
28
+ "ts-loader": "^9.4.1",
29
+ "typescript": "^4.9.3",
30
+ "webpack": "^5.75.0",
31
+ "webpack-cli": "^5.0.0"
32
+ }
33
+ }
package/readme.md ADDED
@@ -0,0 +1,93 @@
1
+ # css-color-parser
2
+ ![QQ](https://img.shields.io/badge/QQ-306863030-green.svg) [![Git](https://img.shields.io/badge/GIT-roman_123-blue.svg)](https://gitee.com/roman_123/css-color-parser/tree/master) [![NPM](https://img.shields.io/badge/NPM-roman_123-blue.svg)](https://www.npmjs.com/package/css-color-parser) [![HOME](https://img.shields.io/badge/HOME-css--color--parser-orange.svg)](http://roman_123.gitee.io/css-color-parser/)
3
+
4
+ > A tool for parsing css color
5
+
6
+ ## Setup
7
+
8
+ ### Node
9
+
10
+ ```shell
11
+ npm install --save css-color-parser-h
12
+ ```
13
+
14
+ ### Browser
15
+
16
+ ```html
17
+ <script src="./dist/css-color-parser.min.js"></script>
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ You can then use it as a window global or as an CommonJs module
23
+
24
+ ```js
25
+ // plain javascript in browser
26
+ new Parser.CssColorParser(255,255,255,1)
27
+
28
+ // commonJs
29
+ const { CssColorParser } = require('css-color-parser-h')
30
+
31
+ // es6 module 使用ES6模块,需要在项目中集成webpack等打包工具
32
+ /**
33
+ * If you want to use this library by esm, you must ensure that your project
34
+ * has used webpack, vite, rollup or other packaging tools.
35
+ */
36
+ import { CssColorParser } from 'css-color-parser-h'
37
+ ```
38
+
39
+ ## Example
40
+
41
+ ```js
42
+ CssColorParser.parseCssColorString('blue') // CssColorParser { r: 0, g: 0, b: 255, a: 1 }
43
+ CssColorParser.parseCssColorString('rgba(76,144,240,0.8)') // CssColorParser { r: 76, g: 144, b: 240, a: 0.8 }
44
+ CssColorParser.parseCssColorString('rgba(76 144 240 / 80%)') // CssColorParser { r: 76, g: 144, b: 240, a: 0.8 }
45
+ CssColorParser.parseCssColorString('rgb(76 144 240)') // CssColorParser { r: 76, g: 144, b: 240, a: 1 }
46
+ CssColorParser.parseCssColorString('rgb(76,144,240)') // CssColorParser { r: 76, g: 144, b: 240, a: 1 }
47
+ CssColorParser.parseCssColorString('#4c90f0') // CssColorParser { r: 76, g: 144, b: 240, a: 1 }
48
+ CssColorParser.parseCssColorString('#4c90f0cc') // CssColorParser { r: 76, g: 144, b: 240, a: 0.8 }
49
+ CssColorParser.parseCssColorString('#ccc') // CssColorParser { r: 204, g: 204, b: 204, a: 1 }
50
+ CssColorParser.parseCssColorString('hsl(215 85% 62% / 0.8)') // CssColorParser { r: 76, g: 144, b: 240, a: 0.8 }
51
+ CssColorParser.parseCssColorString('hsla(215,85%,62%,0.8)') // CssColorParser { r: 76, g: 144, b: 240, a: 0.8 }
52
+ CssColorParser.parseCssColorString('hwb(215deg 30% 6% / 80%)') // CssColorParser { r: 77, g: 145, b: 240, a: 0.8 }
53
+ CssColorParser.parseRGBA('rgba(76 144 240 / 80%)') // CssColorParser {r: 76, g: 144, b: 240, a: 0.8}
54
+ // 随机生成颜色
55
+ CssColorParser.fromRandom('blue', 'red').toCssColorString() // rgb(4,0,34)
56
+ CssColorParser.fromRandom('blue', '#ccffbbaa').toCssColorString() // rgba(127,128,239,0.92)
57
+ CssColorParser.fromRandom(new CssColorParser(205,205,100,0.5), '#ccffbbaa').toCssColorString() // rgba(205,211,152,0.53)
58
+ CssColorParser.fromRandom(CssColorParser.fromArray([205,205,100,0.5]), '#ccffbbaa').toCssColorString() // rgba(205,235,131,0.62)
59
+
60
+ // 归一化
61
+ CssColorParser.fromJson({
62
+ r: 100,
63
+ g: 200,
64
+ b: 0,
65
+ a: 0.552
66
+ }).toNormalize() // { r: 0.39, g: 0.78, b: 0, a: 0.55 }
67
+
68
+ /**
69
+ * 方法总览
70
+ * */
71
+ // 静态方法
72
+ parseKeyWord(v: string): CssColorParser
73
+ parseHEX(v: string): CssColorParser
74
+ parseRGBA(v: string): CssColorParser
75
+ parseHSLA(v: string): CssColorParser
76
+ parseHWB(v: string)
77
+ parseCssColorString(v: string): CssColorParser
78
+ fromHSL(h: number, s: number, l: number, a?: number): CssColorParser
79
+ fromHWB(h: number, w: number, b: number, a?: number)
80
+ fromRandom(color1: string | CssColorParser,color2: string | CssColorParser): CssColorParser
81
+ fromJson(json: ColorJson): CssColorParser
82
+ fromArray(color: Array<number>): CssColorParser
83
+ // 实例方法
84
+ setColor(red?: number | string,green?: number | string,blue?: number | string,alpha?: number | string)
85
+ toCssColorString(): string
86
+ toCssHexString(): string
87
+ toString(): string
88
+ toNormalize(): ColorJson
89
+ toArray(): number[]
90
+ toJson(): ColorJson
91
+ clone():CssColorParser
92
+ equals(color):boolean
93
+ ```
package/release.js ADDED
@@ -0,0 +1,19 @@
1
+ /*
2
+ * @Author: roman_123
3
+ * @Description: webpack打包后处理
4
+ * @Date: 2022-12-05 09:03:05
5
+ * @LastEditTime: 2022-12-06 10:43:33
6
+ */
7
+ const fs=require('fs-extra')
8
+ const path = require('path')
9
+ const basePath = path.resolve(__dirname, './dist')
10
+ const delFileList = ['./utils']
11
+
12
+ delFileList.forEach(file => {
13
+ const filePath = path.join(basePath, file)
14
+ fs.removeSync(filePath)
15
+ })
16
+
17
+ fs.renameSync(path.join(basePath, './main.d.ts'), path.join(basePath, './css-color-parser.min.ts'))
18
+
19
+ console.log(new Date().toLocaleString(), '打包完成!')
package/src/main.ts ADDED
@@ -0,0 +1,307 @@
1
+ /*
2
+ * @Descripttion: 颜色解析器
3
+ * @version: 1.0.0
4
+ * @Author: roman_123
5
+ * @Date: 2021-01-19 09:22:11
6
+ * @LastEditors: Please set LastEditors
7
+ * @LastEditTime: 2022-12-06 10:48:06
8
+ */
9
+ import { CssColorStringParser } from './utils/color-tools'
10
+ import { Check, defaultValue, limitNumber } from './utils/common'
11
+ const convert = require('color-convert')
12
+ export class CssColorParser {
13
+ r = 255
14
+ g = 255
15
+ b = 255
16
+ a = 1
17
+ constructor(
18
+ red?: number | string,
19
+ green?: number | string,
20
+ blue?: number | string,
21
+ alpha?: number | string
22
+ ) {
23
+ this.setColor(red, green, blue, alpha)
24
+ }
25
+ /**
26
+ * 设置颜色
27
+ * @param red
28
+ * @param green
29
+ * @param blue
30
+ * @param alpha
31
+ * @example: this.setColor(255,255,255,1)
32
+ */
33
+ setColor(
34
+ red?: number | string,
35
+ green?: number | string,
36
+ blue?: number | string,
37
+ alpha?: number | string
38
+ ) {
39
+ this.r = limitNumber(0, 255, defaultValue(Number(red), 0))
40
+ this.g = limitNumber(0, 255, defaultValue(Number(green), 0))
41
+ this.b = limitNumber(0, 255, defaultValue(Number(blue), 0))
42
+ this.a = limitNumber(0, 1, defaultValue(Number(alpha), 1))
43
+ }
44
+
45
+ static parseKeyWord(v: string): CssColorParser {
46
+ const cssStr = CssColorStringParser.clearStrSpace(v)
47
+ const res = convert.keyword.rgb(cssStr)
48
+ return res && CssColorParser.fromArray(res)
49
+ }
50
+
51
+ static parseHEX(v: string): CssColorParser {
52
+ const cssStr = CssColorStringParser.clearStrSpace(v)
53
+ let res = CssColorStringParser.parse3BitsHEX(cssStr)
54
+ if (!res) {
55
+ res = CssColorStringParser.parse6BitsHEX(cssStr)
56
+ }
57
+ return res && CssColorParser.fromArray(res)
58
+ }
59
+
60
+ static parseRGBA(v: string): CssColorParser {
61
+ const cssStr = CssColorStringParser.clearStrSpace(v)
62
+ let res = CssColorStringParser.parseRGBA(cssStr)
63
+ if (!res) {
64
+ const cssStr2 = CssColorStringParser.trimStr(v)
65
+ res = CssColorStringParser.parseRGBA2(cssStr2)
66
+ }
67
+ return res && CssColorParser.fromArray(res)
68
+ }
69
+
70
+ static parseHSLA(v: string): CssColorParser {
71
+ const cssStr = CssColorStringParser.clearStrSpace(v)
72
+ let res = CssColorStringParser.parseHSLA(cssStr)
73
+ if (!res) {
74
+ const cssStr2 = CssColorStringParser.trimStr(v)
75
+ res = CssColorStringParser.parseHSLA2(cssStr2)
76
+ }
77
+ return res && CssColorParser.fromHSL(
78
+ res[0],
79
+ res[1],
80
+ res[2],
81
+ res[3]
82
+ )
83
+ }
84
+
85
+ static parseHWB(v: string) {
86
+ const cssStr2 = CssColorStringParser.trimStr(v)
87
+ const res = CssColorStringParser.parseHWB(cssStr2)
88
+ return res && CssColorParser.fromHWB(res[0], res[1], res[2], res[3])
89
+ }
90
+
91
+
92
+ /**
93
+ * @description: 将css字符串转换为解析对象
94
+ * @param {string} v
95
+ * @return {CssColorParser}
96
+ * @example: CssColorParser.parseCssColorString('rgba(255,255,255,1)')
97
+ */
98
+ static parseCssColorString(v: string): CssColorParser {
99
+ Check.type('string', 'color', v)
100
+ return CssColorParser.parseHEX(v) || CssColorParser.parseRGBA(v) || CssColorParser.parseKeyWord(v) || CssColorParser.parseHSLA(v) || CssColorParser.parseHWB(v)
101
+ }
102
+
103
+ /**
104
+ * @description: 将HSL色彩模式转换为解析对象
105
+ * @param {number} hue 色相
106
+ * @param {number} saturation 饱和度
107
+ * @param {number} lightness 亮度
108
+ * @param {number} alpha 不透明度
109
+ * @return {CssColorParser}
110
+ * @example: CssColorParser.fromHSL(0,1,1,1)
111
+ */
112
+ static fromHSL(h: number, s: number, l: number, a?: number): CssColorParser {
113
+ const res = convert.hsl.rgb(limitNumber(0, 360, h), limitNumber(0, 100, s * 100), limitNumber(0, 100, l * 100))
114
+ return new CssColorParser(
115
+ res[0],
116
+ res[1],
117
+ res[2],
118
+ defaultValue(Number(a), 1)
119
+ )
120
+ }
121
+ /**
122
+ * @description: 将HWB色彩模式转换为解析对象
123
+ * @param {number} h 色调
124
+ * @param {number} w 白度
125
+ * @param {number} b 黑度
126
+ * @param {number} a 不透明度
127
+ * @return {CssColorParser}
128
+ * @example: CssColorParser.fromHSL(0,1,1,1)
129
+ */
130
+ static fromHWB(h: number, w: number, b: number, a?: number) {
131
+ const res = convert.hwb.rgb(limitNumber(0, 360, h), limitNumber(0, 100, w * 100), limitNumber(0, 100, b * 100))
132
+ return new CssColorParser(
133
+ res[0],
134
+ res[1],
135
+ res[2],
136
+ defaultValue(Number(a), 1)
137
+ )
138
+ }
139
+ /**
140
+ * @description: 从解析器中产生随机颜色
141
+ * @return {CssColorParser}
142
+ * @author: roman_123
143
+ */
144
+ static fromRandom(
145
+ color1: string | CssColorParser,
146
+ color2: string | CssColorParser
147
+ ): CssColorParser {
148
+ if (typeof color1 === 'string') {
149
+ color1 = CssColorParser.parseCssColorString(color1)
150
+ }
151
+ if (typeof color2 === 'string') {
152
+ color2 = CssColorParser.parseCssColorString(color2)
153
+ }
154
+ if (!color1 || !color2) {
155
+ throw new Error('fail to create object from random')
156
+ }
157
+ const r =
158
+ Math.random() * Math.abs(color2.r - color1.r) +
159
+ Math.min(color1.r, color2.r)
160
+ const g =
161
+ Math.random() * Math.abs(color2.g - color1.g) +
162
+ Math.min(color1.g, color2.g)
163
+ const b =
164
+ Math.random() * Math.abs(color2.b - color1.b) +
165
+ Math.min(color1.b, color2.b)
166
+ const a =
167
+ Math.random() * Math.abs(color2.a - color1.a) +
168
+ Math.min(color1.a, color2.a)
169
+ return new CssColorParser(r, g, b, a)
170
+ }
171
+ /**
172
+ * @description: 将ColorJson格式的json数据转换为解析对象
173
+ * @param {ColorJson} json
174
+ * @return {CssColorParser}
175
+ * @author: roman_123
176
+ */
177
+ static fromJson(json: ColorJson): CssColorParser {
178
+ return new CssColorParser(json.r, json.g, json.b, json.a)
179
+ }
180
+ /**
181
+ * @description: 将rgba数组转换为解析对象
182
+ * @param {Array} color
183
+ * @return {CssColorParser}
184
+ * @author: roman_123
185
+ */
186
+ static fromArray(color: Array<number>): CssColorParser {
187
+ return new CssColorParser(color[0], color[1], color[2], color[3])
188
+ }
189
+ /**
190
+ * @description: 返回rgba格式的css字符串
191
+ * @return {*}
192
+ * @author: roman_123
193
+ */
194
+ toCssColorString(): string {
195
+ const color = this.toJson()
196
+ if (color.a === 1) {
197
+ return `rgb(${color.r},${color.g},${color.b})`
198
+ }
199
+ return `rgba(${color.r},${color.g},${color.b},${color.a})`
200
+ }
201
+ /**
202
+ * @description: 返回字符串
203
+ * @return {*}
204
+ * @author: roman_123
205
+ */
206
+ toString(): string {
207
+ return this.toCssColorString()
208
+ }
209
+ /**
210
+ * @description: 归一化
211
+ * @return {*}
212
+ * @author: roman_123
213
+ */
214
+ toNormalize(): ColorJson {
215
+ return {
216
+ r: parseFloat((this.r / 255).toFixed(2)),
217
+ g: parseFloat((this.g / 255).toFixed(2)),
218
+ b: parseFloat((this.b / 255).toFixed(2)),
219
+ a: parseFloat(this.a.toFixed(2))
220
+ }
221
+ }
222
+ /**
223
+ * @description: 返回16进制格式的css字符串
224
+ * @return {*}
225
+ * @author: roman_123
226
+ */
227
+ toCssHEXString(): string {
228
+ const color = this.toJson()
229
+ let r = color.r.toString(16)
230
+ if (r.length < 2) {
231
+ r = `0${r}`
232
+ }
233
+ let g = color.g.toString(16)
234
+ if (g.length < 2) {
235
+ g = `0${g}`
236
+ }
237
+ let b = color.b.toString(16)
238
+ if (b.length < 2) {
239
+ b = `0${b}`
240
+ }
241
+ // 由于tojson后a会丢失精度,此处使用this.a
242
+ if (this.a < 1) {
243
+ let hexAlpha = parseInt((this.a * 255).toFixed()).toString(16)
244
+ if (hexAlpha.length < 2) {
245
+ hexAlpha = `0${hexAlpha}`
246
+ }
247
+ return `#${r}${g}${b}${hexAlpha}`
248
+ }
249
+ return `#${r}${g}${b}`
250
+ }
251
+ /**
252
+ * @description: 返回rgba数组
253
+ * @return {*}
254
+ * @author: roman_123
255
+ */
256
+ toArray(): number[] {
257
+ const color = this.toJson()
258
+ return [color.r, color.g, color.b, color.a]
259
+ }
260
+ /**
261
+ * @description: 返回ColorJson
262
+ * @return {*}
263
+ * @author: roman_123
264
+ */
265
+ toJson(): ColorJson {
266
+ return {
267
+ r: parseInt(this.r.toFixed()),
268
+ g: parseInt(this.g.toFixed()),
269
+ b: parseInt(this.b.toFixed()),
270
+ a: parseFloat(this.a.toFixed(2))
271
+ }
272
+ }
273
+ /**
274
+ * @description: 拷贝
275
+ * @return {*}
276
+ * @author: roman_123
277
+ */
278
+ clone(): CssColorParser {
279
+ return new CssColorParser(this.r, this.g, this.b, this.a)
280
+ }
281
+ /**
282
+ * @description: 比较两个解析对象的数据是否相等
283
+ * @param {*} color
284
+ * @return {*}
285
+ * @author: roman_123
286
+ */
287
+ equals(color): boolean {
288
+ if (this === color) {
289
+ return true
290
+ } else {
291
+ return (
292
+ this.r === color.r &&
293
+ this.g === color.g &&
294
+ this.b === color.g &&
295
+ this.a === color.a
296
+ )
297
+ }
298
+ }
299
+ }
300
+
301
+
302
+ export class ColorJson {
303
+ r: number
304
+ g: number
305
+ b: number
306
+ a: number
307
+ }
@@ -0,0 +1,146 @@
1
+ import { defaultValue, limitNumber } from "./common"
2
+
3
+ /*
4
+ * @Author: roman_123
5
+ * @Description: 部分核心代码修改自cesium
6
+ * @Date: 2022-11-28 17:32:57
7
+ * @LastEditTime: 2022-12-06 00:02:21
8
+ */
9
+ export class CssColorStringParser {
10
+ // 去除字符串内所有空格
11
+ static clearStrSpace(v: string): string {
12
+ return v.replace(/\s/g, '')
13
+ }
14
+ // 去除字符串两边空格,将中间多个空格合并为一个
15
+ static trimStr(v: string): string {
16
+ v = v.replace(/\s+/g, ' ')
17
+ return v.trim()
18
+ }
19
+ // 解析3位16进制 #fff #fff0
20
+ static parse3BitsHEX(v: string): Array<number> {
21
+ const regx = /^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/i
22
+ const res = regx.exec(v)
23
+ if (res) {
24
+ const res4 = defaultValue(res[4], 'f')
25
+ const r = CssColorStringParser._parseResStrForRgb(parseInt(res[1] + res[1], 16))
26
+ const g = CssColorStringParser._parseResStrForRgb(parseInt(res[2] + res[2], 16))
27
+ const b = CssColorStringParser._parseResStrForRgb(parseInt(res[3] + res[3], 16))
28
+ const a = CssColorStringParser._parsePercent(parseInt(res4 + res4, 16) / 255)
29
+ return [r, g, b, a]
30
+ }
31
+ return null
32
+ }
33
+ // 解析6位16进制 #ffffff #ffffff00
34
+ static parse6BitsHEX(v: string): Array<number> {
35
+ const regx = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i
36
+ const res = regx.exec(v)
37
+ if (res) {
38
+ const res4 = defaultValue(res[4], 'ff')
39
+ const r = CssColorStringParser._parseResStrForRgb(parseInt(res[1], 16))
40
+ const g = CssColorStringParser._parseResStrForRgb(parseInt(res[2], 16))
41
+ const b = CssColorStringParser._parseResStrForRgb(parseInt(res[3], 16))
42
+ const a = CssColorStringParser._parsePercent(parseInt(res4, 16) / 255.0)
43
+ return [r, g, b, a]
44
+ }
45
+ return null
46
+ }
47
+ // 解析rgb rgba rgb(255,255,255) rgba(255,255,255,1) rgba(100%,100%,100%, 1)
48
+ static parseRGBA(v: string): Array<number> {
49
+ const regx = /^rgba?\(([0-9.]+%?),([0-9.]+%?),([0-9.]+%?)(?:,([0-9.]+%?))?\)$/i
50
+ const res = regx.exec(v)
51
+ if (res) {
52
+ const r = CssColorStringParser._parseResStrForRgb(res[1])
53
+ const g = CssColorStringParser._parseResStrForRgb(res[2])
54
+ const b = CssColorStringParser._parseResStrForRgb(res[3])
55
+ const a = CssColorStringParser._parsePercent(res[4])
56
+ return [r,g,b,a]
57
+ }
58
+ return null
59
+ }
60
+ // 解析hsl hsla hsl(360,100%,100%) hsla(360,100%,100%,1)
61
+ static parseHSLA(v: string): Array<number> {
62
+ const regx = /^hsla?\(([0-9.]+)(?:deg)?,([0-9.]+%?),([0-9.]+%?)(?:,([0-9.]+%?))?\)$/i
63
+ const res = regx.exec(v)
64
+ if (res) {
65
+ const h = CssColorStringParser._parseResStrForHue(res[1])
66
+ const s = CssColorStringParser._parsePercent(res[2])
67
+ const l = CssColorStringParser._parsePercent(res[3])
68
+ const a = CssColorStringParser._parsePercent(res[4])
69
+ return [h,s,l,a]
70
+ }
71
+ return null
72
+ }
73
+
74
+ // 解析hwb
75
+ static parseHWB(v: string): Array<number> {
76
+ const regx = /^hwb\s?\(\s?([0-9.]+)(?:deg)?\s([0-9.]+%?)\s([0-9.]+%?)\s?(?:\/\s?([0-9.]+%?))?\s?\)$/i
77
+ const res = regx.exec(v)
78
+ if (res) {
79
+ const h = CssColorStringParser._parseResStrForHue(res[1])
80
+ const w = CssColorStringParser._parsePercent(res[2])
81
+ const b = CssColorStringParser._parsePercent(res[3])
82
+ const a = CssColorStringParser._parsePercent(res[4])
83
+ return [h,w,b,a]
84
+ }
85
+ return null
86
+ }
87
+
88
+ // 解析rgb rgb(178 57 57 / 44%) 字符串中存在空格,因此使用清除两侧空格的原始字符串
89
+ static parseRGBA2(v: string): Array<number> {
90
+ const regx = /^rgba?\s?\(\s?([0-9.]+%?)\s?([0-9.]+%?)\s?([0-9.]+%?)(?:\s?\/\s?([0-9.]+%?))?\s?\)$/i
91
+ const res = regx.exec(v)
92
+ if (res) {
93
+ const r = CssColorStringParser._parseResStrForRgb(res[1])
94
+ const g = CssColorStringParser._parseResStrForRgb(res[2])
95
+ const b = CssColorStringParser._parseResStrForRgb(res[3])
96
+ const a = CssColorStringParser._parsePercent(res[4])
97
+ return [r,g,b,a]
98
+ }
99
+ return null
100
+ }
101
+ // 解析hsl hsl(215 85% 62% / 1)
102
+ static parseHSLA2(v: string): Array<number> {
103
+ const regx = /^hsla?\s?\(\s?([0-9.]+)(?:deg)?\s([0-9.]+%?)\s([0-9.]+%?)\s?(?:\/\s?([0-9.]+%?))?\s?\)$/i
104
+ const res = regx.exec(v)
105
+ if (res) {
106
+ const h = CssColorStringParser._parseResStrForHue(res[1])
107
+ const s = CssColorStringParser._parsePercent(res[2])
108
+ const l = CssColorStringParser._parsePercent(res[3])
109
+ const a = CssColorStringParser._parsePercent(res[4])
110
+ return [h,s,l,a]
111
+ }
112
+ return null
113
+ }
114
+
115
+ // 将结果解析为数字
116
+ static _parseResStrForRgb(v: string|number) {
117
+ if(typeof v === 'string') {
118
+ v = parseFloat(v) / ('%' === v.substr(-1) ? 100.0 / 255 : 1)
119
+ }
120
+ if(isNaN(v)) {
121
+ v = 1
122
+ }
123
+ return limitNumber(0, 255, v)
124
+ }
125
+
126
+ static _parseResStrForHue(v: string|number) {
127
+ if(typeof v === 'string') {
128
+ v = parseFloat(v)
129
+ }
130
+ if(isNaN(v)) {
131
+ v = 0
132
+ }
133
+ return limitNumber(0, 360, v)
134
+ }
135
+
136
+ static _parsePercent(v: string|number) {
137
+ if(typeof v === 'string') {
138
+ v = parseFloat(v) / ('%' === v.substr(-1) ? 100.0 : 1)
139
+ }
140
+ if(isNaN(v)) {
141
+ v = 1
142
+ }
143
+ return limitNumber(0, 1, v)
144
+ }
145
+ }
146
+
@@ -0,0 +1,40 @@
1
+ export class Check {
2
+ static type(type, paramName, value) {
3
+ const valueType = typeof value
4
+ if (valueType !== type) {
5
+ throw new Error(
6
+ `Expected ${paramName} to be typeof ${type}, actual typeof was ${valueType}`
7
+ )
8
+ }
9
+ }
10
+ static types(types: string[], paramName, value) {
11
+ const valueType = typeof value
12
+ const isContained = types.includes(valueType)
13
+ if (!isContained) {
14
+ throw new Error(
15
+ `Expected ${paramName} to be typeof ${types.join(
16
+ '|'
17
+ )}, actual typeof was ${valueType}`
18
+ )
19
+ }
20
+ }
21
+ }
22
+
23
+ export function defaultValue(v, defaultV) {
24
+ if (v === undefined || v === null) {
25
+ return defaultV
26
+ }
27
+ if(isNaN(v) && typeof defaultV === 'number') {
28
+ return defaultV
29
+ }
30
+ return v
31
+ }
32
+
33
+ export function limitNumber(min: number, max: number, v: number) {
34
+ if (v > max) {
35
+ v = max
36
+ } else if (v < min) {
37
+ v = min
38
+ }
39
+ return v
40
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES5",
4
+ "module": "ES2015",
5
+ "declaration": true,
6
+ "pretty": true,
7
+ "sourceMap": true,
8
+ "outDir": "./dist",
9
+ "rootDir": "./src",
10
+ "importHelpers": true,
11
+ "strict": true,
12
+ "noImplicitAny": false,
13
+ "strictNullChecks": false,
14
+ "noImplicitThis": true,
15
+ "alwaysStrict": true,
16
+ "noUnusedLocals": true,
17
+ "noUnusedParameters": false,
18
+ "noImplicitReturns": true,
19
+ "noFallthroughCasesInSwitch": true,
20
+ "moduleResolution": "node",
21
+ "baseUrl": ".",
22
+ "allowSyntheticDefaultImports": true,
23
+ "experimentalDecorators": true,
24
+ "emitDecoratorMetadata": true,
25
+ "resolveJsonModule": true,
26
+ "esModuleInterop": true,
27
+ "lib": [
28
+ "es5",
29
+ "es6",
30
+ "dom",
31
+ "es2015.core",
32
+ "es2015.collection",
33
+ "es2015.generator",
34
+ "es2015.iterable",
35
+ "es2015.promise",
36
+ "es2015.proxy",
37
+ "es2015.reflect",
38
+ "es2015.symbol",
39
+ "es2015.symbol.wellknown",
40
+ "esnext.asynciterable",
41
+ "es2017"
42
+ ],
43
+ "paths": {
44
+ "@/*": ["./src/*"]
45
+ },
46
+ "plugins": [],
47
+ },
48
+ "include": ["src/**/*.ts"],
49
+ "exclude": ["node_modules/**", "dist"]
50
+ }
@@ -0,0 +1,52 @@
1
+ /*
2
+ * @Author: roman_123_123
3
+ * @Description:
4
+ * @Date: 2022-11-29 19:41:35
5
+ * @LastEditTime: 2022-12-06 00:42:46
6
+ */
7
+ const path = require('path')
8
+ const { CleanWebpackPlugin } = require('clean-webpack-plugin')
9
+
10
+ module.exports = {
11
+ mode: 'production',
12
+ entry: './src/main.ts',
13
+ output: {
14
+ filename: 'css-color-parser.min.js',
15
+ path: path.resolve(__dirname, 'dist'),
16
+ globalObject: 'this',
17
+ library: {
18
+ name: 'Parser',
19
+ type: 'umd'
20
+ },
21
+ environment: {
22
+ // The environment supports arrow functions ('() => { ... }').
23
+ arrowFunction:false,
24
+ // The environment supports BigInt as literal (123n).
25
+ bigIntLiteral: false,
26
+ // The environment supports const and let for variable declarations.
27
+ const: false,
28
+ // The environment supports destructuring ('{ a, b } = obj').
29
+ destructuring: false,
30
+ // The environment supports an async import() function to import EcmaScript modules.
31
+ dynamicImport: false,
32
+ // The environment supports 'for of' iteration ('for (const x of array) { ... }').
33
+ forOf: false,
34
+ // The environment supports ECMAScript Module syntax to import ECMAScript modules (import ... from '...').
35
+ module: false,
36
+ // The environment supports optional chaining ('obj?.a' or 'obj?.()').
37
+ optionalChaining: false,
38
+ // The environment supports template literals.
39
+ templateLiteral: true,
40
+ }
41
+ },
42
+ module: {
43
+ rules: [{ test: /\.ts$/, exclude: /node_modules/, use: 'ts-loader' }],
44
+ },
45
+ resolve: {
46
+ extensions: ['.ts', '.js'],
47
+ alias: {
48
+ '@': path.resolve('src')
49
+ }
50
+ },
51
+ plugins: [new CleanWebpackPlugin()]
52
+ }