From 98f56af2e15c7c6f635ec07de83a73fbf9906588 Mon Sep 17 00:00:00 2001 From: Outrun Colors Date: Sat, 24 Sep 2022 17:21:51 -0500 Subject: [PATCH] Update timestamps all at once --- chat/package.json | 2 +- chat/src/features/chat/ChatMessage.tsx | 38 ++++++++++++++++---------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/chat/package.json b/chat/package.json index b3244f7144..82cb297762 100644 --- a/chat/package.json +++ b/chat/package.json @@ -1,6 +1,6 @@ { "name": "chat", - "version": "0.0.10", + "version": "0.0.11", "main": "index.js", "license": "MIT", "dependencies": { diff --git a/chat/src/features/chat/ChatMessage.tsx b/chat/src/features/chat/ChatMessage.tsx index d3d532faaa..b22ece981c 100644 --- a/chat/src/features/chat/ChatMessage.tsx +++ b/chat/src/features/chat/ChatMessage.tsx @@ -7,6 +7,7 @@ import { useChat, useRootContext } from "../../hooks"; import "./ChatMessage.css"; interface ChatMessageProps extends IChatMessage { + timestampUpdates: number; showUser?: boolean; } @@ -27,6 +28,7 @@ export function ChatMessage({ text_censored, time, quotes, + timestampUpdates, }: ChatMessageProps) { const message = { id, @@ -46,7 +48,7 @@ export function ChatMessage({ censored, themeColor, } = useRootContext(); - const { quote, messageLookup, deleteMessage, quoteMessage } = useChat(); + const { messageLookup, deleteMessage, quoteMessage } = useChat(); const content = censored ? text_censored : text_html; const hasMention = content.includes(loggedInUsername); const mentionStyle = hasMention @@ -60,18 +62,10 @@ export function ChatMessage({ setConfirmedDelete(true); } }, [text, confirmedDelete]); - const [timestamp, setTimestamp] = useState(formatTimeAgo(time)); - - useEffect(() => { - const updatingTimestamp = setInterval( - () => setTimestamp(formatTimeAgo(time)), - TIMESTAMP_UPDATE_INTERVAL - ); - - return () => { - clearInterval(updatingTimestamp); - }; - }, []); + const timestamp = useMemo(() => formatTimeAgo(time), [ + time, + timestampUpdates, + ]); return (
@@ -158,6 +152,18 @@ export function ChatMessage({ export function ChatMessageList() { const { messages } = useChat(); + const [timestampUpdates, setTimestampUpdates] = useState(0); + + useEffect(() => { + const updatingTimestamps = setInterval( + () => setTimestampUpdates((prev) => prev + 1), + TIMESTAMP_UPDATE_INTERVAL + ); + + return () => { + clearInterval(updatingTimestamps); + }; + }, []); return (
@@ -165,6 +171,7 @@ export function ChatMessageList() { ))} @@ -174,10 +181,11 @@ export function ChatMessageList() { function formatTimeAgo(time: number) { const now = new Date().getTime(); - - return `${humanizeDuration(time * 1000 - now, { + const humanized = `${humanizeDuration(time * 1000 - now, { round: true, units: ["h", "m", "s"], largest: 2, })} ago`; + + return humanized === "0 seconds ago" ? "just now" : humanized; }