-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcode.ts
404 lines (351 loc) · 13.2 KB
/
code.ts
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// This plugin organises the selected component set into a tidy grid.
// The 'input' event listens for text change in the Quick Actions box after a plugin is 'Tabbed' into.
figma.parameters.on(
"input",
({ key, query, parameters, result }: ParameterInputEvent) => {
let suggestions
switch (key) {
case "row":
case "column":
case "hGroup":
const selection = getFilteredSelection()
if (selection.length !== 1) {
result.setError("⚠️ Select a single component set first")
return
}
const componentSet = selection[0] as ComponentSetNode
let variantGroupProperties
try {
variantGroupProperties = componentSet.variantGroupProperties
} catch (error) {
result.setError(
"⚠️ Resolve conflicting variants in order to continue"
)
return
}
const propNames = Object.keys(variantGroupProperties)
if (propNames.length < 2) {
result.setError(
"⚠️ The component must have more than one property"
)
return
}
suggestions = propNames.filter(
(item) =>
item.toLowerCase().includes(query.toLowerCase()) &&
item !== parameters["column"] &&
item !== parameters["row"]
)
break
case "spacing_subGrid":
case "spacing_groups":
const defaults =
key === "spacing_subGrid"
? ["8", "16", "24", "32", "40"]
: ["96", "192", "288", "384", "480"]
// Check the input is valid
const number = Number(query)
if (!Number.isInteger(number) || number < 0) {
result.setError("⚠️ Try entering a positive number")
return
}
suggestions = (
query === "" || defaults.includes(query)
? defaults
: [query, ...defaults]
) // default values plus the typed value
.filter((s) => s.includes(query)) // just values matching the typed value
.map((value) => ({ name: value, data: Number(value) })) // include the numerical value with the suggestions
break
default:
return
}
result.setSuggestions(suggestions)
}
)
// When the user presses Enter after inputting all parameters, the 'run' event is fired.
figma.on("run", async ({ command, parameters }: RunEvent) => {
let closeMessage
if (command === "organise") {
await loadFonts()
const spacing = await getSpacing()
const errorMessage = organise(parameters, spacing)
if (errorMessage) {
figma.notify(errorMessage)
} else {
closeMessage = "Done"
}
} else {
await figma.clientStorage.setAsync("spacing", {
subGrid: parameters["spacing_subGrid"],
groups: parameters["spacing_groups"],
})
closeMessage = "Preferences updated"
}
figma.closePlugin(closeMessage)
})
function organise(parameters: ParameterValues, spacing): string {
const selection = getFilteredSelection()
if (selection.length !== 1) return "⚠️ Select a single component set first"
// Get variants and variant properties from selected Component Set
const componentSet = selection[0] as ComponentSetNode
const variants = componentSet.children
let variantGroupProperties
try {
variantGroupProperties = componentSet.variantGroupProperties
} catch (error) {
return "⚠️ Resolve conflicting variants in order to continue"
}
const variantKeys = Object.keys(variantGroupProperties)
// Check parameters match component properties
if (parameters) {
const match = Object.values(parameters).every((value) =>
variantKeys.includes(value)
)
if (!match) {
return "⚠️ Chosen properties don't match component properties"
}
}
const {
row = variantKeys[0],
column = variantKeys[1],
hGroup = !parameters && variantKeys[2],
} = parameters || {}
// Determine columns and rows in both sub-grid and horizontal groups
const rowPropValues_subGrid = variantGroupProperties[row].values
const columnPropValues_subGrid =
column && variantGroupProperties[column].values
const columnPropValues_group =
hGroup && variantGroupProperties[hGroup].values
// Calculate grid sizing based on largest variant sizes (rounded up to sit on 8px grid)
const maxWidth =
Math.ceil(Math.max(...variants.map((element) => element.width)) / 8) * 8
const maxHeight =
Math.ceil(Math.max(...variants.map((element) => element.height)) / 8) *
8
const dx_subGrid = maxWidth + spacing.subGrid
const dy_subGrid = maxHeight + spacing.subGrid
const dx_group =
dx_subGrid * (columnPropValues_subGrid?.length ?? 1) -
spacing.subGrid +
spacing.groups
const dy_group =
dy_subGrid * (rowPropValues_subGrid?.length ?? 1) -
spacing.subGrid +
spacing.groups
// Seperate out properties used for vertical grouping
function getGroupProps(variant: ComponentNode) {
const props = variant.variantProperties
const { [column]: columnProp, [row]: rowProp, ...groupProps } = props
if (hGroup) {
delete groupProps[hGroup]
}
return groupProps
}
const groupPropsOfEveryVariant = variants.map((variant: ComponentNode) =>
getGroupProps(variant)
)
// Calculate group numbers and sort according to order of props and values in Component Set
function getPropIdentifier([key, value]) {
const keyIndex = getPaddedIndex(
key,
Object.keys(variantGroupProperties)
)
const valueIndex = getPaddedIndex(
value,
variantGroupProperties[key].values
)
return `${keyIndex}${valueIndex}`
}
function getObjectIdentifier(json) {
const obj = JSON.parse(json)
return Object.entries(obj)
.map((prop) => getPropIdentifier(prop))
.sort()
.toString()
}
const uniqueGroups = [
...new Map(
groupPropsOfEveryVariant.map((obj) => [JSON.stringify(obj), obj])
).keys(),
].sort((a, b) => {
const idA = getObjectIdentifier(a)
const idB = getObjectIdentifier(b)
if (idA < idB) {
return -1
}
if (idA > idB) {
return 1
}
// identifiers must be equal
return 0
})
// Layout variants in grid
componentSet.layoutMode = "NONE"
variants.forEach((variant: ComponentNode) => {
const props = variant.variantProperties
const rowIndex_subGrid = rowPropValues_subGrid.indexOf(props[row])
const columnIndex_subGrid = column
? columnPropValues_subGrid.indexOf(props[column])
: 0
const columnIndex_group = hGroup
? columnPropValues_group.indexOf(props[hGroup])
: 0
const rowIndex_group = uniqueGroups.indexOf(
JSON.stringify(getGroupProps(variant))
)
variant.x =
columnIndex_subGrid * dx_subGrid +
columnIndex_group * dx_group +
spacing.subGrid
variant.y =
rowIndex_subGrid * dy_subGrid +
rowIndex_group * dy_group +
spacing.subGrid
})
// Resize Component Set
const bottomRigthX = Math.max(
...variants.map((child) => child.x + child.width)
)
const bottomRigthY = Math.max(
...variants.map((child) => child.y + child.height)
)
componentSet.resizeWithoutConstraints(
bottomRigthX + spacing.subGrid,
bottomRigthY + spacing.subGrid
)
// Create frame to contain labels and match its size & position to component set
const componentSetIndex = componentSet.parent.children.indexOf(componentSet)
const labelsParentFrame = figma.createFrame()
componentSet.parent.insertChild(componentSetIndex, labelsParentFrame)
labelsParentFrame.x = componentSet.x
labelsParentFrame.y = componentSet.y
labelsParentFrame.resize(componentSet.width, componentSet.height)
labelsParentFrame.fills = []
labelsParentFrame.name = `${componentSet.name} - property labels`
labelsParentFrame.expanded = false
labelsParentFrame.clipsContent = false
// Add labels
const labels_rowGroups = []
const labels_subGridRows = []
// Get list of boolean properties
const booleanPropNames = Object.entries(variantGroupProperties)
.filter((arr) => {
const values = arr[1]["values"]
.map((value) => value.toLowerCase())
.sort()
if (values.length !== 2) return false
return (
(values[0] === "off" && values[1] === "on") ||
(values[0] === "no" && values[1] === "yes") ||
(values[0] === "false" && values[1] === "true")
)
})
.map((arr) => arr[0])
// Include property names with boolean values to make labels clearer
function getLabelText(key, value) {
return booleanPropNames.includes(key) ? `${key}=${value}` : value
}
function createSubGridColumnLabels(groupIndex) {
columnPropValues_subGrid.forEach((value, i) => {
const label = createText(getLabelText(column, value))
labelsParentFrame.appendChild(label)
label.x = dx_subGrid * i + dx_group * groupIndex + spacing.subGrid
label.y = -spacing.subGrid - label.height
})
}
function createSubGridRowLabels(groupIndex) {
rowPropValues_subGrid.forEach((value, i) => {
const label = createText(getLabelText(row, value))
labelsParentFrame.appendChild(label)
labels_subGridRows.push(label)
label.y = dy_subGrid * i + dy_group * groupIndex + spacing.subGrid
})
}
// Generate column labels
if (columnPropValues_group) {
columnPropValues_group.forEach((value, i) => {
const label = createText(getLabelText(hGroup, value), 20, "Bold")
labelsParentFrame.appendChild(label)
label.x = dx_group * i + spacing.subGrid
label.y = -spacing.groups - spacing.subGrid - label.height - 24 // allow 24 for height of sub-grid labels
createSubGridColumnLabels(i)
})
} else if (column) {
createSubGridColumnLabels(0)
}
// Generate row labels
if (uniqueGroups.length > 1) {
uniqueGroups.forEach((json, i) => {
const labelText = Object.entries(JSON.parse(json))
.map(([key, value]) => getLabelText(key, value))
.join(", ")
const label = createText(labelText, 20, "Bold")
labelsParentFrame.appendChild(label)
label.y = dy_group * i + spacing.subGrid
labels_rowGroups.push(label)
createSubGridRowLabels(i)
})
} else {
createSubGridRowLabels(0)
}
// Calculate offsets for row labels
const labelMaxWidth_rowGroups = Math.max(
...labels_rowGroups.map((element) => element.width)
)
const labelMaxWidth_subGridRows = Math.max(
...labels_subGridRows.map((element) => element.width)
)
// Offset row labels to left of component set
labels_rowGroups.forEach((label) => {
label.x =
label.x -
labelMaxWidth_rowGroups -
labelMaxWidth_subGridRows -
spacing.subGrid -
spacing.groups
})
labels_subGridRows.forEach((label) => {
label.x = label.x - labelMaxWidth_subGridRows - spacing.subGrid
})
}
function getFilteredSelection() {
return figma.currentPage.selection.filter(
(node) => node.type === "COMPONENT_SET"
)
}
function zeroPaddedNumber(num, max) {
const countLength = max.toString().length
return num.toString().padStart(countLength, "0")
}
function getPaddedIndex(item, arr) {
return zeroPaddedNumber(arr.indexOf(item), arr.length)
}
async function loadFonts() {
await Promise.all([
figma.loadFontAsync({ family: "Space Mono", style: "Regular" }),
figma.loadFontAsync({ family: "Space Mono", style: "Bold" }),
])
}
function createText(
characters: string,
size: number = 16,
style: string = "Regular"
) {
const text = figma.createText()
text.fontName = { family: "Space Mono", style: style }
text.characters = characters
text.fontSize = size
text.fills = [
{
type: "SOLID",
color: { r: 123 / 255, g: 97 / 255, b: 255 / 255 },
},
]
return text
}
async function getSpacing() {
const spacing = await figma.clientStorage.getAsync("spacing")
if (spacing === undefined) return { subGrid: 24, groups: 96 }
return spacing
}