traffic.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import axios from "axios";
  2. import { useEffect, useState } from "react";
  3. import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
  4. import parseTraffic from "../utils/parse-traffic";
  5. import { Typography } from "@mui/material";
  6. import { Box } from "@mui/system";
  7. const Traffic = () => {
  8. const [traffic, setTraffic] = useState({ up: 0, down: 0 });
  9. useEffect(() => {
  10. const onTraffic = () => {
  11. axios({
  12. url: `http://127.0.0.1:9090/traffic`,
  13. method: "GET",
  14. onDownloadProgress: (progressEvent) => {
  15. const data = progressEvent.currentTarget.response || "";
  16. const lastData = data.slice(data.trim().lastIndexOf("\n") + 1);
  17. try {
  18. if (lastData) setTraffic(JSON.parse(lastData));
  19. } catch {}
  20. },
  21. }).catch(() => setTimeout(onTraffic, 500));
  22. };
  23. onTraffic();
  24. }, []);
  25. const [up, upUnit] = parseTraffic(traffic.up);
  26. const [down, downUnit] = parseTraffic(traffic.down);
  27. const valStyle: any = {
  28. component: "span",
  29. color: "primary",
  30. textAlign: "center",
  31. sx: { flex: "1 1 54px" },
  32. };
  33. const unitStyle: any = {
  34. component: "span",
  35. color: "grey.500",
  36. fontSize: "12px",
  37. textAlign: "right",
  38. sx: { flex: "0 1 28px", userSelect: "none" },
  39. };
  40. return (
  41. <Box width="110px">
  42. <Box mb={2} display="flex" alignItems="center" whiteSpace="nowrap">
  43. <ArrowUpward
  44. fontSize="small"
  45. color={+up > 0 ? "primary" : "disabled"}
  46. />
  47. <Typography {...valStyle}>{up}</Typography>
  48. <Typography {...unitStyle}>{upUnit}</Typography>
  49. </Box>
  50. <Box display="flex" alignItems="center" whiteSpace="nowrap">
  51. <ArrowDownward
  52. fontSize="small"
  53. color={+down > 0 ? "primary" : "disabled"}
  54. />
  55. <Typography {...valStyle}>{down}</Typography>
  56. <Typography {...unitStyle}>{downUnit}</Typography>
  57. </Box>
  58. </Box>
  59. );
  60. };
  61. export default Traffic;