loadable.js 7.2 KB
Newer Older
T
Tim Neutkens 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
@copyright (c) 2017-present James Kyle <me@thejameskyle.com>
 MIT License
 Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
 The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
19
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
T
Tim Neutkens 已提交
20 21 22 23 24 25 26 27
*/
// https://github.com/jamiebuilds/react-loadable/blob/v5.5.0/src/index.js
// Modified to be compatible with webpack 4 / Next.js

import React from 'react'
import PropTypes from 'prop-types'

const ALL_INITIALIZERS = []
28 29
const READY_INITIALIZERS = new Map()
let initialized = false
T
Tim Neutkens 已提交
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

function load (loader) {
  let promise = loader()

  let state = {
    loading: true,
    loaded: null,
    error: null
  }

  state.promise = promise
    .then(loaded => {
      state.loading = false
      state.loaded = loaded
      return loaded
    })
    .catch(err => {
      state.loading = false
      state.error = err
      throw err
    })

  return state
}

function loadMap (obj) {
  let state = {
    loading: false,
    loaded: {},
    error: null
  }

  let promises = []

  try {
    Object.keys(obj).forEach(key => {
      let result = load(obj[key])

      if (!result.loading) {
        state.loaded[key] = result.loaded
        state.error = result.error
      } else {
        state.loading = true
      }

      promises.push(result.promise)

      result.promise
        .then(res => {
          state.loaded[key] = res
        })
        .catch(err => {
          state.error = err
        })
    })
  } catch (err) {
    state.error = err
  }

  state.promise = Promise.all(promises)
    .then(res => {
      state.loading = false
      return res
    })
    .catch(err => {
      state.loading = false
      throw err
    })

  return state
}

function resolve (obj) {
  return obj && obj.__esModule ? obj.default : obj
}

function render (loaded, props) {
  return React.createElement(resolve(loaded), props)
}

function createLoadableComponent (loadFn, options) {
  let opts = Object.assign(
    {
      loader: null,
      loading: null,
      delay: 200,
      timeout: null,
      render: render,
      webpack: null,
      modules: null
    },
    options
  )

  let res = null

  function init () {
    if (!res) {
      res = loadFn(opts.loader)
    }
    return res.promise
  }

133 134 135 136
  // Server only
  if (typeof window === 'undefined') {
    ALL_INITIALIZERS.push(init)
  }
T
Tim Neutkens 已提交
137

138 139 140 141 142 143 144 145
  // Client only
  if (!initialized && typeof window !== 'undefined' && typeof opts.webpack === 'function') {
    const moduleIds = opts.webpack()
    for (const moduleId of moduleIds) {
      READY_INITIALIZERS.set(moduleId, () => {
        return init()
      })
    }
T
Tim Neutkens 已提交
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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
  }

  return class LoadableComponent extends React.Component {
    constructor (props) {
      super(props)
      init()

      this.state = {
        error: res.error,
        pastDelay: false,
        timedOut: false,
        loading: res.loading,
        loaded: res.loaded
      }
    }

    static contextTypes = {
      loadable: PropTypes.shape({
        report: PropTypes.func.isRequired
      })
    };

    static preload () {
      return init()
    }

    componentWillMount () {
      this._mounted = true
      this._loadModule()
    }

    _loadModule () {
      if (this.context.loadable && Array.isArray(opts.modules)) {
        opts.modules.forEach(moduleName => {
          this.context.loadable.report(moduleName)
        })
      }

      if (!res.loading) {
        return
      }

      if (typeof opts.delay === 'number') {
        if (opts.delay === 0) {
          this.setState({ pastDelay: true })
        } else {
          this._delay = setTimeout(() => {
            this.setState({ pastDelay: true })
          }, opts.delay)
        }
      }

      if (typeof opts.timeout === 'number') {
        this._timeout = setTimeout(() => {
          this.setState({ timedOut: true })
        }, opts.timeout)
      }

      let update = () => {
        if (!this._mounted) {
          return
        }

        this.setState({
          error: res.error,
          loaded: res.loaded,
          loading: res.loading
        })

        this._clearTimeouts()
      }

      res.promise
        .then(() => {
          update()
        })
        // eslint-disable-next-line handle-callback-err
        .catch(err => {
          update()
        })
    }

    componentWillUnmount () {
      this._mounted = false
      this._clearTimeouts()
    }

    _clearTimeouts () {
      clearTimeout(this._delay)
      clearTimeout(this._timeout)
    }

    retry = () => {
      this.setState({ error: null, loading: true, timedOut: false })
      res = loadFn(opts.loader)
      this._loadModule()
    };

    render () {
      if (this.state.loading || this.state.error) {
        return React.createElement(opts.loading, {
          isLoading: this.state.loading,
          pastDelay: this.state.pastDelay,
          timedOut: this.state.timedOut,
          error: this.state.error,
          retry: this.retry
        })
      } else if (this.state.loaded) {
        return opts.render(this.state.loaded, this.props)
      } else {
        return null
      }
    }
  }
}

function Loadable (opts) {
  return createLoadableComponent(load, opts)
}

function LoadableMap (opts) {
  if (typeof opts.render !== 'function') {
    throw new Error('LoadableMap requires a `render(loaded, props)` function')
  }

  return createLoadableComponent(loadMap, opts)
}

Loadable.Map = LoadableMap

function flushInitializers (initializers) {
  let promises = []

  while (initializers.length) {
    let init = initializers.pop()
    promises.push(init())
  }

  return Promise.all(promises).then(() => {
    if (initializers.length) {
      return flushInitializers(initializers)
    }
  })
}

Loadable.preloadAll = () => {
  return new Promise((resolve, reject) => {
    flushInitializers(ALL_INITIALIZERS).then(resolve, reject)
  })
}

297
Loadable.preloadReady = (webpackIds) => {
T
Tim Neutkens 已提交
298
  return new Promise((resolve, reject) => {
299 300 301 302 303 304 305 306 307 308 309 310 311 312
    const initializers = webpackIds.reduce((allInitalizers, moduleId) => {
      const initializer = READY_INITIALIZERS.get(moduleId)
      if (!initializer) {
        return allInitalizers
      }

      allInitalizers.push(initializer)
      return allInitalizers
    }, [])

    initialized = true
    // Make sure the object is cleared
    READY_INITIALIZERS.clear()

T
Tim Neutkens 已提交
313
    // We always will resolve, errors should be handled within loading UIs.
314
    flushInitializers(initializers).then(resolve, resolve)
T
Tim Neutkens 已提交
315 316 317
  })
}

318
export default Loadable