-
Notifications
You must be signed in to change notification settings - Fork 28k
/
Copy pathmetadata-to-viewport-export.ts
85 lines (73 loc) · 2.09 KB
/
metadata-to-viewport-export.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
import type { API, FileInfo } from 'jscodeshift'
export default function transformer(file: FileInfo, api: API) {
const j = api.jscodeshift
const root = j(file.source)
// Find the metadata export
const metadataExport = root.find(j.ExportNamedDeclaration, {
declaration: {
type: 'VariableDeclaration',
declarations: [
{
id: { name: 'metadata' },
},
],
},
})
if (metadataExport.size() !== 1) {
return
}
const metadataObject = metadataExport.find(j.ObjectExpression).get(0).node
if (!metadataObject) {
console.error('Could not find metadata object')
return
}
let metadataProperties = metadataObject.properties
let viewportProperties
const viewport = metadataProperties.find(
(prop) => prop.key.name === 'viewport'
)
if (viewport) {
viewportProperties = viewport.value.properties
metadataProperties = metadataProperties.filter(
(prop) => prop.key.name !== 'viewport'
)
} else {
viewportProperties = []
}
const colorScheme = metadataProperties.find(
(prop) => prop.key.name === 'colorScheme'
)
if (colorScheme) {
viewportProperties.push(colorScheme)
metadataProperties = metadataProperties.filter(
(prop) => prop.key.name !== 'colorScheme'
)
}
const themeColor = metadataProperties.find(
(prop) => prop.key.name === 'themeColor'
)
if (themeColor) {
viewportProperties.push(themeColor)
metadataProperties = metadataProperties.filter(
(prop) => prop.key.name !== 'themeColor'
)
}
// Update the metadata export
metadataExport
.find(j.ObjectExpression)
.replaceWith(j.objectExpression(metadataProperties))
// Create the new viewport object
const viewportExport = j.exportNamedDeclaration(
j.variableDeclaration('const', [
j.variableDeclarator(
j.identifier('viewport'),
j.objectExpression(viewportProperties)
),
])
)
// Append the viewport export to the body of the program
if (viewportProperties.length) {
root.get().node.program.body.push(viewportExport)
}
return root.toSource()
}