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"
|
2022-11-14 02:02:31 -05:00
|
|
|
import Badge from "../badge"
|
2022-03-30 23:01:24 -04:00
|
|
|
|
|
|
|
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-03-30 23:01:24 -04:00
|
|
|
}) => {
|
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(() => {
|
2022-11-14 02:02:31 -05:00
|
|
|
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-03-30 23:01:24 -04:00
|
|
|
}
|
|
|
|
|
2022-04-09 20:48:19 -04:00
|
|
|
export default ExpirationBadge
|