-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathcode.ts
64 lines (58 loc) · 1.73 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
// This plugin fetches a list of countries from an external API and shows the capital of the selected country
interface Country {
name: string;
data: {
index: number;
name: string;
capital: string;
};
}
let resolveCountries = (countries: Country[]) => {};
const countriesPromise = new Promise<Country[]>((resolve) => {
resolveCountries = resolve;
});
// Create an invisible iframe UI to use network API's
figma.showUI(
`<script>
(async (event) => {
const res = await fetch("https://api.sampleapis.com/countries/countries");
const json = await res.json();
window.parent.postMessage({ pluginMessage: json }, "*");
})();
</script>`,
{ visible: false }
);
// Resolve the countries promise when a message is received from the iframe
figma.ui.onmessage = (json) => {
resolveCountries(
json.map((country, index) => {
return {
name: country.name,
data: {
index: index,
name: country.name,
capital: country.capital,
},
};
})
);
};
figma.parameters.on(
'input',
async ({ key, query, result }: ParameterInputEvent) => {
// When fetching data from an external source, it is recommended to show a relevant loading message
result.setLoadingMessage('Loading countries...');
const countries = await countriesPromise;
result.setSuggestions(
// Filter suggestions based on the query entered
countries.filter((country) =>
country.name.toLowerCase().includes(query.toLowerCase())
)
);
}
);
figma.on('run', ({ parameters }: RunEvent) => {
const countryName = parameters.country.name;
const capital = parameters.country.capital;
figma.closePlugin(`The capital of ${countryName} is ${capital}`);
});