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'
|
|
|
|
import { PageState, Bounds } from 'types'
|
|
|
|
import {
|
|
|
|
boundsCollide,
|
|
|
|
boundsContain,
|
2021-06-27 12:28:54 +00:00
|
|
|
debounce,
|
2021-06-27 09:07:20 +00:00
|
|
|
deepCompareArrays,
|
2021-06-27 12:28:54 +00:00
|
|
|
getPageState,
|
2021-06-27 09:07:20 +00:00
|
|
|
getViewport,
|
|
|
|
} from 'utils'
|
|
|
|
|
|
|
|
const viewportCache = new WeakMap<PageState, Bounds>()
|
|
|
|
|
|
|
|
export default function usePageShapes(): string[] {
|
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-27 09:07:20 +00:00
|
|
|
return useSelector((s) => {
|
2021-06-27 12:28:54 +00:00
|
|
|
const pageState = getPageState(s.data)
|
2021-06-27 09:07:20 +00:00
|
|
|
|
|
|
|
if (!viewportCache.has(pageState)) {
|
|
|
|
const viewport = getViewport(s.data)
|
|
|
|
viewportCache.set(pageState, viewport)
|
|
|
|
}
|
|
|
|
|
|
|
|
const viewport = viewportCache.get(pageState)
|
|
|
|
|
|
|
|
return s.values.currentShapes
|
|
|
|
.filter((shape) => {
|
|
|
|
const shapeBounds = getShapeUtils(shape).getBounds(shape)
|
|
|
|
return (
|
|
|
|
boundsContain(viewport, shapeBounds) ||
|
|
|
|
boundsCollide(viewport, shapeBounds)
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.map((shape) => shape.id)
|
|
|
|
}, deepCompareArrays)
|
|
|
|
}
|