-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathclient.js
More file actions
245 lines (228 loc) · 7.53 KB
/
client.js
File metadata and controls
245 lines (228 loc) · 7.53 KB
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
237
238
239
240
241
242
243
244
245
/* eslint-env browser */
import 'regenerator-runtime/runtime'
import { BrowserRouter, Route } from 'react-router-dom'
import App from './app'
import { loadableReady } from '@loadable/component'
import React, { Fragment } from 'react'
import { createRoot, hydrateRoot } from 'react-dom/client'
import TagManager from 'react-gtm-module'
import globalEnv from './global-env'
import hashLinkScroll from './utils/hash-link-scroll'
import loggerFactory from './logger'
import releaseBranchConsts from '@twreporter/core/lib/constants/release-branch'
import twreporterRedux from '@twreporter/redux'
import '@material-symbols/font-400/outlined.css'
import 'swiper/swiper.min.css'
import { HelmetProvider } from 'react-helmet-async'
// lodash
import get from 'lodash/get'
const _ = {
get,
}
const logger = loggerFactory.getLogger()
const releaseBranch = globalEnv.releaseBranch
const tagManagerArgs = {
master: {
gtmId: 'GTM-PRMXBBN',
auth: '2pJC7GotZqWa7HtmIgSFIg',
preview: 'env-231',
},
dev: {
gtmId: 'GTM-PRMXBBN',
auth: 'XFsQ67nTp2wXWpJllmNBCQ',
preview: 'env-229',
},
staging: {
gtmId: 'GTM-PRMXBBN',
auth: 'XFsQ67nTp2wXWpJllmNBCQ',
preview: 'env-229',
},
preview: {
gtmId: 'GTM-PRMXBBN',
auth: '83UcO7BTHJ6dJZ8_nCUmug',
preview: 'env-234',
},
release: {
gtmId: 'GTM-PRMXBBN',
},
}
let reduxState
if (window.__REDUX_STATE__) {
reduxState = window.__REDUX_STATE__
}
/**
* Our application is a SPA (Single Page Application).
* In our app, we send requests to API webservices to get data
* if that data is not in the redux store.
* In other words, if data is already in the redux state, we won't send requests.
* There will be a problem of stale data.
* For example,
* 1. end user goes to page A. App will fetch page A data and store it in redux state.
* 2. end user goes to page B. App will fetch page B data and store it in redux state.
* 3. end user goes to page A again. App won't fetch page A data since it already in
* the redux state.
*
* If end users don't refresh the web page, the data will be always in the
* redux store. Therefore, end users might see the stale data
* even the data is already updated.
*
* This function create a closure to store current timestamp + one day timestamp,
* and returns another function.
* If clients invoke that returned function, that function will reload the web page
* if needed.
*
* @return {Function}
*/
function reloadPageIfNeeded() {
const oneDayTs = 60 * 60 * 24 * 1000
const nextTimeReloadTs = Date.now() + oneDayTs
return () => {
const now = Date.now()
if (nextTimeReloadTs < now) {
window.location.reload()
}
return null
}
}
function scrollToTopAndFirePageview() {
window.scrollTo(0, 0)
// send Google Analytics Pageview event on route changed
TagManager.dataLayer({
dataLayer: {
event: 'PageView',
page: window.location.pathname + window.location.search,
},
})
return null
}
function sendGtmUserId() {
if (!store) {
return null
}
const currentState = store.getState()
const userId = _.get(currentState, ['auth', 'userInfo', 'user_id'], '')
if (userId) {
TagManager.dataLayer({
dataLayer: {
userId,
},
})
}
return null
}
const store = twreporterRedux.createStore(
reduxState,
'',
globalEnv.isDevelopment
)
// add Google Tag Manager
TagManager.initialize(tagManagerArgs[releaseBranch])
const jsx = (
<HelmetProvider>
<BrowserRouter>
<Fragment>
<Route path="/" component={reloadPageIfNeeded()} />
<Route path="/" component={scrollToTopAndFirePageview} />
<Route path="/" component={hashLinkScroll} />
<Route path="/" component={sendGtmUserId} />
<App reduxStore={store} releaseBranch={releaseBranch} />
</Fragment>
</BrowserRouter>
</HelmetProvider>
)
loadableReady(() => {
const container = document.getElementById('root')
if (globalEnv.isProduction) {
hydrateRoot(container, jsx)
} else {
createRoot(container).render(jsx)
}
if (globalEnv.isDevelopment) {
// FPS meter
import('stats-js')
.then(Stats => {
const stats = new Stats()
stats.showPanel(0) // 0: fps, 1: ms, 2: mb, 3+: custom
document.body.appendChild(stats.dom)
function animate() {
stats.begin()
stats.end()
window.requestAnimationFrame(animate)
}
window.requestAnimationFrame(animate)
stats.dom.style.right = '0'
stats.dom.style.left = 'initial'
})
.catch(err => {
console.log(err)
})
}
})
/**
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (
'serviceWorker' in navigator &&
globalEnv.isProduction &&
releaseBranch !== releaseBranchConsts.preview
) {
// Delay registration until after the page has loaded, to ensure that our
// precaching requests don't degrade the first visit experience.
// See https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration
window.addEventListener('load', function() {
// Your service-worker.js *must* be located at the top-level directory relative to your site.
// It won't be able to control pages unless it's located at the same level or higher than them.
// *Don't* register service worker file in, e.g., a scripts/ sub-directory!
// See https://github.com/slightlyoff/ServiceWorker/issues/468
navigator.serviceWorker
.register('/sw.js')
.then(function(reg) {
// updatefound is fired if service-worker.js changes.
reg.onupdatefound = function() {
// The updatefound event implies that reg.installing is set; see
// https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event
const installingWorker = reg.installing
installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and the fresh content will
// have been added to the cache.
// It's the perfect time to display a "New content is available; please refresh."
// message in the page's interface.
logger.info('New or updated content is available.')
} else {
// At this point, everything has been precached.
// It's the perfect time to display a "Content is cached for offline use." message.
logger.info('Content is now available offline!')
}
break
case 'redundant':
logger.errorReport({
message: 'The installing service worker became redundant',
})
break
}
}
}
})
.catch(function(e) {
logger.errorReport({
report: e,
message: 'Error during service worker registration.',
})
})
})
}