Skip to content

Commit

Permalink
Unify auto-refresh behaviour by disabling auto-refresh on search bar …
Browse files Browse the repository at this point in the history
…form changes.
  • Loading branch information
linuspahl committed Oct 11, 2023
1 parent 3ad7e2f commit 799705a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ describe('RefreshControls', () => {
children: undefined,
};

const TriggerFormChangeButton = () => {
const { setFieldValue } = useFormikContext();

return (
<Button onClick={() => setFieldValue('example-field', 'example-value')}>
Change form field value
</Button>
);
};

beforeEach(() => {
asMock(useSearchConfiguration).mockReturnValue({
config: {
Expand Down Expand Up @@ -118,16 +128,6 @@ describe('RefreshControls', () => {
asMock(useRefreshConfig).mockReturnValue({ enabled: false, interval: 5000 });
const onSubmitMock = jest.fn();

const TriggerFormChangeButton = () => {
const { setFieldValue } = useFormikContext();

return (
<Button onClick={() => setFieldValue('example-field', 'example-value')}>
Change form field value
</Button>
);
};

render(
<SUT onSubmit={onSubmitMock}>
<TriggerFormChangeButton />
Expand All @@ -139,4 +139,18 @@ describe('RefreshControls', () => {

await waitFor(() => expect(onSubmitMock).toHaveBeenCalled());
});

it('should stop the interval when there are form changes while the interval is active', async () => {
asMock(useRefreshConfig).mockReturnValue({ enabled: true, interval: 5000 });

render(
<SUT>
<TriggerFormChangeButton />
</SUT>,
);

userEvent.click(await screen.findByRole('button', { name: /change form field value/i }));

await waitFor(() => expect(RefreshActions.disable).toHaveBeenCalled());
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,17 @@ const ButtonLabel = ({ refreshConfigEnabled, naturalInterval }: {
return <>{buttonText}</>;
};

const useDisableOnFormChange = () => {
const refreshConfig = useRefreshConfig();
const { dirty, isSubmitting } = useFormikContext();

useEffect(() => {
if (refreshConfig.enabled && !isSubmitting && dirty) {
RefreshActions.disable();
}
}, [dirty, isSubmitting, refreshConfig.enabled]);
};

const durationToMS = (duration: string) => moment.duration(duration).asMilliseconds();

const RefreshControls = () => {
Expand All @@ -69,9 +80,14 @@ const RefreshControls = () => {
});

RefreshActions.setInterval(interval);

if (dirty) {
submitForm();
}
};

useEffect(() => () => RefreshActions.disable(), []);
useDisableOnFormChange();

const _toggleEnable = useCallback(() => {
sendTelemetry(TELEMETRY_EVENT_TYPE.SEARCH_REFRESH_CONTROL_TOGGLED, {
Expand Down

0 comments on commit 799705a

Please sign in to comment.