Unverified Commit 7d3bfac3 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add stitches and material-ui tests for new link behavior + fix TypeScript types…

Add stitches and material-ui tests for new link behavior + fix TypeScript types when imported (#36474)

Adds additional tests for material-ui and stitches based on questions in the Twitter thread.

Fixes TypeScript types when `LinkProps` is imported and used in combination with `<button>`, added a TODO to change this at a later point when the new behavior is the default instead of opt-in.



## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
parent 26efcc5d
...@@ -30,18 +30,21 @@ type InternalLinkProps = { ...@@ -30,18 +30,21 @@ type InternalLinkProps = {
prefetch?: boolean prefetch?: boolean
locale?: string | false locale?: string | false
legacyBehavior?: boolean legacyBehavior?: boolean
// e: any because as it would otherwise overlap with existing types
/** /**
* requires experimental.newNextLinkBehavior * requires experimental.newNextLinkBehavior
*/ */
onMouseEnter?: (e: React.MouseEvent) => void onMouseEnter?: (e: any) => void
// e: any because as it would otherwise overlap with existing types
/** /**
* requires experimental.newNextLinkBehavior * requires experimental.newNextLinkBehavior
*/ */
onClick?: (e: React.MouseEvent) => void onClick?: (e: any) => void
} }
export type LinkProps = InternalLinkProps & // TODO: Include the full set of Anchor props
React.AnchorHTMLAttributes<HTMLAnchorElement> // adding this to the publicly exported type currently breaks existing apps
export type LinkProps = InternalLinkProps
type LinkPropsRequired = RequiredKeys<LinkProps> type LinkPropsRequired = RequiredKeys<LinkProps>
type LinkPropsOptional = OptionalKeys<InternalLinkProps> type LinkPropsOptional = OptionalKeys<InternalLinkProps>
...@@ -116,7 +119,12 @@ function linkClicked( ...@@ -116,7 +119,12 @@ function linkClicked(
}) })
} }
function Link(props: React.PropsWithChildren<LinkProps>) { function Link(
props: React.PropsWithChildren<
Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, keyof LinkProps> &
LinkProps
>
) {
const { const {
legacyBehavior = Boolean(process.env.__NEXT_NEW_LINK_BEHAVIOR) !== true, legacyBehavior = Boolean(process.env.__NEXT_NEW_LINK_BEHAVIOR) !== true,
} = props } = props
......
...@@ -18,7 +18,7 @@ async function matchLogs(browser, includes: string) { ...@@ -18,7 +18,7 @@ async function matchLogs(browser, includes: string) {
return found return found
} }
const appDir = path.join(__dirname, './app') const appDir = path.join(__dirname, 'app')
describe('New Link Behavior', () => { describe('New Link Behavior', () => {
let next: NextInstance let next: NextInstance
......
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import webdriver from 'next-webdriver'
import path from 'path'
const appDir = path.join(__dirname, 'material-ui')
describe('New Link Behavior with material-ui', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
pages: new FileRef(path.join(appDir, 'pages')),
src: new FileRef(path.join(appDir, 'src')),
'next.config.js': new FileRef(path.join(appDir, 'next.config.js')),
},
dependencies: {
'@emotion/cache': 'latest',
'@emotion/react': 'latest',
'@emotion/server': 'latest',
'@emotion/styled': 'latest',
'@mui/icons-material': 'latest',
'@mui/material': 'latest',
next: 'latest',
'prop-types': 'latest',
react: 'latest',
'react-dom': 'latest',
eslint: 'latest',
'eslint-config-next': 'latest',
},
})
})
afterAll(() => next.destroy())
it('should render MuiLink with <a>', async () => {
const browser = await webdriver(next.url, `/`)
const element = await browser.elementByCss('a[href="/about"]')
const color = await element.getComputedCss('color')
expect(color).toBe('rgb(25, 133, 123)')
const text = await element.text()
expect(text).toBe('Go to the about page')
})
})
module.exports = {
reactStrictMode: true,
experimental: {
newNextLinkBehavior: true,
},
}
import * as React from 'react'
import Head from 'next/head'
import { ThemeProvider } from '@mui/material/styles'
import CssBaseline from '@mui/material/CssBaseline'
import { CacheProvider } from '@emotion/react'
import theme from '../src/theme'
import createEmotionCache from '../src/createEmotionCache'
// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache()
export default function MyApp(props) {
const { Component, emotionCache = clientSideEmotionCache, pageProps } = props
return (
<CacheProvider value={emotionCache}>
<Head>
<meta name="viewport" content="initial-scale=1, width=device-width" />
</Head>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</CacheProvider>
)
}
import * as React from 'react'
import Document, { Html, Head, Main, NextScript } from 'next/document'
import createEmotionServer from '@emotion/server/create-instance'
import theme from '../src/theme'
import createEmotionCache from '../src/createEmotionCache'
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
{/* PWA primary color */}
<meta name="theme-color" content={theme.palette.primary.main} />
<link rel="shortcut icon" href="/static/favicon.ico" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
{/* Inject MUI styles first to match with the prepend: true configuration. */}
{this.props.emotionStyleTags}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with static-site generation (SSG).
MyDocument.getInitialProps = async (ctx) => {
// Resolution order
//
// On the server:
// 1. app.getInitialProps
// 2. page.getInitialProps
// 3. document.getInitialProps
// 4. app.render
// 5. page.render
// 6. document.render
//
// On the server with error:
// 1. document.getInitialProps
// 2. app.render
// 3. page.render
// 4. document.render
//
// On the client
// 1. app.getInitialProps
// 2. page.getInitialProps
// 3. app.render
// 4. page.render
const originalRenderPage = ctx.renderPage
// You can consider sharing the same emotion cache between all the SSR requests to speed up performance.
// However, be aware that it can have global side effects.
const cache = createEmotionCache()
const { extractCriticalToChunks } = createEmotionServer(cache)
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) =>
function EnhanceApp(props) {
return <App emotionCache={cache} {...props} />
},
})
const initialProps = await Document.getInitialProps(ctx)
// This is important. It prevents emotion to render invalid HTML.
// See https://github.com/mui/material-ui/issues/26561#issuecomment-855286153
const emotionStyles = extractCriticalToChunks(initialProps.html)
const emotionStyleTags = emotionStyles.styles.map((style) => (
<style
data-emotion={`${style.key} ${style.ids.join(' ')}`}
key={style.key}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: style.css }}
/>
))
return {
...initialProps,
emotionStyleTags,
}
}
import * as React from 'react'
import Container from '@mui/material/Container'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import ProTip from '../src/ProTip'
import Link from '../src/Link'
import Copyright from '../src/Copyright'
export default function About() {
return (
<Container maxWidth="sm">
<Box sx={{ my: 4 }}>
<Typography variant="h4" component="h1" gutterBottom>
Next.js example
</Typography>
<Button variant="contained" component={Link} noLinkStyle href="/">
Go to the main page
</Button>
<ProTip />
<Copyright />
</Box>
</Container>
)
}
import * as React from 'react'
import Container from '@mui/material/Container'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import ProTip from '../src/ProTip'
import Link from '../src/Link'
import Copyright from '../src/Copyright'
export default function Index() {
return (
<Container maxWidth="sm">
<Box sx={{ my: 4 }}>
<Typography variant="h4" component="h1" gutterBottom>
Next.js example
</Typography>
<Link href="/about" color="secondary">
Go to the about page
</Link>
<ProTip />
<Copyright />
</Box>
</Container>
)
}
import * as React from 'react'
import Typography from '@mui/material/Typography'
import MuiLink from '@mui/material/Link'
export default function Copyright() {
return (
<Typography variant="body2" color="text.secondary" align="center">
{'Copyright © '}
<MuiLink color="inherit" href="https://mui.com/">
Your Website
</MuiLink>{' '}
{new Date().getFullYear()}.
</Typography>
)
}
import * as React from 'react'
import NextLink from 'next/link'
import MuiLink from '@mui/material/Link'
import { styled } from '@mui/material/styles'
// Add support for the sx prop for consistency with the other branches.
const Anchor = styled(NextLink)({})
export const NextLinkComposed = React.forwardRef(function NextLinkComposed(
props,
ref
) {
const { children, ...rest } = props
return (
<Anchor href="/" ref={ref} {...rest}>
{children}
</Anchor>
)
})
// A styled version of the Next.js Link component:
// https://nextjs.org/docs/api-reference/next/link
const Link = React.forwardRef(function Link(props, ref) {
return <MuiLink component={NextLinkComposed} ref={ref} {...props} />
})
export default Link
import * as React from 'react'
import Link from '@mui/material/Link'
import SvgIcon from '@mui/material/SvgIcon'
import Typography from '@mui/material/Typography'
function LightBulbIcon(props) {
return (
<SvgIcon {...props}>
<path d="M9 21c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-1H9v1zm3-19C8.14 2 5 5.14 5 9c0 2.38 1.19 4.47 3 5.74V17c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2.26c1.81-1.27 3-3.36 3-5.74 0-3.86-3.14-7-7-7zm2.85 11.1l-.85.6V16h-4v-2.3l-.85-.6C7.8 12.16 7 10.63 7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 1.63-.8 3.16-2.15 4.1z" />
</SvgIcon>
)
}
export default function ProTip() {
return (
<Typography sx={{ mt: 6, mb: 3 }} color="text.secondary">
<LightBulbIcon sx={{ mr: 1, verticalAlign: 'middle' }} />
Pro tip: See more{' '}
<Link href="https://mui.com/getting-started/templates/">
templates
</Link>{' '}
on the MUI documentation.
</Typography>
)
}
import createCache from '@emotion/cache'
// prepend: true moves MUI styles to the top of the <head> so they're loaded first.
// It allows developers to easily override MUI styles with other styling solutions, like CSS modules.
export default function createEmotionCache() {
return createCache({ key: 'css', prepend: true })
}
import { createTheme } from '@mui/material/styles'
import { red } from '@mui/material/colors'
// Create a theme instance.
const theme = createTheme({
palette: {
primary: {
main: '#556cd6',
},
secondary: {
main: '#19857b',
},
error: {
main: red.A400,
},
},
})
export default theme
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import webdriver from 'next-webdriver'
import path from 'path'
const appDir = path.join(__dirname, 'stitches')
describe('New Link Behavior with stitches', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
pages: new FileRef(path.join(appDir, 'pages')),
components: new FileRef(path.join(appDir, 'components')),
'next.config.js': new FileRef(path.join(appDir, 'next.config.js')),
'stitches.config.js': new FileRef(
path.join(appDir, 'stitches.config.js')
),
},
dependencies: {
'@stitches/react': '^1.2.6',
next: 'latest',
react: 'latest',
'react-dom': 'latest',
},
})
})
afterAll(() => next.destroy())
it('should render <a>', async () => {
const browser = await webdriver(next.url, `/`)
const element = await browser.elementByCss('a[href="/about"]')
const color = await element.getComputedCss('color')
expect(color).toBe('rgb(78, 39, 231)')
const text = await element.text()
expect(text).toBe('Visit About')
})
})
const StitchesLogo = () => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="35"
height="35"
viewBox="0 0 35 35"
fill="none"
>
<circle
cx="17.5"
cy="17.5"
r="14.5"
stroke="currentColor"
strokeWidth="2"
/>
<path d="M12.8184 31.3218L31.8709 20.3218" stroke="currentColor" />
<path d="M3.31836 14.8674L22.3709 3.86743" stroke="currentColor" />
<path
d="M8.65332 29.1077L25.9738 19.1077"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M9.21582 16.0815L26.5363 6.08154"
stroke="currentColor"
strokeLinecap="round"
/>
<path
d="M13.2334 14.2297L22.5099 21.1077"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M16.6973 12.2302L25.9736 19.1078"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M9.21582 16.0815L19.0459 23.1078"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)
export default StitchesLogo
module.exports = {
reactStrictMode: true,
experimental: {
newNextLinkBehavior: true,
},
}
import React from 'react'
import NextDocument, { Html, Head, Main, NextScript } from 'next/document'
import { getCssText } from '../stitches.config'
export default class Document extends NextDocument {
render() {
return (
<Html lang="en">
<Head>
<style
id="stitches"
dangerouslySetInnerHTML={{ __html: getCssText() }}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
import { styled } from '../stitches.config'
import StitchesLogo from '../components/StitchesLogo'
const Box = styled('div', {})
const Text = styled('p', {
fontFamily: '$system',
color: '$hiContrast',
})
const Link = styled('a', {
fontFamily: '$system',
textDecoration: 'none',
color: '$purple600',
})
const Container = styled('div', {
marginX: 'auto',
paddingX: '$3',
variants: {
size: {
1: {
maxWidth: '300px',
},
2: {
maxWidth: '585px',
},
3: {
maxWidth: '865px',
},
},
},
})
export default function Home() {
return (
<Box css={{ paddingY: '$6' }}>
<Container size={{ '@initial': '1', '@bp1': '2' }}>
<StitchesLogo />
<Text as="h1">Hello, from About.</Text>
<Text>
<Link href="/">Visit Home</Link>.
</Text>
</Container>
</Box>
)
}
import NextLink from 'next/link'
import { styled } from '../stitches.config'
import StitchesLogo from '../components/StitchesLogo'
const Box = styled('div', {})
const Text = styled('p', {
fontFamily: '$system',
color: '$hiContrast',
})
const Link = styled(NextLink, {
fontFamily: '$system',
textDecoration: 'none',
color: '$purple600',
})
const Container = styled('div', {
marginX: 'auto',
paddingX: '$3',
variants: {
size: {
1: {
maxWidth: '300px',
},
2: {
maxWidth: '585px',
},
3: {
maxWidth: '865px',
},
},
},
})
export default function Home() {
return (
<Box css={{ paddingY: '$6' }}>
<Container size={{ '@initial': '1', '@bp1': '2' }}>
<StitchesLogo />
<Text as="h1">Hello, from Stitches.</Text>
<Text>
<Link href="/about">Visit About</Link>.
</Text>
</Container>
</Box>
)
}
import { createStitches } from '@stitches/react'
export const {
config,
createTheme,
css,
getCssText,
globalCss,
styled,
theme,
} = createStitches({
theme: {
colors: {
hiContrast: 'hsl(206,10%,5%)',
loContrast: 'white',
gray100: 'hsl(206,22%,99%)',
gray200: 'hsl(206,12%,97%)',
gray300: 'hsl(206,11%,92%)',
gray400: 'hsl(206,10%,84%)',
gray500: 'hsl(206,10%,76%)',
gray600: 'hsl(206,10%,44%)',
purple100: 'hsl(252,100%,99%)',
purple200: 'hsl(252,100%,98%)',
purple300: 'hsl(252,100%,94%)',
purple400: 'hsl(252,75%,84%)',
purple500: 'hsl(252,78%,60%)',
purple600: 'hsl(252,80%,53%)',
},
space: {
1: '5px',
2: '10px',
3: '15px',
4: '20px',
5: '25px',
6: '35px',
},
sizes: {
1: '5px',
2: '10px',
3: '15px',
4: '20px',
5: '25px',
6: '35px',
},
fontSizes: {
1: '12px',
2: '13px',
3: '15px',
4: '17px',
5: '19px',
6: '21px',
},
fonts: {
system: 'system-ui',
},
},
utils: {
marginX: (value) => ({
marginLeft: value,
marginRight: value,
}),
marginY: (value) => ({
marginTop: value,
marginBottom: value,
}),
paddingX: (value) => ({
paddingLeft: value,
paddingRight: value,
}),
paddingY: (value) => ({
paddingTop: value,
paddingBottom: value,
}),
},
media: {
bp1: '(min-width: 520px)',
bp2: '(min-width: 900px)',
},
})
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { renderViaHTTP } from 'next-test-utils'
import cheerio from 'cheerio'
import path from 'path'
const appDir = path.join(__dirname, 'typescript')
describe('New Link Behavior', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
pages: new FileRef(path.join(appDir, 'pages')),
'tsconfig.json': new FileRef(path.join(appDir, 'tsconfig.json')),
},
dependencies: {
typescript: '*',
'@types/react': '*',
'@types/node': '*',
},
})
})
afterAll(() => next.destroy())
it('should render link with <a>', async () => {
const html = await renderViaHTTP(next.url, '/')
const $ = cheerio.load(html)
const $a = $('a')
expect($a.text()).toBe('Visit')
expect($a.attr('href')).toBe('/test')
})
})
import {
PropsWithRef,
PropsWithoutRef,
HTMLProps,
CSSProperties,
MouseEventHandler,
} from 'react'
import NextLink, { LinkProps } from 'next/link'
type NativeButtonProps = Omit<
HTMLProps<HTMLButtonElement>,
'type' | 'prefix' | 'size' | 'width' | 'shape' | 'onClick'
>
export type ButtonVariant = 'shadow' | 'invert' | 'unstyled' | 'ghost'
export type ButtonAlignment = 'start' | 'grow' | 'center'
type BaseButtonProps = NativeButtonProps & {
Component?: React.ElementType<any> // this could probably be better...
typeName?: 'button' | 'submit' | 'reset'
loading?: boolean
suffix?: React.ReactNode
prefix?: React.ReactNode
size?: 'small' | 'large'
variant?: ButtonVariant
align?: ButtonAlignment
svgOnly?: boolean
passthroughOnClick?: MouseEventHandler
passthroughOnMouseEnter?: MouseEventHandler
onClick?: () => void
}
type PropsWithShape = BaseButtonProps &
(
| {
width?: CSSProperties['width']
shape?: never
}
| {
shape?: 'square' | 'circle'
width?: never
}
)
type PropsWithSvgOnly = PropsWithShape &
(
| {
// If you're here, you probably got a TS error on the svgOnly prop
// If you specify svgOnly, you MUST provide a descriptive label for the button
svgOnly?: true
'aria-label': string
}
| {
svgOnly?: never
}
)
export type ButtonLinkProps = PropsWithRef<Omit<ButtonProps, 'href'>> &
LinkProps & {
tab?: boolean
}
export const ButtonLink: React.FC<ButtonLinkProps> = ({
href,
as,
shallow,
children,
}) => {
return (
<NextLink
href={href}
as={as}
shallow={shallow}
// Always passHref to the <a> component if it's defined.
passHref={!!href}
>
<a>{children}</a>
</NextLink>
)
}
export type ButtonProps = PropsWithSvgOnly
const Visit = ({ onClick, ...props }: PropsWithoutRef<ButtonProps>) => {
return (
<ButtonLink href={'/test'} tab width={70} {...props}>
Visit
</ButtonLink>
)
}
export default Visit
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment