pinafore/routes/_utils/virtualListStore.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

import { Store } from 'svelte/store.js'
2018-01-16 01:12:07 +01:00
const RENDER_BUFFER = 1000
class VirtualListStore extends Store {
}
const virtualListStore = new VirtualListStore({
items: [],
itemHeights: {},
2018-01-16 01:35:08 +01:00
scrollTop: 0
})
2018-01-16 01:12:07 +01:00
virtualListStore.compute('visibleItems',
2018-01-16 01:35:08 +01:00
['items', 'scrollTop', 'height', 'itemHeights', 'innerHeight'],
(items, scrollTop, height, itemHeights, innerHeight) => {
2018-01-16 01:12:07 +01:00
let visibleItems = []
let currentOffset = 0
2018-01-16 01:35:08 +01:00
items.forEach((item, index) => {
let { props, key } = item
let height = itemHeights[key] || 0
console.log(key, 'scrollTop', scrollTop, 'currentOffset', currentOffset, 'innerHeight', innerHeight)
2018-01-16 01:12:07 +01:00
if (
((currentOffset < scrollTop) && (scrollTop - RENDER_BUFFER < currentOffset)) ||
((currentOffset >= scrollTop) && (currentOffset < (scrollTop + innerHeight + RENDER_BUFFER)))
) {
2018-01-16 01:35:08 +01:00
console.log(' rendering', key)
2018-01-16 01:12:07 +01:00
visibleItems.push({
2018-01-16 01:35:08 +01:00
offset: currentOffset,
props: props,
key: key,
index: index
2018-01-16 01:12:07 +01:00
})
} else {
2018-01-16 01:35:08 +01:00
console.log('not rendering', key)
2018-01-16 01:12:07 +01:00
}
currentOffset += height
})
2018-01-16 01:12:07 +01:00
return visibleItems
})
2018-01-16 01:35:08 +01:00
virtualListStore.compute('height', ['items', 'itemHeights'], (items, itemHeights) => {
let sum = 0
2018-01-16 01:35:08 +01:00
items.forEach(item => {
sum += itemHeights[item.key] || 0
})
return sum
})
if (process.browser && process.env.NODE_ENV !== 'production') {
window.virtualListStore = virtualListStore
}
export {
virtualListStore
}