Fix scroll for ALL modals

main
Ashelyn Dawn 4 years ago
parent 2d1d3ed773
commit 952e3cba4e

@ -5,10 +5,12 @@ import Inventory from '../Modals/Inventory'
import Options from '../Modals/Options'
import Help from '../Modals/Help'
import Map from '../Modals/Map'
import useSyncScroll from '../../hooks/useSyncScroll'
export default function ({containerRef}) {
const scrollRef = useRef()
const [currentMenu, setCurrentMenu] = useSharedState('currentMenu')
useSyncScroll(scrollRef, 'modalScroll', [currentMenu])
function handleButton(name) {
return ev => setCurrentMenu(current => {

@ -1,34 +1,9 @@
import React, { useEffect, useContext } from 'react'
import {ScreenContext} from '../Screen/Screen'
import React from 'react'
import styles from './Help.module.css'
import useSharedState from '../../hooks/useSharedState'
export default function Help({parentRef}) {
const [scroll, setScroll] = useSharedState('helpScroll', 0)
const whichScreen = useContext(ScreenContext)
// Update to top
useEffect(() => setScroll(0), [])
// Update shared state on scroll
useEffect(() => {
if(!parentRef.current) return;
if(whichScreen === 'secondary') return;
function updateScroll(ev){
setScroll(ev.target.scrollTop)
}
parentRef.current.addEventListener('scroll', updateScroll)
return () => parentRef.current.removeEventListener('scroll', updateScroll)
}, [parentRef])
// On shared state change, set scrollTop
useEffect(() => {
if(whichScreen !== 'primary' && parentRef.current)
parentRef.current.scrollTop = scroll
}, [scroll, parentRef])
// useSyncScroll(parentRef, 'helpScroll')
return <>
<h3>How do I play?</h3>

@ -0,0 +1,34 @@
import { useEffect, useContext } from 'react'
import {ScreenContext} from '../components/Screen/Screen'
import useSharedState from './useSharedState'
export default function useSyncScroll(ref, key, deps = []) {
const [scroll, setScroll] = useSharedState(key, 0)
const whichScreen = useContext(ScreenContext)
// Update to top
useEffect(() => setScroll(0), []) // eslint-disable-line react-hooks/exhaustive-deps
// Update shared state on scroll
useEffect(() => {
if(!ref.current) return;
if(whichScreen === 'secondary') return;
function updateScroll(ev){
setScroll(ev.target.scrollTop)
}
const parent = ref.current
parent.addEventListener('scroll', updateScroll)
return () => parent?.removeEventListener('scroll', updateScroll)
}, [ref, ...deps]) // eslint-disable-line react-hooks/exhaustive-deps
// On shared state change, set scrollTop
useEffect(() => {
if(whichScreen !== 'primary' && ref.current)
ref.current.scrollTop = scroll
}, [scroll, ref, ...deps]) // eslint-disable-line react-hooks/exhaustive-deps
}
Loading…
Cancel
Save