Pinafore-Web-Client-Frontend/routes/_utils/AsyncLayout.js

51 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

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