File size: 2,206 Bytes
1e92f2d |
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 |
import type { API, FileInfo } from 'jscodeshift'
import { createParserFromPath } from '../lib/parser'
export default function transformer(file: FileInfo, _api: API) {
const j = createParserFromPath(file.path)
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()
}
|