UnifiedLogs.hooks.ts45 lines · main
1import { useQueryState } from 'nuqs'
2import { useEffect, useMemo, useRef } from 'react'
3
4import { SEARCH_PARAMS_PARSER } from './UnifiedLogs.constants'
5import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
6import { useShortcut } from '@/state/shortcuts/useShortcut'
7
8export const useResetFocus = () => {
9 useShortcut(SHORTCUT_IDS.UNIFIED_LOGS_RESET_FOCUS, () => {
10 // FIXME: some dedicated div[tabindex="0"] do not auto-unblur (e.g. the DataTableFilterResetButton)
11 // REMINDER: we cannot just document.activeElement?.blur(); as the next tab will focus the next element in line,
12 // which is not what we want. We want to reset entirely.
13 document.body.setAttribute('tabindex', '0')
14 document.body.focus()
15 document.body.removeAttribute('tabindex')
16 })
17}
18
19export const useLiveMode = <TData extends { date: Date }>(data: TData[]) => {
20 const [live] = useQueryState('live', SEARCH_PARAMS_PARSER.live)
21 // REMINDER: used to capture the live mode on timestamp
22 const liveTimestamp = useRef<number | undefined>(live ? new Date().getTime() : undefined)
23
24 useEffect(() => {
25 if (live) liveTimestamp.current = new Date().getTime()
26 else liveTimestamp.current = undefined
27 }, [live])
28
29 const anchorRow = useMemo(() => {
30 if (!live) return undefined
31
32 const item = data.find((item) => {
33 // return first item that is there if not liveTimestamp
34 if (!liveTimestamp.current) return true
35 // return first item that is after the liveTimestamp
36 if (item.date.getTime() > liveTimestamp.current) return false
37 return true
38 // return first item if no liveTimestamp
39 })
40
41 return item
42 }, [live, data])
43
44 return { row: anchorRow, timestamp: liveTimestamp.current }
45}