Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
81 changes: 76 additions & 5 deletions src/core/event/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isMobile, mobileBreakpoint } from '../util/env.js';
import { noop } from '../util/core.js';
import * as dom from '../util/dom.js';
import { stripUrlExceptId } from '../router/util.js';

Expand All @@ -12,6 +13,7 @@ export function Events(Base) {
return class Events extends Base {
#intersectionObserver = new IntersectionObserver(() => {});
#isScrolling = false;
#cancelAnchorScroll = noop;
#title = dom.$.title;

// Initialization
Expand Down Expand Up @@ -374,11 +376,7 @@ export function Events(Base) {
);

if (headingElm) {
this.#watchNextScroll();
headingElm.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
this.#scrollToHeading(headingElm);
}
}
// User click/tap
Expand Down Expand Up @@ -606,6 +604,79 @@ export function Events(Base) {
}
}

/**
* Scroll an anchor target into view and keep it aligned while late-loading
* content above the target changes the page height.
*
* @param {Element} headingElm Heading element to scroll to
* @void
*/
#scrollToHeading(headingElm) {
this.#cancelAnchorScroll();

const contentElm = dom.find('.markdown-section');
const userEvents = ['keydown', 'mousedown', 'touchstart', 'wheel'];
/** @type {{ max?: ReturnType<typeof setTimeout>, settle?: ReturnType<typeof setTimeout> }} */
const timers = {};
let cancel = noop;

const removeUserListeners = () => {
userEvents.forEach(eventName => {
window.removeEventListener(eventName, cancel);
});
};

/** @param {ScrollBehavior} [behavior] */
const scrollToHeading = (behavior = 'smooth') => {
if (!document.contains(headingElm)) {
cancel();
return;
}

this.#watchNextScroll();
headingElm.scrollIntoView({
behavior,
block: 'start',
});
};
Comment thread
apples-kksk marked this conversation as resolved.
Outdated

const resync = () => {
scrollToHeading('instant');
clearTimeout(timers.settle);
timers.settle = setTimeout(cancel, 500);
};

scrollToHeading();

if (!contentElm || !('ResizeObserver' in window)) {
return;
}

const resizeObserver = new ResizeObserver(resync);

cancel = () => {
resizeObserver.disconnect();
clearTimeout(timers.settle);
clearTimeout(timers.max);
removeUserListeners();
window.removeEventListener('load', resync);
this.#cancelAnchorScroll = noop;
};

resizeObserver.observe(contentElm);
userEvents.forEach(eventName => {
window.addEventListener(eventName, cancel, {
once: true,
passive: true,
});
});
window.addEventListener('load', resync, { once: true });
timers.max = setTimeout(cancel, 3000);
requestAnimationFrame(() => requestAnimationFrame(resync));

Comment thread
apples-kksk marked this conversation as resolved.
Outdated
this.#cancelAnchorScroll = cancel;
}

/**
* Monitor next scroll start/end and set #isScrolling to true/false
* accordingly. Listeners are removed after the start/end events are fired.
Expand Down
74 changes: 74 additions & 0 deletions test/e2e/anchor-scroll.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import docsifyInit from '../helpers/docsify-init.js';
import { test, expect } from './fixtures/docsify-init-fixture.js';

test.describe('Anchor scrolling', () => {
test('keeps direct anchor targets aligned after images above them load', async ({
page,
}) => {
await page.route('**/slow-anchor-image.svg', async route => {
await new Promise(resolve => setTimeout(resolve, 250));
await route.fulfill({
contentType: 'image/svg+xml',
body: `
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="900">
<rect width="640" height="900" fill="#ddd" />
</svg>
`,
});
});

await docsifyInit({
testURL: '/docsify-init.html#/?id=target-section',
markdown: {
homepage: `
# Anchor Scroll

![Slow image](/slow-anchor-image.svg)

## Middle Section

This section should not stay at the top after the image loads.

## Target Section

This is the linked section.

Trailing content keeps the target scrollable.
`,
},
routes: {
'/docsify-init.html': `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
</body>
</html>
`,
},
style: `
.markdown-section img {
display: block;
width: 100%;
height: auto;
}

.markdown-section {
padding-bottom: 1200px;
}
`,
styleURLs: ['/dist/themes/core.css'],
});

await expect
.poll(async () => {
return page.locator('#target-section').evaluate(el => {
return el.getBoundingClientRect().top;
});
})
.toBeLessThan(80);
Comment thread
apples-kksk marked this conversation as resolved.
Outdated
});
});
Loading