MCPcopy Index your code
hub / github.com/figma/plugin-samples / parseColor

Function parseColor

variables-import-export/code.js:204–255  ·  view source on GitHub ↗
(color)

Source from the content-addressed store, hash-verified

202}
203
204function parseColor(color) {
205 color = color.trim();
206 const rgbRegex = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
207 const rgbaRegex =
208 /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*([\d.]+)\s*\)$/;
209 const hslRegex = /^hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)$/;
210 const hslaRegex =
211 /^hsla\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*,\s*([\d.]+)\s*\)$/;
212 const hexRegex = /^#([A-Fa-f0-9]{3}){1,2}$/;
213 const floatRgbRegex =
214 /^\{\s*r:\s*[\d\.]+,\s*g:\s*[\d\.]+,\s*b:\s*[\d\.]+(,\s*opacity:\s*[\d\.]+)?\s*\}$/;
215
216 if (rgbRegex.test(color)) {
217 const [, r, g, b] = color.match(rgbRegex);
218 return { r: parseInt(r) / 255, g: parseInt(g) / 255, b: parseInt(b) / 255 };
219 } else if (rgbaRegex.test(color)) {
220 const [, r, g, b, a] = color.match(rgbaRegex);
221 return {
222 r: parseInt(r) / 255,
223 g: parseInt(g) / 255,
224 b: parseInt(b) / 255,
225 a: parseFloat(a),
226 };
227 } else if (hslRegex.test(color)) {
228 const [, h, s, l] = color.match(hslRegex);
229 return hslToRgbFloat(parseInt(h), parseInt(s) / 100, parseInt(l) / 100);
230 } else if (hslaRegex.test(color)) {
231 const [, h, s, l, a] = color.match(hslaRegex);
232 return Object.assign(
233 hslToRgbFloat(parseInt(h), parseInt(s) / 100, parseInt(l) / 100),
234 { a: parseFloat(a) }
235 );
236 } else if (hexRegex.test(color)) {
237 const hexValue = color.substring(1);
238 const expandedHex =
239 hexValue.length === 3
240 ? hexValue
241 .split("")
242 .map((char) => char + char)
243 .join("")
244 : hexValue;
245 return {
246 r: parseInt(expandedHex.slice(0, 2), 16) / 255,
247 g: parseInt(expandedHex.slice(2, 4), 16) / 255,
248 b: parseInt(expandedHex.slice(4, 6), 16) / 255,
249 };
250 } else if (floatRgbRegex.test(color)) {
251 return JSON.parse(color);
252 } else {
253 throw new Error("Invalid color format");
254 }
255}
256
257function hslToRgbFloat(h, s, l) {
258 const hue2rgb = (p, q, t) => {

Callers 1

traverseTokenFunction · 0.85

Calls 1

hslToRgbFloatFunction · 0.85

Tested by

no test coverage detected