diff --git a/gatsby-browser.js b/gatsby-browser.js index a0ac90f..9306848 100644 --- a/gatsby-browser.js +++ b/gatsby-browser.js @@ -12,4 +12,26 @@ if (typeof window !== "undefined") { exports.wrapPageElement = ({ element, props }) => { return {element} -}; \ No newline at end of file +}; + +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); + } +} \ No newline at end of file diff --git a/src/theme/assets/scss/ss-docs.scss b/src/theme/assets/scss/ss-docs.scss index f6604e1..f3ba1a4 100644 --- a/src/theme/assets/scss/ss-docs.scss +++ b/src/theme/assets/scss/ss-docs.scss @@ -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; diff --git a/src/utils/rewriteHeader.ts b/src/utils/rewriteHeader.ts index 5c143b4..b9e7a5e 100644 --- a/src/utils/rewriteHeader.ts +++ b/src/utils/rewriteHeader.ts @@ -1,6 +1,16 @@ import { createElement, ReactElement } from "react"; import { DomElement } from 'html-react-parser'; +const generateID = (title: string): string => { + return title + .replace('&', '-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; \ No newline at end of file