Skip to content

Commit 5e1f767

Browse files
authored
Don't scroll page to top when opening or closing a side modal (#3336)
Closes #3321 Because side modals get their own routes, and the scroll height cache is keyed (in part) by route, opening a side modal counts as a new page with no saved scroll height, so it scrolls the document to top. The fix is to handle the modal scenario specially by opting out of resetting scroll when we switch to a new location that has the same underlying page path as the previous one. https://github.com/user-attachments/assets/af40dae5-7065-4599-be55-a9dd7ae7299e ### Example flows Each of these scenarios is covered by e2e tests. The underlying "page path" for a location is the path of the last non-`titleOnly` crumb, i.e., where the nav breadcrumbs point: a regular page's own path, or for a side modal, the path of the page under it. When a nav starts, we save the current scroll under the outgoing location's key. When it completes, if the page path changed we scroll to the new location's cached position (0 if none); if it didn't (side modal open/close), we leave the scroll alone and just record it under the new key so back/forward still works. #### Normal page → page nav (`…/disks` → `…/snapshots`, then back) | Step | Location | Page path | Cache | Scroll | | ----------------------------------------------------- | ------------------ | ------------- | -------------- | ------- | | Scroll the disks page | `…/disks` (k1) | `…/disks` | | 143 | | Click Snapshots: nav starts | `…/disks` (k1) | `…/disks` | k1: 143 | 143 | | Nav completes: page changed → scroll to cached (none) | `…/snapshots` (k2) | `…/snapshots` | k1: 143 | 0 | | Back: nav starts | `…/snapshots` (k2) | `…/snapshots` | k1: 143, k2: 0 | 0 | | Nav completes: page changed → scroll to cached | `…/disks` (k1) | `…/disks` | k1: 143, k2: 0 | **143** | #### Page → modal → page (open the New disk form, then dismiss it) | Step | Location | Page path | Cache | Scroll | | ------------------------------------------------------------- | ------------------ | --------- | ------------------------- | ------- | | Scroll the disks page | `…/disks` (k1) | `…/disks` | | 143 | | Click New disk: nav starts | `…/disks` (k1) | `…/disks` | k1: 143 | 143 | | Nav completes: same page → leave scroll, record under new key | `…/disks-new` (k2) | `…/disks` | k1: 143, k2: 143 | **143** | | Dismiss: nav starts | `…/disks-new` (k2) | `…/disks` | k1: 143, k2: 143 | 143 | | Nav completes: same page → leave scroll, record under new key | `…/disks` (k3) | `…/disks` | k1: 143, k2: 143, k3: 143 | **143** | #### Modal submit → new page (create a VPC, land on VPC detail page) | Step | Location | Page path | Cache | Scroll | | ----------------------------------------------------- | -------------------- | --------------- | ---------------- | ------ | | Modal open over scrolled VPCs page | `…/vpcs-new` (k2) | `…/vpcs` | k1: 143, k2: 143 | 143 | | Submit: nav starts | `…/vpcs-new` (k2) | `…/vpcs` | k1: 143, k2: 143 | 143 | | Nav completes: page changed → scroll to cached (none) | `…/vpcs/my-vpc` (k3) | `…/vpcs/my-vpc` | k1: 143, k2: 143 | **0** |
1 parent 37d98e3 commit 5e1f767

6 files changed

Lines changed: 153 additions & 14 deletions

File tree

‎app/hooks/use-crumbs.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
*
66
* Copyright Oxide Computer Company
77
*/
8-
import { useMatches, type Params, type UIMatch } from 'react-router'
8+
import { useLocation, useMatches, type Params, type UIMatch } from 'react-router'
99

1010
import { invariant } from '~/util/invariant'
1111

@@ -80,3 +80,15 @@ export const useCrumbs = () => matchesToCrumbs(useMatches())
8080
* this one is true.
8181
*/
8282
export const useIsSideModalRoute = () => useCrumbs().some((c) => c.titleOnly)
83+
84+
/**
85+
* Path of the page the current location displays, i.e., where its nav
86+
* breadcrumbs point. For a side modal route this is the parent page it renders
87+
* on top of — side modals are marked `titleOnly` precisely because the page
88+
* underneath doesn't change. Falls back to the pathname for crumbless routes.
89+
*/
90+
export function usePagePath() {
91+
const { pathname } = useLocation()
92+
const pageCrumb = useCrumbs().findLast((c) => !c.titleOnly)
93+
return pageCrumb?.path ?? pathname
94+
}

‎app/hooks/use-scroll-restoration.ts‎

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
*
66
* Copyright Oxide Computer Company
77
*/
8-
import { useEffect } from 'react'
8+
import { useEffect, useRef } from 'react'
99
import { useLocation, useNavigation } from 'react-router'
1010

11+
import { usePagePath } from './use-crumbs'
12+
1113
function getScrollPosition(key: string) {
1214
const pos = window.sessionStorage.getItem(key)
1315
return Number(pos) || 0
@@ -33,15 +35,39 @@ function setScrollPosition(key: string, pos: number) {
3335
export function useScrollRestoration() {
3436
const key = `scroll-position-${useLocation().key}`
3537
const { state } = useNavigation()
38+
// page path looks at the page under a side modal, which we use to distinguish
39+
// modal open/close (which shouldn't reset scroll) from full page navs (which
40+
// should)
41+
const page = usePagePath()
42+
// last committed location, tracked at idle. We can't track it during
43+
// 'loading' because a nav with cached loader data can complete without ever
44+
// hitting state === 'loading'.
45+
const prev = useRef<{ key: string; page: string } | null>(null)
3646
useEffect(() => {
37-
// opt out of the browser's native scroll restoration so it doesn't jump
38-
// the still-visible old page to the new page's saved position on POP,
39-
// before the new route's loader resolves. We restore manually below.
47+
// opt out of native scroll restoration, it conflicts with ours
4048
window.history.scrollRestoration = 'manual'
49+
50+
// idle + new key = we just landed somewhere (or this is the initial render)
51+
const landed = state === 'idle' && prev.current?.key !== key
52+
53+
// underlying page didn't change, which either means the nav was opening
54+
// or closing a side modal, a query param tab change, or clicking the
55+
// breadcrumb for the page you're already on
56+
const samePage = prev.current?.page === page
57+
4158
if (state === 'loading') {
59+
// nav in flight: save current scroll under the outgoing location's key
4260
setScrollPosition(key, window.scrollY)
43-
} else if (state === 'idle') {
44-
window.scrollTo(0, getScrollPosition(key))
61+
} else if (landed) {
62+
if (samePage) {
63+
// leave scroll alone, record under the new key so it can be restored
64+
// on forward/back
65+
setScrollPosition(key, window.scrollY)
66+
} else {
67+
// landed on a new page: restore its saved scroll, or 0 if none saved
68+
window.scrollTo(0, getScrollPosition(key))
69+
}
4570
}
46-
}, [key, state])
71+
if (state === 'idle') prev.current = { key, page }
72+
}, [key, state, page])
4773
}

