All files / src SceneView.js

82.14% Statements 23/28
72% Branches 18/25
80% Functions 4/5
85.19% Lines 23/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                  4x 4x 4x 4x               5x 5x 5x 5x 5x 5x 5x         2x   3x         10x       13x 13x 13x 13x 1x 12x   12x   12x 12x                          
/* @flow */
 
import * as React from 'react'
import {
  matchPath,
  type RouterHistory,
  type Location,
  type Match,
} from 'react-router'
import type { Route, RouteProps } from './TypeDefinitions'
 
type Props = Route &
  RouteProps & {
    history: RouterHistory,
  }
 
type State = {|
  location: Location,
  match: ?Match,
|}
 
class SceneView extends React.Component<Props, State> {
  unlisten: ?Function
 
  constructor(props: Props) {
    super(props)
    const { history, routeMatch } = props
    this.state = { match: routeMatch || null, location: history.location }
    this.unlisten = history.listen(this.onHistoryChange)
  }
 
  componentWillUnmount() {
    if (this.unlisten) this.unlisten()
  }
 
  onHistoryChange = (location: Location) => {
    const { routePath, path, exact, strict } = this.props
    const { match: oldMatch } = this.state
    const minimalRoute = { path: routePath || path, exact, strict }
    const minimalMatch = matchPath(location.pathname, minimalRoute)
    const route = { path, exact, strict }
    const match = matchPath(location.pathname, route)
    if (
      match &&
      minimalMatch &&
      (!oldMatch || (oldMatch.url !== match.url && oldMatch.url.includes(minimalMatch.url)))
    ) {
      this.setState({ match, location })
    } else {
      this.setState({ location })
    }
  }
 
  shouldComponentUpdate(nextProps: Props, nextState: State) {
    return !!nextState.match
  }
 
  render() {
    const { render, children, component: Component, history } = this.props
    const { match, location } = this.state
    const contextRouter = { history, match, location }
    if (render) {
      return render(contextRouter)
    } else Iif (children && typeof children === 'function') {
      return children(contextRouter)
    } else Iif (children && React.Children.count(children) === 0) {
      return React.cloneElement(children, contextRouter)
    } else Eif (Component) {
      return (
        <Component
          match={contextRouter.match}
          location={contextRouter.location}
          history={contextRouter.history}
        />
      )
    }
    return null
  }
}
 
export default SceneView