Skip to content

Instantly share code, notes, and snippets.

@starakaj
Created July 8, 2021 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starakaj/c428bcb14a1e8cd430450a68077b831f to your computer and use it in GitHub Desktop.
Save starakaj/c428bcb14a1e8cd430450a68077b831f to your computer and use it in GitHub Desktop.
import * as csstree from "css-tree";
// ...
ontext(data: string) {
if (inStyle) {
let styleFunctionName;
let inDeclaration = false;
const cssast = csstree.parse(data);
csstree.walk(cssast, {
enter(node: csstree.CssNode) {
if (node.type === "Rule") {
// Reset state machine
styleFunctionName = undefined;
}
else if (node.type === "ClassSelector") {
styleFunctionName = createLegalName(node.name);
}
else if (node.type === "Declaration") {
inDeclaration = true;
}
else if (node.type === "HexColor") {
if (inDeclaration && styleFunctionName) {
const color = hexColorToColorArray(node.value);
styleFunctions = styleFunctions.concat(
makeStyleFunction({
styleFunctionName: t.identifier(styleFunctionName),
r: t.numericLiteral(color[0]),
g: t.numericLiteral(color[1]),
b: t.numericLiteral(color[2]),
a: t.numericLiteral(color[3])
})
);
// Make sure we only have one
styleFunctionName = undefined;
}
}
},
leave(node: csstree.CssNode) {
if (node.type === "Declaration") {
inDeclaration = false;
}
}
});
}
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment