From 5bb7ee15ac33204f4b769042a8b28deae54496df Mon Sep 17 00:00:00 2001 From: Yinghao Zhao Date: Sat, 14 Nov 2026 22:30:30 +0800 Subject: [PATCH] fix(elements-core): follow hashchange-only navigation in hash router mode React Router v6's hash history listens to `popstate` only. Host routers that change the URL with `history.pushState()` and then dispatch `hashchange` never fire `popstate`, so the router keeps the old route while the URL shows the new one. VitePress does this for every same-page link it intercepts: it calls `preventDefault()`, so React Router's `` skips its own navigation, then pushes the URL and dispatches a synthetic `HashChangeEvent`. Elements v8 worked because the history v4 hash history also listened to `hashchange`. Back and Forward are unaffected, because a real history traversal fires `popstate`. Add HashRouterSync, rendered next to the HashRouter that withRouter creates for `router="hash"`. On `hashchange` it moves the router to the new hash with `replace`, because the host already created the history entry. It: - acts only on hashes that are routes of this router (`#/...` under `basePath`, or an empty hash for the root), so a host page's own fragments, such as a skip link (`#main-content`), are left alone; - strips `basePath` before calling `navigate()`, which adds it again; - does nothing when the router is already at that location, for example after a native fragment navigation that React Router handled via `popstate`. Fixes #2792 Co-authored-by: Drew Zhao Co-Authored-By: Claude Opus 5.5 --- .../HashRouterSync/HashRouterSync.spec.tsx | 232 ++++++++++++++++++ .../src/components/HashRouterSync/index.tsx | 76 ++++++ packages/elements-core/src/hoc/withRouter.tsx | 2 + 3 files changed, 310 insertions(+) create mode 100644 packages/elements-core/src/components/HashRouterSync/HashRouterSync.spec.tsx create mode 100644 packages/elements-core/src/components/HashRouterSync/index.tsx diff --git a/packages/elements-core/src/components/HashRouterSync/HashRouterSync.spec.tsx b/packages/elements-core/src/components/HashRouterSync/HashRouterSync.spec.tsx new file mode 100644 index 000000000..820c04133 --- /dev/null +++ b/packages/elements-core/src/components/HashRouterSync/HashRouterSync.spec.tsx @@ -0,0 +1,232 @@ +import { act, render, screen } from '@testing-library/react'; +import * as React from 'react'; +import { HashRouter, useLocation } from 'react-router-dom'; + +import { withRouter } from '../../hoc/withRouter'; +import { getRouterPathFromHash, HashRouterSync } from '.'; + +const LocationProbe = () => { + const { pathname, search, hash } = useLocation(); + return
{`${pathname}${search}${hash}`}
; +}; + +const routerLocation = () => screen.getByTestId('router-location').textContent; + +// What a host SPA router (for example VitePress) does when a same-page link is clicked: +// it updates the URL with pushState(), which fires no event, and then dispatches a hashchange event. +const hostNavigate = (url: string) => { + act(() => { + window.history.pushState({}, '', url); + window.dispatchEvent(new HashChangeEvent('hashchange')); + }); +}; + +describe('HashRouterSync', () => { + beforeEach(() => { + window.history.replaceState(null, '', '/'); + }); + + it('is needed because React Router alone ignores hashchange-only navigation', () => { + render( + + + , + ); + + hostNavigate('/#/operations/b'); + + expect(window.location.hash).toBe('#/operations/b'); + expect(routerLocation()).toBe('/'); + }); + + it('moves the router to a route hash set by the host page', () => { + render( + + + + , + ); + + hostNavigate('/#/operations/b'); + + expect(routerLocation()).toBe('/operations/b'); + }); + + it('keeps the history entry created by the host instead of adding another one', () => { + render( + + + + , + ); + const lengthBefore = window.history.length; + + hostNavigate('/#/operations/b'); + + expect(window.history.length).toBe(lengthBefore + 1); + expect(window.location.hash).toBe('#/operations/b'); + }); + + it('keeps the query and the in-page anchor of the route', () => { + render( + + + + , + ); + + hostNavigate('/#/operations/b?tab=1#request-body'); + + expect(routerLocation()).toBe('/operations/b?tab=1#request-body'); + }); + + it('ignores fragments that are not routes, such as a skip link', () => { + render( + + + + , + ); + hostNavigate('/#/operations/a'); + + hostNavigate('/#main-content'); + + expect(routerLocation()).toBe('/operations/a'); + expect(window.location.hash).toBe('#main-content'); + }); + + it('treats an empty hash as the router root', () => { + render( + + + + , + ); + hostNavigate('/#/operations/a'); + + hostNavigate('/'); + + expect(routerLocation()).toBe('/'); + }); + + it('does not navigate again when the router already followed a popstate', () => { + render( + + + + , + ); + const replaceState = jest.spyOn(window.history, 'replaceState'); + + // A real fragment navigation fires popstate (handled by React Router) and then hashchange. + act(() => { + window.history.pushState({}, '', '/#/operations/c'); + window.dispatchEvent(new PopStateEvent('popstate', { state: null })); + }); + act(() => { + window.dispatchEvent(new HashChangeEvent('hashchange')); + }); + + expect(routerLocation()).toBe('/operations/c'); + expect(replaceState).not.toHaveBeenCalled(); + replaceState.mockRestore(); + }); + + it('resolves routes relative to basePath', () => { + window.history.replaceState(null, '', '/#/docs'); + render( + + + + , + ); + + hostNavigate('/#/docs/operations/b'); + + expect(routerLocation()).toBe('/operations/b'); + expect(window.location.hash).toBe('#/docs/operations/b'); + }); + + it('ignores hashes outside basePath', () => { + window.history.replaceState(null, '', '/#/docs/operations/a'); + render( + + + + , + ); + + hostNavigate('/#/other/page'); + + expect(routerLocation()).toBe('/operations/a'); + }); + + it('stops listening when unmounted', () => { + const { unmount } = render( + + + + , + ); + unmount(); + const replaceState = jest.spyOn(window.history, 'replaceState'); + + hostNavigate('/#/operations/b'); + + expect(replaceState).not.toHaveBeenCalled(); + replaceState.mockRestore(); + }); +}); + +describe('getRouterPathFromHash()', () => { + it.each([ + ['', '/', '/'], + ['#/', '/', '/'], + ['#/operations/a', '/', '/operations/a'], + ['#/operations/a?x=1#heading', '/', '/operations/a?x=1#heading'], + ['#main-content', '/', null], + ['#VPContent', '/', null], + ['', '/docs', '/'], + ['#/docs', '/docs', '/'], + ['#/docs/operations/a', '/docs', '/operations/a'], + ['#/DOCS/operations/a', 'docs/', '/operations/a'], + ['#/docs-old/operations/a', '/docs', null], + ['#/other', '/docs', null], + ])('maps %p under basePath %p to %p', (hash, basePath, expected) => { + expect(getRouterPathFromHash(hash, basePath)).toBe(expected); + }); +}); + +describe('withRouter() with HashRouterSync', () => { + const Page = withRouter(() => ); + + beforeEach(() => { + window.history.replaceState(null, '', '/'); + }); + + it('follows hashchange-only navigation when router is "hash"', () => { + render(); + + hostNavigate('/#/operations/b'); + + expect(routerLocation()).toBe('/operations/b'); + }); + + it('passes basePath through when router is "hash"', () => { + window.history.replaceState(null, '', '/#/docs'); + render(); + + hostNavigate('/#/docs/operations/b'); + + expect(routerLocation()).toBe('/operations/b'); + }); + + it('is not added for other router types', () => { + const addEventListener = jest.spyOn(window, 'addEventListener'); + + render(); + + expect(addEventListener).not.toHaveBeenCalledWith('hashchange', expect.any(Function)); + addEventListener.mockRestore(); + }); +}); diff --git a/packages/elements-core/src/components/HashRouterSync/index.tsx b/packages/elements-core/src/components/HashRouterSync/index.tsx new file mode 100644 index 000000000..f656842c9 --- /dev/null +++ b/packages/elements-core/src/components/HashRouterSync/index.tsx @@ -0,0 +1,76 @@ +import * as React from 'react'; +import { parsePath, useLocation, useNavigate } from 'react-router-dom'; + +type HashRouterSyncProps = { + /** The `basename` the surrounding `HashRouter` was created with. */ + basePath?: string; +}; + +/** + * Keeps a `HashRouter` in step with hash changes that are announced only by a `hashchange` event. + * + * React Router v6's hash history listens to `popstate` only. Browsers fire `popstate` for a real fragment + * navigation, but `history.pushState()` fires nothing. Host frameworks that intercept link clicks, such as + * VitePress, update the URL with `pushState()` and then dispatch a `hashchange` event. The router never sees + * that change, so the URL shows the new route while Elements keeps rendering the old one. The hash history + * of React Router v5 (Elements v8) also listened to `hashchange`, which is why v8 worked in those hosts. + * + * On `hashchange`, this component moves the router to the new hash, but only when the hash is a route of this + * router: `#/...` under `basePath`, or an empty hash for the root. Other fragments, such as a host page's skip + * link (`#main-content`), are left alone. It navigates with `replace` because the host already created the + * history entry. + */ +export const HashRouterSync = ({ basePath = '/' }: HashRouterSyncProps): null => { + const navigate = useNavigate(); + const location = useLocation(); + + // The listener is registered once and reads the latest router state from this ref. + const latest = React.useRef({ navigate, location }); + React.useLayoutEffect(() => { + latest.current = { navigate, location }; + }); + + React.useEffect(() => { + const onHashChange = () => { + const target = getRouterPathFromHash(window.location.hash, basePath); + if (target === null) return; + + const { navigate, location } = latest.current; + if (target === `${location.pathname}${location.search}${location.hash}`) return; + + navigate(target, { replace: true }); + }; + + window.addEventListener('hashchange', onHashChange); + return () => window.removeEventListener('hashchange', onHashChange); + }, [basePath]); + + return null; +}; + +/** + * Returns the router path (relative to `basePath`) that a URL hash points to, or `null` when the hash is not a + * route of a hash router mounted at `basePath`. Paths are parsed the same way React Router's hash history does. + */ +export const getRouterPathFromHash = (hash: string, basePath = '/'): string | null => { + if (hash === '' || hash === '#') return '/'; + if (!hash.startsWith('#/')) return null; + + const { pathname = '/', search = '', hash: innerHash = '' } = parsePath(hash.slice(1)); + const routerPathname = stripBasePath(pathname, basePath); + if (routerPathname === null) return null; + + return `${routerPathname}${search}${innerHash}`; +}; + +// Same rules as React Router's basename handling: case-insensitive and aligned to a path segment. +const stripBasePath = (pathname: string, basePath: string): string | null => { + const base = basePath.replace(/^\/*/, '/').replace(/\/+$/, ''); + if (base === '') return pathname; + if (!pathname.toLowerCase().startsWith(base.toLowerCase())) return null; + + const nextChar = pathname.charAt(base.length); + if (nextChar && nextChar !== '/') return null; + + return pathname.slice(base.length) || '/'; +}; diff --git a/packages/elements-core/src/hoc/withRouter.tsx b/packages/elements-core/src/hoc/withRouter.tsx index 7a8509a61..01077eb4c 100644 --- a/packages/elements-core/src/hoc/withRouter.tsx +++ b/packages/elements-core/src/hoc/withRouter.tsx @@ -2,6 +2,7 @@ import { DefaultComponentMapping } from '@stoplight/markdown-viewer'; import * as React from 'react'; import { Route, Routes, useInRouterContext } from 'react-router-dom'; +import { HashRouterSync } from '../components/HashRouterSync'; import { LinkHeading } from '../components/LinkHeading'; import { MarkdownComponentsProvider } from '../components/MarkdownViewer/CustomComponents/Provider'; import { ReactRouterMarkdownLink } from '../components/MarkdownViewer/CustomComponents/ReactRouterLink'; @@ -48,6 +49,7 @@ export function withRouter

( return ( + {routerType === 'hash' && }