|
| 1 | +const React = require(`react`); |
| 2 | + |
| 3 | +const pluginDefaults = { |
| 4 | + className: `anchor`, |
| 5 | + icon: true, |
| 6 | + offsetY: 0, |
| 7 | +}; |
| 8 | + |
| 9 | +exports.onRenderBody = ({setHeadComponents}, pluginOptions) => { |
| 10 | + const {className, icon, offsetY} = Object.assign( |
| 11 | + pluginDefaults, |
| 12 | + pluginOptions, |
| 13 | + ); |
| 14 | + |
| 15 | + const styles = ` |
| 16 | + .${className} { |
| 17 | + float: left; |
| 18 | + padding-right: 4px; |
| 19 | + margin-left: -20px; |
| 20 | + } |
| 21 | + h1 .${className} svg, |
| 22 | + h2 .${className} svg, |
| 23 | + h3 .${className} svg, |
| 24 | + h4 .${className} svg, |
| 25 | + h5 .${className} svg, |
| 26 | + h6 .${className} svg { |
| 27 | + visibility: hidden; |
| 28 | + } |
| 29 | + h1:hover .${className} svg, |
| 30 | + h2:hover .${className} svg, |
| 31 | + h3:hover .${className} svg, |
| 32 | + h4:hover .${className} svg, |
| 33 | + h5:hover .${className} svg, |
| 34 | + h6:hover .${className} svg, |
| 35 | + h1 .${className}:focus svg, |
| 36 | + h2 .${className}:focus svg, |
| 37 | + h3 .${className}:focus svg, |
| 38 | + h4 .${className}:focus svg, |
| 39 | + h5 .${className}:focus svg, |
| 40 | + h6 .${className}:focus svg { |
| 41 | + visibility: visible; |
| 42 | + } |
| 43 | + `; |
| 44 | + |
| 45 | + const script = ` |
| 46 | + document.addEventListener("DOMContentLoaded", function(event) { |
| 47 | + var hash = window.decodeURI(location.hash.replace('#', '')) |
| 48 | + if (hash !== '') { |
| 49 | + var element = document.getElementById(hash) |
| 50 | + if (element) { |
| 51 | + var offset = element.offsetTop |
| 52 | + // Wait for the browser to finish rendering before scrolling. |
| 53 | + setTimeout((function() { |
| 54 | + window.scrollTo(0, offset - ${offsetY}) |
| 55 | + }), 0) |
| 56 | + } |
| 57 | + } |
| 58 | + }) |
| 59 | + `; |
| 60 | + |
| 61 | + const style = icon ? ( |
| 62 | + <style key="gatsby-remark-header-custom-ids-style" type="text/css"> |
| 63 | + {styles} |
| 64 | + </style> |
| 65 | + ) : ( |
| 66 | + undefined |
| 67 | + ); |
| 68 | + |
| 69 | + return setHeadComponents([ |
| 70 | + style, |
| 71 | + <script |
| 72 | + key="gatsby-remark-header-custom-ids-script" |
| 73 | + dangerouslySetInnerHTML={{__html: script}} |
| 74 | + />, |
| 75 | + ]); |
| 76 | +}; |
0 commit comments