Skip to content

Commit c791371

Browse files
[8.8] [RAM] Alert table reset pagination after filter (#157216) (#157223)
# Backport This will backport the following commits from `main` to `8.8`: - [[RAM] Alert table reset pagination after filter (#157216)](#157216) <!--- Backport version: 8.9.7 --> ### Questions ? Please refer to the [Backport tool documentation](https://github.com/sqren/backport) <!--BACKPORT [{"author":{"name":"Xavier Mouligneau","email":"xavier.mouligneau@elastic.co"},"sourceCommit":{"committedDate":"2023-05-09T21:16:23Z","message":"[RAM] Alert table reset pagination after filter (#157216)\n\n## Summary\r\n\r\nFix https://github.com/elastic/kibana/issues/157133\r\n\r\n### Checklist\r\n\r\n- [x] [Unit or functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere updated or added to match the most common scenarios","sha":"ee3d4e47449f07d1a4fac7df44e4cd98ca58bac1","branchLabelMapping":{"^v8.9.0$":"main","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","Team:ResponseOps","v8.8.0","v8.9.0"],"number":157216,"url":"https://github.com/elastic/kibana/pull/157216","mergeCommit":{"message":"[RAM] Alert table reset pagination after filter (#157216)\n\n## Summary\r\n\r\nFix https://github.com/elastic/kibana/issues/157133\r\n\r\n### Checklist\r\n\r\n- [x] [Unit or functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere updated or added to match the most common scenarios","sha":"ee3d4e47449f07d1a4fac7df44e4cd98ca58bac1"}},"sourceBranch":"main","suggestedTargetBranches":["8.8"],"targetPullRequestStates":[{"branch":"8.8","label":"v8.8.0","labelRegex":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"main","label":"v8.9.0","labelRegex":"^v8.9.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/157216","number":157216,"mergeCommit":{"message":"[RAM] Alert table reset pagination after filter (#157216)\n\n## Summary\r\n\r\nFix https://github.com/elastic/kibana/issues/157133\r\n\r\n### Checklist\r\n\r\n- [x] [Unit or functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere updated or added to match the most common scenarios","sha":"ee3d4e47449f07d1a4fac7df44e4cd98ca58bac1"}}]}] BACKPORT--> Co-authored-by: Xavier Mouligneau <xavier.mouligneau@elastic.co>
1 parent 0536e10 commit c791371

4 files changed

Lines changed: 144 additions & 12 deletions

File tree

x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/alerts_table_state.tsx

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,10 @@ const AlertsTableStateWithQueryProvider = ({
219219
initialBrowserFields: propBrowserFields,
220220
});
221221

222+
const onPageChange = useCallback((_pagination: RuleRegistrySearchRequestPagination) => {
223+
setPagination(_pagination);
224+
}, []);
225+
222226
const [
223227
isLoading,
224228
{
@@ -236,6 +240,7 @@ const AlertsTableStateWithQueryProvider = ({
236240
featureIds,
237241
query,
238242
pagination,
243+
onPageChange,
239244
runtimeMappings,
240245
sort,
241246
skip: false,
@@ -261,10 +266,6 @@ const AlertsTableStateWithQueryProvider = ({
261266
fetchCases
262267
);
263268

264-
const onPageChange = useCallback((_pagination: RuleRegistrySearchRequestPagination) => {
265-
setPagination(_pagination);
266-
}, []);
267-
268269
const initialBulkActionsState = useReducer(bulkActionsReducer, {
269270
rowSelection: new Map<number, RowSelectionState>(),
270271
isAllSelected: false,
@@ -318,7 +319,7 @@ const AlertsTableStateWithQueryProvider = ({
318319
oldAlertsData,
319320
onPageChange,
320321
onSortChange,
321-
pagination.pageIndex,
322+
pagination,
322323
refresh,
323324
sort,
324325
updatedAt,
@@ -374,7 +375,7 @@ const AlertsTableStateWithQueryProvider = ({
374375
memoizedCases,
375376
columns,
376377
flyoutSize,
377-
pagination.pageSize,
378+
pagination,
378379
id,
379380
leadingControlColumns,
380381
showExpandToDetails,

x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_fetch_alerts.test.tsx

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import { act, renderHook } from '@testing-library/react-hooks';
1111
import { useFetchAlerts, FetchAlertsArgs, FetchAlertResp } from './use_fetch_alerts';
1212
import { useKibana } from '../../../../common/lib/kibana';
1313
import { IKibanaSearchResponse } from '@kbn/data-plugin/public';
14+
import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
15+
import { useState } from 'react';
1416

1517
jest.mock('../../../../common/lib/kibana');
1618

@@ -88,6 +90,7 @@ const expectedResponse: FetchAlertResp = {
8890

8991
describe('useFetchAlerts', () => {
9092
let clock: sinon.SinonFakeTimers;
93+
const onPageChangeMock = jest.fn();
9194
const args: FetchAlertsArgs = {
9295
featureIds: ['siem'],
9396
fields: [
@@ -101,6 +104,7 @@ describe('useFetchAlerts', () => {
101104
pageIndex: 0,
102105
pageSize: 10,
103106
},
107+
onPageChange: onPageChangeMock,
104108
sort: [],
105109
skip: false,
106110
};
@@ -474,4 +478,75 @@ describe('useFetchAlerts', () => {
474478
},
475479
]);
476480
});
481+
482+
it('reset pagination when query is used', async () => {
483+
const useWrapperHook = ({ query }: { query: Pick<QueryDslQueryContainer, 'bool' | 'ids'> }) => {
484+
const [pagination, setPagination] = useState({ pageIndex: 5, pageSize: 10 });
485+
const handlePagination = (newPagination: { pageIndex: number; pageSize: number }) => {
486+
onPageChangeMock(newPagination);
487+
setPagination(newPagination);
488+
};
489+
const result = useFetchAlerts({
490+
...args,
491+
pagination,
492+
onPageChange: handlePagination,
493+
query,
494+
});
495+
return result;
496+
};
497+
498+
const { rerender } = renderHook(
499+
({ initialValue }) =>
500+
useWrapperHook({
501+
query: initialValue,
502+
}),
503+
{
504+
initialProps: { initialValue: {} },
505+
}
506+
);
507+
508+
expect(dataSearchMock).lastCalledWith(
509+
{
510+
featureIds: args.featureIds,
511+
fields: [...args.fields],
512+
pagination: {
513+
pageIndex: 5,
514+
pageSize: 10,
515+
},
516+
query: {},
517+
sort: args.sort,
518+
},
519+
{ abortSignal: expect.anything(), strategy: 'privateRuleRegistryAlertsSearchStrategy' }
520+
);
521+
522+
rerender({
523+
initialValue: {
524+
ids: {
525+
values: ['alert-id-1'],
526+
},
527+
},
528+
});
529+
530+
expect(dataSearchMock).lastCalledWith(
531+
{
532+
featureIds: args.featureIds,
533+
fields: [...args.fields],
534+
pagination: {
535+
pageIndex: 0,
536+
pageSize: 10,
537+
},
538+
query: {
539+
ids: {
540+
values: ['alert-id-1'],
541+
},
542+
},
543+
sort: args.sort,
544+
},
545+
{ abortSignal: expect.anything(), strategy: 'privateRuleRegistryAlertsSearchStrategy' }
546+
);
547+
expect(onPageChangeMock).lastCalledWith({
548+
pageIndex: 0,
549+
pageSize: 10,
550+
});
551+
});
477552
});

x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_fetch_alerts.tsx

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { Subscription } from 'rxjs';
1515
import { isCompleteResponse, isErrorResponse } from '@kbn/data-plugin/common';
1616
import type {
1717
RuleRegistrySearchRequest,
18+
RuleRegistrySearchRequestPagination,
1819
RuleRegistrySearchResponse,
1920
} from '@kbn/rule-registry-plugin/common/search_strategy';
2021
import type {
@@ -36,12 +37,13 @@ export interface FetchAlertsArgs {
3637
pageIndex: number;
3738
pageSize: number;
3839
};
40+
onPageChange: (pagination: RuleRegistrySearchRequestPagination) => void;
3941
runtimeMappings?: MappingRuntimeFields;
4042
sort: SortCombinations[];
4143
skip: boolean;
4244
}
4345

44-
type AlertRequest = Omit<FetchAlertsArgs, 'featureIds' | 'skip'>;
46+
type AlertRequest = Omit<FetchAlertsArgs, 'featureIds' | 'skip' | 'onPageChange'>;
4547

4648
type Refetch = () => void;
4749

@@ -67,7 +69,7 @@ export interface FetchAlertResp {
6769
type AlertResponseState = Omit<FetchAlertResp, 'getInspectQuery' | 'refetch'>;
6870
interface AlertStateReducer {
6971
loading: boolean;
70-
request: Omit<FetchAlertsArgs, 'skip'>;
72+
request: Omit<FetchAlertsArgs, 'skip' | 'onPageChange'>;
7173
response: AlertResponseState;
7274
}
7375

@@ -81,7 +83,7 @@ type AlertActions =
8183
ecsAlertsData: unknown[];
8284
}
8385
| { type: 'resetPagination' }
84-
| { type: 'request'; request: Omit<FetchAlertsArgs, 'skip'> };
86+
| { type: 'request'; request: Omit<FetchAlertsArgs, 'skip' | 'onPageChange'> };
8587

8688
const initialAlertState: AlertStateReducer = {
8789
loading: false,
@@ -146,6 +148,7 @@ export type UseFetchAlerts = ({
146148
fields,
147149
query,
148150
pagination,
151+
onPageChange,
149152
runtimeMappings,
150153
skip,
151154
sort,
@@ -155,6 +158,7 @@ const useFetchAlerts = ({
155158
fields,
156159
query,
157160
pagination,
161+
onPageChange,
158162
runtimeMappings,
159163
skip,
160164
sort,
@@ -279,6 +283,9 @@ const useFetchAlerts = ({
279283
[skip, data, featureIds, query, fields]
280284
);
281285

286+
// FUTURE ENGINEER
287+
// This useEffect is only to fetch the alert when these props below changed
288+
// fields, pagination, sort, runtimeMappings
282289
useEffect(() => {
283290
if (featureIds.length === 0) {
284291
return;
@@ -287,7 +294,7 @@ const useFetchAlerts = ({
287294
featureIds,
288295
fields,
289296
pagination,
290-
query,
297+
query: prevAlertRequest.current?.query ?? {},
291298
runtimeMappings,
292299
sort,
293300
};
@@ -300,7 +307,37 @@ const useFetchAlerts = ({
300307
request: newAlertRequest,
301308
});
302309
}
303-
}, [featureIds, fields, pagination, query, sort, runtimeMappings]);
310+
}, [featureIds, fields, pagination, sort, runtimeMappings]);
311+
312+
// FUTURE ENGINEER
313+
// This useEffect is only to fetch the alert when query props changed
314+
// because we want to reset the pageIndex of pagination to 0
315+
useEffect(() => {
316+
if (featureIds.length === 0 || !prevAlertRequest.current) {
317+
return;
318+
}
319+
const resetPagination = {
320+
pageIndex: 0,
321+
pageSize: prevAlertRequest.current?.pagination?.pageSize ?? 50,
322+
};
323+
const newAlertRequest = {
324+
...prevAlertRequest.current,
325+
featureIds,
326+
pagination: resetPagination,
327+
query,
328+
};
329+
330+
if (
331+
(newAlertRequest?.fields ?? []).length > 0 &&
332+
!deepEqual(newAlertRequest.query, prevAlertRequest.current.query)
333+
) {
334+
dispatch({
335+
type: 'request',
336+
request: newAlertRequest,
337+
});
338+
onPageChange(resetPagination);
339+
}
340+
}, [featureIds, onPageChange, query]);
304341

305342
useEffect(() => {
306343
if (alertRequest.featureIds.length > 0 && !deepEqual(alertRequest, prevAlertRequest.current)) {

x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_table/hooks/use_pagination.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* 2.0; you may not use this file except in compliance with the Elastic License
55
* 2.0.
66
*/
7-
import { useCallback, useContext, useState } from 'react';
7+
import { useCallback, useContext, useEffect, useState } from 'react';
88
import { RuleRegistrySearchRequestPagination } from '@kbn/rule-registry-plugin/common';
99
import { BulkActionsVerbs } from '../../../../types';
1010
import { BulkActionsContext } from '../bulk_actions/context';
@@ -75,6 +75,25 @@ export function usePagination({ onPageChange, pageIndex, pageSize }: PaginationP
7575
[onChangePageIndex, pagination.pageIndex, pagination.pageSize]
7676
);
7777

78+
useEffect(() => {
79+
setPagination((prevPagination) => {
80+
const newPagination = { ...prevPagination };
81+
let updated = false;
82+
if (prevPagination.pageIndex !== pageIndex) {
83+
updated = true;
84+
newPagination.pageIndex = pageIndex;
85+
}
86+
if (prevPagination.pageSize !== pageSize) {
87+
updated = true;
88+
newPagination.pageSize = pageSize;
89+
}
90+
if (updated === true) {
91+
return newPagination;
92+
}
93+
return prevPagination;
94+
});
95+
}, [pageIndex, pageSize]);
96+
7897
return {
7998
pagination,
8099
onChangePageSize,

0 commit comments

Comments
 (0)