-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.ts
More file actions
107 lines (97 loc) · 2.8 KB
/
Copy pathcode.ts
File metadata and controls
107 lines (97 loc) · 2.8 KB
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
import { TokenSet, DesignToken, FlattenedToken } from './src/types';
figma.showUI(__html__, { width: 800, height: 600, themeColors: true });
figma.ui.onmessage = async (msg) => {
if (msg.type === 'import-tokens') {
await handleImportedTokens(msg.tokens);
} else if (msg.type === 'apply-token') {
await applyToken(msg.token);
} else if (msg.type === 'close-plugin') {
figma.closePlugin();
}
};
async function handleImportedTokens(tokens: TokenSet) {
try {
for (const [key, value] of Object.entries(tokens)) {
if ('$type' in value && '$value' in value) {
await processToken(key, value as DesignToken);
} else {
await processTokenGroup(key, value as TokenSet);
}
}
figma.notify('Tokens imported successfully');
} catch (error) {
console.error('Error importing tokens:', error);
figma.notify('Error importing tokens', { error: true });
}
}
async function processTokenGroup(prefix: string, group: TokenSet) {
for (const [key, value] of Object.entries(group)) {
const fullKey = `${prefix}/${key}`;
if ('$type' in value && '$value' in value) {
await processToken(fullKey, value as DesignToken);
} else {
await processTokenGroup(fullKey, value as TokenSet);
}
}
}
async function processToken(name: string, token: DesignToken) {
if (token.$type === 'color') {
const style = figma.createPaintStyle();
style.name = name;
const color = hexToRgb(token.$value as string);
if (color) {
style.paints = [
{
type: 'SOLID',
color: {
r: color.r / 255,
g: color.g / 255,
b: color.b / 255,
},
},
];
}
}
}
async function applyToken(token: FlattenedToken) {
if (!figma.currentPage.selection.length) {
figma.notify('Please select at least one layer');
return;
}
try {
if (token.type === 'color') {
const color = hexToRgb(token.value as string);
if (!color) return;
for (const node of figma.currentPage.selection) {
if ('fills' in node) {
node.fills = [
{
type: 'SOLID',
color: {
r: color.r / 255,
g: color.g / 255,
b: color.b / 255,
},
},
];
}
}
}
figma.notify(
`Applied ${token.path.join('.')} to ${figma.currentPage.selection.length} layers`
);
} catch (error) {
console.error('Error applying token:', error);
figma.notify('Error applying token', { error: true });
}
}
function hexToRgb(hex: string) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: null;
}