forked from six7/style-swap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.ts
151 lines (128 loc) · 4.53 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
figma.showUI(__html__, { visible: false, width: 600, height: 400 });
figma.skipInvisibleInstanceChildren = true;
// declarations
let uniqueStyleIds = [];
const allTextNodes = figma.root.findAllWithCriteria({
types: ["TEXT"],
});
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
async function getStyleIdsWithName() {
const uniqueStyleIds = [];
for (var i = 0; i < allTextNodes.length; i++) {
// sleep every 500 items to avoid figma freezing
if (i % 500 === 0) {
await sleep(1);
}
// iterate over segments, if segment has a styleId, add it to the list of ids
if (typeof allTextNodes[i].textStyleId === "symbol") {
allTextNodes[i].getStyledTextSegments(["textStyleId"]).forEach((segment) => {
if (!uniqueStyleIds.includes(segment.textStyleId)) {
uniqueStyleIds.push(segment.textStyleId);
}
});
}
// if string, add to list of ids
if (typeof allTextNodes[i].textStyleId === "string" && !uniqueStyleIds.includes(allTextNodes[i].textStyleId)) {
uniqueStyleIds.push(allTextNodes[i].textStyleId);
}
}
return uniqueStyleIds
.map((styleId) => {
const style = figma.getStyleById(styleId);
return style
? {
name: style.name.toLowerCase(),
data: styleId,
}
: null;
})
.filter((n) => n);
}
// check if node contains old style and transform to new style
async function convertOldToNewStyle(parameters: ParameterValues) {
let numberOfNodesUpdated = 0;
allTextNodes.forEach((node) => {
if (typeof node.textStyleId === "symbol") {
node.getStyledTextSegments(["textStyleId"]).forEach((segment) => {
const isSegmentStyleExist = parameters.hasOwnProperty(segment.textStyleId);
if (isSegmentStyleExist) {
numberOfNodesUpdated += 1;
node.setRangeTextStyleId(segment.start, segment.end, parameters[segment.textStyleId]);
}
});
} else if (parameters.hasOwnProperty(node.textStyleId)) {
numberOfNodesUpdated += 1;
node.textStyleId = parameters[node.textStyleId];
}
});
return numberOfNodesUpdated;
}
async function startPluginWithParameters(parameters: ParameterValues) {
const numberOfNodesUpdated = await convertOldToNewStyle(parameters);
figma.notify(`Styles swap done successfully and No. of nodes changed are ${numberOfNodesUpdated}`);
figma.closePlugin();
}
figma.on("run", async ({ command, parameters }: RunEvent) => {
if (parameters) {
const mappedParameters = {};
mappedParameters[parameters["old-style"]] = parameters["new-style"];
await startPluginWithParameters(mappedParameters);
}
});
async function runPlugin() {
const ids = (uniqueStyleIds = await getStyleIdsWithName());
figma.parameters.on("input", async ({ parameters, key, query, result }: ParameterInputEvent) => {
switch (key) {
case "old-style":
result.setSuggestions(ids.filter((s) => s.name.includes(query.toLowerCase())));
break;
case "new-style":
result.setSuggestions(ids.filter((s) => s.name.includes(query.toLowerCase())));
break;
default:
return;
}
});
}
figma.ui.onmessage = (msg) => {
if (msg.type === "check-and-update") {
if (IsJsonString(msg.json)) {
const inputObject: ParameterValues = JSON.parse(msg.json);
const mappedObject = {};
const mappedUniqueStyleIds: ParameterValues = {};
uniqueStyleIds.forEach((id: any) => {
mappedUniqueStyleIds[id.name] = id.data;
});
for (const name in inputObject) {
const oldStyleId = mappedUniqueStyleIds[name];
const newStyleId = mappedUniqueStyleIds[inputObject[name]];
// check if the styles exist or not, if not notify the user
if (oldStyleId && newStyleId) {
mappedObject[oldStyleId] = newStyleId;
}
}
startPluginWithParameters(mappedObject);
} else {
notifyUserAndClosePlugin();
}
}
// Make sure to close the plugin when you're done. Otherwise the plugin will
// keep running, which shows the cancel button at the bottom of the screen.
figma.closePlugin();
};
// <-- helper functions -->
// notify the user about the invalid parameters he/she entered and close the plugin
function notifyUserAndClosePlugin() {
figma.notify("One of the parameters was not correctly specified. Please try again.");
figma.closePlugin();
}
// To validate the input whether its a valid JSON are not
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
runPlugin();