Skip to content

Commit

Permalink
Handle styled-jsx in newLinkBehavior codemod (#36628)
Browse files Browse the repository at this point in the history
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
timneutkens and kodiakhq[bot] authored May 2, 2022
1 parent 9e53af8 commit 20e5fed
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
@@ -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;
3 changes: 2 additions & 1 deletion packages/next-codemod/transforms/__tests__/new-link.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
16 changes: 16 additions & 0 deletions packages/next-codemod/transforms/new-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -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
Expand Down

0 comments on commit 20e5fed

Please sign in to comment.