/
Visibility.js
426 lines (349 loc) · 11.5 KB
/
Visibility.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import { Ref } from '@stardust-ui/react-component-ref'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React, { Component, createRef } from 'react'
import {
eventStack,
getElementType,
getUnhandledProps,
normalizeOffset,
isBrowser,
} from '../../lib'
/**
* Visibility provides a set of callbacks for when a content appears in the viewport.
*/
export default class Visibility extends Component {
static propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** Primary content. */
children: PropTypes.node,
/** Context which visibility should attach onscroll events. */
context: PropTypes.object,
/**
* When set to true a callback will occur anytime an element passes a condition not just immediately after the
* threshold is met.
*/
continuous: PropTypes.bool,
/** Fires callbacks immediately after mount. */
fireOnMount: PropTypes.bool,
/**
* Element's bottom edge has passed top of screen.
*
* @param {null}
* @param {object} data - All props.
*/
onBottomPassed: PropTypes.func,
/**
* Element's bottom edge has not passed top of screen.
*
* @param {null}
* @param {object} data - All props.
*/
onBottomPassedReverse: PropTypes.func,
/**
* Element's bottom edge has passed bottom of screen
*
* @param {null}
* @param {object} data - All props.
*/
onBottomVisible: PropTypes.func,
/**
* Element's bottom edge has not passed bottom of screen.
*
* @param {null}
* @param {object} data - All props.
*/
onBottomVisibleReverse: PropTypes.func,
/**
* Value that context should be adjusted in pixels. Useful for making content appear below content fixed to the
* page.
*/
offset: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string])),
]),
/** When set to false a callback will occur each time an element passes the threshold for a condition. */
once: PropTypes.bool,
/** Element is not visible on the screen. */
onPassed: PropTypes.object,
/**
* Any part of an element is visible on screen.
*
* @param {null}
* @param {object} data - All props.
*/
onPassing: PropTypes.func,
/**
* Element's top has not passed top of screen but bottom has.
*
* @param {null}
* @param {object} data - All props.
*/
onPassingReverse: PropTypes.func,
/**
* Element is not visible on the screen.
*
* @param {null}
* @param {object} data - All props.
*/
onOffScreen: PropTypes.func,
/**
* Element is visible on the screen.
*
* @param {null}
* @param {object} data - All props.
*/
onOnScreen: PropTypes.func,
/**
* Element's top edge has passed top of the screen.
*
* @param {null}
* @param {object} data - All props.
*/
onTopPassed: PropTypes.func,
/**
* Element's top edge has not passed top of the screen.
*
* @param {null}
* @param {object} data - All props.
*/
onTopPassedReverse: PropTypes.func,
/**
* Element's top edge has passed bottom of screen.
*
* @param {null}
* @param {object} data - All props.
*/
onTopVisible: PropTypes.func,
/**
* Element's top edge has not passed bottom of screen.
*
* @param {null}
* @param {object} data - All props.
*/
onTopVisibleReverse: PropTypes.func,
/**
* Element's top edge has passed bottom of screen.
*
* @param {null}
* @param {object} data - All props.
*/
onUpdate: PropTypes.func,
/**
* Allows to choose the mode of the position calculations:
* - `events` - (default) update and fire callbacks only on scroll/resize events
* - `repaint` - update and fire callbacks on browser repaint (animation frames)
*/
updateOn: PropTypes.oneOf(['events', 'repaint']),
}
static defaultProps = {
context: isBrowser() ? window : null,
continuous: false,
offset: [0, 0],
once: true,
updateOn: 'events',
}
calculations = {
bottomPassed: false,
bottomVisible: false,
fits: false,
passing: false,
offScreen: false,
onScreen: false,
topPassed: false,
topVisible: false,
}
firedCallbacks = []
ref = createRef()
// ----------------------------------------
// Lifecycle
// ----------------------------------------
componentDidMount() {
this.mounted = true
if (!isBrowser()) return
const { context, fireOnMount, updateOn } = this.props
this.pageYOffset = this.getPageYOffset()
this.attachHandlers(context, updateOn)
if (fireOnMount) this.update()
}
componentDidUpdate(prevProps) {
const cleanHappened =
prevProps.continuous !== this.props.continuous ||
prevProps.once !== this.props.once ||
prevProps.updateOn !== this.props.updateOn
// Heads up! We should clean up array of happened callbacks, if values of these props are changed
if (cleanHappened) this.firedCallbacks = []
if (prevProps.context !== this.props.context || prevProps.updateOn !== this.props.updateOn) {
this.unattachHandlers(prevProps.context)
this.attachHandlers(this.props.context, this.props.updateOn)
}
}
componentWillUnmount() {
const { context } = this.props
this.unattachHandlers(context)
this.mounted = false
}
attachHandlers(context, updateOn) {
if (updateOn === 'events') {
if (context) {
eventStack.sub('resize', this.handleUpdate, { target: context })
eventStack.sub('scroll', this.handleUpdate, { target: context })
}
return
}
// Heads up!
// We will deal with `repaint` there
this.handleUpdate()
}
unattachHandlers(context) {
if (context) {
eventStack.unsub('resize', this.handleUpdate, { target: context })
eventStack.unsub('scroll', this.handleUpdate, { target: context })
}
if (this.frameId) cancelAnimationFrame(this.frameId)
}
// ----------------------------------------
// Callback handling
// ----------------------------------------
execute(callback, name) {
const { continuous } = this.props
if (!callback) return
// Heads up! When `continuous` is true, callback will be fired always
if (!continuous && _.includes(this.firedCallbacks, name)) return
callback(null, { ...this.props, calculations: this.calculations })
this.firedCallbacks.push(name)
}
fire = ({ callback, name }, value, reverse = false) => {
const { continuous, once } = this.props
// Heads up! For the execution is required:
// - current value correspond to the fired direction
// - `continuous` is true or calculation values are different
const matchesDirection = this.calculations[value] !== reverse
const executionPossible = continuous || this.calculations[value] !== this.oldCalculations[value]
if (matchesDirection && executionPossible) this.execute(callback, name)
// Heads up! We should remove callback from the happened when it's not `once`
if (!once) this.firedCallbacks = _.without(this.firedCallbacks, name)
}
fireOnPassed() {
const { percentagePassed, pixelsPassed } = this.calculations
const { onPassed } = this.props
_.forEach(onPassed, (callback, passed) => {
const pixelsValue = Number(passed)
if (pixelsValue && pixelsPassed >= pixelsValue) {
this.execute(callback, passed)
return
}
const matchPercentage = `${passed}`.match(/^(\d+)%$/)
if (!matchPercentage) return
const percentageValue = Number(matchPercentage[1]) / 100
if (percentagePassed >= percentageValue) this.execute(callback, passed)
})
}
handleUpdate = () => {
if (this.ticking) return
this.ticking = true
this.frameId = requestAnimationFrame(this.update)
}
update = () => {
if (!this.mounted) return
this.ticking = false
this.oldCalculations = this.calculations
this.calculations = this.computeCalculations()
this.pageYOffset = this.getPageYOffset()
const {
onBottomPassed,
onBottomPassedReverse,
onBottomVisible,
onBottomVisibleReverse,
onPassing,
onPassingReverse,
onTopPassed,
onTopPassedReverse,
onTopVisible,
onTopVisibleReverse,
onOffScreen,
onOnScreen,
updateOn,
} = this.props
const forward = {
bottomPassed: { callback: onBottomPassed, name: 'onBottomPassed' },
bottomVisible: { callback: onBottomVisible, name: 'onBottomVisible' },
passing: { callback: onPassing, name: 'onPassing' },
offScreen: { callback: onOffScreen, name: 'onOffScreen' },
onScreen: { callback: onOnScreen, name: 'onOnScreen' },
topPassed: { callback: onTopPassed, name: 'onTopPassed' },
topVisible: { callback: onTopVisible, name: 'onTopVisible' },
}
const reverse = {
bottomPassed: { callback: onBottomPassedReverse, name: 'onBottomPassedReverse' },
bottomVisible: { callback: onBottomVisibleReverse, name: 'onBottomVisibleReverse' },
passing: { callback: onPassingReverse, name: 'onPassingReverse' },
topPassed: { callback: onTopPassedReverse, name: 'onTopPassedReverse' },
topVisible: { callback: onTopVisibleReverse, name: 'onTopVisibleReverse' },
}
_.invoke(this.props, 'onUpdate', null, { ...this.props, calculations: this.calculations })
this.fireOnPassed()
// Heads up! Reverse callbacks should be fired first
_.forEach(reverse, (data, value) => this.fire(data, value, true))
_.forEach(forward, (data, value) => this.fire(data, value))
if (updateOn === 'repaint') this.handleUpdate()
}
// ----------------------------------------
// Helpers
// ----------------------------------------
computeCalculations() {
const { offset } = this.props
const { bottom, height, top, width } = this.ref.current.getBoundingClientRect()
const [topOffset, bottomOffset] = normalizeOffset(offset)
const newOffset = this.getPageYOffset()
const direction = newOffset > this.pageYOffset ? 'down' : 'up'
const topPassed = top < topOffset
const bottomPassed = bottom < bottomOffset
const pixelsPassed = bottomPassed ? 0 : Math.max(top * -1, 0)
const percentagePassed = pixelsPassed / height
const bottomVisible = bottom >= bottomOffset && bottom <= window.innerHeight
const topVisible = top >= topOffset && top <= window.innerHeight
const fits = topVisible && bottomVisible
const passing = topPassed && !bottomPassed
const onScreen = (topVisible || topPassed) && !bottomPassed
const offScreen = !onScreen
return {
bottomPassed,
bottomVisible,
direction,
fits,
height,
passing,
percentagePassed,
pixelsPassed,
offScreen,
onScreen,
topPassed,
topVisible,
width,
}
}
getPageYOffset() {
const { context } = this.props
if (context) {
// Heads up! `window` doesn't have `pageYOffset` property
return context === window ? window.pageYOffset : context.scrollTop
}
return 0
}
// ----------------------------------------
// Render
// ----------------------------------------
render() {
const { children } = this.props
const ElementType = getElementType(Visibility, this.props)
const rest = getUnhandledProps(Visibility, this.props)
return (
<Ref innerRef={this.ref}>
<ElementType {...rest}>{children}</ElementType>
</Ref>
)
}
}