Header IDs, smooth scrolling, smaller code font

This commit is contained in:
Aaron Carlino 2019-11-19 17:03:40 +13:00
parent 181fef9e99
commit 04eefa3e37
3 changed files with 52 additions and 8 deletions

View File

@ -12,4 +12,26 @@ if (typeof window !== "undefined") {
exports.wrapPageElement = ({ element, props }) => {
return <Layout {...props}>{element}</Layout>
};
};
exports.onRouteUpdate = ({location}) => {
anchorScroll(location);
return true;
};
exports.shouldUpdateScroll = ({
routerProps: { location },
}) => {
anchorScroll(location);
return true;
}
const anchorScroll = location => {
// Check for location so build does not fail
if (location && location.hash) {
setTimeout(() => {
const item = document.querySelector(`${location.hash}`).offsetTop;
const mainNavHeight = document.querySelector(`header`).offsetHeight;
window.scrollTo({top: item - mainNavHeight, left: 0, behavior: 'smooth'});
}, 0);
}
}

View File

@ -205,6 +205,10 @@ h1, h2, h3 {
}
}
code[class*="language-"], pre[class*="language-"] {
font-size: 0.8rem;
}
:not(pre) > code[class*="language-"] {
background: #f5f6f8;
color: #5d6778;

View File

@ -1,6 +1,16 @@
import { createElement, ReactElement } from "react";
import { DomElement } from 'html-react-parser';
const generateID = (title: string): string => {
return title
.replace('&amp;', '-and-')
.replace('&', '-and-')
.replace(/[^A-Za-z0-9]/g, '-')
.replace(/-+/g, '-')
.replace(/^-/g, '')
.replace(/-$/g, '')
.toLowerCase();
}
/**
* If a header has a {#explicit-id}, add it as an attribute
* @param domNode
@ -13,18 +23,26 @@ const rewriteHeaders = (domNode: DomElement): ReactElement | false => {
if (firstChild && firstChild.type === 'text') {
const { data } = firstChild;
const matches = data.match(/^(.*?){#([A-Za-z0-9_-]+)\}$/);
let header;
let id;
if (matches) {
const header = matches[1]
const id = matches[2];
return createElement(
domNode.name,
{ id },
header
);
header = matches[1];
id = matches[2];
} else {
header = data;
id = generateID(data);
}
return createElement(
domNode.name,
{ id },
header
);
}
return false;
}
export default rewriteHeaders;