UNPKG

css-modular-type

Version:

A PostCSS and TailwindCSS plugin for generating modular type scales.

53 lines (52 loc) 2.3 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const postcss_value_parser_1 = __importDefault(require("postcss-value-parser")); const config_1 = require("./config"); const generateFontScales_1 = __importDefault(require("./generateFontScales")); const plugin = (opts = {}) => { const resolvedOptions = { ...config_1.defaultPostcssConfig, ...opts }; const { prefix, replaceInline, generatorDirective } = resolvedOptions; const stepsMap = (0, generateFontScales_1.default)(resolvedOptions); return { postcssPlugin: "css-modular-type", // Replace each rule that has a variable matching the prefix Once(root, { result }) { root.walkDecls((decl) => { if (replaceInline && decl.value.includes(prefix)) { const parsed = (0, postcss_value_parser_1.default)(decl.value); parsed.walk((valueNode) => { // CSS variables is declared as a `word` node in `postcss-value-parser` if (valueNode.type !== "word") return; const value = stepsMap.get(valueNode.value.replace(/^--/, "")); if (value) { decl.value = value; } else { decl.warn(result, "Not replacing the following declaration. Step maybe out-of-bound.\n" + `${decl.prop}: ${decl.value}`); } }); } }); }, // Replace generatorDirective with variables Rule(rule, { Declaration }) { if (replaceInline) return; rule.walkComments((cmt) => { if (cmt.text === generatorDirective) { const fontVars = []; for (const [key, value] of stepsMap) { fontVars.push(new Declaration({ prop: `--${key}`, value })); } cmt.replaceWith(fontVars); } }); }, }; }; plugin.postcss = true; module.exports = plugin;