You need to sign in or sign up before continuing.
client-app.js 8.29 KB
Newer Older
1 2
/* global siteConfig */

3
import Vue from 'vue'
NGPixel's avatar
NGPixel committed
4
import VueRouter from 'vue-router'
5
import VueClipboards from 'vue-clipboards'
NGPixel's avatar
NGPixel committed
6
import { ApolloClient } from 'apollo-client'
7 8
import { BatchHttpLink } from 'apollo-link-batch-http'
import { ApolloLink, split } from 'apollo-link'
9
import { WebSocketLink } from 'apollo-link-ws'
10
import { ErrorLink } from 'apollo-link-error'
NGPixel's avatar
NGPixel committed
11
import { InMemoryCache } from 'apollo-cache-inmemory'
12
import { getMainDefinition } from 'apollo-utilities'
13
import VueApollo from 'vue-apollo'
14
import Vuetify from 'vuetify/lib'
15
import Velocity from 'velocity-animate'
Nicolas Giard's avatar
Nicolas Giard committed
16
import Vuescroll from 'vuescroll/dist/vuescroll-native'
17
import Hammer from 'hammerjs'
18
import moment from 'moment-timezone'
NGPixel's avatar
NGPixel committed
19
import VueMoment from 'vue-moment'
20
import store from './store'
21
import Cookies from 'js-cookie'
22

23 24 25 26
// ====================================
// Load Modules
// ====================================

27
import boot from './modules/boot'
28
import localization from './modules/localization'
29

30 31 32 33 34 35
// ====================================
// Load Helpers
// ====================================

import helpers from './helpers'

36 37 38 39
// ====================================
// Initialize Global Vars
// ====================================

40
window.WIKI = null
41 42
window.boot = boot
window.Hammer = Hammer
43

44 45
moment.locale(siteConfig.lang)

46 47
store.commit('user/REFRESH_AUTH')

48 49 50 51
// ====================================
// Initialize Apollo Client (GraphQL)
// ====================================

52
const graphQLEndpoint = window.location.protocol + '//' + window.location.host + '/graphql'
53
const graphQLWSEndpoint = ((window.location.protocol === 'https:') ? 'wss:' : 'ws:') + '//' + window.location.host + '/graphql-subscriptions'
54

55 56 57
const graphQLLink = ApolloLink.from([
  new ErrorLink(({ graphQLErrors, networkError }) => {
    if (graphQLErrors) {
58 59 60 61 62 63 64
      let isAuthError = false
      graphQLErrors.map(({ message, locations, path }) => {
        if (message === `Forbidden`) {
          isAuthError = true
        }
        console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
      })
65 66
      store.commit('showNotification', {
        style: 'red',
67
        message: isAuthError ? `You are not authorized to access this resource.` : `An unexpected error occurred.`,
68
        icon: 'alert'
69 70 71 72 73 74 75
      })
    }
    if (networkError) {
      console.error(networkError)
      store.commit('showNotification', {
        style: 'red',
        message: `Network Error: ${networkError.message}`,
76
        icon: 'alert'
77 78 79 80
      })
    }
  }),
  new BatchHttpLink({
81 82 83
    includeExtensions: true,
    uri: graphQLEndpoint,
    credentials: 'include',
84
    fetch: async (uri, options) => {
85 86
      // Strip __typename fields from variables
      let body = JSON.parse(options.body)
87 88 89 90 91 92
      body = body.map(bd => {
        return ({
          ...bd,
          variables: JSON.parse(JSON.stringify(bd.variables), (key, value) => { return key === '__typename' ? undefined : value })
        })
      })
93 94 95
      options.body = JSON.stringify(body)

      // Inject authentication token
96 97 98 99
      const jwtToken = Cookies.get('jwt')
      if (jwtToken) {
        options.headers.Authorization = `Bearer ${jwtToken}`
      }
100

101 102 103 104 105 106 107 108
      const resp = await fetch(uri, options)

      // Handle renewed JWT
      const newJWT = resp.headers.get('new-jwt')
      if (newJWT) {
        Cookies.set('jwt', newJWT, { expires: 365 })
      }
      return resp
109 110
    }
  })
111
])
112

113 114 115 116 117 118 119 120
const graphQLWSLink = new WebSocketLink({
  uri: graphQLWSEndpoint,
  options: {
    reconnect: true,
    lazy: true
  }
})

121
window.graphQL = new ApolloClient({
122 123 124
  link: split(({ query }) => {
    const { kind, operation } = getMainDefinition(query)
    return kind === 'OperationDefinition' && operation === 'subscription'
Nick's avatar
Nick committed
125
  }, graphQLWSLink, graphQLLink),
NGPixel's avatar
NGPixel committed
126 127
  cache: new InMemoryCache(),
  connectToDevTools: (process.env.node_env === 'development')
128 129
})

130
// ====================================
131
// Initialize Vue Modules
132 133
// ====================================

NGPixel's avatar
NGPixel committed
134 135
Vue.config.productionTip = false

NGPixel's avatar
NGPixel committed
136
Vue.use(VueRouter)
137
Vue.use(VueApollo)
138
Vue.use(VueClipboards)
139
Vue.use(localization.VueI18Next)
140
Vue.use(helpers)
141
Vue.use(Vuetify)
NGPixel's avatar
NGPixel committed
142
Vue.use(VueMoment, { moment })
Nicolas Giard's avatar
Nicolas Giard committed
143
Vue.use(Vuescroll)
144

