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

Add handling for prefetching onTouchStart and initial mobile testing #38805

Merged
merged 4 commits into from Jul 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 6 additions & 9 deletions .github/workflows/build_test_deploy.yml
Expand Up @@ -816,13 +816,9 @@ jobs:
runs-on: ubuntu-latest
needs: [build, build-native-test]
env:
BROWSERSTACK: true
BROWSER_NAME: 'safari'
NEXT_TELEMETRY_DISABLED: 1
NEXT_TEST_MODE: 'start'
SKIP_LOCAL_SELENIUM_SERVER: true
BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}
BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
NEXT_TELEMETRY_DISABLED: 1
steps:
- name: Setup node
uses: actions/setup-node@v3
Expand Down Expand Up @@ -851,12 +847,13 @@ jobs:
- run: npm i -g pnpm@${PNPM_VERSION}
if: ${{needs.build.outputs.docsChange == 'nope'}}

# TODO: use macos runner so that we can use playwright to test against
# PRs instead of only running on canary?
- run: '[[ -z "$BROWSERSTACK_ACCESS_KEY" ]] && echo "Skipping for PR" || npm i -g browserstack-local@1.4.0'
- run: npx playwright install-deps && npx playwright install webkit
if: ${{needs.build.outputs.docsChange == 'nope'}}

- run: node run-tests.js -c 1 test/integration/production/test/index.test.js test/e2e/basepath.test.ts
if: ${{needs.build.outputs.docsChange == 'nope'}}

- run: '[[ -z "$BROWSERSTACK_ACCESS_KEY" ]] && echo "Skipping for PR" || node run-tests.js -c 1 test/integration/production/test/index.test.js test/e2e/basepath.test.ts'
- run: DEVICE_NAME='iPhone XR' node run-tests.js -c 1 test/production/prerender-prefetch/index.test.ts
if: ${{needs.build.outputs.docsChange == 'nope'}}

testSafariOld:
Expand Down
31 changes: 30 additions & 1 deletion packages/next/client/link.tsx
Expand Up @@ -48,6 +48,11 @@ type InternalLinkProps = {
*/
onMouseEnter?: (e: any) => void
// e: any because as it would otherwise overlap with existing types
/**
* requires experimental.newNextLinkBehavior
*/
onTouchStart?: (e: any) => void
// e: any because as it would otherwise overlap with existing types
/**
* requires experimental.newNextLinkBehavior
*/
Expand Down Expand Up @@ -215,6 +220,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
locale: true,
onClick: true,
onMouseEnter: true,
onTouchStart: true,
legacyBehavior: true,
} as const
const optionalProps: LinkPropsOptional[] = Object.keys(
Expand All @@ -239,7 +245,11 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
actual: valType,
})
}
} else if (key === 'onClick' || key === 'onMouseEnter') {
} else if (
key === 'onClick' ||
key === 'onMouseEnter' ||
key === 'onTouchStart'
) {
if (props[key] && valType !== 'function') {
throw createPropError({
key,
Expand Down Expand Up @@ -296,6 +306,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
locale,
onClick,
onMouseEnter,
onTouchStart,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we consider using the onPointerEnter to handle all mouse/touch in the future? maybe we can use it to handle touch events first?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are there any quirks to using onPointerEnter vs onMouseEnter/onTouchStart? If not and it handles both definitely sounds ideal

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel the only blocker is browser support. Previously pointer event wasn't supported quite well among all browsers, I remembered years ago safari doesn't. but now it looks not bad, safari 13 has supported it since 2019.

https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can investigate using pointer events in a follow-up, seems onTouchStart should be a good start for compatibility.

legacyBehavior = Boolean(process.env.__NEXT_NEW_LINK_BEHAVIOR) !== true,
...restProps
} = props
Expand Down Expand Up @@ -411,6 +422,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
}, [as, href, isVisible, locale, p, router])

const childProps: {
onTouchStart: React.TouchEventHandler
onMouseEnter: React.MouseEventHandler
onClick: React.MouseEventHandler
href?: string
Expand Down Expand Up @@ -466,6 +478,23 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
prefetch(router, href, as, { priority: true })
}
},
onTouchStart: (e: React.TouchEvent<HTMLAnchorElement>) => {
if (!legacyBehavior && typeof onTouchStart === 'function') {
onTouchStart(e)
}

if (
legacyBehavior &&
child.props &&
typeof child.props.onTouchStart === 'function'
) {
child.props.onTouchStart(e)
}

if (isLocalURL(href)) {
prefetch(router, href, as, { priority: true })
}
},
}

