-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathbabel-iconify.js
96 lines (79 loc) · 2.6 KB
/
babel-iconify.js
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
const { locate } = require('@iconify/json')
const { stringToIcon, getIconData } = require('@iconify/utils')
module.exports = function (babel, options) {
const { types: t } = babel
return {
name: 'react-native-iconify',
visitor: {
JSXElement(path) {
const { openingElement } = path.node
const tagName = openingElement.name.name
const isIcon = tagName === 'Iconify'
if (!isIcon) {
return
}
const iconProp = openingElement.attributes.find(
node => t.isJSXAttribute(node) && node.name.name === 'icon',
)
const iconValue
= iconProp?.value?.value
|| iconProp?.value?.expression?.value
|| iconProp?.value?.expression?.extra?.rawValue
if (!iconValue) {
throw new Error('Iconify: \'icon\' prop must be a string literal')
}
const icon = stringToIcon(iconValue)
let iconAsJson
if (options?.collections && options.collections[icon.prefix]) {
iconAsJson = options.collections[icon.prefix]
}
else {
const filename = locate(icon.prefix)
try {
iconAsJson = require(filename)
}
catch {
throw new Error(`Iconify: Could not find icon set "${icon.prefix}"`)
}
}
const iconData = getIconData(iconAsJson, icon.name)
if (!iconData) {
throw new Error(
`Iconify: Icon not found!\nCould not find icon ${iconValue}\n\nCheck all icons at\nhttps://iconify.design/icon-sets/`,
)
}
const iconDataExpression = [
t.objectProperty(
t.stringLiteral('body'),
t.stringLiteral(iconData.body),
),
]
if (iconData.width) {
iconDataExpression.push(
t.objectProperty(
t.stringLiteral('width'),
t.numericLiteral(iconData.width),
),
)
}
if (iconData.height) {
iconDataExpression.push(
t.objectProperty(
t.stringLiteral('height'),
t.numericLiteral(iconData.height),
),
)
}
const iconDataProp = t.jSXAttribute(
t.jSXIdentifier('iconData'),
t.jSXExpressionContainer(t.objectExpression(iconDataExpression)),
)
const isPluginInstalledProp = t.jSXAttribute(
t.jSXIdentifier('isPluginInstalled'),
t.jSXExpressionContainer(t.booleanLiteral(true)),
)
openingElement.attributes.push(iconDataProp, isPluginInstalledProp)
},
},
}
}