forked from aaroniker/figma-remove-bg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.ts
85 lines (73 loc) · 2.22 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
if(figma.command == 'removebgfunc') {
async function checkFill(fill, apiKey) {
if(fill.type === 'IMAGE') {
const image = figma.getImageByHash(fill.imageHash)
const bytes = await image.getBytesAsync()
figma.showUI(__html__, { visible: false })
figma.ui.postMessage({
type: 'run',
bytes: bytes,
apikey: apiKey
})
const array: Uint8Array = await new Promise((resolve, reject) => {
figma.ui.onmessage = response => {
if(typeof response.errors !== 'undefined') {
figma.closePlugin(response.errors[0].title)
} else {
resolve(response as Uint8Array)
}
}
})
const newImageFill = JSON.parse(JSON.stringify(fill))
newImageFill.imageHash = figma.createImage(array).hash
return {
fill: newImageFill,
updated: true
}
}
return {
fill: fill,
updated: false
}
}
async function removeBG(node, apiKey) {
let types = ['RECTANGLE', 'ELLIPSE', 'POLYGON', 'STAR', 'VECTOR', 'TEXT']
if(types.indexOf(node.type) > -1) {
let newFills = [],
updated = false,
check
for(const fill of node.fills) {
check = await checkFill(fill, apiKey)
updated = check.updated || updated
newFills.push(check.fill)
}
node.fills = newFills
figma.closePlugin(updated ? 'Image background removed.' : 'Nothing changed.')
} else {
figma.closePlugin('Select a node with image fill.')
}
}
if(figma.currentPage.selection.length !== 1) {
figma.closePlugin('Select a single node.')
}
figma.clientStorage.getAsync('removeBgApiKey').then(apiKey => {
if(apiKey) {
removeBG(figma.currentPage.selection[0], apiKey)
} else {
figma.closePlugin('Set API Key first.')
}
})
} else if(figma.command == 'removebgkey') {
figma.clientStorage.getAsync('removeBgApiKey').then(apiKey => {
figma.showUI(__html__, { visible: true })
figma.ui.postMessage({
type: 'key',
apikey: apiKey
})
figma.ui.onmessage = response => {
figma.clientStorage.setAsync('removeBgApiKey', response).then(() => {
figma.closePlugin('API Key set.')
})
}
})
}