145 146
Vue.prototype.Velocity = Velocity

NGPixel's avatar
NGPixel committed
147 148 149 150
// ====================================
// Register Vue Components
// ====================================

NGPixel's avatar
NGPixel committed
151
Vue.component('admin', () => import(/* webpackChunkName: "admin" */ './components/admin.vue'))
NGPixel's avatar
NGPixel committed
152
Vue.component('comments', () => import(/* webpackChunkName: "comments" */ './components/comments.vue'))
153
Vue.component('editor', () => import(/* webpackPrefetch: -100, webpackChunkName: "editor" */ './components/editor.vue'))
154
Vue.component('history', () => import(/* webpackChunkName: "history" */ './components/history.vue'))
155
Vue.component('loader', () => import(/* webpackPrefetch: true, webpackChunkName: "ui-extra" */ './components/common/loader.vue'))
156
Vue.component('login', () => import(/* webpackPrefetch: true, webpackChunkName: "login" */ './components/login.vue'))
157
Vue.component('nav-header', () => import(/* webpackMode: "eager" */ './components/common/nav-header.vue'))
158
Vue.component('new-page', () => import(/* webpackChunkName: "new-page" */ './components/new-page.vue'))
159
Vue.component('notify', () => import(/* webpackMode: "eager" */ './components/common/notify.vue'))
160
Vue.component('not-found', () => import(/* webpackChunkName: "not-found" */ './components/not-found.vue'))
161
Vue.component('page-selector', () => import(/* webpackPrefetch: true, webpackChunkName: "ui-extra" */ './components/common/page-selector.vue'))
NGPixel's avatar
NGPixel committed
162
Vue.component('page-source', () => import(/* webpackChunkName: "source" */ './components/source.vue'))
NGPixel's avatar
NGPixel committed
163
Vue.component('profile', () => import(/* webpackChunkName: "profile" */ './components/profile.vue'))
164
Vue.component('register', () => import(/* webpackChunkName: "register" */ './components/register.vue'))
165
Vue.component('search-results', () => import(/* webpackPrefetch: true, webpackChunkName: "ui-extra" */ './components/common/search-results.vue'))
NGPixel's avatar
NGPixel committed
166
Vue.component('social-sharing', () => import(/* webpackPrefetch: true, webpackChunkName: "ui-extra" */ './components/common/social-sharing.vue'))
167
Vue.component('tags', () => import(/* webpackChunkName: "tags" */ './components/tags.vue'))
Nick's avatar
Nick committed
168
Vue.component('unauthorized', () => import(/* webpackChunkName: "unauthorized" */ './components/unauthorized.vue'))
169
Vue.component('v-card-chin', () => import(/* webpackPrefetch: true, webpackChunkName: "ui-extra" */ './components/common/v-card-chin.vue'))
NGPixel's avatar
NGPixel committed
170
Vue.component('v-card-info', () => import(/* webpackPrefetch: true, webpackChunkName: "ui-extra" */ './components/common/v-card-info.vue'))
171
Vue.component('welcome', () => import(/* webpackChunkName: "welcome" */ './components/welcome.vue'))
NGPixel's avatar
NGPixel committed
172

173 174
Vue.component('nav-footer', () => import(/* webpackChunkName: "theme" */ './themes/' + siteConfig.theme + '/components/nav-footer.vue'))
Vue.component('page', () => import(/* webpackChunkName: "theme" */ './themes/' + siteConfig.theme + '/components/page.vue'))
175

176
let bootstrap = () => {
177 178 179
  // ====================================
  // Notifications
  // ====================================
180

NGPixel's avatar
NGPixel committed
181
  window.addEventListener('beforeunload', () => {
182
    store.dispatch('startLoading')
183
  })
184

185 186 187 188
  const apolloProvider = new VueApollo({
    defaultClient: window.graphQL
  })

189 190 191 192
  // ====================================
  // Bootstrap Vue
  // ====================================

193
  const i18n = localization.init()
194 195 196 197 198 199

  let darkModeEnabled = siteConfig.darkMode
  if ((store.get('user/appearance') || '').length > 0) {
    darkModeEnabled = (store.get('user/appearance') === 'dark')
  }

200
  window.WIKI = new Vue({
201
    el: '#root',
NGPixel's avatar
NGPixel committed
202
    components: {},
203
    mixins: [helpers],
204
    apolloProvider,
205
    store,
206 207
    i18n,
    vuetify: new Vuetify({
208 209
      rtl: siteConfig.rtl,
      theme: {
210
        dark: darkModeEnabled
211
      }
212 213 214 215 216 217 218 219 220 221 222 223 224 225
    }),
    mounted () {
      this.$moment.locale(siteConfig.lang)
      if ((store.get('user/dateFormat') || '').length > 0) {
        this.$moment.updateLocale(this.$moment.locale(), {
          longDateFormat: {
            'L': store.get('user/dateFormat')
          }
        })
      }
      if ((store.get('user/timezone') || '').length > 0) {
        this.$moment.tz.setDefault(store.get('user/timezone'))
      }
    }
226
  })
227

228 229 230 231 232 233 234 235
  // ----------------------------------
  // Dispatch boot ready
  // ----------------------------------

  window.boot.notify('vue')
}

window.boot.onDOMReady(bootstrap)