// If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is
Expand Down
2 changes: 1 addition & 1 deletion test/integration/production/test/index.test.js
Expand Up @@ -750,7 +750,7 @@ describe('Production Usage', () => {
.elementByCss('a')
.click()
.waitForElementByCss('.about-page')
.elementByCss('div')
.elementByCss('.about-page')
.text()

expect(text).toBe('About Page')
Expand Down
3 changes: 3 additions & 0 deletions test/lib/browsers/base.ts
Expand Up @@ -31,6 +31,9 @@ export class BrowserInterface {
elementById(selector: string): BrowserInterface {
return this
}
touchStart(): BrowserInterface {
return this
}
click(opts?: { modifierKey?: boolean }): BrowserInterface {
return this
}
Expand Down
20 changes: 19 additions & 1 deletion test/lib/browsers/playwright.ts
Expand Up @@ -8,6 +8,7 @@ import {
BrowserContext,
Page,
ElementHandle,
devices,
} from 'playwright-chromium'
import path from 'path'

Expand Down Expand Up @@ -49,6 +50,17 @@ class Playwright extends BrowserInterface {
async setup(browserName: string, locale?: string) {
if (browser) return
const headless = !!process.env.HEADLESS
let device

if (process.env.DEVICE_NAME) {
device = devices[process.env.DEVICE_NAME]

if (!device) {
throw new Error(
`Invalid playwright device name ${process.env.DEVICE_NAME}`
)
}
}

if (browserName === 'safari') {
browser = await webkit.launch({ headless })
Expand All @@ -57,7 +69,7 @@ class Playwright extends BrowserInterface {
} else {
browser = await chromium.launch({ headless, devtools: !headless })
}
context = await browser.newContext({ locale })
context = await browser.newContext({ locale, ...device })
}

async get(url: string): Promise<void> {
Expand Down Expand Up @@ -284,6 +296,12 @@ class Playwright extends BrowserInterface {
})
}

touchStart() {
return this.chain((el: ElementHandle) => {
return el.dispatchEvent('touchstart').then(() => el)
})
}

elementsByCss(sel) {
return this.chain(() =>
page.$$(sel).then((els) => {
Expand Down
106 changes: 73 additions & 33 deletions test/production/prerender-prefetch/index.test.ts
Expand Up @@ -134,43 +134,83 @@ describe('Prerender prefetch', () => {
expect(isNaN(newTime)).toBe(false)
})

it('should attempt cache update on link hover', async () => {
const browser = await webdriver(next.url, '/')
const timeRes = await fetchViaHTTP(
next.url,
`/_next/data/${next.buildId}/blog/first.json`,
undefined,
{
headers: {
purpose: 'prefetch',
},
}
)
const startTime = (await timeRes.json()).pageProps.now

// ensure stale data is used by default
await browser.elementByCss('#to-blog-first').click()
await check(() => browser.elementByCss('#page').text(), 'blog/[slug]')
if (process.env.DEVICE_NAME) {
it('should attempt cache update on touchstart', async () => {
const browser = await webdriver(next.url, '/')
const timeRes = await fetchViaHTTP(
next.url,
`/_next/data/${next.buildId}/blog/first.json`,
undefined,
{
headers: {
purpose: 'prefetch',
},
}
)
const startTime = (await timeRes.json()).pageProps.now

expect(JSON.parse(await browser.elementByCss('#props').text()).now).toBe(
startTime
)
await browser.back().waitForElementByCss('#to-blog-first')
const requests = []
// ensure stale data is used by default
await browser.elementByCss('#to-blog-first').click()
await check(() => browser.elementByCss('#page').text(), 'blog/[slug]')

browser.on('request', (req) => {
requests.push(req.url())
expect(JSON.parse(await browser.elementByCss('#props').text()).now).toBe(
startTime
)
await browser.back().waitForElementByCss('#to-blog-first')
const requests = []

browser.on('request', (req) => {
requests.push(req.url())
})

// now trigger cache update and navigate again
await check(async () => {
await browser.elementByCss('#to-blog-second').touchStart()
await browser.elementByCss('#to-blog-first').touchStart()
return requests.some((url) => url.includes('/blog/first.json'))
? 'success'
: requests
}, 'success')
})
} else {
it('should attempt cache update on link hover', async () => {
const browser = await webdriver(next.url, '/')
const timeRes = await fetchViaHTTP(
next.url,
`/_next/data/${next.buildId}/blog/first.json`,
undefined,
{
headers: {
purpose: 'prefetch',
},
}
)
const startTime = (await timeRes.json()).pageProps.now

// now trigger cache update and navigate again
await check(async () => {
await browser.elementByCss('#to-blog-second').moveTo()
await browser.elementByCss('#to-blog-first').moveTo()
return requests.some((url) => url.includes('/blog/first.json'))
? 'success'
: requests
}, 'success')
})
// ensure stale data is used by default
await browser.elementByCss('#to-blog-first').click()
await check(() => browser.elementByCss('#page').text(), 'blog/[slug]')

expect(JSON.parse(await browser.elementByCss('#props').text()).now).toBe(
startTime
)
await browser.back().waitForElementByCss('#to-blog-first')
const requests = []

browser.on('request', (req) => {
requests.push(req.url())
})

// now trigger cache update and navigate again
await check(async () => {
await browser.elementByCss('#to-blog-second').moveTo()
await browser.elementByCss('#to-blog-first').moveTo()
return requests.some((url) => url.includes('/blog/first.json'))
? 'success'
: requests
}, 'success')
})
}

it('should handle failed data fetch and empty cache correctly', async () => {
const browser = await webdriver(next.url, '/')
Expand Down