All files / src CardStack.js

80.56% Statements 58/72
68.09% Branches 32/47
89.47% Functions 17/19
83.61% Lines 51/61
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208                    1x                   19x 10x   10x   19x 26x   19x 19x 19x 19x                                                             10x   10x 10x   10x     10x       10x   10x   10x         10x 10x 10x                     8x 8x 8x                             8x 8x 8x   8x 13x   8x 8x 11x   8x         8x 8x   2x           2x     5x     5x 5x 2x                       3x       5x     1x             1x                 1x 1x 1x           16x               18x             1x      
/* @flow */
 
import React from 'react'
import { BackHandler } from 'react-native'
import { StateUtils } from 'react-navigation'
import { type RouterHistory, type Location, withRouter, matchPath } from 'react-router'
import type { CardsRendererProps, NavigationState, Card } from './TypeDefinitions'
import * as StackUtils from './StackUtils'
import * as HistoryUtils from './HistoryUtils'
 
const buildNavigationState = (
  location: Location,
  entries: Array<Location>,
  cards: Array<Card>,
): NavigationState<{
  path?: string,
  params?: Object,
}> => {
  // Find last route and reproduce actual route stack
  // Fix > https://github.com/LeoLeBras/react-router-navigation/issues/37
  const lastRouteIndex = entries.findIndex(entry => entry.pathname === location.pathname)
  const initialEntries = entries.slice(0, lastRouteIndex + 1)
  // $FlowFixMe
  return initialEntries.reduce(
    (state, entry) => {
      const card = cards.find(({ path, exact, strict }) => {
        return matchPath(entry.pathname, { path, exact, strict })
      })
      Iif (!card || !card.path) return state
      const route = StackUtils.getRoute(cards, entry)
      Iif (!route) return { index: -1, routes: [] }
      return {
        index: matchPath(location.pathname, card) ? state.routes.length : state.index,
        routes: [...state.routes, route],
      }
    },
    { index: -1, routes: [] },
  )
}
 
type State = {
  key: number,
  navigationState: NavigationState<{
    path?: string,
    params?: Object,
  }>,
  cards: Array<Card>,
}
 
type Props = {
  history: RouterHistory, // eslint-disable-next-line
  children?: React$Node,
  render: (props: CardsRendererProps) => React$Element<any>,
}
 
class CardStack extends React.Component<Props, State> {
  props: Props
  state: State
 
  unlistenHistory: Function
 
  constructor(props: Props) {
    super(props)
    // Build the card stack
    const { children, history: { entries, index, location } } = props
    const cards = children && StackUtils.build(children)
    // CardStack can be mount ?
    Iif (!cards) {
      throw new Error('No initial route found')
    }
    Iif (!entries || index === undefined) {
      throw new Error('No history entries found')
    }
    // Build navigation state
    const navigationState = buildNavigationState(location, entries, cards)
    // Set key
    const key = 0
    // Save everything in component state
    this.state = { navigationState, cards, key }
  }
 
  // Listen hardware BackHandler event + history event
  componentDidMount() {
    const { history } = this.props
    this.unlistenHistory = HistoryUtils.runHistoryListenner(history, this.onListenHistory)
    BackHandler.addEventListener('hardwareBackPress', this.onNavigateBack)
  }
 
  // Remove all listeners
  componentWillUnmount() {
    this.unlistenHistory()
    BackHandler.removeEventListener('hardwareBackPress', this.onNavigateBack)
  }
 
  // Update cards
  componentWillReceiveProps(nextProps: Props) {
    const { children } = this.props
    const { children: nextChildren, history: { entries, location } } = nextProps
    Iif (children !== nextChildren && entries) {
      const nextCards = nextChildren && StackUtils.build(nextChildren)
      if (nextCards) {
        const newNavigationState = buildNavigationState(location, entries, nextCards)
        this.setState(prevState => ({
          key: prevState.key + 1,
          cards: nextCards,
          navigationState: newNavigationState,
        }))
      }
    }
  }
 
  // Update navigation state
  onListenHistory = (history: RouterHistory, nextHistory: RouterHistory) => {
    const { location, entries, index } = history
    const { location: nextLocation, action, index: nextIndex } = nextHistory
    const { navigationState, cards } = this.state
    // Get current card
    const currentRoute = navigationState.routes[navigationState.index]
    const currentCard = cards.find(({ key }) => key === currentRoute.routeName)
    // Get next card
    const nextRoute = StackUtils.getRoute(cards, nextLocation)
    Iif (!nextRoute) return
    const nextCard = cards.find(({ key }) => key === nextRoute.routeName)
    // Local state must be updated ?
    Eif (
      currentCard &&
      nextCard &&
      StackUtils.shouldUpdate(currentCard, nextCard, location, nextLocation)
    ) {
      const key = StackUtils.createKey(nextRoute)
      switch (action) {
        case 'PUSH': {
          this.setState(state => ({
            navigationState: StateUtils.push(state.navigationState, {
              ...nextRoute,
              key,
            }),
          }))
          break
        }
        case 'POP': {
          Iif (index === undefined || nextIndex === undefined || entries === undefined) {
            return
          }
          const n = index - nextIndex
          if (n > 1) {
            this.setState(state => ({
              navigationState: StateUtils.reset(
                state.navigationState,
                state.navigationState.routes.slice(
                  0,
                  // eslint-disable-next-line
                  state.navigationState.index - n + 1,
                ),
                state.navigationState.index - n,
              ),
            }))
          } else {
            this.setState(state => ({
              navigationState: StateUtils.pop(state.navigationState),
            }))
          }
          break
        }
        case 'REPLACE': {
          this.setState(state => ({
            navigationState: StateUtils.replaceAtIndex(
              state.navigationState,
              state.navigationState.index,
              { ...nextRoute, key },
            ),
          }))
          break
        }
        default:
      }
    }
  }
 
  // Pop to previous scene (n-1)
  onNavigateBack = () => {
    Eif (this.state.navigationState.index > 0) {
      this.props.history.goBack()
      return true
    }
    return false
  }
 
  shouldComponentUpdate(nextProps: Props, nextState: State) {
    return (
      this.state.key !== nextState.key ||
      this.state.cards !== nextState.cards ||
      this.state.navigationState !== nextState.navigationState
    )
  }
 
  render() {
    return this.props.render({
      ...this.state,
      onNavigateBack: this.onNavigateBack,
    })
  }
}
 
const CardStackWithHistory = withRouter(CardStack)
 
export default CardStackWithHistory