/
LoadScript.tsx
230 lines (190 loc) · 5.94 KB
/
LoadScript.tsx
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
import * as React from 'react'
import invariant from 'invariant'
import { injectScript } from './utils/injectscript'
import { preventGoogleFonts } from './utils/prevent-google-fonts'
import { isBrowser } from './utils/isbrowser'
import { LoadScriptUrlOptions, makeLoadScriptUrl } from './utils/make-load-script-url'
let cleaningUp = false
interface LoadScriptState {
loaded: boolean
}
export interface LoadScriptProps extends LoadScriptUrlOptions {
id: string
nonce?: string
loadingElement?: React.ReactNode
onLoad?: () => void
onError?: (error: Error) => void
onUnmount?: () => void
preventGoogleFontsLoading?: boolean
}
export function DefaultLoadingElement(): JSX.Element {
return <div>{`Loading...`}</div>
}
export const defaultLoadScriptProps = {
id: 'script-loader',
version: 'weekly',
}
class LoadScript extends React.PureComponent<LoadScriptProps, LoadScriptState> {
public static defaultProps = defaultLoadScriptProps
check: React.RefObject<HTMLDivElement> = React.createRef()
state = {
loaded: false,
}
cleanupCallback = (): void => {
// @ts-ignore
delete window.google.maps
this.injectScript()
}
componentDidMount(): void {
if (isBrowser) {
if (window.google && window.google.maps && !cleaningUp) {
console.error('google api is already presented')
return
}
this.isCleaningUp()
.then(this.injectScript)
.catch(function error(err) {
console.error('Error at injecting script after cleaning up: ', err)
})
}
}
componentDidUpdate(prevProps: LoadScriptProps): void {
if (this.props.libraries !== prevProps.libraries) {
console.warn(
'Performance warning! LoadScript has been reloaded unintentionally! You should not pass `libraries` prop as new array. Please keep an array of libraries as static class property for Components and PureComponents, or just a const variable outside of component, or somewhere in config files or ENV variables'
)
}
if (isBrowser && prevProps.language !== this.props.language) {
this.cleanup()
// TODO: refactor to use gDSFP maybe... wait for hooks refactoring.
// eslint-disable-next-line react/no-did-update-set-state
this.setState(function setLoaded() {
return {
loaded: false,
}
}, this.cleanupCallback)
}
}
componentWillUnmount(): void {
if (isBrowser) {
this.cleanup()
const timeoutCallback = (): void => {
if (!this.check.current) {
// @ts-ignore
delete window.google
cleaningUp = false
}
}
window.setTimeout(timeoutCallback, 1)
if (this.props.onUnmount) {
this.props.onUnmount()
}
}
}
isCleaningUp = async (): Promise<void> => {
function promiseCallback(resolve: () => void): void {
if (!cleaningUp) {
resolve()
} else {
if (isBrowser) {
const timer = window.setInterval(function interval() {
if (!cleaningUp) {
window.clearInterval(timer)
resolve()
}
}, 1)
}
}
return
}
return new Promise(promiseCallback)
}
cleanup = (): void => {
cleaningUp = true
const script = document.getElementById(this.props.id)
if (script && script.parentNode) {
script.parentNode.removeChild(script)
}
Array.prototype.slice
.call(document.getElementsByTagName('script'))
.filter(function filter(script: HTMLScriptElement): boolean {
return typeof script.src === 'string' && script.src.includes('maps.googleapis')
})
.forEach(function forEach(script: HTMLScriptElement): void {
if (script.parentNode) {
script.parentNode.removeChild(script)
}
})
Array.prototype.slice
.call(document.getElementsByTagName('link'))
.filter(function filter(link: HTMLLinkElement): boolean {
return (
link.href === 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Google+Sans'
)
})
.forEach(function forEach(link: HTMLLinkElement) {
if (link.parentNode) {
link.parentNode.removeChild(link)
}
})
Array.prototype.slice
.call(document.getElementsByTagName('style'))
.filter(function filter(style: HTMLStyleElement): boolean {
return (
style.innerText !== undefined &&
style.innerText.length > 0 &&
style.innerText.includes('.gm-')
)
})
.forEach(function forEach(style: HTMLStyleElement) {
if (style.parentNode) {
style.parentNode.removeChild(style)
}
})
}
injectScript = (): void => {
if (this.props.preventGoogleFontsLoading) {
preventGoogleFonts()
}
invariant(!!this.props.id, 'LoadScript requires "id" prop to be a string: %s', this.props.id)
const injectScriptOptions = {
id: this.props.id,
nonce: this.props.nonce,
url: makeLoadScriptUrl(this.props),
}
injectScript(injectScriptOptions)
.then(() => {
if (this.props.onLoad) {
this.props.onLoad()
}
this.setState(function setLoaded() {
return {
loaded: true,
}
})
return
})
.catch(err => {
if (this.props.onError) {
this.props.onError(err)
}
console.error(`
There has been an Error with loading Google Maps API script, please check that you provided correct google API key (${this
.props.googleMapsApiKey || '-'}) or Client ID (${this.props.googleMapsClientId ||
'-'}) to <LoadScript />
Otherwise it is a Network issue.
`)
})
}
render(): React.ReactNode {
return (
<>
<div ref={this.check} />
{this.state.loaded
? this.props.children
: this.props.loadingElement || <DefaultLoadingElement />}
</>
)
}
}
export default LoadScript