-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.ts
More file actions
191 lines (163 loc) · 7.1 KB
/
Copy pathcode.ts
File metadata and controls
191 lines (163 loc) · 7.1 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
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
// Показываем UI плагина с фиксированными размерами окна
figma.showUI(__html__, { width: 300, height: 300 });
// Функция для преобразования цвета из формата Figma (r,g,b 0-1) в CSS rgba()
function rgba(color: { r: number; g: number; b: number; a?: number }): string {
const r = Math.round(color.r * 255);
const g = Math.round(color.g * 255);
const b = Math.round(color.b * 255);
const a = color.a !== undefined ? color.a : 1;
if (a === 1) return `rgb(${r}, ${g}, ${b})`;
return `rgba(${r}, ${g}, ${b}, ${a})`; // возвращаем CSS-строку
}
function getBorderRadius(node: FrameNode): string | null {
const { topLeftRadius, topRightRadius, bottomRightRadius, bottomLeftRadius } =
node;
if (
topLeftRadius === 0 &&
topRightRadius === 0 &&
bottomRightRadius === 0 &&
bottomLeftRadius === 0
)
return null;
// Все одинаковые → одно значение
if (
topLeftRadius === topRightRadius &&
topLeftRadius === bottomRightRadius &&
topLeftRadius === bottomLeftRadius
) {
return `${Math.round(topLeftRadius)}px`;
}
// Две и две одинаковые (верхние и нижние)
if (
topLeftRadius === bottomRightRadius &&
topRightRadius === bottomLeftRadius
) {
return `${Math.round(topLeftRadius)}px ${Math.round(topRightRadius)}px`;
}
// Три угла одинаковые, а один отличается
if (topLeftRadius === topRightRadius && topLeftRadius === bottomLeftRadius) {
return `${Math.round(topLeftRadius)}px ${Math.round(bottomRightRadius)}px`;
}
// Два соседних одинаковые, два других тоже одинаковые
if (
topLeftRadius === bottomLeftRadius &&
topRightRadius === bottomRightRadius
) {
return `${Math.round(topLeftRadius)}px ${Math.round(topRightRadius)}px ${Math.round(bottomRightRadius)}px`;
}
// По умолчанию — все 4 значения
return `${Math.round(topLeftRadius)}px ${Math.round(topRightRadius)}px ${Math.round(bottomRightRadius)}px ${Math.round(bottomLeftRadius)}px`;
}
function getPadding(node: FrameNode): string | null {
const { paddingTop, paddingRight, paddingBottom, paddingLeft } = node;
// Всё ноль → null
if (
paddingTop === 0 &&
paddingRight === 0 &&
paddingBottom === 0 &&
paddingLeft === 0
)
return null;
// 1 значение
if (
paddingTop === paddingRight &&
paddingTop === paddingBottom &&
paddingTop === paddingLeft
)
return `${Math.round(paddingTop)}px`;
// 2 значения: vertical | horizontal
if (paddingTop === paddingBottom && paddingRight === paddingLeft)
return `${Math.round(paddingTop)}px ${Math.round(paddingRight)}px`;
// 3 значения: top | horizontal | bottom
if (paddingRight === paddingLeft)
return `${Math.round(paddingTop)}px ${Math.round(paddingRight)}px ${Math.round(paddingBottom)}px`;
// 4 значения: top right bottom left
return `${Math.round(paddingTop)}px ${Math.round(paddingRight)}px ${Math.round(paddingBottom)}px ${Math.round(paddingLeft)}px`;
}
// Основная функция для отправки информации о выделенном элементе в UI
function sendSelectionInfo() {
const selection = figma.currentPage.selection; // получаем выделенные элементы на текущей странице
// Сразу отправляем сигнал на UI, что нужно подстроить размер окна (пока просто триггер)
figma.ui.postMessage({ type: "resize" });
// Если ничего не выделено, отправляем ошибку в UI
if (selection.length === 0) {
figma.ui.postMessage({
type: "error",
message: "Выделите элемент на канвасе",
});
} else {
const node = selection[0]; // берём первый выделенный элемент
let info;
// Если это текстовый элемент, собираем его ключевые CSS-подобные свойства
if (node.type === "TEXT") {
info = {
type: node.type,
text: node.name.slice(0, 20) + "...",
data: {
// Шрифт: проверяем, что fontName — объект с полем family
fontFamily:
node.fontName && typeof node.fontName === "object" && node.fontName
? `"${node.fontName.family}", sans-serif`
: "sans-serif",
// Размер шрифта в px
fontSize: `clamp(${Math.round((node.fontSize as number) * 0.8)}px, ${
Math.round(node.fontSize as number) / 16
}vw, ${Math.round(node.fontSize as number)}px)`,
fontWeight: node.fontWeight,
textAlign: node.textAlignHorizontal.toLocaleLowerCase(),
letterSpacing:
typeof node.letterSpacing === "object" &&
node.letterSpacing.unit === "PERCENT"
? `${node.letterSpacing.value}%`
: 0,
// Цвет текста: проверяем, что fills массив и первый элемент имеет color
color: Array.isArray(node.fills) && rgba(node.fills[0].color),
lineHeight:
typeof node.lineHeight === "object" &&
"value" in node.lineHeight &&
Math.round(node.lineHeight.value) + "%",
// Прозрачность текста: берём поле opacity, если есть
opacity:
Array.isArray(node.fills) && node.fills[0].opacity !== 1
? node.fills[0].opacity
: null,
},
};
} else if (node.type === "FRAME") {
info = {
type: node.type,
data: {
backgroundColor:
Array.isArray(node.fills) && node.fills.length > 0 && node.fills[0]
? rgba(node.fills[0].color)
: null,
with: Math.round(node.width) + "px",
height: Math.round(node.height) + "px",
borderRadius: getBorderRadius(node),
padding: getPadding(node),
borderWidth: Math.round(node.strokeWeight as number) + "px",
borderStyle:
Array.isArray(node.strokes) &&
node.strokes.length > 0 &&
node.strokes[0].type
? node.strokes[0].type.toLowerCase()
: null,
borderColor:
Array.isArray(node.strokes) &&
node.strokes.length > 0 &&
"color" in node.strokes[0]
? rgba(node.strokes[0].color)
: null,
},
};
}
// Отправляем собранную информацию в UI
figma.ui.postMessage({ type: "value", value: info });
}
}
// Изначальный вызов функции при загрузке плагина
sendSelectionInfo();
// Событие: когда пользователь меняет выделение, отправляем новую информацию
figma.on("selectionchange", () => {
sendSelectionInfo();
});