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