Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add current page parameter to the route in the listing and search block pagination #4159

Merged
merged 32 commits into from
Apr 5, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
deb5988
Fixes: #3868 - Added the current page parameter in route in Listing a…
bipoza Dec 21, 2022
76da8e7
Merge branch 'master' into pagination-with-router-params
erral Dec 21, 2022
7115d8f
Documentation improvements
bipoza Dec 21, 2022
dd88b26
Added support for multiple paginations
bipoza Dec 21, 2022
386d340
Merge branch 'pagination-with-router-params' of https://github.com/pl…
bipoza Dec 21, 2022
fb04de8
usePagination code refactoring
bipoza Dec 21, 2022
5f18384
Added unit test
bipoza Dec 21, 2022
0ca3316
Added changelog
bipoza Dec 21, 2022
b9d518a
Merge branch 'master' into pagination-with-router-params
erral Dec 21, 2022
ab87619
Merge branch 'master' into pagination-with-router-params
erral Jan 9, 2023
e0b7b1a
Merge branch 'master' into pagination-with-router-params
bipoza Jan 23, 2023
34ee368
Merge branch 'master' into pagination-with-router-params
erral Feb 1, 2023
4effc3d
Merge branch 'master' into pagination-with-router-params
bipoza Feb 3, 2023
7c4be39
Merge branch 'master' into pagination-with-router-params
erral Feb 6, 2023
b1e86d5
Merge branch 'master' into pagination-with-router-params
erral Feb 9, 2023
ca3c116
Merge branch 'master' into pagination-with-router-params
erral Feb 13, 2023
e59f19b
Merge branch 'master' into pagination-with-router-params
erral Feb 23, 2023
fa15daf
Merge branch 'master' into pagination-with-router-params
erral Feb 28, 2023
9829c53
Merge branch 'master' into pagination-with-router-params
sneridagh Mar 15, 2023
570bb04
Merge branch 'master' into pagination-with-router-params
bipoza Mar 21, 2023
8fd8b74
Merge branch 'master' into pagination-with-router-params
bipoza Mar 29, 2023
a7b3cc9
fixed the bug when combining the search block with the pagination
bipoza Mar 30, 2023
bdc850d
usePagination jest tests
bipoza Mar 30, 2023
3d54c67
eslist
bipoza Mar 30, 2023
015572f
rename the blockId param to id and the defaultPage param to be 1 inst…
ionlizarazu Mar 30, 2023
cc9b1cd
fix and add tests for usePagination.js
ionlizarazu Mar 30, 2023
5e20cd3
Merge branch 'master' into pagination-with-router-params
ionlizarazu Mar 31, 2023
88b2ae5
changelog
ionlizarazu Mar 31, 2023
e04278e
Merge branch 'master' into pagination-with-router-params
erral Apr 1, 2023
205457a
Merge branch 'master' into pagination-with-router-params
sneridagh Apr 5, 2023
09b69ff
Merge branch 'master' into pagination-with-router-params
erral Apr 5, 2023
8b264cb
Merge branch 'master' into pagination-with-router-params
erral Apr 5, 2023
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
38 changes: 22 additions & 16 deletions src/helpers/Utils/usePagination.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useRef } from 'react';
import React, { useRef, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import qs from 'query-string';
import { useSelector } from 'react-redux';
Expand All @@ -11,9 +11,12 @@ import { slugify } from '@plone/volto/helpers/Utils/Utils';
*/
const useCreatePageQueryStringKey = (id) => {
const blockTypesWithPagination = ['search', 'listing'];
const blocks = useSelector((state) => state.content.data.blocks);
const blocks = useSelector((state) => state?.content?.data?.blocks) || [];
const blocksLayout =
useSelector((state) => state?.content?.data?.blocks_layout?.items) || [];
const displayedBlocks = blocksLayout?.map((item) => blocks[item]);
const hasMultiplePaginations =
Object.values(blocks).filter((item) =>
displayedBlocks.filter((item) =>
blockTypesWithPagination.includes(item['@type']),
).length > 1 || false;

Expand All @@ -24,26 +27,29 @@ const useCreatePageQueryStringKey = (id) => {
* A pagination helper that tracks the query and resets pagination in case the
* query changes.
*/
export const usePagination = (id = null, defaultPage = 1) => {
export const usePagination = (blockId = null, defaultPage = '1') => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd think we should stick to a generic id rather then blockId and a number for the defaultPage.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean the "blockId" naming or something else?

const location = useLocation();
const history = useHistory();
const pageQueryStringKey = useCreatePageQueryStringKey(id);
const pageQueryStringKey = useCreatePageQueryStringKey(blockId);
const pageQueryParam =
qs.parse(location.search)[pageQueryStringKey] || defaultPage;
const [currentPage, setCurrentPage] = React.useState(pageQueryParam);
const firstUpdate = useRef(true);
const [currentPage, setCurrentPage] = React.useState(
parseInt(pageQueryParam),
);
const queryRef = useRef(qs.parse(location.search)?.query);

useEffect(() => {
if (!firstUpdate.current) {
const newParams = {
...qs.parse(location.search),
[pageQueryStringKey]: currentPage,
};
history.replace({
search: qs.stringify(newParams),
});
if (queryRef.current !== qs.parse(location.search)?.query) {
setCurrentPage(defaultPage);
queryRef.current = qs.parse(location.search)?.query;
}
firstUpdate.current = false;
const newParams = {
...qs.parse(location.search),
[pageQueryStringKey]: currentPage,
};
history.replace({
search: qs.stringify(newParams),
});
}, [currentPage, defaultPage, location.search, history, pageQueryStringKey]);

return {
Expand Down
147 changes: 147 additions & 0 deletions src/helpers/Utils/usePagination.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { renderHook } from '@testing-library/react-hooks';
import { usePagination } from './usePagination';
import * as redux from 'react-redux';
import routeData from 'react-router';

const state = {
content: {
data: {
blocks: {
'1a4ebb48-8095-4182-98a5-d7ccf5761bd2': {
'@type': 'title',
},
'545b33de-92cf-4747-969d-68851837b317': {
'@type': 'search',
query: {
b_size: '4',
query: [
{
i: 'path',
o: 'plone.app.querystring.operation.string.relativePath',
v: '',
},
],
sort_order: 'ascending',
},
showSearchInput: true,
showTotalResults: true,
},
'454b33de-92cf-4747-969d-68851837b317': {
'@type': 'search',
query: {
b_size: '4',
query: [
{
i: 'path',
o: 'plone.app.querystring.operation.string.relativePath',
v: '',
},
],
sort_order: 'ascending',
},
showSearchInput: true,
showTotalResults: true,
},
'81509424-dcbc-4478-8db0-903c74b28b3d': {
'@type': 'slate',
plaintext: '',
value: [
{
children: [
{
text: '',
},
],
type: 'p',
},
],
},
},
blocks_layout: {
items: [
'545b33de-92cf-4747-969d-68851837b317',
'81509424-dcbc-4478-8db0-903c74b28b3d',
],
},
},
},
};

let mockUseLocationValue = {
pathname: '/testroute',
search: '',
};

// jest.mock('react-router-dom', () => ({
// ...jest.requireActual('react-router-dom'),
// useLocation: () => ({
// pathname: 'localhost:3000/example/path',
// }),
// }));

const setUp = (searchParam) => {
mockUseLocationValue.search = searchParam;
return renderHook(
({ blockId, defaultPage }) => usePagination(blockId, defaultPage),
{
initialProps: {
blockId: '545b33de-92cf-4747-969d-68851837b317',
defaultPage: 1,
},
},
);
};

// jest.mock('react-router-dom', () => ({
// useHistory: () => ({ replace: jest.fn() }),
// useLocation: () => ({
// search: jest.fn().mockImplementation(() => {
// return mockUseLocationValue;
// }),
// }),
// }));

jest.spyOn(redux, 'useSelector').mockImplementation((cb) => cb(state));
describe('Utils tests', () => {
const useLocation = jest.spyOn(routeData, 'useLocation');
const useHistory = jest.spyOn(routeData, 'useHistory');
const useSelector = jest.spyOn(redux, 'useSelector');
beforeEach(() => {
useLocation.mockReturnValue(mockUseLocationValue);
useHistory.mockReturnValue({ replace: jest.fn() });
// useSelector.mockReturnValue((cb) => cb(state));
});

it('with blockId and defaultPage 1 - shoud be 1', () => {
const { result } = setUp();
expect(result.current.currentPage).toBe(1);
});

it('without params - shoud be 1', () => {
const { result } = setUp();
expect(result.current.currentPage).toBe(1);
});

it('with page 2 param - shoud be 2', () => {
const { result } = setUp('?page=2');
expect(result.current.currentPage).toBe(2);
});

it('first time with page 2 - shoud be 2', () => {
const { result } = setUp('?page-545b33de-92cf-4747-969d-68851837b317=2');
expect(result.current.currentPage).toBe(2);
});
});

// it('should always return previous state after each update', () => {
// const { result, rerender } = setUp();

// rerender({ state: 2 });
// expect(result.current).toBe(0);

// rerender({ state: 4 });
// expect(result.current).toBe(2);

// rerender({ state: 6 });
// expect(result.current).toBe(4);
// });