Skip to content

Commit 867dea0

Browse files
authored
Fix same page anchor links (#944)
* Fix same page anchor links * Add smooth scroll * fmt
1 parent 02f8cbb commit 867dea0

File tree

4 files changed

+24
-3
lines changed

4 files changed

+24
-3
lines changed

src/Elastic.Markdown/Assets/main.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { openDetailsWithAnchor } from './open-details-with-anchor'
1111
import { $, $$ } from 'select-dom'
1212

1313
import { UAParser } from 'ua-parser-js'
14+
import { initSmoothScroll } from './smooth-scroll'
1415
const { getOS } = new UAParser()
1516

1617
document.addEventListener('htmx:load', function () {
@@ -19,6 +20,7 @@ document.addEventListener('htmx:load', function () {
1920
initCopyButton()
2021
initTabs()
2122
initNav()
23+
initSmoothScroll()
2224
openDetailsWithAnchor()
2325
})
2426

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { $$ } from 'select-dom'
2+
3+
export function initSmoothScroll() {
4+
$$('#markdown-content a[href^="#"]').forEach((el) => {
5+
el.addEventListener('click', (e) => {
6+
const target = document.getElementById(
7+
el.getAttribute('href').slice(1)
8+
)
9+
if (target) {
10+
e.preventDefault()
11+
target.scrollIntoView({ behavior: 'smooth' })
12+
history.pushState(null, '', el.getAttribute('href'))
13+
}
14+
})
15+
})
16+
}

src/Elastic.Markdown/Assets/toc-nav.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,9 +134,9 @@ function setupSmoothScrolling(elements: TocElements) {
134134
link.addEventListener('click', (e) => {
135135
const href = link.getAttribute('href')
136136
if (href?.charAt(0) === '#') {
137-
e.preventDefault()
138137
const target = document.getElementById(href.slice(1))
139138
if (target) {
139+
e.preventDefault()
140140
target.scrollIntoView({ behavior: 'smooth' })
141141
history.pushState(null, '', href)
142142
}

src/Elastic.Markdown/Myst/InlineParsers/DiagnosticLinkInlineParser.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,8 +357,11 @@ private static void UpdateLinkUrl(LinkInline link, MarkdownFile? linkMarkdown, s
357357
if (newUrl.EndsWith(".toml"))
358358
newUrl = url[..^5];
359359

360-
link.Url = string.IsNullOrEmpty(anchor) ? newUrl : $"{newUrl}#{anchor}";
361-
360+
link.Url = !string.IsNullOrEmpty(anchor)
361+
? newUrl == context.CurrentUrlPath
362+
? $"#{anchor}"
363+
: $"{newUrl}#{anchor}"
364+
: newUrl;
362365
}
363366

364367
private static bool IsCrossLink([NotNullWhen(true)] Uri? uri) =>

0 commit comments

Comments
 (0)