Files
codey.lol/src/components/RandomMsg.tsx

95 lines
3.0 KiB
TypeScript
Raw Normal View History

2025-07-25 09:56:45 -04:00
import { useState, useEffect } from "react";
2025-06-22 09:50:36 -04:00
import { API_URL } from "../config";
2025-12-19 11:59:00 -05:00
interface RandomMsgResponse {
msg?: string;
}
2025-06-22 09:50:36 -04:00
2025-12-19 11:59:00 -05:00
export default function RandomMsg(): React.ReactElement {
const [randomMsg, setRandomMsg] = useState<string>("");
const [responseTime, setResponseTime] = useState<number | null>(null);
const [showResponseTime, setShowResponseTime] = useState<boolean>(false);
const getRandomMsg = async (): Promise<void> => {
2025-07-25 09:56:45 -04:00
try {
2025-12-17 13:33:31 -05:00
const start = performance.now();
2025-07-25 09:56:45 -04:00
const response = await fetch(`${API_URL}/randmsg`, {
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
2025-07-25 09:56:45 -04:00
});
2025-12-17 13:33:31 -05:00
const end = performance.now();
setResponseTime(Math.round(end - start));
if (!response.ok) throw new Error(`HTTP ${response.status}`);
2025-07-25 09:56:45 -04:00
const data = await response.json();
2025-12-17 13:33:31 -05:00
if (data?.msg) setRandomMsg(data.msg.replace(/<br\s*\/?\>/gi, "\n"));
2025-07-25 09:56:45 -04:00
} catch (err) {
console.error("Failed to fetch random message:", err);
2025-12-17 13:33:31 -05:00
setResponseTime(null);
2025-07-25 09:56:45 -04:00
}
};
2025-06-22 09:50:36 -04:00
useEffect(() => void getRandomMsg(), []);
2025-06-22 09:50:36 -04:00
2025-07-25 09:56:45 -04:00
return (
<div className="random-msg-container">
{randomMsg && (
2025-12-19 07:46:41 -05:00
<div className="random-msg" style={{ position: "relative", display: "inline" }}>
<small
style={{ cursor: responseTime !== null ? "pointer" : "default" }}
onClick={() => {
if (responseTime !== null) setShowResponseTime((v) => !v);
}}
tabIndex={0}
onBlur={() => setShowResponseTime(false)}
>
2025-12-19 07:46:41 -05:00
<i>{randomMsg}</i>
</small>
<button
aria-label="New footer message"
type="button"
className="random-msg-reload"
onClick={getRandomMsg}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
width="12"
height="12"
aria-hidden="true"
focusable="false"
>
<path
d="M17.65 6.35a7.95 7.95 0 0 0-5.65-2.35 8 8 0 1 0 7.75 9.94h-2.08a6 6 0 1 1-5.67-7.94 5.94 5.94 0 0 1 4.22 1.78L13 11h7V4z"
fill="currentColor"
/>
</svg>
</button>
{showResponseTime && responseTime !== null && (
<div
style={{
position: "absolute",
left: "50%",
top: "100%",
transform: "translateX(-50%)",
marginTop: 4,
background: "#222",
color: "#fff",
fontSize: "0.75em",
padding: "2px 8px",
borderRadius: 6,
boxShadow: "0 2px 8px rgba(0,0,0,0.15)",
zIndex: 10,
whiteSpace: "nowrap"
}}
role="status"
aria-live="polite"
>
API response: {responseTime} ms
</div>
)}
</div>
)}
2025-07-25 09:56:45 -04:00
</div>
);
}