-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathindex.js
351 lines (332 loc) · 9.75 KB
/
index.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import Waypoint from 'react-waypoint'
import Media from '../Media'
import {icons, loadStates} from '../constants'
import {xhrLoader, imageLoader, timeout, combineCancel} from '../loaders'
import {
guessMaxImageWidth,
bytesToSize,
supportsWebp,
ssr,
nativeConnection,
selectSrc,
fallbackParams,
} from '../helpers'
const {initial, loading, loaded, error} = loadStates
const defaultShouldAutoDownload = ({
connection,
size,
threshold,
possiblySlowNetwork,
}) => {
if (possiblySlowNetwork) return false
if (!connection) return true
const {downlink, rtt, effectiveType} = connection
switch (effectiveType) {
case 'slow-2g':
case '2g':
return false
case '3g':
if (downlink && size && threshold) {
return (size * 8) / (downlink * 1000) + rtt < threshold
}
return false
case '4g':
default:
return true
}
}
const defaultGetMessage = (icon, state) => {
switch (icon) {
case icons.noicon:
case icons.loaded:
return null
case icons.loading:
return 'Loading...'
case icons.load:
// we can show `alt` here
const {pickedSrc} = state
const {size} = pickedSrc
if (size) {
return [
'Click to load (',
<nobr key="nb">{bytesToSize(size)}</nobr>,
')',
]
} else {
return 'Click to load'
}
case icons.offline:
return 'Your browser is offline. Image not loaded'
case icons.error:
const {loadInfo} = state
if (loadInfo === 404) {
return '404. Image not found'
} else {
return 'Error. Click to reload'
}
default:
throw new Error(`Wrong icon: ${icon}`)
}
}
const defaultGetIcon = state => {
const {loadState, onLine, overThreshold, userTriggered} = state
if (ssr) return icons.noicon
switch (loadState) {
case loaded:
return icons.loaded
case loading:
return overThreshold ? icons.loading : icons.noicon
case initial:
if (onLine) {
const {shouldAutoDownload} = state
if (shouldAutoDownload === undefined) return icons.noicon
return userTriggered || !shouldAutoDownload ? icons.load : icons.noicon
} else {
return icons.offline
}
case error:
return onLine ? icons.error : icons.offline
default:
throw new Error(`Wrong state: ${loadState}`)
}
}
export default class IdealImage extends Component {
constructor(props) {
super(props)
// TODO: validate props.srcSet
this.state = {
loadState: initial,
connection: nativeConnection
? {
downlink: navigator.connection.downlink, // megabits per second
rtt: navigator.connection.rtt, // ms
effectiveType: navigator.connection.effectiveType, // 'slow-2g', '2g', '3g', or '4g'
}
: null,
onLine: true,
overThreshold: false,
inViewport: false,
userTriggered: false,
possiblySlowNetwork: false,
}
}
static propTypes = {
/** how much to wait in ms until concider download to slow */
threshold: PropTypes.number,
/** function to generate src based on width and format */
getUrl: PropTypes.func,
/** array of sources */
srcSet: PropTypes.arrayOf(
PropTypes.shape({
width: PropTypes.number.isRequired,
src: PropTypes.string,
size: PropTypes.number,
format: PropTypes.oneOf(['jpeg', 'webp']),
}),
).isRequired,
/** function which decides if image should be downloaded */
shouldAutoDownload: PropTypes.func,
/** function which decides what message to show */
getMessage: PropTypes.func,
/** function which decides what icon to show */
getIcon: PropTypes.func,
/** type of loader */
loader: PropTypes.oneOf(['image', 'xhr']),
/** Width of the image in px */
width: PropTypes.number.isRequired,
/** Height of the image in px */
height: PropTypes.number.isRequired,
placeholder: PropTypes.oneOfType([
PropTypes.shape({
/** Solid color placeholder */
color: PropTypes.string.isRequired,
}),
PropTypes.shape({
/**
* [Low Quality Image Placeholder](https://github.com/zouhir/lqip)
* [SVG-Based Image Placeholder](https://github.com/technopagan/sqip)
* base64 encoded image of low quality
*/
lqip: PropTypes.string.isRequired,
}),
]).isRequired,
/** Map of icons */
icons: PropTypes.object.isRequired,
/** theme object - CSS Modules or React styles */
theme: PropTypes.object.isRequired,
}
static defaultProps = {
shouldAutoDownload: defaultShouldAutoDownload,
getMessage: defaultGetMessage,
getIcon: defaultGetIcon,
loader: 'xhr',
}
componentDidMount() {
if (nativeConnection) {
this.updateConnection = () => {
if (!navigator.onLine) return
if (this.state.loadState === initial) {
this.setState({
connection: {
effectiveType: navigator.connection.effectiveType,
downlink: navigator.connection.downlink,
rtt: navigator.connection.rtt,
},
})
}
}
navigator.connection.addEventListener('onchange', this.updateConnection)
} else if (this.props.threshold) {
this.possiblySlowNetworkListener = e => {
if (this.state.loadState !== initial) return
const {possiblySlowNetwork} = e.detail
if (!this.state.possiblySlowNetwork && possiblySlowNetwork) {
this.setState({possiblySlowNetwork})
}
}
window.document.addEventListener(
'possiblySlowNetwork',
this.possiblySlowNetworkListener,
)
}
this.updateOnlineStatus = () => this.setState({onLine: navigator.onLine})
this.updateOnlineStatus()
window.addEventListener('online', this.updateOnlineStatus)
window.addEventListener('offline', this.updateOnlineStatus)
}
componentWillUnmount() {
this.clear()
if (nativeConnection) {
navigator.connection.removeEventListener(
'onchange',
this.updateConnection,
)
} else if (this.props.threshold) {
window.document.removeEventListener(
'possiblySlowNetwork',
this.possiblySlowNetworkListener,
)
}
window.removeEventListener('online', this.updateOnlineStatus)
window.removeEventListener('offline', this.updateOnlineStatus)
}
onClick = () => {
const {loadState, onLine, overThreshold} = this.state
if (!onLine) return
switch (loadState) {
case loading:
if (overThreshold) this.cancel(true)
return
case loaded:
// nothing
return
case initial:
case error:
this.load(true)
return
default:
throw new Error(`Wrong state: ${loadState}`)
}
}
clear() {
if (this.loader) {
this.loader.cancel()
this.loader = undefined
}
}
cancel(userTriggered) {
if (loading !== this.state.loadState) return
this.clear()
this.loadStateChange(initial, userTriggered)
}
loadStateChange(loadState, userTriggered, loadInfo = null) {
this.setState({
loadState,
overThreshold: false,
userTriggered: !!userTriggered,
loadInfo,
})
}
load = userTriggered => {
const {loadState, url} = this.state
if (ssr || loaded === loadState || loading === loadState) return
this.loadStateChange(loading, userTriggered)
const {threshold} = this.props
const loader =
this.props.loader === 'xhr' ? xhrLoader(url) : imageLoader(url)
loader
.then(() => {
this.clear()
this.loadStateChange(loaded, false)
})
.catch(e => {
this.clear()
if (e.status === 404) {
this.loadStateChange(error, false, 404)
} else {
this.loadStateChange(error, false)
}
})
if (threshold) {
const timeoutLoader = timeout(threshold)
timeoutLoader.then(() => {
if (!this.loader) return
window.document.dispatchEvent(
new CustomEvent('possiblySlowNetwork', {
detail: {possiblySlowNetwork: true},
}),
)
this.setState({overThreshold: true})
if (!this.state.userTriggered) this.cancel(true)
})
this.loader = combineCancel(loader, timeoutLoader)
} else {
this.loader = loader
}
}
onEnter = () => {
if (this.state.inViewport) return
this.setState({inViewport: true})
const pickedSrc = selectSrc({
srcSet: this.props.srcSet,
maxImageWidth:
this.props.srcSet.length > 1
? guessMaxImageWidth(this.state.dimensions) // eslint-disable-line react/no-access-state-in-setstate
: 0,
supportsWebp,
})
const {getUrl} = this.props
const url = getUrl ? getUrl(pickedSrc) : pickedSrc.src
const shouldAutoDownload = this.props.shouldAutoDownload({
...this.state, // eslint-disable-line react/no-access-state-in-setstate
size: pickedSrc.size,
})
this.setState({pickedSrc, shouldAutoDownload, url})
if (shouldAutoDownload) this.load(false)
}
onLeave = () => {
if (this.state.loadState === loading && !this.state.userTriggered) {
this.setState({inViewport: false})
this.cancel(false)
}
}
render() {
const icon = this.props.getIcon(this.state)
const message = this.props.getMessage(icon, this.state)
return (
<Waypoint onEnter={this.onEnter} onLeave={this.onLeave}>
<Media
{...this.props}
{...fallbackParams(this.props)}
onClick={this.onClick}
icon={icon}
src={this.state.url || ''}
onDimensions={dimensions => this.setState({dimensions})}
message={message}
/>
</Waypoint>
)
}
}