1
0
mirror of https://github.com/oceanprotocol/docs.git synced 2024-06-29 00:58:02 +02:00

smooth scrolling for everyone

This commit is contained in:
Matthias Kretschmann 2019-01-28 15:12:12 +01:00
parent 5fc4bec0f3
commit ffee29e8db
Signed by: m
GPG Key ID: 606EEEF3C479A91F
4 changed files with 89 additions and 7 deletions

View File

@ -63,6 +63,7 @@
"remark": "^10.0.1",
"remark-react": "^5.0.0",
"slugify": "^1.3.4",
"smoothscroll-polyfill": "^0.4.3",
"swagger-client": "^3.8.22"
},
"devDependencies": {

View File

@ -11,7 +11,6 @@
html {
font-size: $font-size-root;
scroll-behavior: smooth;
}
body {

View File

@ -2,6 +2,7 @@ import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import slugify from 'slugify'
import Scrollspy from 'react-scrollspy'
import TocScroll from './TocScroll'
import { filterByKindOfProperty } from './utils'
import stylesSidebar from '../../components/Sidebar.module.scss'
@ -18,12 +19,14 @@ export default class Toc extends PureComponent {
return (
<li key={name}>
<a
data-deprecated={!!deprecation}
href={`#${parentName}-${slugify(name)}`}
<TocScroll
type="id"
element={`${parentName}-${slugify(name)}`}
deprecation={!!deprecation}
offset={-20}
>
<code>{name}</code>
</a>
</TocScroll>
</li>
)
})
@ -40,9 +43,9 @@ export default class Toc extends PureComponent {
return (
<li key={name}>
<a href={`#${slugify(name)}`}>
<TocScroll type="id" element={`${slugify(name)}`} offset={-20}>
<code>{name}</code>
</a>
</TocScroll>
<Scrollspy
items={subIds[0]}
currentClassName={stylesSidebar.scrollspyActive}

View File

@ -0,0 +1,79 @@
import smoothscroll from 'smoothscroll-polyfill'
import React from 'react'
import PropTypes from 'prop-types'
export default class TocScroll extends React.Component {
static propTypes = {
type: PropTypes.string,
element: PropTypes.string,
offset: PropTypes.number,
timeout: PropTypes.number,
children: PropTypes.node.isRequired,
deprecation: PropTypes.bool
}
componentDidMount() {
smoothscroll.polyfill()
}
handleClick = e => {
e.preventDefault()
let elem = 0
let scroll = true
const { type, element, offset, timeout } = this.props
if (type && element) {
switch (type) {
case 'class':
// eslint-disable-next-line prefer-destructuring
elem = document.getElementsByClassName(element)[0]
scroll = !!elem
break
case 'id':
elem = document.getElementById(element)
scroll = !!elem
break
default:
}
}
scroll
? this.scrollTo(elem, offset, timeout)
: console.log(`Element not found: ${element}`) // eslint-disable-line
}
scrollTo(element, offSet = 0, timeout = null) {
const elemPos = element
? element.getBoundingClientRect().top + window.pageYOffset
: 0
if (timeout) {
setTimeout(() => {
window.scroll({
top: elemPos + offSet,
left: 0,
behavior: 'smooth'
})
}, timeout)
} else {
window.scroll({
top: elemPos + offSet,
left: 0,
behavior: 'smooth'
})
}
}
render() {
return (
<a
onClick={this.handleClick}
href={`#${this.props.element}`}
data-deprecated={!!this.props.deprecation}
>
{this.props.children}
</a>
)
}
}