traffic.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { useEffect, useState } from "react";
  2. import { Box, Typography } from "@mui/material";
  3. import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
  4. import { getInfomation } from "../services/api";
  5. import { ApiType } from "../services/types";
  6. import parseTraffic from "../utils/parse-traffic";
  7. const Traffic = () => {
  8. const [traffic, setTraffic] = useState({ up: 0, down: 0 });
  9. useEffect(() => {
  10. let ws: WebSocket | null = null;
  11. getInfomation().then((result) => {
  12. const { server = "", secret = "" } = result;
  13. ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
  14. ws.addEventListener("message", (event) => {
  15. setTraffic(JSON.parse(event.data) as ApiType.TrafficItem);
  16. });
  17. });
  18. return () => ws?.close();
  19. }, []);
  20. const [up, upUnit] = parseTraffic(traffic.up);
  21. const [down, downUnit] = parseTraffic(traffic.down);
  22. const valStyle: any = {
  23. component: "span",
  24. color: "primary",
  25. textAlign: "center",
  26. sx: { flex: "1 1 54px" },
  27. };
  28. const unitStyle: any = {
  29. component: "span",
  30. color: "grey.500",
  31. fontSize: "12px",
  32. textAlign: "right",
  33. sx: { flex: "0 1 28px", userSelect: "none" },
  34. };
  35. return (
  36. <Box width="110px">
  37. <Box mb={1.5} display="flex" alignItems="center" whiteSpace="nowrap">
  38. <ArrowUpward
  39. fontSize="small"
  40. color={+up > 0 ? "primary" : "disabled"}
  41. />
  42. <Typography {...valStyle}>{up}</Typography>
  43. <Typography {...unitStyle}>{upUnit}/s</Typography>
  44. </Box>
  45. <Box display="flex" alignItems="center" whiteSpace="nowrap">
  46. <ArrowDownward
  47. fontSize="small"
  48. color={+down > 0 ? "primary" : "disabled"}
  49. />
  50. <Typography {...valStyle}>{down}</Typography>
  51. <Typography {...unitStyle}>{downUnit}/s</Typography>
  52. </Box>
  53. </Box>
  54. );
  55. };
  56. export default Traffic;