Skip to content

Commit

Permalink
Merge pull request pmndrs#19 from eyr1n/strictmode
Browse files Browse the repository at this point in the history
Support React.StrictMode
  • Loading branch information
drcmda authored May 8, 2024
2 parents 923ac9e + 0472178 commit 076a8f6
Showing 1 changed file with 20 additions and 19 deletions.
39 changes: 20 additions & 19 deletions src/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,32 @@ function isRefObject<T>(ref: any): ref is React.MutableRefObject<T> {
export function Canvas({ eventSource, worker, fallback, style, className, id, ...props }: CanvasProps) {
const [shouldFallback, setFallback] = React.useState(false)
const canvasRef = useRef<HTMLCanvasElement>(null!)
const hasTransferredToOffscreen = useRef(false)

useEffect(() => {
if (!worker) return

const canvas = canvasRef.current
let offscreen
try {
// @ts-ignore
offscreen = canvasRef.current.transferControlToOffscreen()
if (!hasTransferredToOffscreen.current) {
const offscreen = canvasRef.current.transferControlToOffscreen()
hasTransferredToOffscreen.current = true
worker.postMessage(
{
type: 'init',
payload: {
props,
drawingSurface: offscreen,
width: canvas.clientWidth,
height: canvas.clientHeight,
top: canvas.offsetTop,
left: canvas.offsetLeft,
pixelRatio: window.devicePixelRatio,
},
},
[offscreen]
)
}
} catch (e) {
// Browser doesn't support offscreen canvas at all
setFallback(true)
Expand All @@ -48,22 +65,6 @@ export function Canvas({ eventSource, worker, fallback, style, className, id, ..
}
}

worker.postMessage(
{
type: 'init',
payload: {
props,
drawingSurface: offscreen,
width: canvas.clientWidth,
height: canvas.clientHeight,
top: canvas.offsetTop,
left: canvas.offsetLeft,
pixelRatio: window.devicePixelRatio,
},
},
[offscreen]
)

const currentEventSource = isRefObject(eventSource) ? eventSource.current : eventSource || canvas

Object.values(EVENTS).forEach(([eventName, passive]) => {
Expand Down

0 comments on commit 076a8f6

Please sign in to comment.