|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { formatDistanceToNow } from 'date-fns'; |
| 4 | +import { useSession } from 'next-auth/react'; |
| 5 | +import useSWR from 'swr'; |
| 6 | + |
| 7 | +import type { QueryUsage as QueryUsageType } from '@/app/(chat)/types'; |
| 8 | +import { fetcher } from '@/lib/utils'; |
| 9 | + |
| 10 | +import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'; |
| 11 | + |
| 12 | +export function QueryUsage() { |
| 13 | + const { status } = useSession(); |
| 14 | + const { data, isLoading } = useSWR<QueryUsageType>( |
| 15 | + status === 'authenticated' ? '/api/query-usage' : null, |
| 16 | + fetcher, |
| 17 | + { revalidateOnFocus: false, revalidateOnReconnect: false }, |
| 18 | + ); |
| 19 | + |
| 20 | + if (status !== 'authenticated') return null; |
| 21 | + |
| 22 | + if (isLoading) { |
| 23 | + return ( |
| 24 | + <div className="flex items-center gap-2 text-sm text-muted-foreground"> |
| 25 | + <div className="size-4 animate-pulse rounded-full bg-muted" /> |
| 26 | + <span>Loading usage...</span> |
| 27 | + </div> |
| 28 | + ); |
| 29 | + } |
| 30 | + |
| 31 | + if (!data) return null; |
| 32 | + |
| 33 | + const { |
| 34 | + todayQueryCount, |
| 35 | + remainingQueriesToday, |
| 36 | + maxQueryAllowancePerDay, |
| 37 | + nextResetTime, |
| 38 | + } = data; |
| 39 | + |
| 40 | + const resetTime = formatDistanceToNow(new Date(nextResetTime), { |
| 41 | + addSuffix: true, |
| 42 | + }); |
| 43 | + |
| 44 | + return ( |
| 45 | + <Tooltip> |
| 46 | + <TooltipTrigger asChild> |
| 47 | + <div className="flex items-center justify-between text-sm cursor-pointer border rounded-md px-2 py-1 dark:border-zinc-700"> |
| 48 | + <span className="text-muted-foreground mr-2">Credits</span> |
| 49 | + <span className="font-medium"> |
| 50 | + {remainingQueriesToday} / {maxQueryAllowancePerDay} |
| 51 | + </span> |
| 52 | + </div> |
| 53 | + </TooltipTrigger> |
| 54 | + <TooltipContent> |
| 55 | + <div className="flex flex-col gap-2"> |
| 56 | + <div className="flex items-center gap-2"> |
| 57 | + <span className="text-muted-foreground">Used today:</span> |
| 58 | + <span className="font-medium">{todayQueryCount}</span> |
| 59 | + </div> |
| 60 | + <div className="flex items-center gap-2"> |
| 61 | + <span className="text-muted-foreground">Resets:</span> |
| 62 | + <span className="font-medium">{resetTime}</span> |
| 63 | + </div> |
| 64 | + </div> |
| 65 | + </TooltipContent> |
| 66 | + </Tooltip> |
| 67 | + ); |
| 68 | +} |
0 commit comments