Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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 <div data-testid="router-location">{`${pathname}${search}${hash}`}</div>;
};

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(
<HashRouter>
<LocationProbe />
</HashRouter>,
);

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(
<HashRouter>
<HashRouterSync />
<LocationProbe />
</HashRouter>,
);

hostNavigate('/#/operations/b');

expect(routerLocation()).toBe('/operations/b');
});

it('keeps the history entry created by the host instead of adding another one', () => {
render(
<HashRouter>
<HashRouterSync />
<LocationProbe />
</HashRouter>,
);
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(
<HashRouter>
<HashRouterSync />
<LocationProbe />
</HashRouter>,
);

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(
<HashRouter>
<HashRouterSync />
<LocationProbe />
</HashRouter>,
);
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(
<HashRouter>
<HashRouterSync />
<LocationProbe />
</HashRouter>,
);
hostNavigate('/#/operations/a');

hostNavigate('/');

expect(routerLocation()).toBe('/');
});

it('does not navigate again when the router already followed a popstate', () => {
render(
<HashRouter>
<HashRouterSync />
<LocationProbe />
</HashRouter>,
);
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(
<HashRouter basename="/docs">
<HashRouterSync basePath="/docs" />
<LocationProbe />
</HashRouter>,
);

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(
<HashRouter basename="/docs">
<HashRouterSync basePath="/docs" />
<LocationProbe />
</HashRouter>,
);

hostNavigate('/#/other/page');

expect(routerLocation()).toBe('/operations/a');
});

it('stops listening when unmounted', () => {
const { unmount } = render(
<HashRouter>
<HashRouterSync />
<LocationProbe />
</HashRouter>,
);
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(() => <LocationProbe />);

beforeEach(() => {
window.history.replaceState(null, '', '/');
});

it('follows hashchange-only navigation when router is "hash"', () => {
render(<Page router="hash" />);

hostNavigate('/#/operations/b');

expect(routerLocation()).toBe('/operations/b');
});

it('passes basePath through when router is "hash"', () => {
window.history.replaceState(null, '', '/#/docs');
render(<Page router="hash" basePath="/docs" />);

hostNavigate('/#/docs/operations/b');

expect(routerLocation()).toBe('/operations/b');
});

it('is not added for other router types', () => {
const addEventListener = jest.spyOn(window, 'addEventListener');

render(<Page router="memory" />);

expect(addEventListener).not.toHaveBeenCalledWith('hashchange', expect.any(Function));
addEventListener.mockRestore();
});
});
76 changes: 76 additions & 0 deletions packages/elements-core/src/components/HashRouterSync/index.tsx
Original file line number Diff line number Diff line change
@@ -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) || '/';
};
2 changes: 2 additions & 0 deletions packages/elements-core/src/hoc/withRouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -48,6 +49,7 @@ export function withRouter<P extends RoutingProps>(
return (
<RouterTypeContext.Provider value={routerType}>
<Router {...routerProps} key={basePath}>
{routerType === 'hash' && <HashRouterSync basePath={basePath} />}
<InternalRoutes>
<WrappedComponent {...props} outerRouter={false} />
</InternalRoutes>
Expand Down