Created
December 3, 2019 07:55
-
-
Save suhomozgy-andrey/68a36342cb44e98b7f03c28c75a55ade to your computer and use it in GitHub Desktop.
This file contains hidden or 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 dotenv = require('dotenv'); | |
| dotenv.config(); | |
| const { | |
| PAGE_ID, | |
| TEAM_ID, | |
| FILE_KEY, | |
| FIGMA_PERSONAL_TOKEN | |
| } = process.env; | |
| const fetch = require('node-fetch'); | |
| const fs = require('fs'); | |
| const path = require('path'); | |
| if (!FIGMA_PERSONAL_TOKEN) { | |
| console.error('No environment configured.'); | |
| process.exit(1); | |
| } | |
| const doFetch = (url) => | |
| fetch(`https://api.figma.com/v1${url}`, { | |
| headers: { | |
| 'X-Figma-Token': FIGMA_PERSONAL_TOKEN | |
| } | |
| }) | |
| .then((res) => { | |
| if (!res.ok) { | |
| throw new Error(`Status: ${res.status}`); | |
| } | |
| return res.json(); | |
| }) | |
| .then((json) => { | |
| if (json.error || (json.status && json.status !== 200)) { | |
| throw new Error( | |
| json.error || `Status ${json.status}: ${json.err}` | |
| ); | |
| } | |
| return json; | |
| }); | |
| const fetchStyles = async(teamId) => { | |
| const json = await doFetch(`/teams/${teamId}/styles?page_size=99`); | |
| return json.meta.styles; | |
| }; | |
| const fetchFile = async(key) => await doFetch(`/files/${key}`); | |
| const fetchStyle = async(key) => await doFetch(`/styles/${key}`); | |
| const fetchAllColorStyles = async () => { | |
| const styles = await fetchStyles(TEAM_ID); | |
| const file = await fetchFile(FILE_KEY); | |
| const canvas = file.document.children.find((page) => page.id === PAGE_ID); | |
| return ( | |
| canvas && canvas.children | |
| .filter(child => child.type === 'INSTANCE') | |
| .map(instance => instance.children.filter(instance => instance.type === 'RECTANGLE')[0]) | |
| .map(color => { | |
| const { name } = color; | |
| return color.fills.map(f => { | |
| const { r, g, b } = f.color; | |
| const rgbColor = `rgb(${[(r * 255 << 0), (g * 255 << 0), (b * 255 << 0)].join(',')})`; | |
| return { [name]: rgbColor }; | |
| })[0] | |
| }) | |
| ); | |
| }; | |
| const writeColorsFromFigma = async() => { | |
| const styles = await fetchAllColorStyles(); | |
| if (!styles) { | |
| throw new Error('No styles found'); | |
| } | |
| const fileContents = `/* Updated at ${new Date().toUTCString()}*/ | |
| module.exports = { styles: ${JSON.stringify(styles)} }`; | |
| fs.writeFile('./modules/colors/styles.js', fileContents, () => { | |
| console.log(`Wrote ${styles.length} styles to /modules/colors/styles.js`); | |
| }); | |
| }; | |
| writeColorsFromFigma().catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment