From 3a19c02e340094737a370d71d276dd713cfdcd36 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Tue, 12 Oct 2021 23:12:47 -0700 Subject: [PATCH] fix: In page anchor links not working on shared docs closes #2652 --- app/components/Editor.js | 4 ++-- app/utils/urls.js | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/app/components/Editor.js b/app/components/Editor.js index eb9480940..d31f57133 100644 --- a/app/components/Editor.js +++ b/app/components/Editor.js @@ -15,7 +15,7 @@ import useToasts from "hooks/useToasts"; import { type Theme } from "types"; import { isModKey } from "utils/keyboard"; import { uploadFile } from "utils/uploadFile"; -import { isInternalUrl } from "utils/urls"; +import { isInternalUrl, isHash } from "utils/urls"; const RichMarkdownEditor = React.lazy(() => import(/* webpackChunkName: "rich-markdown-editor" */ "rich-markdown-editor") @@ -78,7 +78,7 @@ function Editor(props: PropsWithRef) { const onClickLink = React.useCallback( (href: string, event: MouseEvent) => { // on page hash - if (href[0] === "#") { + if (isHash(href)) { window.location.href = href; return; } diff --git a/app/utils/urls.js b/app/utils/urls.js index 7e19f3df7..b13bc2996 100644 --- a/app/utils/urls.js +++ b/app/utils/urls.js @@ -20,6 +20,27 @@ export function isInternalUrl(href: string) { return false; } +export function isHash(href: string) { + if (href[0] === "#") return true; + + try { + const outline = new URL(window.location.href); + const parsed = new URL(href); + + if ( + outline.hostname === parsed.hostname && + outline.pathname === parsed.pathname && + !!parsed.hash + ) { + return true; + } + } catch (e) { + // failed to parse as url + } + + return false; +} + export function decodeURIComponentSafe(text: string) { return text ? decodeURIComponent(text.replace(/%(?![0-9][0-9a-fA-F]+)/g, "%25"))