// @flow const speedOffset = 5; type ListenerFunctionType = (shouldHide: boolean) => void; export type OnScrollType = { nativeEvent: { contentInset: {bottom: number, left: number, right: number, top: number}, contentOffset: {x: number, y: number}, contentSize: {height: number, width: number}, layoutMeasurement: {height: number, width: number}, zoomScale: number, }, }; /** * Class used to detect when to show or hide a component based on scrolling */ export default class AutoHideHandler { lastOffset: number; isHidden: boolean; listeners: Array; constructor(startHidden: boolean) { this.listeners = []; this.isHidden = startHidden; } /** * Adds a listener to the hide event * * @param listener */ addListener(listener: (shouldHide: boolean) => void) { this.listeners.push(listener); } /** * Notifies every listener whether they should hide or show. * * @param shouldHide */ notifyListeners(shouldHide: boolean) { this.listeners.forEach((func: ListenerFunctionType) => { func(shouldHide); }); } /** * Callback to be used on the onScroll animated component event. * * Detects if the current speed exceeds a threshold and notifies listeners to hide or show. * * The hide even is triggered when the user scrolls down, and the show event on scroll up. * This does not take into account the speed when the y coordinate is negative, to prevent hiding on over scroll. * (When scrolling up and hitting the top on ios for example) * * //TODO Known issue: * When refreshing a list with the pull down gesture on ios, * this can trigger the hide event as it scrolls down the list to show the refresh indicator. * Android shows the refresh indicator on top of the list so this is not an issue. * * @param event The scroll event generated by the animated component onScroll prop */ onScroll(event: OnScrollType) { const {nativeEvent} = event; const speed = nativeEvent.contentOffset.y < 0 ? 0 : this.lastOffset - nativeEvent.contentOffset.y; if (speed < -speedOffset && !this.isHidden) { // Go down this.notifyListeners(true); this.isHidden = true; } else if (speed > speedOffset && this.isHidden) { // Go up this.notifyListeners(false); this.isHidden = false; } this.lastOffset = nativeEvent.contentOffset.y; } }