From 5c6e6af5c674ef57f22bbd8f74364a2e50128f8c Mon Sep 17 00:00:00 2001 From: Jeppe Reinhold Date: Fri, 19 Apr 2024 15:05:32 +0200 Subject: [PATCH] Merge pull request #26488 from storybookjs/jeppe/allow-http-docs-external-links MDX: Don't transform `http://` links (cherry picked from commit c12ae69ff1e08d74e66bbd226cce744670b8db92) --- code/ui/blocks/src/blocks/mdx.tsx | 72 +++++++++++++++---------------- 1 file changed, 35 insertions(+), 37 deletions(-) diff --git a/code/ui/blocks/src/blocks/mdx.tsx b/code/ui/blocks/src/blocks/mdx.tsx index 453f5c9ff8ed..fe9c8c24f5c9 100644 --- a/code/ui/blocks/src/blocks/mdx.tsx +++ b/code/ui/blocks/src/blocks/mdx.tsx @@ -96,45 +96,43 @@ export const AnchorMdx: FC> = (props) => { const { href, target, children, ...rest } = props; const context = useContext(DocsContext); - if (href) { - // Enable scrolling for in-page anchors. - if (href.startsWith('#')) { - return {children}; - } - - // Links to other pages of SB should use the base URL of the top level iframe instead of the base URL of the preview iframe. - if (target !== '_blank' && !href.startsWith('https://')) { - return ( - ) => { - // Cmd/Ctrl/Shift/Alt + Click should trigger default browser behaviour. Same applies to non-left clicks - const LEFT_BUTTON = 0; - const isLeftClick = - event.button === LEFT_BUTTON && - !event.altKey && - !event.ctrlKey && - !event.metaKey && - !event.shiftKey; - - if (isLeftClick) { - event.preventDefault(); - // use the A element's href, which has been modified for - // local paths without a `?path=` query param prefix - navigate(context, event.currentTarget.getAttribute('href')); - } - }} - target={target} - {...rest} - > - {children} - - ); - } + // links to external locations don't need any modifications. + if (!href || target === '_blank' || /^https?:\/\//.test(href)) { + return ; } - // External URL dont need any modification. - return ; + // Enable scrolling for in-page anchors. + if (href.startsWith('#')) { + return {children}; + } + + // Links to other pages of SB should use the base URL of the top level iframe instead of the base URL of the preview iframe. + return ( + ) => { + // Cmd/Ctrl/Shift/Alt + Click should trigger default browser behaviour. Same applies to non-left clicks + const LEFT_BUTTON = 0; + const isLeftClick = + event.button === LEFT_BUTTON && + !event.altKey && + !event.ctrlKey && + !event.metaKey && + !event.shiftKey; + + if (isLeftClick) { + event.preventDefault(); + // use the A element's href, which has been modified for + // local paths without a `?path=` query param prefix + navigate(context, event.currentTarget.getAttribute('href')); + } + }} + target={target} + {...rest} + > + {children} + + ); }; const SUPPORTED_MDX_HEADERS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;