-
Notifications
You must be signed in to change notification settings - Fork 317
/
Copy pathcode.js
101 lines (95 loc) Β· 2.68 KB
/
code.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
console.clear();
initialize();
async function initialize() {
const styles = await figma.getLocalPaintStylesAsync();
const tokenDataMap = styles.reduce(styleToTokenDataMap, {});
const tokenData = Object.values(tokenDataMap);
createTokens(tokenData);
figma.closePlugin();
}
function createTokens(tokenData) {
if (tokenData.length <= 0) {
figma.notify("No convertible styles found. :(");
return;
}
const collection = figma.variables.createVariableCollection(`Style Tokens`);
let aliasCollection;
const modeId = collection.modes[0].modeId;
collection.renameMode(modeId, "Style");
console.log(tokenData);
tokenData.forEach(({ color, hex, opacity, tokens }) => {
if (tokens.length > 1) {
aliasCollection =
aliasCollection ||
figma.variables.createVariableCollection(`Style Tokens: Aliased`);
aliasCollection.renameMode(aliasCollection.modes[0].modeId, "Style");
const opacityName =
opacity === 1 ? "" : ` (${Math.round(opacity * 100)}%)`;
const parentToken = figma.variables.createVariable(
`${hex.toUpperCase()}${opacityName}`,
aliasCollection,
"COLOR"
);
parentToken.setValueForMode(aliasCollection.modes[0].modeId, {
r: color.r,
g: color.g,
b: color.b,
a: opacity,
});
tokens.forEach((name) => {
const token = figma.variables.createVariable(name, collection, "COLOR");
token.setValueForMode(modeId, {
type: "VARIABLE_ALIAS",
id: parentToken.id,
});
});
} else {
const token = figma.variables.createVariable(
tokens[0],
collection,
"COLOR"
);
token.setValueForMode(modeId, {
r: color.r,
g: color.g,
b: color.b,
a: opacity,
});
}
});
}
function styleToTokenDataMap(into, current) {
const paints = current.paints.filter(
({ visible, type }) => visible && type === "SOLID"
);
if (paints.length === 1) {
const {
blendMode,
color: { r, g, b },
opacity,
type,
} = paints[0];
const hex = rgbToHex({ r, g, b });
if (blendMode === "NORMAL") {
const uniqueId = [hex, opacity].join("-");
into[uniqueId] = into[uniqueId] || {
color: { r, g, b },
hex,
opacity,
tokens: [],
};
into[uniqueId].tokens.push(current.name);
} else {
// do something different i guess
}
}
return into;
}
function rgbToHex({ r, g, b }) {
const toHex = (value) => {
const hex = Math.round(value * 255).toString(16);
return hex.length === 1 ? "0" + hex : hex;
};
const hex = [toHex(r), toHex(g), toHex(b)].join("");
return `#${hex}`;
}