Change the timer data structure to fix network bugs and refactored shared timer functions

This commit is contained in:
Mitchell McCaffrey
2020-08-05 12:01:54 +10:00
parent 0c1ec22234
commit 4199d7ab6a
5 changed files with 83 additions and 51 deletions

View File

@@ -58,7 +58,15 @@ function Party({
stream={partyStreams[id]}
/>
))}
<Timer timer={timer} />
{timer && <Timer timer={timer} index={0} />}
{Object.entries(partyTimers).map(([id, partyTimer], index) => (
<Timer
timer={partyTimer}
key={id}
// Put party timers above your timer if there is one
index={timer ? index + 1 : index}
/>
))}
</Box>
<Flex sx={{ flexDirection: "column" }}>
<ChangeNicknameButton nickname={nickname} onChange={onNicknameChange} />

View File

@@ -1,33 +1,18 @@
import React, { useEffect, useState, useRef } from "react";
import React, { useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import { Box, Progress } from "theme-ui";
import usePortal from "../../helpers/usePortal";
function getTimerDuration(t) {
if (!t) {
return 0;
}
return t.hour * 3600000 + t.minute * 60000 + t.second * 1000;
}
function Timer({ timer }) {
const [maxDuration, setMaxDuration] = useState(0);
const previousTimerRef = useRef(timer);
useEffect(() => {
if (!previousTimerRef.current && timer) {
setMaxDuration(getTimerDuration(timer));
}
previousTimerRef.current = timer;
});
useEffect(() => {
progressBarRef.current.value = getTimerDuration(timer);
}, [timer]);
function Timer({ timer, index }) {
const progressBarRef = useRef();
useEffect(() => {
if (progressBarRef.current && timer) {
progressBarRef.current.value = timer.current;
}
}, [timer]);
useEffect(() => {
let request = requestAnimationFrame(animate);
let previousTime = performance.now();
@@ -36,13 +21,15 @@ function Timer({ timer }) {
const deltaTime = time - previousTime;
previousTime = time;
progressBarRef.current.value -= deltaTime;
if (progressBarRef.current && progressBarRef.current.value > 0) {
progressBarRef.current.value -= deltaTime;
}
}
return () => {
cancelAnimationFrame(request);
};
}, [maxDuration]);
}, []);
const timerContainer = usePortal("root");
@@ -59,15 +46,15 @@ function Timer({ timer }) {
borderRadius: "28px",
left: "50%",
maxWidth: "500px",
width: "60%",
transform: "translateX(-50%)",
width: "40%",
transform: `translate(-50%, -${index * 36}px)`,
padding: "0 8px",
margin: "8px",
}}
bg="overlay"
>
<Progress
max={maxDuration}
max={timer && timer.max}
m={2}
sx={{ width: "100%" }}
ref={progressBarRef}