LiveButton.tsx74 lines · main
1import type { FetchPreviousPageOptions } from '@tanstack/react-query'
2import { CirclePause, CirclePlay } from 'lucide-react'
3import { useQueryStates } from 'nuqs'
4import { useEffect } from 'react'
5import { cn } from 'ui'
6
7import { ButtonTooltip } from '../ButtonTooltip'
8import { useDataTable } from './providers/DataTableProvider'
9import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
10import { useShortcut } from '@/state/shortcuts/useShortcut'
11
12const REFRESH_INTERVAL = 10_000
13
14interface LiveButtonProps {
15 searchParamsParser: any
16 fetchPreviousPage?: (options?: FetchPreviousPageOptions | undefined) => Promise<unknown>
17}
18
19export function LiveButton({ fetchPreviousPage, searchParamsParser }: LiveButtonProps) {
20 const [{ live, date, sort }, setSearch] = useQueryStates(searchParamsParser)
21 const { table } = useDataTable()
22 useShortcut(SHORTCUT_IDS.DATA_TABLE_TOGGLE_LIVE, handleClick)
23
24 useEffect(() => {
25 let timeoutId: NodeJS.Timeout
26
27 async function fetchData() {
28 if (live) {
29 await fetchPreviousPage?.()
30 timeoutId = setTimeout(fetchData, REFRESH_INTERVAL)
31 } else {
32 clearTimeout(timeoutId)
33 }
34 }
35
36 fetchData()
37
38 return () => {
39 clearTimeout(timeoutId)
40 }
41 }, [live, fetchPreviousPage])
42
43 // REMINDER: make sure to reset live when date is set
44 // TODO: test properly
45 useEffect(() => {
46 if ((date || sort) && live) {
47 setSearch((prev) => ({ ...prev, live: null }))
48 }
49 }, [date, sort])
50
51 function handleClick() {
52 setSearch((prev) => ({
53 ...prev,
54 live: !prev.live,
55 date: null,
56 sort: null,
57 }))
58 table.getColumn('date')?.setFilterValue(undefined)
59 table.resetSorting()
60 }
61
62 return (
63 <ButtonTooltip
64 className={cn(live && 'border-info text-info hover:text-info')}
65 onClick={handleClick}
66 type={live ? 'primary' : 'default'}
67 size="tiny"
68 icon={live ? <CirclePause className="h-4 w-4" /> : <CirclePlay className="h-4 w-4" />}
69 tooltip={{ content: { side: 'bottom', text: live ? 'Pause live mode' : 'Start live mode' } }}
70 >
71 Live
72 </ButtonTooltip>
73 )
74}