‎app/routes.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,14 @@ export const routes = createRoutesFromElements(
446446
element={null}
447447
handle={{ crumb: 'Firewall Rules' }}
448448
/>
449-
<Route element={null} handle={{ crumb: 'Firewall Rules' }}>
449+
<Route
450+
element={null}
451+
// path makes crumb link straight to the tab instead of
452+
// bouncing through the redirect at the VPC root
453+
handle={makeCrumb('Firewall Rules', (p) =>
454+
pb.vpcFirewallRules(getVpcSelector(p))
455+
)}
456+
>
450457
<Route
451458
path="firewall-rules-new/:rule?"
452459
lazy={() => import('./forms/firewall-rules-create').then(convert)}

‎app/util/__snapshots__/path-builder.spec.ts.snap‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -960,7 +960,7 @@ exports[`breadcrumbs 2`] = `
960960
},
961961
{
962962
"label": "Firewall Rules",
963-
"path": "/projects/p/vpcs/v/",
963+
"path": "/projects/p/vpcs/v/firewall-rules",
964964
},
965965
],
966966
"vpcFirewallRuleEdit (/projects/p/vpcs/v/firewall-rules/fr/edit)": [
@@ -982,7 +982,7 @@ exports[`breadcrumbs 2`] = `
982982
},
983983
{
984984
"label": "Firewall Rules",
985-
"path": "/projects/p/vpcs/v/",
985+
"path": "/projects/p/vpcs/v/firewall-rules",
986986
},
987987
],
988988
"vpcFirewallRules (/projects/p/vpcs/v/firewall-rules)": [
@@ -1026,7 +1026,7 @@ exports[`breadcrumbs 2`] = `
10261026
},
10271027
{
10281028
"label": "Firewall Rules",
1029-
"path": "/projects/p/vpcs/v/",
1029+
"path": "/projects/p/vpcs/v/firewall-rules",
10301030
},
10311031
],
10321032
"vpcInternetGateway (/projects/p/vpcs/v/internet-gateways/g)": [

‎test/e2e/route-announcer.e2e.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const announcements = (page: Page) =>
1515

1616
test('route announcer', async ({ page }) => {
1717
await page.goto('/projects')
18-
await page.getByRole('heading', { name: 'Projects' }).waitFor()
18+
await expect(page.getByRole('heading', { name: 'Projects' })).toBeVisible()
1919

2020
// nothing on first load — the browser already announced the page
2121
await expect(announcements(page)).toHaveCount(0)

‎test/e2e/scroll-restore.e2e.ts‎

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ test('scroll restore', async ({ page }) => {
1616
// nav to disks and scroll it
1717
await page.goto('/projects/mock-project/disks')
1818
// wait for content to render so the page is tall enough to scroll
19-
await page.getByRole('heading', { name: 'Disks' }).waitFor()
19+
await expect(page.getByRole('heading', { name: 'Disks' })).toBeVisible()
2020
await expectScrollTop(page, 0)
2121
await scrollTo(page, 143)
2222

@@ -50,3 +50,97 @@ test('scroll restore', async ({ page }) => {
5050
await expect(page).toHaveURL('/projects/mock-project/snapshots')
5151
await expectScrollTop(page, 0)
5252
})
53+
54+
// https://github.com/oxidecomputer/console/issues/3321
55+
test('opening and closing side modal preserves scroll', async ({ page }) => {
56+
await page.setViewportSize({ width: 1280, height: 500 })
57+
58+
await page.goto('/projects/mock-project/disks')
59+
await expect(page.getByRole('heading', { name: 'Disks' })).toBeVisible()
60+
61+
// visit snapshots and come back so its data is cached: the later nav to it
62+
// can then complete without rendering a loading state, which would otherwise
63+
// save the scroll position and mask a failure to record it at modal close
64+
await page.getByRole('link', { name: 'Snapshots' }).click()
65+
await expect(page.getByRole('heading', { name: 'Snapshots' })).toBeVisible()
66+
await page.getByRole('link', { name: 'Disks' }).click()
67+
await expect(page.getByRole('heading', { name: 'Disks' })).toBeVisible()
68+
69+
// click the last disk in the table. clicking auto-scrolls it into view, so
70+
// read the resulting scroll position as the baseline rather than setting one
71+
const lastDisk = page
72+
.locator('table')
73+
.getByRole('link', { name: /^disk-/ })
74+
.last()
75+
await lastDisk.scrollIntoViewIfNeeded()
76+
const baseline = await page.evaluate(() => window.scrollY)
77+
expect(baseline).toBeGreaterThan(0)
78+
79+
// opening the detail side modal doesn't scroll the page underneath
80+
await lastDisk.click()
81+
await expect(page.getByRole('dialog')).toBeVisible()
82+
await expectScrollTop(page, baseline)
83+
84+
// closing it doesn't either
85+
await page.keyboard.press('Escape')
86+
await expect(page.getByRole('dialog')).toBeHidden()
87+
await expectScrollTop(page, baseline)
88+
89+
// nav away and back: the scroll recorded at modal close is restored
90+
await page.getByRole('link', { name: 'Snapshots' }).click()
91+
await expectScrollTop(page, 0)
92+
await page.goBack()
93+
await expect(page).toHaveURL('/projects/mock-project/disks')
94+
await expectScrollTop(page, baseline)
95+
})
96+
97+
// this modal route is trickier than the others: it hangs off a pathless crumb
98+
// wrapper route rather than being a direct child of the page route
99+
test('opening firewall rule modal preserves scroll', async ({ page }) => {
100+
await page.setViewportSize({ width: 1280, height: 300 })
101+
102+
await page.goto('/projects/mock-project/vpcs/default/firewall-rules')
103+
await expect(page.getByRole('tab', { name: 'Firewall Rules' })).toBeVisible()
104+
await scrollTo(page, 100)
105+
await expectScrollTop(page, 100)
106+
107+
// clicking auto-scrolls the link into view, so read the resulting scroll
108+
// position as the baseline rather than assuming it stays at 100
109+
const newRuleLink = page.getByRole('link', { name: 'New rule' })
110+
await newRuleLink.scrollIntoViewIfNeeded()
111+
const baseline = await page.evaluate(() => window.scrollY)
112+
expect(baseline).toBeGreaterThan(0)
113+
114+
await newRuleLink.click()
115+
await expect(page.getByRole('dialog', { name: 'Add firewall rule' })).toBeVisible()
116+
await expectScrollTop(page, baseline)
117+
118+
await page.keyboard.press('Escape')
119+
await expect(page.getByRole('dialog')).toBeHidden()
120+
await expectScrollTop(page, baseline)
121+
})
122+
123+
test('navigating from a side modal to a new page resets scroll', async ({ page }) => {
124+
await page.setViewportSize({ width: 1280, height: 300 })
125+
126+
await page.goto('/projects/mock-project/vpcs')
127+
await expect(page.getByRole('heading', { name: 'VPCs' })).toBeVisible()
128+
await scrollTo(page, 100)
129+
await expectScrollTop(page, 100)
130+
131+
await page.getByRole('link', { name: 'New VPC' }).click()
132+
await expect(page.getByRole('dialog', { name: 'Create VPC' })).toBeVisible()
133+
await expectScrollTop(page, 100)
134+
135+
await page.getByRole('textbox', { name: 'Name', exact: true }).fill('scroll-test-vpc')
136+
await page.getByRole('textbox', { name: 'DNS name' }).fill('scroll-test-vpc')
137+
await page.getByRole('button', { name: 'Create VPC' }).click()
138+
139+
await expect(page.getByRole('heading', { name: 'scroll-test-vpc' })).toBeVisible()
140+
await expectScrollTop(page, 0)
141+
142+
// going back reopens the modal with the underlying page's scroll restored
143+
await page.goBack()
144+
await expect(page.getByRole('dialog', { name: 'Create VPC' })).toBeVisible()
145+
await expectScrollTop(page, 100)
146+
})

0 commit comments

Comments
 (0)