UNPKG

3.3 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", {
3 value: true
4});
5function _export(target, all) {
6 for(var name in all)Object.defineProperty(target, name, {
7 enumerable: true,
8 get: all[name]
9 });
10}
11_export(exports, {
12 parseColor: ()=>parseColor,
13 formatColor: ()=>formatColor
14});
15const _colorName = /*#__PURE__*/ _interopRequireDefault(require("color-name"));
16function _interopRequireDefault(obj) {
17 return obj && obj.__esModule ? obj : {
18 default: obj
19 };
20}
21let HEX = /^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i;
22let SHORT_HEX = /^#([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i;
23let VALUE = /(?:\d+|\d*\.\d+)%?/;
24let SEP = /(?:\s*,\s*|\s+)/;
25let ALPHA_SEP = /\s*[,/]\s*/;
26let CUSTOM_PROPERTY = /var\(--(?:[^ )]*?)\)/;
27let RGB = new RegExp(`^(rgb)a?\\(\\s*(${VALUE.source}|${CUSTOM_PROPERTY.source})(?:${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?(?:${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?(?:${ALPHA_SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?\\s*\\)$`);
28let HSL = new RegExp(`^(hsl)a?\\(\\s*((?:${VALUE.source})(?:deg|rad|grad|turn)?|${CUSTOM_PROPERTY.source})(?:${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?(?:${SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?(?:${ALPHA_SEP.source}(${VALUE.source}|${CUSTOM_PROPERTY.source}))?\\s*\\)$`);
29function parseColor(value, { loose =false } = {}) {
30 var ref, ref1;
31 if (typeof value !== "string") {
32 return null;
33 }
34 value = value.trim();
35 if (value === "transparent") {
36 return {
37 mode: "rgb",
38 color: [
39 "0",
40 "0",
41 "0"
42 ],
43 alpha: "0"
44 };
45 }
46 if (value in _colorName.default) {
47 return {
48 mode: "rgb",
49 color: _colorName.default[value].map((v)=>v.toString())
50 };
51 }
52 let hex = value.replace(SHORT_HEX, (_, r, g, b, a)=>[
53 "#",
54 r,
55 r,
56 g,
57 g,
58 b,
59 b,
60 a ? a + a : ""
61 ].join("")).match(HEX);
62 if (hex !== null) {
63 return {
64 mode: "rgb",
65 color: [
66 parseInt(hex[1], 16),
67 parseInt(hex[2], 16),
68 parseInt(hex[3], 16)
69 ].map((v)=>v.toString()),
70 alpha: hex[4] ? (parseInt(hex[4], 16) / 255).toString() : undefined
71 };
72 }
73 var ref2;
74 let match = (ref2 = value.match(RGB)) !== null && ref2 !== void 0 ? ref2 : value.match(HSL);
75 if (match === null) {
76 return null;
77 }
78 let color = [
79 match[2],
80 match[3],
81 match[4]
82 ].filter(Boolean).map((v)=>v.toString());
83 if (!loose && color.length !== 3) {
84 return null;
85 }
86 if (color.length < 3 && !color.some((part)=>/^var\(.*?\)$/.test(part))) {
87 return null;
88 }
89 return {
90 mode: match[1],
91 color,
92 alpha: (ref = match[5]) === null || ref === void 0 ? void 0 : (ref1 = ref.toString) === null || ref1 === void 0 ? void 0 : ref1.call(ref)
93 };
94}
95function formatColor({ mode , color , alpha }) {
96 let hasAlpha = alpha !== undefined;
97 return `${mode}(${color.join(" ")}${hasAlpha ? ` / ${alpha}` : ""})`;
98}