diff --git a/src/components/AnimationProxy.tsx b/src/components/AnimationProxy.tsx new file mode 100644 index 0000000..230022e --- /dev/null +++ b/src/components/AnimationProxy.tsx @@ -0,0 +1,21 @@ +import React, { useEffect } from "react" + +import { FrameContext } from "./Canvas" + +interface AnimationProxyProps { + things: T[], + factory: (thing: T) => JSX.Element +} + +function AnimationProxy({ things, factory }: AnimationProxyProps) { + const frameCount = React.useContext(FrameContext) + const [keptThings, setKeptThings] = React.useState([]) + + useEffect(() => { + setKeptThings(things) + }, [frameCount]) + + return <>{keptThings.map((thing) => factory(thing))} +} + +export default AnimationProxy diff --git a/src/components/Canvas.tsx b/src/components/Canvas.tsx index 5e56704..0ba2ca4 100644 --- a/src/components/Canvas.tsx +++ b/src/components/Canvas.tsx @@ -2,29 +2,48 @@ import React from "react" import CanvasContext from "./CanvasContext" +export const FrameContext = React.createContext(0) + export interface SystemCanvasProps { height: number, width: number, - children?: JSX.Element[] + children?: JSX.Element[] | JSX.Element } function SystemCanvas({ height, width, children }: SystemCanvasProps) { const canvasRef = React.useRef(null) const [context, setContext] = React.useState(null) + const [frameCount, setFrameCount] = React.useState(0) React.useEffect(() => { - const context = canvasRef.current.getContext("2d") + if (canvasRef.current != null) { + const context = canvasRef.current.getContext("2d") + setContext(context) + } + }, [frameCount]) + + React.useEffect(() => { + const frameId = requestAnimationFrame(() => { + setFrameCount(frameCount + 1) + }) + return () => { + cancelAnimationFrame(frameId) + } + }, [frameCount]) + + if (context != null) { context.save() context.fillStyle = "black" context.fillRect(0, 0, width, height) context.restore() - setContext(context) - }) + } return (
- - {children} + + + {children} +
) diff --git a/src/components/Home.tsx b/src/components/Home.tsx index cbfe7fa..224c396 100644 --- a/src/components/Home.tsx +++ b/src/components/Home.tsx @@ -1,6 +1,7 @@ import React, { useEffect, useState } from "react" import { Body, Bounds, Message } from "@app/types" +import AnimationProxy from "./AnimationProxy" import Canvas from "./Canvas" import Client from "@app/client" import RenderedBody from "./RenderedBody" @@ -49,12 +50,12 @@ function Home() {

Hello, World!

Iteration: { iteration }, message count: { messageCount }, nObjects: { bodies.length }.

- {bodies.map((body) => )} + />}/> )