All files / src CardStack.js

80.26% Statements 61/76
71.43% Branches 35/49
88.89% Functions 16/18
84.62% Lines 55/65
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 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236                                      1x                   10x 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           8x 8x 8x   8x 13x   8x 8x 11x   8x         8x 8x   2x           2x     5x             5x 5x 2x                       3x       5x     1x             1x                 1x 1x 1x             26x               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?: Array<React$Element<any>>,
  render: (props: CardsRendererProps) => React$Element<any>,
}
 
class CardStack extends React.PureComponent<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, history: { entries, location } } = nextProps
    const { cards, navigationState } = this.state
    // Rebuild cards<x
    const nextCards = children && StackUtils.build(children, cards)
    // Get current route
    const route = navigationState.routes[navigationState.index]
    // Get current card
    const card = Array.isArray(nextCards) && StackUtils.get(nextCards, route)
    Iif (entries && card && !card.path) {
      // Build cards from scratch
      const newCards = children && StackUtils.build(children)
      if (!newCards) throw new Error("Can't rebuild cards")
      const newNavigationState = buildNavigationState(
        location,
        entries,
        newCards,
      )
      // Update state + rebuild navigation state
      this.setState(prevState => ({
        key: prevState.key + 1,
        cards: newCards,
        navigationState: newNavigationState,
      }))
    } else {
      // Update state
      this.setState({ cards: nextCards })
    }
  }
 
  // 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
  }
 
  // Render view
  render() {
    return this.props.render({
      ...this.state,
      history: this.props.history,
      onNavigateBack: this.onNavigateBack,
    })
  }
}
 
const CardStackWithHistory = withRouter(CardStack)
 
export default CardStackWithHistory