forked from stevage/figmasset
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
206 lines (189 loc) · 6.02 KB
/
index.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
function figmaApi({ personalAccessToken, fetchFunc }) {
this._personalAccessToken = personalAccessToken;
this._fetchFunc = fetchFunc;
}
figmaApi.prototype.get = async function (api, params) {
const search = params ? '?' + new URLSearchParams(params).toString() : '';
const response = await this._fetchFunc(
`https://api.figma.com/v1/${api}${search}`,
{
headers: { 'X-Figma-Token': this._personalAccessToken },
}
);
if (response.status >= 400) {
let extra = '';
try {
extra += (await response.json()).err;
} finally {
throw new Error(
`HTTP error ${response.status} accessing Figma. ${extra}`
);
}
}
return response.json();
};
// For each nodeId, find its corresponding node by searching the document.
// Note this is pretty inefficient, we can end up traversing the entire document quite a few times. Likely insignificant on smallish documents.
const findNodesById = function ({ file, nodeIds }) {
function findNode(nodeId, searchNode) {
if (nodeId === searchNode.id) {
return searchNode;
} else if (searchNode.children) {
return searchNode.children
.map((n) => findNode(nodeId, n))
.find(Boolean);
} else {
return null;
}
}
return nodeIds.map((nodeId) => findNode(nodeId, file.document));
};
const findNodeIdsForNames = function ({ file, names }) {
// find node IDs for names with a depth-first search
function findNameInNode(name, node) {
if (name === node.name && node.type === 'FRAME') {
return node.id;
} else if (node.children) {
return node.children
.map((n) => findNameInNode(name, n))
.find(Boolean);
} else {
return null;
}
}
return names.map((name) => findNameInNode(name, file.document));
};
/* Request images for some assets, and combine multiple scales into one object per asset */
async function getAssetImages({
api,
fileKey,
assetList,
scales = [1],
format = 'png',
}) {
async function getImageList(scale) {
return api.get(`images/${fileKey}`, {
ids: Object.values(assetList),
format,
scale,
});
}
const assetsWithUrls = {};
const imageLists = await Promise.all(
scales.map((scale) => getImageList(scale))
);
scales.forEach((scale, scaleIndex) => {
for (const name of Object.keys(assetList)) {
const nodeId = assetList[name];
assetsWithUrls[name] = assetsWithUrls[name] || { id: nodeId };
assetsWithUrls[name][`@${scale}x`] =
imageLists[scaleIndex].images[nodeId];
}
});
return assetsWithUrls;
}
// Given a number of frames, compiles a set of named top-level nodes within them. Later nodes of the same name replace earlier ones.
function makeAssetList(frames) {
const assetList = {};
for (const frame of frames.filter(Boolean)) {
for (const node of frame.children) {
assetList[node.name] = node.id;
}
}
return assetList;
}
/*
Returns URLs of rasterisations of all objects within one or more frames specified by ID or name, for one or more scales.
Return format:
{
'asset-name': {
id: '102:5',
'@1x': 'https://s3-us-west-2.amazonaws
'@2x': '...'
},
...
}
*/
async function getFigmassets({
frameIds = [],
frameNames = [],
fileKey,
personalAccessToken,
scales = [1],
format = 'png',
fetchFunc = (...args) => window.fetch(...args),
}) {
const api = new figmaApi({ personalAccessToken, fetchFunc });
const file = await api.get(`files/${fileKey}`);
if (frameNames.length) {
frameIds = [
...frameIds,
...findNodeIdsForNames({ file, names: frameNames }),
];
}
const frames = findNodesById({ file, nodeIds: frameIds }).filter(Boolean);
if (!frames.length) {
throw new Error(`No matching frames for ${frameIds}, ${frameNames}`);
}
const assetList = makeAssetList(frames);
return await getAssetImages({ api, fileKey, assetList, scales, format });
}
function getScale(asset) {
return Math.max(
...Object.keys(asset)
.filter((k) => k[0] === '@')
.map((k) => +k.replace(/[^0-9.]/g, ''))
);
}
async function addAssetToMap(map, iconId, asset, options = {}) {
const { replace } = options;
const scale = getScale(asset);
if (replace && map.hasImage(iconId)) {
map.removeImage(iconId);
}
return new Promise((resolve, reject) => {
map.loadImage(asset[`@${scale}x`], (error, image) => {
if (error) return reject(error);
map.addImage(iconId, image, {
pixelRatio: scale,
});
resolve();
});
});
}
async function addAssetsToMap(map, assets, options = {}) {
return Promise.all(
Object.entries(assets)
.map(([iconId, asset]) => addAssetToMap(map, iconId, asset, options))
);
}
async function loadFigmassets({ map, replace = false, ...otherArgs }) {
if (map && !otherArgs.scales) {
// makes sense to load map assets at 2x
otherArgs.scales = [2];
}
const assets = await getFigmassets(otherArgs);
if (map) {
await addAssetsToMap(map, assets, { replace });
}
return assets;
}
// path is URL path to directory containing assets.json and every referenced image
async function loadStoredFigmassets({ map, path = '' }) {
if (path) {
path = path.replace(/([^/])$/, '$1/');
}
const assets = await fetch(`${path}assets.json`).then((r) => r.json());
for (const asset of assets) {
map.loadImage(`${path}${asset.fileName}`, (error, image) => {
map.addImage(asset.id, image, { pixelRatio: asset.scale });
});
}
}
export {
getFigmassets as getFigmaIconsByFrames,
getFigmassets,
addAssetsToMap,
loadFigmassets,
loadStoredFigmassets,
};