Created
December 8, 2016 15:23
-
-
Save Buslowicz/589ac35ab5b8a7ed8821b8349e3b1026 to your computer and use it in GitHub Desktop.
CSS Transform getter and setter from single template
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
function buildPatterns(order) { | |
let orderMap = {}; | |
let orderArray = order.split("|"); | |
orderArray.forEach((t, i) => orderMap[ t ] = i); | |
return (consts, ...vars) => { | |
const escapePars = [ /(\(|\))/g, "\\$1" ]; | |
const map = { | |
number: { match: `([\\de.-]+)`, cast: Number }, | |
string: { match: `([\\w.-]+)`, cast: String }, | |
object: { match: `(.+?)`, cast: _ => _ }, | |
undefined: { match: "", cast: _ => _ } | |
}; | |
const params = []; | |
let regExp = new RegExp(consts.reduce((a, c, i) => { | |
let param = map[ typeof vars[ i ] ]; | |
params[ i ] = { | |
cast: param.cast, | |
default: vars[ i ] | |
}; | |
return a + c.replace(...escapePars) + (param.match); | |
}, "")); | |
return { | |
getTransform(style) { | |
let match = style.transform.match(regExp) || []; | |
return { | |
x: params[ orderMap.x ].cast(match[ orderMap.x + 1 ] || params[ orderMap.x ].default), | |
y: params[ orderMap.y ].cast(match[ orderMap.y + 1 ] || params[ orderMap.y ].default), | |
scale: params[ orderMap.scale ].cast(match[ orderMap.scale + 1 ] || params[ orderMap.scale ].default) | |
} | |
}, | |
setTransform(style, values) { | |
style.transform = consts.reduce((a, c, i) => a + c + (values[ orderArray[ i ] ] || ""), ""); | |
} | |
}; | |
} | |
} | |
// Example usage | |
const { getTransform, setTransform } = buildPatterns("x|y|scale")`translate(${0}%, ${0}%) scale(${0})`; | |
let { scale, x, y } = getTransform(style); | |
// do something with scale, x and y | |
setTransform(style, { scale, x, y }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment