1
0
mirror of https://github.com/kremalicious/portfolio.git synced 2024-06-23 01:36:39 +02:00
portfolio/src/components/molecules/ProjectNav.jsx

106 lines
2.5 KiB
React
Raw Normal View History

2018-11-25 01:52:31 +01:00
import React, { PureComponent } from 'react'
2018-04-16 22:32:30 +02:00
import PropTypes from 'prop-types'
2018-06-22 18:54:29 +02:00
import { Link, graphql, StaticQuery } from 'gatsby'
2019-11-25 13:46:44 +01:00
import shortid from 'shortid'
2020-03-07 03:11:52 +01:00
import ProjectImage from '../atoms/ProjectImage'
2021-03-12 23:47:28 +01:00
import { item, link, title, projectNav } from './ProjectNav.module.css'
2018-04-16 22:32:30 +02:00
const query = graphql`
query {
allProjectsYaml {
edges {
node {
title
slug
img {
childImageSharp {
fluid(maxWidth: 500, quality: 85) {
...GatsbyImageSharpFluid_noBase64
}
}
}
}
}
}
}
`
2019-11-25 13:46:44 +01:00
const Project = ({ node, refCurrentItem }) => (
2021-03-12 23:47:28 +01:00
<div className={item} ref={refCurrentItem}>
<Link className={link} to={node.slug}>
<ProjectImage fluid={node.img.childImageSharp.fluid} alt={node.title} />
<h1 className={title}>{node.title}</h1>
2019-11-25 13:46:44 +01:00
</Link>
</div>
)
Project.propTypes = {
node: PropTypes.any.isRequired,
refCurrentItem: PropTypes.any
}
2018-11-25 01:52:31 +01:00
export default class ProjectNav extends PureComponent {
static propTypes = {
currentSlug: PropTypes.string.isRequired
}
2018-09-06 14:28:01 +02:00
state = {
scrollLeftPosition: 0
}
scrollContainer = React.createRef()
currentItem = React.createRef()
componentDidMount() {
this.scrollToCurrent()
}
componentDidUpdate() {
this.scrollToCurrent()
2018-06-23 16:31:08 +02:00
}
scrollToCurrent = () => {
const scrollContainer = this.scrollContainer.current
const activeItem = this.currentItem.current
const scrollRect = scrollContainer.getBoundingClientRect()
2019-11-25 13:46:44 +01:00
const activeRect = activeItem && activeItem.getBoundingClientRect()
const scrollLeftPosition =
2019-11-25 13:46:44 +01:00
activeRect &&
activeRect.left -
2019-11-25 13:46:44 +01:00
scrollRect.left -
scrollRect.width / 2 +
activeRect.width / 2
scrollContainer.scrollLeft += this.state.scrollLeftPosition
2019-03-29 23:43:40 +01:00
this.setState({ scrollLeftPosition })
}
render() {
const { currentSlug } = this.props
return (
<StaticQuery
query={query}
2020-03-21 23:55:40 +01:00
render={(data) => {
2018-06-22 18:54:29 +02:00
const projects = data.allProjectsYaml.edges
2018-06-12 11:16:17 +02:00
return (
2021-03-12 23:47:28 +01:00
<nav className={projectNav} ref={this.scrollContainer}>
2019-03-29 23:43:40 +01:00
{projects.map(({ node }) => {
const isCurrent = node.slug === currentSlug
return (
2019-11-25 13:46:44 +01:00
<Project
key={shortid.generate()}
2019-03-29 23:43:40 +01:00
node={node}
refCurrentItem={isCurrent ? this.currentItem : null}
/>
)
})}
2018-10-17 20:26:08 +02:00
</nav>
2018-06-12 11:16:17 +02:00
)
2018-06-22 18:54:29 +02:00
}}
/>
)
}
}