UNPKG

tweak-tools

Version:

Tweak your React projects until awesomeness

54 lines (53 loc) 2.14 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.normalize = exports.format = exports.sanitize = exports.schema = void 0; const v8n_1 = __importDefault(require("v8n")); const colord_1 = require("colord"); const names_1 = __importDefault(require("colord/plugins/names")); const utils_1 = require("../../utils"); (0, colord_1.extend)([names_1.default]); const convertMap = { rgb: 'toRgb', hsl: 'toHsl', hsv: 'toHsv', hex: 'toHex', }; v8n_1.default.extend({ color: () => (value) => (0, colord_1.colord)(value).isValid(), }); // prettier-ignore // @ts-expect-error const schema = (o) => (0, v8n_1.default)().color().test(o); exports.schema = schema; function convert(color, { format, hasAlpha, isString }) { const convertFn = convertMap[format] + (isString && format !== 'hex' ? 'String' : ''); // @ts-ignore const result = color[convertFn](); return typeof result === 'object' && !hasAlpha ? (0, utils_1.omit)(result, ['a']) : result; } const sanitize = (v, settings) => { const color = (0, colord_1.colord)(v); if (!color.isValid()) throw Error('Invalid color'); return convert(color, settings); }; exports.sanitize = sanitize; const format = (v, settings) => { return convert((0, colord_1.colord)(v), Object.assign(Object.assign({}, settings), { isString: true, format: 'hex' })); }; exports.format = format; const normalize = ({ value }) => { const _f = (0, colord_1.getFormat)(value); const format = (_f === 'name' ? 'hex' : _f); const hasAlpha = typeof value === 'object' ? 'a' in value : (_f === 'hex' && value.length === 8) || /^(rgba)|(hsla)|(hsva)/.test(value); const settings = { format, hasAlpha, isString: typeof value === 'string' }; // by santizing the value we make sure the returned value is parsed and fixed, // consistent with future updates. return { value: (0, exports.sanitize)(value, settings), settings }; }; exports.normalize = normalize;