Last active
August 2, 2019 08:21
-
-
Save lunelson/71abe2a872ab7be0974c9be27c5aae21 to your computer and use it in GitHub Desktop.
JS2Sass: parse JS values to Sass values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const parseUnit = require('parse-unit'); | |
const colorString = require('color-string'); | |
// this function can receive either dart-sass or node-sass as sassEngine | |
module.exports = function(sassEngine) { | |
return function js2sass(jsValue) { | |
// UnitNumber | Color | String | |
if (typeof jsValue === 'string') { | |
const unitNumber = parseUnit(jsValue); | |
if (!isNaN(unitNumber[0])) return new sassEngine.types.Number(...unitNumber); | |
const rgbColor = colorString.get.rgb(jsValue); | |
if (rgbColor != null) return new sassEngine.types.Color(...rgbColor); | |
return new sassEngine.types.String(jsValue); | |
} | |
// Boolean | |
else if (typeof jsValue === 'boolean') { | |
return jsValue | |
? sassEngine.types.Boolean.TRUE | |
: sassEngine.types.Boolean.FALSE; | |
} | |
// Null | |
else if (typeof jsValue === 'undefined' || jsValue === null) { | |
return sassEngine.types.Null.NULL; | |
} else if (typeof jsValue === 'number') { | |
return new sassEngine.types.Number(jsValue); | |
} | |
// List -> set up and recurse | |
else if (jsValue && jsValue.constructor.name === 'Array') { | |
var list = new sassEngine.types.List(jsValue.length); | |
for (var i = 0; i < jsValue.length; i++) { | |
list.setValue(i, js2sass(jsValue[i])); | |
} | |
var isComma = | |
typeof jsValue.separator === 'undefined' ? true : jsValue.separator; | |
list.setSeparator(isComma); | |
return list; | |
} | |
// Map -> set up and recurse | |
else if (typeof jsValue === 'object') { | |
var keys = []; | |
for (var k in jsValue) { | |
if (jsValue.hasOwnProperty(k)) { | |
keys[keys.length] = k; | |
} | |
} | |
var map = new sassEngine.types.Map(keys.length); | |
for (var m = 0; m < keys.length; m++) { | |
var key = keys[m]; | |
map.setKey(m, new sassEngine.types.String(key)); | |
map.setValue(m, js2sass(jsValue[key])); | |
} | |
return map; | |
} | |
// this shouldn't happen 😏 | |
else { | |
throw new Error("Don't know how to coerce: " + jsValue.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment