UNPKG

@ec0lint/plugin-css

Version:

ec0lint plugin that provides rules to verify CSS definition objects

117 lines (116 loc) 3.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseRgb = exports.ColorFromRgb = void 0; const color_class_1 = require("./color-class"); const colord_1 = require("./colord"); const parser_1 = require("./parser"); class ColorFromRgb extends color_class_1.AbsColor { constructor(rgb) { super(); this.type = "rgb"; this.rgb = rgb; } getRgb() { const rgb = this.rgb.rgb; if (!rgb.value) { return null; } return { r: this.parseColor(rgb.value.r), g: this.parseColor(rgb.value.g), b: this.parseColor(rgb.value.b), }; } isComplete() { var _a; return (this.rgb.complete && ((_a = this.getColord()) === null || _a === void 0 ? void 0 : _a.isValid())) || false; } getAlpha() { var _a, _b; return (_b = (_a = this.rgb.alpha) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : null; } removeAlpha() { return new ColorFromRgb(Object.assign(Object.assign({}, this.rgb), { rawName: this.rgb.rawName.replace(/a$/iu, ""), alpha: null })); } toColorString() { return `${this.rgb.rawName}(${this.rgb.rgb}${this.rgb.alpha || ""}${(this.rgb.extraArgs || []).join("")})`; } newColord() { const rgb = this.getRgb(); if (rgb && rgb.r != null && rgb.g != null && rgb.b != null) { 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 })); } return null; } parseColor(value) { const num = value.unit === "%" ? value.number / 100 : value.number / 255; if (0 <= num && num <= 1) { return num; } return null; } } exports.ColorFromRgb = ColorFromRgb; function parseRgb(input) { const fn = (0, parser_1.parseFunction)(input, ["rgb", "rgba"]); if (fn == null) { return null; } const values = (0, parser_1.parseArgumentValues)(fn.arguments, { argCount: 3, generate: (tokens) => { if (tokens.length !== 3) { return null; } const r = (0, parser_1.parseNumberUnit)(tokens[0], ["", "%"]); if (!isValidColor(r)) { return null; } const g = (0, parser_1.parseNumberUnit)(tokens[1], [r.unit]); const b = (0, parser_1.parseNumberUnit)(tokens[2], [r.unit]); if (!isValidColor(g) || !isValidColor(b)) { return null; } return { r, g, b, unit: r.unit, }; }, }); const rgb = values.values; const alpha = values.alpha; if (rgb.complete && (!alpha || alpha.valid) && fn.arguments.length === 0) { return { complete: true, rawName: fn.rawName, rgb, alpha, }; } return { complete: false, rawName: fn.rawName, rgb, alpha, extraArgs: fn.arguments, }; } exports.parseRgb = parseRgb; function isValidColor(node) { if (!node) { return false; } return node.unit === "%" ? (0, parser_1.isPercentRange)(node) : node.number >= 0 && node.number <= 255; }