/
Indicator.js
307 lines (263 loc) · 8.54 KB
/
Indicator.js
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
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
297
298
299
300
301
302
303
304
305
306
307
import React, { useState, useEffect, useRef } from "react"
import IndicatorProvider from "../context/indicatorProvider"
import { BuildStatus } from "../models/enums"
import { useTrackEvent, getBuildInfo } from "../utils"
import {
LinkIndicatorButton,
InfoIndicatorButton,
GatsbyIndicatorButton,
} from "./buttons"
import Style from "./Style"
import { usePollForNodeManifest } from "../utils/use-poll-for-node-manifest"
const POLLING_INTERVAL = process.env.GATSBY_PREVIEW_POLL_INTERVAL
? parseInt(process.env.GATSBY_PREVIEW_POLL_INTERVAL)
: 2000
const PAGE_DATA_RETRY_LIMIT = 60
const PreviewIndicator = ({ children }) => (
<>
<Style />
<div
data-testid="preview-status-indicator"
data-gatsby-preview-indicator="root"
aria-live="assertive"
>
{children}
</div>
</>
)
const getContentSyncInfoFromURL = () => {
const urlSearchParams = new URLSearchParams(window.location.search)
// mid and plgn are shortened to keep the url short
const { mid: manifestId, plgn: pluginName } = JSON.parse(
atob(urlSearchParams.get(`csync`) || ``) || `{}`
)
if (!manifestId || !pluginName) {
return null
}
return { manifestId, pluginName }
}
let buildId = ``
let pageData
let latestCheckedBuild
let refreshNeeded = false
const Indicator = () => {
const [buildInfo, setBuildInfo] = useState()
const [contentSyncInfo, setContentSyncInfo] = useState(null)
const usingContentSync = !!contentSyncInfo
const timeoutRef = useRef(null)
const shouldPoll = useRef(false)
const trackedInitialLoad = useRef(false)
const { track } = useTrackEvent()
async function fetchPageData() {
const urlHostString = window.location.origin
const pathAdjustment =
window.location.pathname === `/` ? `/index` : window.location.pathname
const normalizedPath = `/page-data${pathAdjustment}/page-data.json`.replace(
/\/\//g,
`/`
)
const url = urlHostString + normalizedPath
try {
const resp = await fetch(url)
const data = await resp.text()
// for local dev with `gatsby develop` where page-data.json files never 404 and return an empty object instead.
if (data === `{}`) {
// for local development, force an error if page is missing.
const err = new Error(`Not Found`)
err.status = 404
throw err
}
return { data, errorMessage: null }
} catch (e) {
if (e.status === 404) {
return { data: null, errorMessage: `This page has moved.` }
} else {
return { data: null, errorMessage: null }
}
}
}
useEffect(() => {
const fetchData = async () => {
const { data } = await fetchPageData()
pageData = data
}
const contentSyncUrlParamInfo = getContentSyncInfoFromURL()
// prefer content sync
if (contentSyncUrlParamInfo) {
setContentSyncInfo(contentSyncUrlParamInfo)
}
// fall back to diffing page data
else {
fetchData()
}
}, [])
const pollForNodeManifestArgs = {
contentLoaderInfo: {
orgId: buildInfo?.siteInfo?.orgId,
previewBuildStatus: buildInfo?.currentBuild?.buildStatus,
previewUrl:
// for local dev / debugging
process.env.GATSBY_PREVIEW_URL ||
// for production
window.location.origin,
},
manifestId: contentSyncInfo?.manifestId,
sourcePluginName: contentSyncInfo?.pluginName,
siteId: buildInfo?.siteInfo?.siteId,
shouldPoll: !!contentSyncInfo,
}
const {
redirectUrl: nodeManifestRedirectUrl,
errorMessage: nodeManifestErrorMessage,
} = usePollForNodeManifest(pollForNodeManifestArgs)
React.useEffect(() => {
if (nodeManifestErrorMessage) {
console.error(nodeManifestErrorMessage)
} else if (nodeManifestRedirectUrl) {
// Force a "This page has updated message" until the page is refreshed
refreshNeeded = true
}
}, [nodeManifestRedirectUrl, nodeManifestErrorMessage])
const hasPageDataChanged = async () => {
if (buildId !== latestCheckedBuild) {
let pageDataCounter = 0
let hasPageChanged = false
while (!hasPageChanged && pageDataCounter <= PAGE_DATA_RETRY_LIMIT) {
const loadedPageData = pageData
const { data, errorMessage } = await fetchPageData()
if (errorMessage) {
return { hasPageChanged: false, errorMessage }
}
pageDataCounter++
hasPageChanged = loadedPageData !== data
if (!hasPageChanged) {
await new Promise(resolve => setTimeout(resolve, POLLING_INTERVAL))
}
}
latestCheckedBuild = buildId
return { hasPageChanged, errorMessage: null }
}
return { hasPageChanged: false, errorMessage: null }
}
const { siteInfo, currentBuild } = buildInfo || {
siteInfo: {},
currentBuild: {},
}
const { orgId, siteId } = siteInfo || {}
const pollData = async function pollData() {
const prettyUrlRegex = /^preview-/
const host = window.location.hostname
// currentBuild is the most recent build that is not QUEUED.
// latestBuild is the most recent build that finished running (ONLY status ERROR or SUCCESS)
const isOnPrettyUrl = prettyUrlRegex.test(host)
const { siteInfo, currentBuild, latestBuild } = await getBuildInfo()
if (!buildId) {
if (isOnPrettyUrl || host === `localhost`) {
buildId = latestBuild?.id
} else {
// Match UUID from preview build URL https://build-af44185e-b8e5-11eb-8529-0242ac130003.gtsb.io
const buildIdMatch = host?.match(/build-(.*?(?=\.))/)
if (buildIdMatch) {
buildId = buildIdMatch[1]
}
}
}
const newBuildInfo = {
currentBuild,
latestBuild,
siteInfo,
isOnPrettyUrl,
}
if (
[
BuildStatus.BUILDING,
BuildStatus.ERROR,
BuildStatus.QUEUED,
BuildStatus.UPLOADING,
].includes(currentBuild?.buildStatus)
) {
setBuildInfo({ ...newBuildInfo, buildStatus: currentBuild?.buildStatus })
} else if (buildId && buildId === newBuildInfo?.currentBuild?.id) {
setBuildInfo({ ...newBuildInfo, buildStatus: BuildStatus.UPTODATE })
} else if (
buildId &&
buildId !== newBuildInfo?.latestBuild?.id &&
currentBuild?.buildStatus === BuildStatus.SUCCESS
) {
if (refreshNeeded) {
setBuildInfo({ ...newBuildInfo, buildStatus: BuildStatus.SUCCESS })
} else if (!usingContentSync) {
const { hasPageChanged, errorMessage } = await hasPageDataChanged(
buildId
)
if (errorMessage) {
setBuildInfo({
...newBuildInfo,
buildStatus: BuildStatus.ERROR,
errorMessage,
})
} else if (hasPageChanged) {
// Force a "This page has updated message" until a page is refreshed
refreshNeeded = true
// Build updated, data for this specific page has changed!
setBuildInfo({ ...newBuildInfo, buildStatus: BuildStatus.SUCCESS })
} else {
// Build updated, data for this specific page has NOT changed, no need to refresh content.
setBuildInfo({ ...newBuildInfo, buildStatus: BuildStatus.UPTODATE })
}
}
}
if (shouldPoll.current) {
timeoutRef.current = setTimeout(pollData, POLLING_INTERVAL)
}
}
useEffect(() => {
if (buildInfo?.siteInfo && !trackedInitialLoad.current) {
track({
eventType: `PREVIEW_INDICATOR_LOADED`,
buildId,
orgId,
siteId,
})
trackedInitialLoad.current = true
}
}, [buildInfo])
useEffect(() => {
shouldPoll.current = true
pollData()
return function cleanup() {
shouldPoll.current = false
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
timeoutRef.current = null
}
}
}, [])
const buttonProps = {
orgId,
siteId,
buildId,
buildStatus: buildInfo?.buildStatus,
isOnPrettyUrl: buildInfo?.isOnPrettyUrl,
sitePrefix: siteInfo?.sitePrefix,
createdAt: currentBuild?.createdAt,
erroredBuildId: currentBuild?.id,
}
return (
<IndicatorProvider>
<PreviewIndicator>
<GatsbyIndicatorButton {...buttonProps} buttonIndex={1} />
<InfoIndicatorButton
{...buttonProps}
nodeManifestRedirectUrl={nodeManifestRedirectUrl}
usingContentSync={usingContentSync}
nodeManifestErrorMessage={nodeManifestErrorMessage}
buttonIndex={2}
/>
<LinkIndicatorButton {...buttonProps} buttonIndex={3} />
</PreviewIndicator>
</IndicatorProvider>
)
}
export { PreviewIndicator }
export default Indicator