UNPKG

@ec0lint/plugin-css

Version:

ec0lint plugin that provides rules to verify CSS definition objects

91 lines (90 loc) 2.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseHex = exports.isHex = exports.ColorFromHex = void 0; const color_class_1 = require("./color-class"); const colord_1 = require("./colord"); class ColorFromHex extends color_class_1.AbsColor { constructor(hex) { super(); this.type = "hex"; this.hex = hex; } getRgb() { return { r: this.parseColor(this.hex.r), g: this.parseColor(this.hex.g), b: this.parseColor(this.hex.b), }; } isComplete() { return true; } getAlpha() { if (!this.hex.alpha) { return null; } return this.parseColor(this.hex.alpha); } removeAlpha() { if (!this.hex.alpha) { return this; } return new ColorFromHex(Object.assign(Object.assign({}, this.hex), { alpha: undefined })); } toColorString() { return `#${this.hex.r}${this.hex.g}${this.hex.b}${this.hex.alpha || ""}`; } toHexImpl() { return this.toColorString(); } parseColor(hex) { const v = parseInt(hex, 16); if (hex.length === 1) { return v / 15; } return v / 255; } newColord() { const rgb = this.getRgb(); const base = { r: rgb.r * 255, g: rgb.g * 255, b: rgb.b * 255, }; const alpha = this.getAlpha(); return alpha == null ? (0, colord_1.parseColord)(base) : (0, colord_1.parseColord)(Object.assign(Object.assign({}, base), { a: alpha })); } } exports.ColorFromHex = ColorFromHex; function isHex(str) { return /^#[\da-f]+$/iu.test(str); } exports.isHex = isHex; function parseHex(input) { const hex = typeof input === "string" ? input : input.type === "word" ? input.value : ""; if (!isHex(hex)) { return null; } if (hex.length === 4 || hex.length === 5) { const [, r, g, b, alpha] = hex; return { kind: "RGB", r, g, b, alpha }; } if (hex.length === 7 || hex.length === 9) { const [, r1, r2, g1, g2, b1, b2, ...alpha] = hex; return { kind: "RRGGBB", r: r1 + r2, g: g1 + g2, b: b1 + b2, alpha: alpha.length ? alpha.join("") : undefined, }; } return null; } exports.parseHex = parseHex;