@aurigma/design-atoms
Version:
Design Atoms is a part of Customer's Canvas SDK which allows for manipulating individual design elements through your code.
47 lines • 2.06 kB
JavaScript
import { RgbColor } from "@aurigma/design-atoms-model/Colors";
import { convertRelativeToByte } from "./Utils";
export class RgbColorParser {
constructor() {
this._mappedParsers = {
"#": this._parseHex,
"rgb(": this._parseRgb,
"rgba(": this._parseRgba
};
}
parse(colorString) {
colorString = colorString.trim().toLowerCase();
const parserKey = Object.keys(this._mappedParsers).find(key => colorString.startsWith(key));
if (parserKey == null) {
return null;
}
return this._mappedParsers[parserKey](colorString);
}
_parseHex(hexString) {
const shortHexRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hexString = hexString.replace(shortHexRegex, (r, g, b) => r + r + g + g + b + b);
const standardHexRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
const match = standardHexRegex.exec(hexString);
if (match == null || match.length !== 4) {
return null;
}
return new RgbColor(parseInt(match[1], 16), parseInt(match[2], 16), parseInt(match[3], 16), 255);
}
_parseRgb(rgbString) {
const rgbRegex = /^\s*rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)\s*;{0,1}\s*$/;
const match = rgbRegex.exec(rgbString);
if (match == null || match.length !== 4) {
return null;
}
return new RgbColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]), 255);
}
_parseRgba(rgbaString) {
const rgbaRegex = /^\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\,\s*(\d{1,}(\.\d{1,})?)\s*\)\s*;{0,1}\s*$/;
const match = rgbaRegex.exec(rgbaString);
if (match == null || match.length !== 6) {
return null;
}
let alpha = convertRelativeToByte(parseFloat(match[4]));
return new RgbColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]), alpha);
}
}
//# sourceMappingURL=RgbColorParser.js.map