2018-01-17 19:16:04 -08:00
|
|
|
// Use intersection observer to calculate rects asynchronously
|
2018-01-23 17:25:56 -08:00
|
|
|
import { getRectFromEntry } from './getRectFromEntry'
|
|
|
|
|
2018-01-17 19:16:04 -08:00
|
|
|
class AsyncLayout {
|
2018-02-08 22:29:29 -08:00
|
|
|
constructor (generateKeyFromNode) {
|
2018-01-17 19:16:04 -08:00
|
|
|
this._onIntersectionCallbacks = {}
|
|
|
|
|
|
|
|
this._intersectionObserver = new IntersectionObserver(entries => {
|
|
|
|
entries.forEach(entry => {
|
|
|
|
let key = generateKeyFromNode(entry.target)
|
|
|
|
this._onIntersectionCallbacks[key](entry)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-02-08 22:29:29 -08:00
|
|
|
observe (key, node, callback) {
|
2018-01-27 10:46:52 -08:00
|
|
|
if (!node) {
|
|
|
|
return
|
|
|
|
}
|
2018-01-23 21:02:51 -08:00
|
|
|
if (this._intersectionObserver) {
|
|
|
|
this._onIntersectionCallbacks[key] = (entry) => {
|
|
|
|
callback(getRectFromEntry(entry))
|
|
|
|
this.unobserve(key, node)
|
|
|
|
}
|
|
|
|
this._intersectionObserver.observe(node)
|
2018-01-17 19:16:04 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-08 22:29:29 -08:00
|
|
|
unobserve (key, node) {
|
2018-01-17 19:16:04 -08:00
|
|
|
if (key in this._onIntersectionCallbacks) {
|
|
|
|
return
|
|
|
|
}
|
2018-01-27 10:46:52 -08:00
|
|
|
if (!node) {
|
|
|
|
return
|
|
|
|
}
|
2018-01-23 21:02:51 -08:00
|
|
|
if (this._intersectionObserver) {
|
|
|
|
this._intersectionObserver.unobserve(node)
|
|
|
|
}
|
2018-01-17 19:16:04 -08:00
|
|
|
delete this._onIntersectionCallbacks[key]
|
|
|
|
}
|
2018-01-21 10:32:18 -08:00
|
|
|
|
2018-02-08 22:29:29 -08:00
|
|
|
disconnect () {
|
2018-01-23 21:02:51 -08:00
|
|
|
if (this._intersectionObserver) {
|
|
|
|
this._intersectionObserver.disconnect()
|
|
|
|
this._intersectionObserver = null
|
|
|
|
}
|
2018-01-21 10:32:18 -08:00
|
|
|
}
|
2018-01-17 19:16:04 -08:00
|
|
|
}
|
|
|
|
|
2018-02-08 22:29:29 -08:00
|
|
|
export { AsyncLayout }
|