UNPKG

@vulcancreative/cross-colour

Version:

Dynamically translates a SASS/SCSS colour file to a JS object

86 lines (62 loc) 2.04 kB
const { camelise } = require("./camelise"); const { readColours, writeColours } = require("./io"); class CrossColour { constructor(props) { this.state = { ...props, build_: "" }; } build() { return this.state.build_; } colors(input) { return this.colours(input); } colours(input) { return this.cross(input); } cross(input) { // in block-comment marker let comment = false; // simple parser/lexer const lines = input.trim().split(/\n/g); const trans = lines.map((line, idx) => { const trimmed = line.trim(); // determine early failures if (trimmed === "") return line; if (trimmed.indexOf(":") < 0) return ""; if (trimmed.indexOf("$") < 0) return ""; const startsComment = trimmed.indexOf("/*") > -1; const endsComment = trimmed.indexOf("*/") > -1; comment = (comment || startsComment) && !endsComment; if (comment) return ""; // compile const parts = trimmed.split(/\s*:\s*|:/); const key = parts[0].replace("$", "").trim(); const val = parts[1].replace(";", "").trim(); const tail = idx < lines.length - 1 ? "," : ""; return ` "${camelise(key)}": "${val}"${tail}`; }); // convert to JS object and write to state const temp = `{${trans.join("\n")}}`; this.state = { ...this.state, build_: JSON.parse(temp) }; return this; } read(configOverride = null) { const { sassFilename } = this.state; const filename = configOverride || sassFilename; this.cross(readColours(filename)); return this; } write(coloursOverride = null, configOverride = null) { const { build_, jsFilename, silent } = this.state; const colours = coloursOverride || build_; const filename = configOverride || jsFilename; writeColours(colours, filename, silent); return this; } readWrite(sassOverride = null, jsOverride = null) { this.read(sassOverride); this.write(jsOverride); return this; } } module.exports = CrossColour;