|
| 1 | +import { Alert, AlertTitle, Box, Button, Typography } from "@mui/material"; |
| 2 | +import { useQuery } from "@tanstack/react-query"; |
| 3 | +import { type z } from "zod"; |
| 4 | + |
| 5 | +import { type MotdEntrySchema } from "../pages/api/motd"; |
| 6 | + |
| 7 | +type MotdResponse = z.infer<typeof MotdEntrySchema>[]; |
| 8 | + |
| 9 | +const fetchMotd = async (): Promise<MotdResponse | null> => { |
| 10 | + const response = await fetch("/api/motd", { cache: "no-store" }); |
| 11 | + |
| 12 | + if (response.status === 204) { |
| 13 | + return null; |
| 14 | + } |
| 15 | + |
| 16 | + if (!response.ok) { |
| 17 | + throw new Error("Failed to load MOTD"); |
| 18 | + } |
| 19 | + |
| 20 | + const data = (await response.json()) as MotdResponse; |
| 21 | + return data; |
| 22 | +}; |
| 23 | + |
| 24 | +function formatDate(dateStr?: string) { |
| 25 | + if (!dateStr) { |
| 26 | + return undefined; |
| 27 | + } |
| 28 | + const date = new Date(dateStr); |
| 29 | + if (Number.isNaN(date.getTime())) { |
| 30 | + return undefined; |
| 31 | + } |
| 32 | + return date.toLocaleString(); |
| 33 | +} |
| 34 | + |
| 35 | +export const Motd = () => { |
| 36 | + const { data, isError, isLoading } = useQuery({ |
| 37 | + queryKey: ["motd"], |
| 38 | + queryFn: fetchMotd, |
| 39 | + staleTime: 0, |
| 40 | + refetchOnWindowFocus: true, |
| 41 | + refetchOnReconnect: true, |
| 42 | + retry: 1, |
| 43 | + }); |
| 44 | + |
| 45 | + if (isLoading || isError || !data) { |
| 46 | + return null; |
| 47 | + } |
| 48 | + |
| 49 | + return data.map(({ title, message, url, begin, end }) => ( |
| 50 | + <Alert |
| 51 | + action={ |
| 52 | + url ? ( |
| 53 | + <Button |
| 54 | + color="inherit" |
| 55 | + component="a" |
| 56 | + href={url} |
| 57 | + rel="noopener noreferrer" |
| 58 | + target="_blank" |
| 59 | + > |
| 60 | + More details |
| 61 | + </Button> |
| 62 | + ) : undefined |
| 63 | + } |
| 64 | + key={`${title}-${message}`} |
| 65 | + severity="info" |
| 66 | + sx={{ mb: 2 }} |
| 67 | + > |
| 68 | + <Box> |
| 69 | + {!!title && <AlertTitle sx={{ mb: 0.5 }}>{title}</AlertTitle>} |
| 70 | + <Typography component="div" sx={{ whiteSpace: "pre-line", mb: 1 }}> |
| 71 | + {message} |
| 72 | + </Typography> |
| 73 | + {!!(begin ?? end) && ( |
| 74 | + <Typography color="text.secondary" variant="caption"> |
| 75 | + {!!begin && `From: ${formatDate(begin)} `} |
| 76 | + {!!end && `Until: ${formatDate(end)}`} |
| 77 | + </Typography> |
| 78 | + )} |
| 79 | + </Box> |
| 80 | + </Alert> |
| 81 | + )); |
| 82 | +}; |
0 commit comments