Skip to content

Instantly share code, notes, and snippets.

@alexcmgit
Created June 18, 2022 07:00
Show Gist options
  • Save alexcmgit/1ba84283f04b6de3ef2c8e93c7cccfe7 to your computer and use it in GitHub Desktop.
Save alexcmgit/1ba84283f04b6de3ef2c8e93c7cccfe7 to your computer and use it in GitHub Desktop.
Select a theme: https://primer.style/primitives/colors/ and scrap it's variables
function colorName(c) {
if (c.startsWith("#")) {
return `Color(0xff${c.substr(1, c.length)})`;
} else {
const color = c.split(/(\(|\))/g)[2];
return `Color.fromRGBO(${color})`;
}
}
function varName(c) {
const lower = c.toLowerCase();
const fUpper = lower[0].toUpperCase();
const name = `${fUpper}${lower.substr(1, lower.length)}`;
return `k${name}`;
}
function colorName(c) {
if (c.startsWith("#")) {
return `Color(0xff${c.substr(1, c.length)})`;
} else if (c.startsWith("rgba")) {
const color = c.split(/(\(|\))/g)[2];
return `Color.fromRGBO(${color})`;
} else {
const color = c.split(/(\(|\))/g)[2];
const [h, s, l, a] = color
.split(",")
.map((x) => parseFloat(x.replace("%", "")));
return `HSLColor.fromAHSL(${a}, ${h}, ${s / 100}, ${l / 100}).toColor()`;
}
}
const mapper = {};
function registerVar(node) {
const [k, v] = node[0].textContent.split(".");
const name = varName(k);
if (name === "kShadow") return;
const color = colorName(node[2].textContent);
mapper[name] = [...(mapper[name] ?? []), { variant: v, value: color }];
}
const nodes = [...document.querySelectorAll(".Box-nv15kw-0.hUGesT")];
const childNodes = nodes
.map((n) => [...n.children])
.filter((n) => n.length === 4)
.map((n) => n.slice(1, n.length));
for (const node of childNodes) {
registerVar(node);
}
let generatedCode = ``;
for (const [k, v] of Object.entries(mapper)) {
const hsl = v.some(({ value }) => value.includes("HSL"));
const varType = hsl ? "final" : "const";
generatedCode += `${varType} ${k} = <String, Color>{
${v
.map(
({ variant, value }) => `'${variant}': ${hsl ? "const" : ""} ${value}`
)
.join(",\n ")}
};\n\n`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment