useLiveTailControls.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import React, { useCallback } from 'react';
  2. import { useDispatch } from 'react-redux';
  3. import { RefreshPicker } from '@grafana/ui';
  4. import { ExploreId } from '../../types';
  5. import { setPausedStateAction, runQueries } from './state/query';
  6. import { changeRefreshInterval } from './state/time';
  7. /**
  8. * Hook that gives you all the functions needed to control the live tailing.
  9. */
  10. export function useLiveTailControls(exploreId: ExploreId) {
  11. const dispatch = useDispatch();
  12. const pause = useCallback(() => {
  13. dispatch(setPausedStateAction({ exploreId, isPaused: true }));
  14. }, [exploreId, dispatch]);
  15. const resume = useCallback(() => {
  16. dispatch(setPausedStateAction({ exploreId, isPaused: false }));
  17. }, [exploreId, dispatch]);
  18. const stop = useCallback(() => {
  19. // We need to pause here first because there is transition where we are not live but live logs are still shown
  20. // to cross fade with the normal view. This will prevent reordering of the logs in the live view during the
  21. // transition.
  22. pause();
  23. // TODO referencing this from perspective of refresh picker when there is designated button for it now is not
  24. // great. Needs a bit of refactoring.
  25. dispatch(changeRefreshInterval(exploreId, RefreshPicker.offOption.value));
  26. dispatch(runQueries(exploreId));
  27. }, [exploreId, dispatch, pause]);
  28. const start = useCallback(() => {
  29. dispatch(changeRefreshInterval(exploreId, RefreshPicker.liveOption.value));
  30. }, [exploreId, dispatch]);
  31. return {
  32. pause,
  33. resume,
  34. stop,
  35. start,
  36. };
  37. }
  38. type Props = {
  39. exploreId: ExploreId;
  40. children: (controls: ReturnType<typeof useLiveTailControls>) => React.ReactElement;
  41. };
  42. /**
  43. * If you can't use the hook you can use this as a render prop pattern.
  44. */
  45. export function LiveTailControls(props: Props) {
  46. const controls = useLiveTailControls(props.exploreId);
  47. return props.children(controls);
  48. }