2021-06-27 12:28:54 +00:00
|
|
|
import { useEffect } from 'react'
|
|
|
|
import state, { useSelector } from 'state'
|
2021-06-27 09:07:20 +00:00
|
|
|
import { getShapeUtils } from 'state/shape-utils'
|
2021-07-09 16:15:27 +00:00
|
|
|
import { PageState, Bounds, ShapeType, Shape } from 'types'
|
2021-06-27 09:07:20 +00:00
|
|
|
import {
|
|
|
|
boundsCollide,
|
|
|
|
boundsContain,
|
2021-06-27 12:28:54 +00:00
|
|
|
debounce,
|
2021-06-27 09:07:20 +00:00
|
|
|
deepCompareArrays,
|
|
|
|
} from 'utils'
|
2021-06-29 12:00:59 +00:00
|
|
|
import tld from 'utils/tld'
|
2021-06-27 09:07:20 +00:00
|
|
|
|
|
|
|
const viewportCache = new WeakMap<PageState, Bounds>()
|
|
|
|
|
2021-07-09 16:15:27 +00:00
|
|
|
export default function usePageShapes(): Shape[] {
|
2021-06-27 12:28:54 +00:00
|
|
|
// Reset the viewport cache when the window resizes
|
|
|
|
useEffect(() => {
|
|
|
|
const handleResize = debounce(() => state.send('RESIZED_WINDOW'), 32)
|
|
|
|
|
|
|
|
window.addEventListener('resize', handleResize)
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
window.removeEventListener('resize', handleResize)
|
|
|
|
}
|
|
|
|
}, [])
|
|
|
|
|
|
|
|
// Get the shapes that fit into the current window
|
2021-06-28 12:13:34 +00:00
|
|
|
const visiblePageShapeIds = useSelector((s) => {
|
2021-06-29 12:00:59 +00:00
|
|
|
const pageState = tld.getPageState(s.data)
|
2021-06-27 09:07:20 +00:00
|
|
|
|
|
|
|
if (!viewportCache.has(pageState)) {
|
2021-06-29 12:00:59 +00:00
|
|
|
const viewport = tld.getViewport(s.data)
|
2021-06-27 09:07:20 +00:00
|
|
|
viewportCache.set(pageState, viewport)
|
|
|
|
}
|
|
|
|
|
|
|
|
const viewport = viewportCache.get(pageState)
|
|
|
|
|
2021-07-09 16:15:27 +00:00
|
|
|
const shapesToShow = s.values.currentShapes.filter((shape) => {
|
|
|
|
if (shape.type === ShapeType.Ray || shape.type === ShapeType.Line) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
const shapeBounds = getShapeUtils(shape).getBounds(shape)
|
|
|
|
return (
|
|
|
|
boundsContain(viewport, shapeBounds) ||
|
|
|
|
boundsCollide(viewport, shapeBounds)
|
|
|
|
)
|
|
|
|
})
|
2021-07-04 08:24:45 +00:00
|
|
|
|
|
|
|
return shapesToShow
|
2021-06-27 09:07:20 +00:00
|
|
|
}, deepCompareArrays)
|
2021-06-28 12:13:34 +00:00
|
|
|
|
|
|
|
return visiblePageShapeIds
|
2021-06-27 09:07:20 +00:00
|
|
|
}
|