-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
191 lines (160 loc) · 5.29 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
require('dotenv').config()
const fetch = require('node-fetch');
const fs = require('fs');
const figma = require('./lib/figma');
const headers = new fetch.Headers();
let devToken = process.env.DEV_TOKEN;
if (process.argv.length < 3) {
console.log('Usage: node setup.js <file-key> [figma-dev-token]');
process.exit(0);
}
if (process.argv.length > 3) {
devToken = process.argv[3];
}
headers.append('X-Figma-Token', devToken);
const fileKey = process.argv[2];
const baseUrl = 'https://api.figma.com';
const vectorMap = {};
const vectorList = [];
const vectorTypes = ['VECTOR', 'LINE', 'REGULAR_POLYGON', 'ELLIPSE', 'STAR'];
function preprocessTree(node) {
let vectorsOnly = node.name.charAt(0) !== '#';
let vectorVConstraint = null;
let vectorHConstraint = null;
function paintsRequireRender(paints) {
if (!paints) return false;
let numPaints = 0;
for (const paint of paints) {
if (paint.visible === false) continue;
numPaints++;
if (paint.type === 'EMOJI') return true;
}
return numPaints > 1;
}
if (paintsRequireRender(node.fills) ||
paintsRequireRender(node.strokes) ||
(node.blendMode != null && ['PASS_THROUGH', 'NORMAL'].indexOf(node.blendMode) < 0)) {
node.type = 'VECTOR';
}
const children = node.children && node.children.filter((child) => child.visible !== false);
if (children) {
for (let j=0; j<children.length; j++) {
if (vectorTypes.indexOf(children[j].type) < 0) vectorsOnly = false;
else {
if (vectorVConstraint != null && children[j].constraints.vertical != vectorVConstraint) vectorsOnly = false;
if (vectorHConstraint != null && children[j].constraints.horizontal != vectorHConstraint) vectorsOnly = false;
vectorVConstraint = children[j].constraints.vertical;
vectorHConstraint = children[j].constraints.horizontal;
}
}
}
node.children = children;
if (children && children.length > 0 && vectorsOnly) {
node.type = 'VECTOR';
node.constraints = {
vertical: vectorVConstraint,
horizontal: vectorHConstraint,
};
}
if (vectorTypes.indexOf(node.type) >= 0) {
node.type = 'VECTOR';
vectorMap[node.id] = node;
vectorList.push(node.id);
node.children = [];
}
if (node.children) {
for (const child of node.children) {
preprocessTree(child);
}
}
}
async function main() {
let resp = await fetch(`${baseUrl}/v1/files/${fileKey}`, {headers});
let data = await resp.json();
const doc = data.document;
doc.children[0].children.forEach((child) => {
if (child.name.charAt(0) === '#' && child.visible !== false) {
preprocessTree(child);
} else {
child.children.forEach((ch) => {
if (ch.name.charAt(0) === '#') {
preprocessTree(ch);
}
})
}
})
let guids = vectorList.join(',');
data = await fetch(`${baseUrl}/v1/images/${fileKey}?ids=${guids}&format=svg`, {headers});
const imageJSON = await data.json();
const images = imageJSON.images || {};
if (images) {
let promises = [];
let guids = [];
for (const guid in images) {
if (images[guid] == null) continue;
guids.push(guid);
promises.push(fetch(images[guid]));
}
let responses = await Promise.all(promises);
promises = [];
for (const resp of responses) {
promises.push(resp.text());
}
responses = await Promise.all(promises);
for (let i=0; i<responses.length; i++) {
images[guids[i]] = responses[i].replace('<svg ', '<svg preserveAspectRatio="none" ');
}
}
const componentMap = {};
let contents = `import React from 'react';\n`;
let nextSection = '';
const setCurrentElement = (child) => {
figma.createComponent(child, images, componentMap);
nextSection += `export const Master${child.name.replace(/\W+/g, "")} = () => {\n`;
nextSection += " return (\n";
nextSection += ` <div className="master" style={{backgroundColor: "${figma.colorString(child.backgroundColor)}"}}>\n`;
nextSection += ` <C${child.name.replace(/\W+/g, "")} {...this.props} nodeId="${child.id}" />\n`;
nextSection += " </div>\n";
nextSection += " )\n";
nextSection += "}\n\n";
}
doc.children[0].children.forEach((child) => {
if (child.name.charAt(0) === '#' && child.visible !== false) {
setCurrentElement(child);
} else {
child.children.forEach((ch) => {
if (ch.name.charAt(0) === '#') {
setCurrentElement(ch);
}
})
}
})
const imported = {};
for (const key in componentMap) {
const component = componentMap[key];
const name = component.name;
if (!imported[name]) {
contents += `import { ${name} } from './components/${name}';\n`;
}
imported[name] = true;
}
contents += "\n";
contents += nextSection;
nextSection = '';
contents += `export function getComponentFromId(id) {\n`;
for (const key in componentMap) {
contents += ` if (id === "${key}") return ${componentMap[key].instance};\n`;
nextSection += componentMap[key].doc + "\n";
}
contents += " return null;\n}\n\n";
contents += nextSection;
const path = "./src/figmaComponents.js";
fs.writeFile(path, contents, function(err) {
if (err) console.log(err);
console.log(`wrote ${path}`);
});
}
main().catch((err) => {
console.error(err);
console.error(err.stack);
});