From b42be007440f7cbc7f5b83d6e810bc87b98d0812 Mon Sep 17 00:00:00 2001 From: mrjvs Date: Sat, 9 Dec 2023 17:29:58 +0100 Subject: [PATCH] add figma token extraction script for themes --- .eslintrc.js | 1 + plugins/.gitignore | 1 + plugins/figmaTokensToThemeTokens.mjs | 43 ++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 plugins/.gitignore create mode 100644 plugins/figmaTokensToThemeTokens.mjs diff --git a/.eslintrc.js b/.eslintrc.js index 8b0c8e15..edbb76cf 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -22,6 +22,7 @@ module.exports = { "/*.js", "/*.ts", "/plugins/*.ts", + "/plugins/*.mjs", "/themes/**/*.ts" ], parser: "@typescript-eslint/parser", diff --git a/plugins/.gitignore b/plugins/.gitignore new file mode 100644 index 00000000..e9ee2f2d --- /dev/null +++ b/plugins/.gitignore @@ -0,0 +1 @@ +figmaTokens.json diff --git a/plugins/figmaTokensToThemeTokens.mjs b/plugins/figmaTokensToThemeTokens.mjs new file mode 100644 index 00000000..5be386d0 --- /dev/null +++ b/plugins/figmaTokensToThemeTokens.mjs @@ -0,0 +1,43 @@ +/** + * This script turns output from the figma plugin "style to JSON" into a usuable theme. + * It expects a format of "themes/{NAME}/anythinghere" + */ + +import fs from "fs"; + +const fileLocation = "./figmaTokens.json"; +const theme = "blue"; + +const fileContents = fs.readFileSync(fileLocation, { + encoding: "utf-8" +}); +const tokens = JSON.parse(fileContents); + +const themeTokens = tokens.themes[theme]; +const output = {}; + +function setKey(obj, key, defaultVal) { + const realKey = key.match(/^\d+$/g) ? "c" + key : key; + if (obj[key]) return obj[key]; + obj[realKey] = defaultVal; + return obj[realKey]; +} + +function handleToken(token, path) { + if (typeof token.name === "string" && typeof token.description === "string") { + let ref = output; + const lastKey = path.pop(); + path.forEach((v) => { + ref = setKey(ref, v, {}); + }); + setKey(ref, lastKey, token.hex); + return; + } + + for (let key in token) { + handleToken(token[key], [...path, key]); + } +} + +handleToken(themeTokens, []); +console.log(JSON.stringify(output, null, 2));