import React from 'react' ; import { HashURLs } from "polar-shared/src/util/HashURLs" ; import { IDStr } from "polar-shared/src/util/Strings" ; import { IListenable } from './UseLocationChangeHook' ; import { useLocationChangeStore } from './UseLocationChangeStore' ; import { useHistory , useLocation } from 'react-router-dom' ; import { Optional } from 'polar-shared/src/util/ts/Optional' ; export function scrollIntoView ( scrollTarget , ref ) { const alignToTop = scrollTarget . pos === 'top' ; ref . scrollIntoView ( alignToTop ) ; } export function useScrollIntoViewUsingLocation ( ) { const [ scrollTargetElem , setScrollTargetElem ] = React . useState < HTMLElement | null > ( null ) ; const { initialScrollLoader } = useLocationChangeStore ( [ 'initialScrollLoader' ] ) ; const scrollTarget = useScrollTarget ( ) ; React . useEffect ( ( ) => { if ( scrollTarget && scrollTargetElem ) { initialScrollLoader ( scrollTarget , scrollTargetElem ) ; } } , [ scrollTarget , scrollTargetElem , initialScrollLoader ] ) ; return ( newRef ) => { if ( scrollTargetElem !== newRef ) { setScrollTargetElem ( newRef ) ; } } ; } export interface IScrollTarget { readonly target : IDStr ; readonly pos : 'top' | 'bottom' ; /**
     * The iteration code so we can re-jump if a user clicks two times on the
     * same position.
     */ readonly n : string ; /**
     * Add some scroll buffer so that we scroll a bit more to better highlight
     * the item we scrolled to.
     */ readonly b : number ; } export namespace ScrollTargets { import QueryOrLocation = HashURLs . QueryOrLocation ; export function parse ( queryOrLocation ) { const params = HashURLs . parse ( queryOrLocation ) ; const target = params . get ( 'target' ) || undefined ; const n = params . get ( 'n' ) ; const b = Optional . of ( params . get ( 'b' ) ) . map ( parseInt ) . getOrElse ( 0 ) ; const pos = params . get ( 'pos' ) === 'bottom' ? 'bottom' : 'top' ; if ( ! n ) { return undefined ; } if ( ! target ) { return undefined ; } return { target , pos , n , b } ; } } export function useScrollTarget ( ) { const location = useLocation ( ) ; return ScrollTargets . parse ( location ) ; } /**
 *
 */ export function useScrollTargetUpdateListener ( ) { const history = useHistory ( ) ; function listen ( listener ) { return history . listen ( newLocation => { const scrollTarget = ScrollTargets . parse ( newLocation ) ; if ( scrollTarget ) { listener ( scrollTarget ) ; } } ) ; } return { listen } ; }