Handle styled-jsx in newLinkBehavior codemod (#36628)

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
Tim Neutkens 2022-05-02 19:07:14 +02:00 committed by GitHub
parent 9e53af8e30
commit 20e5fed1cf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 70 additions and 1 deletions

View file

@ -0,0 +1,26 @@
import Link from 'next/link';
const CustomLink = ({
href,
title,
children,
}) => {
return (
<span className="link-container">
<Link href={href}>
<a className="link" title={title}>
{children}
</a>
</Link>
<style jsx>{`
.link {
text-decoration: none;
color: var(--geist-foreground);
font-weight: 500;
}
`}</style>
</span>
);
};
export default CustomLink;

View file

@ -0,0 +1,26 @@
import Link from 'next/link';
const CustomLink = ({
href,
title,
children,
}) => {
return (
<span className="link-container">
<Link href={href} legacyBehavior>
<a className="link" title={title}>
{children}
</a>
</Link>
<style jsx>{`
.link {
text-decoration: none;
color: var(--geist-foreground);
font-weight: 500;
}
`}</style>
</span>
);
};
export default CustomLink;

View file

@ -9,7 +9,8 @@ const fixtures = [
'excludes-links-with-legacybehavior-prop',
'children-interpolation',
'spread-props',
'link-string'
'link-string',
'styled-jsx',
]
for (const fixture of fixtures) {

View file

@ -22,6 +22,13 @@ export default function transformer(file: FileInfo, api: API) {
}
const linkElements = $j.findJSXElements(variableName)
const hasStylesJSX = $j.findJSXElements('style').some((stylePath) => {
const $style = j(stylePath)
const hasJSXProp =
$style.find(j.JSXAttribute, { name: { name: 'jsx' } }).size() !== 0
return hasJSXProp
})
linkElements.forEach((linkPath) => {
const $link = j(linkPath).filter((childPath) => {
@ -37,6 +44,15 @@ export default function transformer(file: FileInfo, api: API) {
return
}
// If file has <style jsx> enable legacyBehavior
// and keep <a> to stay on the safe side
if (hasStylesJSX) {
$link
.get('attributes')
.push(j.jsxAttribute(j.jsxIdentifier('legacyBehavior')))
return
}
const linkChildrenNodes = $link.get('children')
// Text-only link children are already correct with the new behavior