UnifiedLogs.hooks.ts 1.7 KB

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