tldraw/components/canvas/canvas.tsx

85 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-05-28 14:37:23 +00:00
import styled from 'styles'
2021-05-28 16:25:43 +00:00
import state, { useSelector } from 'state'
2021-05-28 14:37:23 +00:00
import inputs from 'state/inputs'
import React, { useCallback, useRef } from 'react'
import useZoomEvents from 'hooks/useZoomEvents'
import useCamera from 'hooks/useCamera'
import Defs from './defs'
import Page from './page'
import Brush from './brush'
import Bounds from './bounds/bounding-box'
import BoundsBg from './bounds/bounds-bg'
2021-05-28 16:25:43 +00:00
import Selected from './selected'
2021-05-09 13:04:42 +00:00
export default function Canvas() {
const rCanvas = useRef<SVGSVGElement>(null)
const rGroup = useRef<SVGGElement>(null)
const events = useZoomEvents(rCanvas)
2021-05-09 21:22:25 +00:00
useCamera(rGroup)
2021-05-09 13:04:42 +00:00
2021-05-28 16:25:43 +00:00
const isReady = useSelector((s) => s.isIn('ready'))
2021-05-10 12:16:57 +00:00
const handlePointerDown = useCallback((e: React.PointerEvent) => {
if (!inputs.canAccept(e.pointerId)) return
2021-05-10 12:16:57 +00:00
rCanvas.current.setPointerCapture(e.pointerId)
2021-05-28 14:37:23 +00:00
state.send('POINTED_CANVAS', inputs.pointerDown(e, 'canvas'))
2021-05-10 12:16:57 +00:00
}, [])
const handleTouchStart = useCallback((e: React.TouchEvent) => {
if (e.touches.length === 2) {
state.send('TOUCH_UNDO')
}
}, [])
2021-05-10 12:16:57 +00:00
const handlePointerMove = useCallback((e: React.PointerEvent) => {
if (!inputs.canAccept(e.pointerId)) return
if (inputs.canAccept(e.pointerId)) {
state.send('MOVED_POINTER', inputs.pointerMove(e))
}
2021-05-10 12:16:57 +00:00
}, [])
const handlePointerUp = useCallback((e: React.PointerEvent) => {
if (!inputs.canAccept(e.pointerId)) return
2021-05-10 12:16:57 +00:00
rCanvas.current.releasePointerCapture(e.pointerId)
2021-05-28 14:37:23 +00:00
state.send('STOPPED_POINTING', { id: 'canvas', ...inputs.pointerUp(e) })
2021-05-10 12:16:57 +00:00
}, [])
2021-05-09 13:04:42 +00:00
return (
2021-05-10 12:16:57 +00:00
<MainSVG
ref={rCanvas}
{...events}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onTouchStart={handleTouchStart}
2021-05-10 12:16:57 +00:00
>
2021-05-28 14:37:23 +00:00
<Defs />
2021-05-28 16:25:43 +00:00
{isReady && (
<g ref={rGroup}>
<BoundsBg />
<Page />
<Selected />
<Bounds />
2021-05-28 16:25:43 +00:00
<Brush />
</g>
)}
2021-05-09 13:04:42 +00:00
</MainSVG>
)
}
2021-05-28 14:37:23 +00:00
const MainSVG = styled('svg', {
position: 'fixed',
2021-05-09 13:04:42 +00:00
top: 0,
left: 0,
2021-05-28 14:37:23 +00:00
width: '100%',
height: '100%',
touchAction: 'none',
2021-05-09 13:04:42 +00:00
zIndex: 100,
2021-05-30 13:49:33 +00:00
backgroundColor: '$canvas',
2021-05-23 13:46:04 +00:00
2021-05-28 14:37:23 +00:00
'& *': {
userSelect: 'none',
2021-05-23 13:46:04 +00:00
},
2021-05-09 13:04:42 +00:00
})