| 267 | } |
| 268 | |
| 269 | static parse(value: string) { |
| 270 | let colors: Array<number | undefined> = []; |
| 271 | // matching #rgb, #rgba, #rrggbb, #rrggbbaa |
| 272 | if (/^#[\da-f]+$/i.test(value) && [4, 5, 7, 9].includes(value.length)) { |
| 273 | const values = (value.length < 6 ? value.replace(/[^#]/gi, '$&$&') : value) |
| 274 | .slice(1) |
| 275 | .split(''); |
| 276 | while (values.length > 0) { |
| 277 | colors.push(parseInt(values.splice(0, 2).join(''), 16)); |
| 278 | } |
| 279 | colors[3] = colors[3] !== undefined ? colors[3] / 255 : undefined; |
| 280 | } |
| 281 | |
| 282 | // matching rgb(rrr, ggg, bbb), rgba(rrr, ggg, bbb, 0.a) |
| 283 | const match = value.match(/^rgba?\((.*)\)$/); |
| 284 | if (match?.[1]) { |
| 285 | colors = match[1].split(',').map(value => Number(value.trim())); |
| 286 | colors = colors.map((num, i) => { |
| 287 | return clamp(num ?? 0, 0, i < 3 ? 255 : 1); |
| 288 | }); |
| 289 | } |
| 290 | if (colors[0] === undefined || colors[1] === undefined || colors[2] === undefined) { |
| 291 | return undefined; |
| 292 | } |
| 293 | |
| 294 | return colors.length < 3 |
| 295 | ? undefined |
| 296 | : new RGBColor(colors[0], colors[1], colors[2], colors[3] ?? 1); |
| 297 | } |
| 298 | |
| 299 | toString(format: ColorFormat | 'css' = 'css') { |
| 300 | switch (format) { |