CoastalCommitsPastes/client/app/components/badges/expiration-badge/index.tsx

59 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-12-04 04:31:51 -05:00
"use client"
2022-11-12 21:39:03 -05:00
import Tooltip from "@components/tooltip"
2022-04-09 20:48:19 -04:00
import { timeUntil } from "@lib/time-ago"
2022-11-12 21:39:03 -05:00
import { useEffect, useMemo, useState } from "react"
import Badge from "../badge"
const ExpirationBadge = ({
2022-04-09 20:48:19 -04:00
postExpirationDate
2022-12-04 04:31:51 -05:00
}: {
2022-04-09 20:48:19 -04:00
postExpirationDate: Date | string | null
onExpires?: () => void
}) => {
2022-04-09 20:48:19 -04:00
const expirationDate = useMemo(
() => (postExpirationDate ? new Date(postExpirationDate) : null),
[postExpirationDate]
)
const [timeUntilString, setTimeUntil] = useState<string | null>(
expirationDate ? timeUntil(expirationDate) : null
)
useEffect(() => {
let interval: NodeJS.Timer | null = null
if (expirationDate) {
interval = setInterval(() => {
if (expirationDate) {
setTimeUntil(timeUntil(expirationDate))
}
}, 1000)
}
return () => {
if (interval) {
clearInterval(interval)
}
}
}, [expirationDate])
const isExpired = useMemo(() => {
return timeUntilString === "in 0 seconds"
2022-04-09 20:48:19 -04:00
}, [timeUntilString])
if (!expirationDate) {
return null
}
return (
<Badge type={isExpired ? "error" : "warning"}>
<Tooltip
2022-11-12 21:39:03 -05:00
content={`${expirationDate.toLocaleDateString()} ${expirationDate.toLocaleTimeString()}`}
2022-04-09 20:48:19 -04:00
>
2022-11-12 21:39:03 -05:00
<>{isExpired ? "Expired" : `Expires ${timeUntilString}`}</>
2022-04-09 20:48:19 -04:00
</Tooltip>
</Badge>
)
}
2022-04-09 20:48:19 -04:00
export default ExpirationBadge