Nuxt/lib/app/client.js

433 lines
15 KiB
JavaScript
Raw Normal View History

'use strict'
2016-11-07 01:34:58 +00:00
import Vue from 'vue'
2017-02-03 14:09:27 +00:00
import middleware from './middleware'
2017-05-02 06:57:39 +00:00
import { createApp, NuxtError } from './index'
import { applyAsyncData, sanitizeComponent, getMatchedComponents, getMatchedComponentsInstances, flatMapComponents, getContext, middlewareSeries, promisify, getLocation, compile } from './utils'
2016-11-07 01:34:58 +00:00
const noopData = () => { return {} }
const noopFetch = () => {}
let _lastPaths = []
2016-12-20 12:44:00 +00:00
let _lastComponentsFiles = []
let app
let router
<%= (store ? 'let store' : '') %>
2017-05-02 06:57:39 +00:00
function mapTransitions(Components, to, from) {
const componentTransitions = (component) => {
if (!component || !component.options || !component.options.transition) {
return {}
}
let transition = component.options.transition
if (typeof transition === 'function') {
transition = transition(to, from)
}
return (typeof transition === 'string' ? { name: transition } : transition)
}
return Components.map((Component) => {
// Clone original object to prevent overrides
const transitions = Object.assign({}, componentTransitions(Component))
// Combine transitions & prefer `leave` transitions of 'from' route
if (from && from.matched.length && from.matched[0].components.default) {
const from_transitions = componentTransitions(from.matched[0].components.default)
Object.keys(from_transitions)
.filter(key => from_transitions[key] && key.toLowerCase().indexOf('leave') !== -1)
.forEach(key => { transitions[key] = from_transitions[key] })
}
return transitions
})
}
2016-11-07 01:34:58 +00:00
2017-01-29 06:49:36 +00:00
function loadAsyncComponents (to, from, next) {
2016-11-07 01:34:58 +00:00
const resolveComponents = flatMapComponents(to, (Component, _, match, key) => {
if (typeof Component === 'function' && !Component.options) {
return new Promise(function (resolve, reject) {
const _resolve = (Component) => {
Component = sanitizeComponent(Component)
2016-11-07 01:34:58 +00:00
match.components[key] = Component
resolve(Component)
}
Component().then(_resolve).catch(reject)
})
}
Component = sanitizeComponent(Component)
match.components[key] = Component
return match.components[key]
2016-11-07 01:34:58 +00:00
})
2017-02-06 12:24:59 +00:00
const fromPath = from.fullPath.split('#')[0]
const toPath = to.fullPath.split('#')[0]
this._hashChanged = (fromPath === toPath)
2017-01-29 06:49:36 +00:00
if (!this._hashChanged) {
<%= (loading ? 'this.$loading.start && this.$loading.start()' : '') %>
}
2016-11-07 01:34:58 +00:00
Promise.all(resolveComponents)
.then(() => next())
.catch((err) => {
let statusCode = err.statusCode || err.status || (err.response && err.response.status) || 500
this.error({ statusCode, message: err.message })
2016-11-07 01:34:58 +00:00
next(false)
})
}
2017-02-03 14:09:27 +00:00
function callMiddleware (Components, context, layout) {
2017-03-17 17:02:58 +00:00
// if layout is undefined, only call global middleware
2017-02-03 14:09:27 +00:00
let midd = <%= serialize(router.middleware, { isJSON: true }) %>
2017-03-17 17:02:58 +00:00
let unknownMiddleware = false
if (typeof layout !== 'undefined') {
midd = [] // exclude global middleware if layout defined (already called before)
if (layout.middleware) {
midd = midd.concat(layout.middleware)
2017-02-03 14:09:27 +00:00
}
2017-03-17 17:02:58 +00:00
Components.forEach((Component) => {
if (Component.options.middleware) {
midd = midd.concat(Component.options.middleware)
}
})
}
2017-02-03 14:09:27 +00:00
midd = midd.map((name) => {
if (typeof middleware[name] !== 'function') {
2017-03-17 17:02:58 +00:00
unknownMiddleware = true
2017-02-03 14:09:27 +00:00
this.error({ statusCode: 500, message: 'Unknown middleware ' + name })
}
return middleware[name]
})
2017-03-17 17:02:58 +00:00
if (unknownMiddleware) return
2017-05-04 07:57:10 +00:00
return middlewareSeries(midd, context)
2017-02-03 14:09:27 +00:00
}
2017-05-09 12:43:47 +00:00
async function render (to, from, next) {
2017-01-29 06:49:36 +00:00
if (this._hashChanged) return next()
2017-05-09 12:43:47 +00:00
let layout
let nextCalled = false
2017-02-03 14:09:27 +00:00
const _next = function (path) {
<%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %>
2017-05-09 12:43:47 +00:00
if (nextCalled) return
2017-02-03 14:09:27 +00:00
nextCalled = true
next(path)
}
2017-05-14 21:56:00 +00:00
let context = getContext({ to<%= (store ? ', store' : '') %>, isClient: true, next: _next.bind(this), error: this.error.bind(this) }, app)
2016-11-07 01:34:58 +00:00
let Components = getMatchedComponents(to)
2017-03-17 17:02:58 +00:00
this._context = context
2017-01-27 22:10:02 +00:00
this._dateLastError = this.$options._nuxt.dateErr
this._hadError = !!this.$options._nuxt.err
2016-11-07 01:34:58 +00:00
if (!Components.length) {
2016-12-24 11:34:41 +00:00
// Default layout
2017-05-09 12:43:47 +00:00
await callMiddleware.call(this, Components, context)
if (context._redirected) return
layout = await this.loadLayout(typeof NuxtError.layout === 'function' ? NuxtError.layout(context) : NuxtError.layout)
await callMiddleware.call(this, Components, context, layout)
if (context._redirected) return
this.error({ statusCode: 404, message: 'This page could not be found.' })
return next()
2016-11-07 01:34:58 +00:00
}
// Update ._data and other properties if hot reloaded
Components.forEach(function (Component) {
2016-12-24 00:55:32 +00:00
if (Component._Ctor && Component._Ctor.options) {
2017-02-28 12:10:58 +00:00
Component.options.asyncData = Component._Ctor.options.asyncData
Component.options.fetch = Component._Ctor.options.fetch
2016-11-07 01:34:58 +00:00
}
})
this.setTransitions(mapTransitions(Components, to, from))
2017-05-09 12:43:47 +00:00
try {
// Set layout
await callMiddleware.call(this, Components, context)
if (context._redirected) return
layout = Components[0].options.layout
2017-03-17 17:02:58 +00:00
if (typeof layout === 'function') {
layout = layout(context)
}
2017-05-09 12:43:47 +00:00
layout = await this.loadLayout(layout)
await callMiddleware.call(this, Components, context, layout)
if (context._redirected) return
2016-12-24 11:34:41 +00:00
// Pass validation?
let isValid = true
Components.forEach((Component) => {
if (!isValid) return
if (typeof Component.options.validate !== 'function') return
isValid = Component.options.validate({
2017-04-05 16:25:12 +00:00
params: to.params || {},
2017-04-05 19:25:44 +00:00
query : to.query || {}<%= (store ? ', store: context.store' : '') %>
2016-11-07 01:34:58 +00:00
})
2016-12-24 11:34:41 +00:00
})
if (!isValid) {
2017-02-03 14:09:27 +00:00
this.error({ statusCode: 404, message: 'This page could not be found.' })
2016-12-24 11:34:41 +00:00
return next()
2016-11-07 01:34:58 +00:00
}
2017-05-09 12:43:47 +00:00
await Promise.all(Components.map((Component, i) => {
2016-12-24 11:34:41 +00:00
// Check if only children route changed
Component._path = compile(to.matched[i].path)(to.params)
2017-01-27 22:10:02 +00:00
if (!this._hadError && Component._path === _lastPaths[i] && (i + 1) !== Components.length) {
2016-12-24 11:34:41 +00:00
return Promise.resolve()
}
let promises = []
2017-02-28 12:10:58 +00:00
// asyncData method
if (Component.options.asyncData && typeof Component.options.asyncData === 'function') {
var promise = promisify(Component.options.asyncData, context)
promise.then((asyncDataResult) => {
2017-04-14 14:31:14 +00:00
applyAsyncData(Component, asyncDataResult)
2016-12-24 11:34:41 +00:00
<%= (loading ? 'this.$loading.increase && this.$loading.increase(30)' : '') %>
})
promises.push(promise)
}
if (Component.options.fetch) {
var p = Component.options.fetch(context)
if (!p || (!(p instanceof Promise) && (typeof p.then !== 'function'))) { p = Promise.resolve(p) }
2016-12-24 11:34:41 +00:00
<%= (loading ? 'p.then(() => this.$loading.increase && this.$loading.increase(30))' : '') %>
promises.push(p)
}
return Promise.all(promises)
}))
_lastPaths = Components.map((Component, i) => compile(to.matched[i].path)(to.params))
2016-11-07 01:34:58 +00:00
<%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %>
2016-11-10 23:01:36 +00:00
// If not redirected
if (!nextCalled) {
next()
}
2017-05-09 12:43:47 +00:00
} catch (error) {
_lastPaths = []
error.statusCode = error.statusCode || error.status || (error.response && error.response.status) || 500
2017-03-17 17:02:58 +00:00
let layout = NuxtError.layout
if (typeof layout === 'function') {
layout = layout(context)
}
this.loadLayout(layout)
2017-02-20 22:11:34 +00:00
.then(() => {
this.error(error)
next(false)
})
2017-05-09 12:43:47 +00:00
}
2016-11-07 01:34:58 +00:00
}
2017-01-20 17:32:43 +00:00
// Fix components format in matched, it's due to code-splitting of vue-router
function normalizeComponents (to, ___) {
flatMapComponents(to, (Component, _, match, key) => {
if (typeof Component === 'object' && !Component.options) {
// Updated via vue-router resolveAsyncComponents()
Component = Vue.extend(Component)
Component._Ctor = Component
match.components[key] = Component
}
return Component
})
}
2016-11-22 23:27:07 +00:00
// When navigating on a different route but the same component is used, Vue.js
// will not update the instance data, so we have to update $data ourselves
function fixPrepatch (to, ___) {
2017-01-29 06:49:36 +00:00
if (this._hashChanged) return
2016-11-22 23:27:07 +00:00
Vue.nextTick(() => {
let instances = getMatchedComponentsInstances(to)
2016-12-20 12:44:00 +00:00
_lastComponentsFiles = instances.map((instance, i) => {
if (!instance) return '';
2016-12-20 13:11:51 +00:00
if (_lastPaths[i] === instance.constructor._path && typeof instance.constructor.options.data === 'function') {
2017-04-14 14:31:14 +00:00
let newData = instance.constructor.options.data.call(instance)
2016-11-22 23:27:07 +00:00
for (let key in newData) {
Vue.set(instance.$data, key, newData[key])
}
}
2016-12-20 12:44:00 +00:00
return instance.constructor.options.__file
2016-11-22 23:27:07 +00:00
})
2017-01-27 22:10:02 +00:00
// hide error component if no error
if (this._hadError && this._dateLastError === this.$options._nuxt.dateErr) {
this.error()
}
2017-02-20 22:11:34 +00:00
// Set layout
2017-03-17 17:02:58 +00:00
let layout = this.$options._nuxt.err ? NuxtError.layout : to.matched[0].components.default.options.layout
if (typeof layout === 'function') {
layout = layout(this._context)
}
this.setLayout(layout)
2017-01-27 22:10:02 +00:00
// hot reloading
2017-03-24 15:52:18 +00:00
setTimeout(() => hotReloadAPI(this), 100)
2016-11-22 23:27:07 +00:00
})
}
2017-03-16 17:52:06 +00:00
// Special hot reload with asyncData(context)
2016-11-07 01:34:58 +00:00
function hotReloadAPI (_app) {
2016-12-24 13:15:00 +00:00
if (!module.hot) return
2017-03-16 17:52:06 +00:00
let $components = []
let $nuxt = _app.$nuxt
while ($nuxt && $nuxt.$children && $nuxt.$children.length) {
$nuxt.$children.forEach(function (child, i) {
if (child.$vnode.data.nuxtChild) {
let hasAlready = false
$components.forEach(function (component) {
if (component.$options.__file === child.$options.__file) {
hasAlready = true
}
})
if (!hasAlready) {
$components.push(child)
}
}
$nuxt = child
})
}
$components.forEach(addHotReload.bind(_app))
}
function addHotReload ($component, depth) {
if ($component.$vnode.data._hasHotReload) return
$component.$vnode.data._hasHotReload = true
var _forceUpdate = $component.$forceUpdate.bind($component.$parent)
$component.$vnode.context.$forceUpdate = () => {
2017-03-17 17:02:58 +00:00
let Components = getMatchedComponents(router.currentRoute)
let Component = Components[depth]
2016-11-07 01:34:58 +00:00
if (!Component) return _forceUpdate()
if (typeof Component === 'object' && !Component.options) {
// Updated via vue-router resolveAsyncComponents()
Component = Vue.extend(Component)
Component._Ctor = Component
}
2017-03-16 17:52:06 +00:00
this.error()
2016-11-07 01:34:58 +00:00
let promises = []
2016-11-10 23:01:36 +00:00
const next = function (path) {
<%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %>
router.push(path)
}
2017-05-31 11:21:24 +00:00
let context = getContext({ route: router.currentRoute<%= (store ? ', store' : '') %>, isClient: true, hotReload: true, next: next.bind(this), error: this.error }, app)
2016-11-22 23:27:07 +00:00
<%= (loading ? 'this.$loading.start && this.$loading.start()' : '') %>
2017-03-17 17:02:58 +00:00
callMiddleware.call(this, Components, context)
.then(() => {
// If layout changed
if (depth !== 0) return Promise.resolve()
let layout = Component.options.layout || 'default'
if (typeof layout === 'function') {
layout = layout(context)
}
if (this.layoutName === layout) return Promise.resolve()
let promise = this.loadLayout(layout)
promise.then(() => {
this.setLayout(layout)
Vue.nextTick(() => hotReloadAPI(this))
})
return promise
})
.then(() => {
return callMiddleware.call(this, Components, context, this.layout)
})
.then(() => {
2017-04-14 14:31:14 +00:00
// Call asyncData(context)
2017-03-17 17:02:58 +00:00
let pAsyncData = promisify(Component.options.asyncData || noopData, context)
pAsyncData.then((asyncDataResult) => {
2017-04-14 14:31:14 +00:00
applyAsyncData(Component, asyncDataResult)
2017-03-17 17:02:58 +00:00
<%= (loading ? 'this.$loading.increase && this.$loading.increase(30)' : '') %>
})
promises.push(pAsyncData)
// Call fetch()
Component.options.fetch = Component.options.fetch || noopFetch
let pFetch = Component.options.fetch(context)
if (!pFetch || (!(pFetch instanceof Promise) && (typeof pFetch.then !== 'function'))) { pFetch = Promise.resolve(pFetch) }
2017-03-17 17:02:58 +00:00
<%= (loading ? 'pFetch.then(() => this.$loading.increase && this.$loading.increase(30))' : '') %>
promises.push(pFetch)
return Promise.all(promises)
})
.then(() => {
2016-11-10 23:01:36 +00:00
<%= (loading ? 'this.$loading.finish && this.$loading.finish()' : '') %>
2016-11-07 01:34:58 +00:00
_forceUpdate()
2017-03-16 17:52:06 +00:00
setTimeout(() => hotReloadAPI(this), 100)
2016-11-07 01:34:58 +00:00
})
}
}
// Load vue app
const NUXT = window.__NUXT__ || {}
if (!NUXT) {
throw new Error('[nuxt.js] cannot find the global variable __NUXT__, make sure the server is working.')
}
// Get matched components
const resolveComponents = function (router) {
const path = getLocation(router.options.base)
return flatMapComponents(router.match(path), (Component, _, match, key, index) => {
if (typeof Component === 'function' && !Component.options) {
return new Promise(function (resolve, reject) {
const _resolve = (Component) => {
Component = sanitizeComponent(Component)
if (NUXT.serverRendered) {
applyAsyncData(Component, NUXT.data[index])
}
match.components[key] = Component
resolve(Component)
2016-11-07 01:34:58 +00:00
}
Component().then(_resolve).catch(reject)
})
}
Component = sanitizeComponent(Component)
match.components[key] = Component
return Component
})
}
2016-11-07 01:34:58 +00:00
2016-11-25 14:36:27 +00:00
function nuxtReady (app) {
2016-12-07 22:58:32 +00:00
window._nuxtReadyCbs.forEach((cb) => {
2016-11-25 14:36:27 +00:00
if (typeof cb === 'function') {
cb(app)
}
})
2017-05-30 14:08:51 +00:00
// Special JSDOM
if (typeof window._onNuxtLoaded === 'function') {
window._onNuxtLoaded(app)
}
2016-12-07 22:43:57 +00:00
// Add router hooks
2016-12-07 22:58:32 +00:00
router.afterEach(function (to, from) {
2016-12-07 22:43:57 +00:00
app.$nuxt.$emit('routeChanged', to, from)
})
2016-11-25 14:36:27 +00:00
}
createApp()
.then(async (__app) => {
app = __app.app
router = __app.router
<%= (store ? 'store = __app.store' : '') %>
const Components = await Promise.all(resolveComponents(router))
2016-11-07 01:34:58 +00:00
const _app = new Vue(app)
const layout = NUXT.layout || 'default'
await _app.loadLayout(layout)
_app.setLayout(layout)
const mountApp = () => {
_app.$mount('#__nuxt')
2017-03-02 16:31:37 +00:00
Vue.nextTick(() => {
// Hot reloading
hotReloadAPI(_app)
// Call window.onNuxtReady callbacks
nuxtReady(_app)
})
}
_app.setTransitions = _app.$options._nuxt.setTransitions.bind(_app)
if (Components.length) {
_app.setTransitions(mapTransitions(Components, router.currentRoute))
_lastPaths = router.currentRoute.matched.map((route) => compile(route.path)(router.currentRoute.params))
2016-12-20 12:44:00 +00:00
_lastComponentsFiles = Components.map((Component) => Component.options.__file)
}
_app.error = _app.$options._nuxt.error.bind(_app)
_app.$loading = {} // to avoid error while _app.$nuxt does not exist
2016-11-07 01:34:58 +00:00
if (NUXT.error) _app.error(NUXT.error)
// Add router hooks
router.beforeEach(loadAsyncComponents.bind(_app))
router.beforeEach(render.bind(_app))
2017-01-20 17:32:43 +00:00
router.afterEach(normalizeComponents)
2016-11-22 23:27:07 +00:00
router.afterEach(fixPrepatch.bind(_app))
if (NUXT.serverRendered) {
mountApp()
return
2016-11-07 01:34:58 +00:00
}
render.call(_app, router.currentRoute, router.currentRoute, function (path) {
if (path) {
let mounted = false
router.afterEach(function () {
if (mounted) return
mounted = true
mountApp()
})
router.push(path)
return
}
2017-01-27 22:10:02 +00:00
normalizeComponents(router.currentRoute, router.currentRoute)
fixPrepatch.call(_app, router.currentRoute, router.currentRoute)
mountApp()
})
2016-11-07 01:34:58 +00:00
})
.catch((err) => {
2016-12-08 15:41:20 +00:00
console.error('[nuxt.js] Cannot load components', err) // eslint-disable-line no-console
2016-11-07 01:34:58 +00:00
})