Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: add types to name-default-components.ts #21291

37 changes: 21 additions & 16 deletions packages/next-codemod/transforms/name-default-component.ts
@@ -1,39 +1,44 @@
import { basename, extname } from 'path'

const camelCase = (value) => {
const camelCase = (value: string): string => {
const val = value.replace(/[-_\s.]+(.)?/g, (_match, chr) =>
chr ? chr.toUpperCase() : ''
)
return val.substr(0, 1).toUpperCase() + val.substr(1)
}

const isValidIdentifier = (value) => /^[a-zA-ZÀ-ÿ][0-9a-zA-ZÀ-ÿ]+$/.test(value)
const isValidIdentifier = (value: string): boolean =>
/^[a-zA-ZÀ-ÿ][0-9a-zA-ZÀ-ÿ]+$/.test(value)

type Node = {
type: string
declaration: {
type: string
body: any
timneutkens marked this conversation as resolved.
Show resolved Hide resolved
id?: any
}
}

export default function transformer(file, api, options) {
const j = api.jscodeshift
const root = j(file.source)

let hasModifications
let hasModifications: boolean

const returnsJSX = (node) =>
const returnsJSX = (node): boolean =>
node.type === 'JSXElement' ||
(node.type === 'BlockStatement' &&
j(node)
.find(j.ReturnStatement)
.some(
(path) =>
path.value.argument && path.value.argument.type === 'JSXElement'
))
.some((path) => path.value.argument?.type === 'JSXElement'))

const hasRootAsParent = (path) => {
const hasRootAsParent = (path): boolean => {
const program = path.parentPath.parentPath.parentPath.parentPath.parentPath
return (
!program || (program && program.value && program.value.type === 'Program')
)
return !program || program?.value?.type === 'Program'
}

const nameFunctionComponent = (path) => {
const node = path.value
const nameFunctionComponent = (path): void => {
const node: Node = path.value

if (!node.declaration) {
return
Expand All @@ -49,8 +54,8 @@ export default function transformer(file, api, options) {
return
}

const fileName = basename(file.path, extname(file.path))
let name = camelCase(fileName)
const fileName: string = basename(file.path, extname(file.path))
timneutkens marked this conversation as resolved.
Show resolved Hide resolved
let name: string = camelCase(fileName)
timneutkens marked this conversation as resolved.
Show resolved Hide resolved

// If the generated name looks off, don't add a name
if (!isValidIdentifier(name)) {
Expand Down