diff --git a/src/Elastic.Markdown/Assets/main.ts b/src/Elastic.Markdown/Assets/main.ts index 81defa7a3..b65740208 100644 --- a/src/Elastic.Markdown/Assets/main.ts +++ b/src/Elastic.Markdown/Assets/main.ts @@ -11,6 +11,7 @@ import { openDetailsWithAnchor } from './open-details-with-anchor' import { $, $$ } from 'select-dom' import { UAParser } from 'ua-parser-js' +import { initSmoothScroll } from './smooth-scroll' const { getOS } = new UAParser() document.addEventListener('htmx:load', function () { @@ -19,6 +20,7 @@ document.addEventListener('htmx:load', function () { initCopyButton() initTabs() initNav() + initSmoothScroll() openDetailsWithAnchor() }) diff --git a/src/Elastic.Markdown/Assets/smooth-scroll.ts b/src/Elastic.Markdown/Assets/smooth-scroll.ts new file mode 100644 index 000000000..929501f8e --- /dev/null +++ b/src/Elastic.Markdown/Assets/smooth-scroll.ts @@ -0,0 +1,16 @@ +import { $$ } from 'select-dom' + +export function initSmoothScroll() { + $$('#markdown-content a[href^="#"]').forEach((el) => { + el.addEventListener('click', (e) => { + const target = document.getElementById( + el.getAttribute('href').slice(1) + ) + if (target) { + e.preventDefault() + target.scrollIntoView({ behavior: 'smooth' }) + history.pushState(null, '', el.getAttribute('href')) + } + }) + }) +} diff --git a/src/Elastic.Markdown/Assets/toc-nav.ts b/src/Elastic.Markdown/Assets/toc-nav.ts index bd3aa6cb1..7067a5e2c 100644 --- a/src/Elastic.Markdown/Assets/toc-nav.ts +++ b/src/Elastic.Markdown/Assets/toc-nav.ts @@ -134,9 +134,9 @@ function setupSmoothScrolling(elements: TocElements) { link.addEventListener('click', (e) => { const href = link.getAttribute('href') if (href?.charAt(0) === '#') { - e.preventDefault() const target = document.getElementById(href.slice(1)) if (target) { + e.preventDefault() target.scrollIntoView({ behavior: 'smooth' }) history.pushState(null, '', href) } diff --git a/src/Elastic.Markdown/Myst/InlineParsers/DiagnosticLinkInlineParser.cs b/src/Elastic.Markdown/Myst/InlineParsers/DiagnosticLinkInlineParser.cs index 0a5208a26..6e7ee5c19 100644 --- a/src/Elastic.Markdown/Myst/InlineParsers/DiagnosticLinkInlineParser.cs +++ b/src/Elastic.Markdown/Myst/InlineParsers/DiagnosticLinkInlineParser.cs @@ -357,8 +357,11 @@ private static void UpdateLinkUrl(LinkInline link, MarkdownFile? linkMarkdown, s if (newUrl.EndsWith(".toml")) newUrl = url[..^5]; - link.Url = string.IsNullOrEmpty(anchor) ? newUrl : $"{newUrl}#{anchor}"; - + link.Url = !string.IsNullOrEmpty(anchor) + ? newUrl == context.CurrentUrlPath + ? $"#{anchor}" + : $"{newUrl}#{anchor}" + : newUrl; } private static bool IsCrossLink([NotNullWhen(true)] Uri? uri) =>