Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ type Props = {
placement?: 'top' | 'right' | 'bottom' | 'left';
iconSize?: SizeProp;
pullRight?: boolean;
title?: string;
triggerTitle?: string;
title?: React.ComponentProps<typeof OverlayTrigger>['title'];
testId?: string;
trigger?: React.ComponentProps<typeof OverlayTrigger>['trigger'];
type?: 'info' | 'error';
Expand All @@ -85,6 +86,7 @@ const HoverForHelp = ({
id = 'help-popover',
pullRight = true,
placement = 'bottom',
triggerTitle = undefined,
testId = undefined,
type = 'info',
iconSize = undefined,
Expand All @@ -94,6 +96,7 @@ const HoverForHelp = ({
trigger={trigger}
placement={placement}
overlay={<StyledPopover id={id}>{children}</StyledPopover>}
triggerTitle={triggerTitle}
title={title}
testId={testId}>
<StyledIcon
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type Props = {
trigger?: Triggers | Array<Triggers>;
className?: string;
rootClose?: boolean;
triggerTitle?: string;
width?: number;
title?: React.ReactNode;
};
Expand All @@ -59,6 +60,7 @@ const OverlayTrigger = (
trigger = 'click',
testId = undefined,
className = undefined,
triggerTitle = undefined,
title = undefined,
width = 275,
}: Props,
Expand All @@ -75,6 +77,7 @@ const OverlayTrigger = (
);

// @ts-ignore
// eslint-disable-next-line react-hooks/immutability
OverlayTrigger.hide = close;

const containerRef = useRef();
Expand All @@ -97,6 +100,8 @@ const OverlayTrigger = (
className={children.props.className}
ref={setControl}
role="button"
aria-label={triggerTitle ?? (typeof title === 'string' ? title : undefined)}
title={triggerTitle}
onClick={click ? toggle : undefined}
onMouseEnter={hover ? open : undefined}
onMouseLeave={hover ? close : undefined}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import type { UrlQueryFilters } from 'components/common/EntityFilters/types';
import TableFetchContextProvider from 'components/common/PaginatedEntityTable/TableFetchContextProvider';
import type { PaginatedResponse, FetchOptions } from 'components/common/PaginatedEntityTable/useFetchEntities';
import useFetchEntities from 'components/common/PaginatedEntityTable/useFetchEntities';
import useOnRefresh from 'components/common/PaginatedEntityTable/useOnRefresh';
import type { PaginationQueryParameterResult } from 'hooks/usePaginationQueryParameter';
import Slicing, { type SliceRenderers } from 'components/common/PaginatedEntityTable/slicing';
import type { FetchSlices } from 'components/common/PaginatedEntityTable/slicing/useFetchSlices';
Expand Down Expand Up @@ -138,8 +137,6 @@ const PaginatedEntityTableInner = <T extends EntityBase, M = unknown>({
fetchOptions: reactQueryOptions,
});

useOnRefresh(refetch);

useEffect(() => {
if (!onDataLoaded || isLoadingEntities) {
return;
Expand Down Expand Up @@ -328,6 +325,7 @@ export type PaginatedEntityTableProps<T, M> = {
additionalAttributes?: Array<Attribute>;
bulkSelection?: EntityDataTableProps['bulkSelection'];
columnRenderers: EntityDataTableProps['columnRenderers'];
// eslint-disable-next-line react/no-unused-prop-types
defaultFilters?: UrlQueryFilters;
entityActions?: EntityDataTableProps['entityActions'];
entityAttributesAreCamelCase: boolean;
Expand Down
12 changes: 7 additions & 5 deletions graylog2-web-interface/src/components/common/RefreshControls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,22 @@ const FlexibleButtonGroup = styled(ButtonGroup)`
}
`;

const ButtonLabel = () => {
const ButtonLabel = ({ children }: React.PropsWithChildren) => {
const { refreshConfig } = useAutoRefresh();

if (!refreshConfig?.enabled) {
return <>Not updating</>;
return <>Not updating{children}</>;
}

return (
<>
Every <ReadableDuration duration={refreshConfig.interval} />
{children}
</>
);
};

type Props = {
type Props = React.PropsWithChildren<{
disable: boolean;
intervalOptions: Array<[string, string]>;
isLoadingMinimumInterval: boolean;
Expand All @@ -60,9 +61,10 @@ type Props = {
onEnable?: () => void;
onDisable?: () => void;
humanName: string;
};
}>;

const RefreshControls = ({
children = null,
humanName,
disable,
onToggle = null,
Expand Down Expand Up @@ -137,7 +139,7 @@ const RefreshControls = ({
<Icon name={refreshConfig?.enabled ? 'pause' : 'update'} />
</Button>

<DropdownButton title={<ButtonLabel />} disabled={disable} id="refresh-options-dropdown">
<DropdownButton title={<ButtonLabel>{children}</ButtonLabel>} disabled={disable} id="refresh-options-dropdown">
{isLoadingMinimumInterval && <Spinner />}
{!isLoadingMinimumInterval &&
intervalOptions.map(([interval, label]) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
/*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
import * as React from 'react';
import userEvent from '@testing-library/user-event';
import { render, screen, waitFor } from 'wrappedTestingLibrary';
import type { Location } from 'history';

import type { SearchParams } from 'stores/PaginationTypes';
import TableFetchContext, { type ContextValue } from 'components/common/PaginatedEntityTable/TableFetchContext';
import { asMock } from 'helpers/mocking';
import useSearchConfiguration from 'hooks/useSearchConfiguration';
import type { SearchesConfig } from 'components/search/SearchConfig';
import useLocation from 'routing/useLocation';
import useSendTelemetry from 'logic/telemetry/useSendTelemetry';
import type { AutoRefreshContextType } from 'views/components/contexts/AutoRefreshContext';
import useAutoRefresh from 'views/hooks/useAutoRefresh';
import useMinimumRefreshInterval from 'views/hooks/useMinimumRefreshInterval';

import EventsRefreshControls from './EventsRefreshControls';

jest.mock('hooks/useSearchConfiguration');
jest.mock('routing/useLocation');
jest.mock('logic/telemetry/useSendTelemetry');
jest.mock('views/hooks/useAutoRefresh');
jest.mock('views/hooks/useMinimumRefreshInterval');

const autoRefreshOptions: SearchesConfig['auto_refresh_timerange_options'] = {
PT1S: '1 second',
PT2S: '2 seconds',
PT5S: '5 seconds',
};

describe('EventsRefreshControls', () => {
const sendTelemetry = jest.fn();

const autoRefreshContextValue: AutoRefreshContextType = {
refreshConfig: null,
stopAutoRefresh: jest.fn(),
startAutoRefresh: jest.fn(),
restartAutoRefresh: jest.fn(),
animationId: 'animation-id',
};

const renderSUT = (searchParamsOverrides: Partial<SearchParams> = {}) => {
const contextValue: ContextValue = {
searchParams: {
page: 1,
pageSize: 10,
query: '',
sort: { attributeId: 'timestamp', direction: 'desc' },
sliceCol: undefined,
slice: undefined,
filters: undefined,
...searchParamsOverrides,
},
refetch: jest.fn(),
attributes: [],
entityTableId: 'events-table',
};

return render(
<TableFetchContext.Provider value={contextValue}>
<EventsRefreshControls />
</TableFetchContext.Provider>,
);
};

beforeEach(() => {
jest.clearAllMocks();

asMock(useLocation).mockReturnValue({ pathname: '/alerts' } as Location);
asMock(useSendTelemetry).mockReturnValue(sendTelemetry);

asMock(useAutoRefresh).mockReturnValue(autoRefreshContextValue);

asMock(useMinimumRefreshInterval).mockReturnValue({
data: 'PT1S',
isInitialLoading: false,
});

asMock(useSearchConfiguration).mockReturnValue({
config: {
auto_refresh_timerange_options: autoRefreshOptions,
default_auto_refresh_option: 'PT5S',
} as unknown as SearchesConfig,
refresh: jest.fn(),
});
});

it('renders enabled refresh controls when slicing is inactive', async () => {
renderSUT();

expect(await screen.findByTitle(/start refresh/i)).toBeEnabled();
expect(screen.getByRole('button', { name: /not updating/i })).toBeEnabled();
expect(screen.queryByRole('button', { name: /auto refresh unavailable/i })).not.toBeInTheDocument();
});

it('disables refresh controls and shows help while slicing is active', async () => {
const user = userEvent.setup();

renderSUT({ sliceCol: 'source' });

expect(await screen.findByTitle(/start refresh/i)).toBeDisabled();
expect(screen.getByRole('button', { name: /not updating/i })).toBeDisabled();

await user.hover(screen.getByRole('button', { name: /auto refresh unavailable/i }));

expect(
await screen.findByText(/auto refresh is turned off during slicing to avoid performance issues/i),
).toBeInTheDocument();
});

it('stops auto refresh when slicing becomes active and refresh is enabled', async () => {
const stopAutoRefresh = jest.fn();

asMock(useAutoRefresh).mockReturnValue({
...autoRefreshContextValue,
stopAutoRefresh,
refreshConfig: { enabled: true, interval: 1000 },
});

renderSUT({ sliceCol: 'source' });

await waitFor(() => expect(stopAutoRefresh).toHaveBeenCalledTimes(1));
});

it('does not stop auto refresh when slicing is active but refresh is already disabled', () => {
const stopAutoRefresh = jest.fn();

asMock(useAutoRefresh).mockReturnValue({
...autoRefreshContextValue,
stopAutoRefresh,
refreshConfig: { enabled: false, interval: 1000 },
});

renderSUT({ sliceCol: 'source' });

expect(stopAutoRefresh).not.toHaveBeenCalled();
});

it('starts auto refresh when slicing is inactive', async () => {
const startAutoRefresh = jest.fn();

asMock(useAutoRefresh).mockReturnValue({
...autoRefreshContextValue,
startAutoRefresh,
refreshConfig: { enabled: false, interval: 1000 },
});

renderSUT();

await userEvent.click(await screen.findByTitle(/start refresh/i));

expect(startAutoRefresh).toHaveBeenCalledWith(1000);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
import * as React from 'react';
import { useCallback } from 'react';
import { useCallback, useEffect } from 'react';

import { HoverForHelp } from 'components/common';
import useSearchConfiguration from 'hooks/useSearchConfiguration';
import useSendTelemetry from 'logic/telemetry/useSendTelemetry';
import { TELEMETRY_EVENT_TYPE } from 'logic/telemetry/Constants';
Expand All @@ -25,13 +26,31 @@ import useLocation from 'routing/useLocation';
import useMinimumRefreshInterval from 'views/hooks/useMinimumRefreshInterval';
import RefreshControls from 'components/common/RefreshControls';
import useDefaultInterval from 'views/hooks/useDefaultIntervalForRefresh';
import useAutoRefresh from 'views/hooks/useAutoRefresh';

import useTableFetchContext from '../../common/PaginatedEntityTable/useTableFetchContext';

const useDisableRefreshWhileSlicing = () => {
const tableFetchContext = useTableFetchContext();
const { refreshConfig, stopAutoRefresh } = useAutoRefresh();
const isSlicingEnabled = Boolean(tableFetchContext?.searchParams.sliceCol);

useEffect(() => {
if (isSlicingEnabled && refreshConfig?.enabled) {
stopAutoRefresh();
}
}, [isSlicingEnabled, refreshConfig?.enabled, stopAutoRefresh]);

return isSlicingEnabled;
};

const EventsRefreshControls = () => {
const location = useLocation();
const sendTelemetry = useSendTelemetry();
const { config } = useSearchConfiguration();
const autoRefreshTimerangeOptions = config?.auto_refresh_timerange_options;
const { data: minimumRefreshInterval, isInitialLoading: isLoadingMinimumInterval } = useMinimumRefreshInterval();
const isSlicingEnabled = useDisableRefreshWhileSlicing();

const onSelectInterval = useCallback(
(interval: string) => {
Expand Down Expand Up @@ -67,15 +86,20 @@ const EventsRefreshControls = () => {

return (
<RefreshControls
disable={false}
disable={isSlicingEnabled}
intervalOptions={intervalOptions}
isLoadingMinimumInterval={isLoadingMinimumInterval}
minimumRefreshInterval={minimumRefreshInterval}
defaultInterval={defaultInterval}
humanName="Events"
onToggle={onToggle}
onSelectInterval={onSelectInterval}
/>
onSelectInterval={onSelectInterval}>
{isSlicingEnabled && (
<HoverForHelp title="Auto refresh unavailable" placement="left" pullRight={false} iconSize="sm">
Auto refresh is turned off during slicing to avoid performance issues.
</HoverForHelp>
)}
</RefreshControls>
);
};

Expand Down
Loading
Loading