Skip to content

Commit

Permalink
feat: optimize header-anchor scroll
Browse files Browse the repository at this point in the history
  • Loading branch information
sanyuan0704 committed Sep 7, 2022
1 parent 81a4869 commit 6e87cd2
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 5 deletions.
1 change: 1 addition & 0 deletions src/client/app/client-entry.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { hydrateRoot, createRoot } from 'react-dom/client';
import React, { createElement } from 'react';
import { BrowserRouter } from 'react-router-dom';
import './sideEffects';

async function renderInBrowser() {
const containerEl = document.getElementById('root');
Expand Down
5 changes: 0 additions & 5 deletions src/client/app/sideEffect.ts

This file was deleted.

79 changes: 79 additions & 0 deletions src/client/app/sideEffects.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { inBrowser } from './utils';

const DEFAULT_NAV_HEIGHT = 72;

if (inBrowser) {
function scrollTo(el: HTMLElement, hash: string, smooth = false) {
let target: HTMLElement | null = null;

try {
target = el.classList.contains('header-anchor')
? el
: document.querySelector(decodeURIComponent(hash));
} catch (e) {
console.warn(e);
}

if (target) {
const targetPadding = parseInt(
window.getComputedStyle(target).paddingTop,
10
);
const targetTop =
window.scrollY +
target.getBoundingClientRect().top -
DEFAULT_NAV_HEIGHT +
targetPadding;

window.scrollTo({
left: 0,
top: targetTop,
behavior: 'smooth'
});
}
}

window.addEventListener(
'click',
(e) => {
// Only handle a tag click
const link = (e.target as Element).closest('a');
if (link) {
const { origin, pathname, hash, search, target } = link;
const currentUrl = window.location;
const extMatch = pathname.match(/\.\w+$/);
// only intercept inbound links
if (
!e.ctrlKey &&
!e.shiftKey &&
!e.altKey &&
!e.metaKey &&
target !== `_blank` &&
origin === currentUrl.origin &&
// don't intercept if non-html extension is present
!(extMatch && extMatch[0] !== '.html')
) {
e.preventDefault();
if (
pathname === currentUrl.pathname &&
search === currentUrl.search
) {
// scroll between hash anchors in the same page
if (hash && hash !== currentUrl.hash) {
history.pushState(null, '', hash);
// still emit the event so we can listen to it in themes
window.dispatchEvent(new Event('hashchange'));
// use smooth scroll when clicking on header anchor links
scrollTo(link, hash, link.classList.contains('header-anchor'));
}
}
}
}
},
{ capture: true }
);

window.addEventListener('hashchange', (e) => {
e.preventDefault();
});
}
1 change: 1 addition & 0 deletions src/client/app/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const inBrowser = typeof window !== undefined;

0 comments on commit 6e87cd2

Please sign in to comment.