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
64 changes: 64 additions & 0 deletions .storybook/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,69 @@ const withExplicitFullscreenStoryCanvas = (Story, context) => {
return React.createElement(Story);
};

const shouldBlockStorybookLinkNavigation = (anchor) => {
const href = anchor.getAttribute('href');

if (!href) {
return false;
}

if (href.startsWith('#') || href.startsWith('mailto:') || href.startsWith('tel:')) {
return false;
}

return true;
};

/**
* Prevent links rendered inside stories from navigating away from Storybook.
*
* @type {(Story: any, context: any) => import('react').ReactElement}
*/
const withStorybookLinkNavigationGuard = (Story, context) => {
React.useEffect(() => {
if (context.viewMode !== 'story' && context.viewMode !== 'docs') {
return undefined;
}

const handleAnchorClick = (event) => {
if (
event.defaultPrevented ||
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}

const target = event.target;
if (!(target instanceof Element)) {
return;
}

const anchor = target.closest('a[href]');
if (!(anchor instanceof HTMLAnchorElement)) {
return;
}

if (!shouldBlockStorybookLinkNavigation(anchor)) {
return;
}

event.preventDefault();
};

document.addEventListener('click', handleAnchorClick, true);
return () => {
document.removeEventListener('click', handleAnchorClick, true);
};
}, [context.id, context.viewMode]);

return React.createElement(Story);
};

export const globalTypes = {
responsivePreview: {
name: 'Responsive preview',
Expand All @@ -338,6 +401,7 @@ export const initialGlobals = {
export const decorators = [
renderResponsivePreviews,
withExplicitFullscreenStoryCanvas,
withStorybookLinkNavigationGuard,
];

export const preview = {
Expand Down
6 changes: 5 additions & 1 deletion src/components/Link/link.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { BrowserRouter } from 'react-router';
import { expect, within } from 'storybook/test';
import { expect, userEvent, within } from 'storybook/test';
import { Heading, Link, List, ListLink } from '~/src/index';

const meta: Meta<typeof Link> = {
Expand Down Expand Up @@ -36,6 +36,10 @@ export const Standalone: Story = {
const canvas = within(canvasElement);
const link = canvas.getByRole('link', { name: /standalone link/i });
await expect(link).toHaveAttribute('href', '/#');

const initialHref = globalThis.location.href;
await userEvent.click(link);
await expect(globalThis.location.href).toBe(initialHref);
},
};

Expand Down