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 all 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
1 change: 1 addition & 0 deletions news/4159.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added current page parameter to route in listing and search block pagination - Fix: #3868 @bipoza
20 changes: 20 additions & 0 deletions src/components/manage/Blocks/Listing/ListingBody.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,26 @@ test('renders a ListingBody component', () => {
content: {
data: {
is_folderish: true,
blocks: {
'839ee00b-013b-4f4a-9b10-8867938fdac3': {
'@type': 'listing',
block: '839ee00b-013b-4f4a-9b10-8867938fdac3',
headlineTag: 'h2',
query: [],
querystring: {
b_size: '2',
query: [
{
i: 'path',
o: 'plone.app.querystring.operation.string.absolutePath',
v: '/',
},
],
sort_order: 'ascending',
},
variation: 'default',
},
},
},
},
intl: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export default function withQuerystringResults(WrappedComponent) {
const [initialPath] = React.useState(getBaseUrl(path));

const copyFields = ['limit', 'query', 'sort_on', 'sort_order', 'depth'];

const { currentPage, setCurrentPage } = usePagination(data.block, 1);
const adaptedQuery = Object.assign(
variation?.fullobjects ? { fullobjects: 1 } : { metadata_fields: '_all' },
{
Expand All @@ -37,7 +37,6 @@ export default function withQuerystringResults(WrappedComponent) {
: {},
),
);
const { currentPage, setCurrentPage } = usePagination(querystring, 1);
const querystringResults = useSelector(
(state) => state.querystringsearch.subrequests,
);
Expand Down
12 changes: 8 additions & 4 deletions src/components/manage/Blocks/Search/hocs/withSearch.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,16 @@ const getSearchFields = (searchData) => {
};

/**
* A HOC that will mirror the search block state to a hash location
* A hook that will mirror the search block state to a hash location
*/
const useHashState = () => {
const location = useLocation();
const history = useHistory();

/**
* Required to maintain parameter compatibility.
With this we will maintain support for receiving hash (#) and search (?) type parameters.
*/
const oldState = React.useMemo(() => {
return {
...qs.parse(location.search),
Expand All @@ -165,7 +169,7 @@ const useHashState = () => {

const setSearchData = React.useCallback(
(searchData) => {
const newParams = qs.parse(location.hash);
const newParams = qs.parse(location.search);

let changed = false;

Expand All @@ -182,11 +186,11 @@ const useHashState = () => {

if (changed) {
history.push({
hash: qs.stringify(newParams),
search: qs.stringify(newParams),
});
}
},
[history, oldState, location.hash],
[history, oldState, location.search],
);

return [current, setSearchData];
Expand Down
62 changes: 48 additions & 14 deletions src/helpers/Utils/usePagination.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,59 @@
import React from 'react';
import { isEqual } from 'lodash';
import { usePrevious } from './usePrevious';
import useDeepCompareEffect from 'use-deep-compare-effect';
import React, { useRef, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import qs from 'query-string';
import { useSelector } from 'react-redux';
import { slugify } from '@plone/volto/helpers/Utils/Utils';

/**
* @function useCreatePageQueryStringKey
* @description A hook that creates a key with an id if there are multiple blocks with pagination.
* @returns {string} Example: page || page_012345678
*/
const useCreatePageQueryStringKey = (id) => {
const blockTypesWithPagination = ['search', 'listing'];
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 =
displayedBlocks.filter((item) =>
blockTypesWithPagination.includes(item['@type']),
).length > 1 || false;

return hasMultiplePaginations ? slugify(`page-${id}`) : 'page';
};

/**
* A pagination helper that tracks the query and resets pagination in case the
* query changes.
*/
export const usePagination = (query, defaultPage = 1) => {
const previousQuery = usePrevious(query);
const [currentPage, setCurrentPage] = React.useState(defaultPage);
export const usePagination = (id = null, defaultPage = 1) => {
const location = useLocation();
const history = useHistory();
const pageQueryStringKey = useCreatePageQueryStringKey(id);
const pageQueryParam =
qs.parse(location.search)[pageQueryStringKey] || defaultPage;
const [currentPage, setCurrentPage] = React.useState(
parseInt(pageQueryParam),
);
const queryRef = useRef(qs.parse(location.search)?.query);

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

return {
currentPage:
previousQuery && !isEqual(previousQuery, query)
? defaultPage
: currentPage,
currentPage,
setCurrentPage,
};
};
115 changes: 115 additions & 0 deletions src/helpers/Utils/usePagination.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { renderHook } from '@testing-library/react-hooks';
import { usePagination } from './usePagination';
import * as redux from 'react-redux';
import routeData from 'react-router';
import { slugify } from '@plone/volto/helpers/Utils/Utils';

const searchBlockId = '545b33de-92cf-4747-969d-68851837b317';
const searchBlockId2 = '454b33de-92cf-4747-969d-68851837b713';
const searchBlock = {
'@type': 'search',
query: {
b_size: '4',
query: [
{
i: 'path',
o: 'plone.app.querystring.operation.string.relativePath',
v: '',
},
],
sort_order: 'ascending',
},
showSearchInput: true,
showTotalResults: true,
};
let state = {
content: {
data: {
blocks: {
[searchBlockId]: searchBlock,
},
blocks_layout: {
items: [searchBlockId],
},
},
},
};

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

const setUp = (searchParam, numberOfSearches) => {
mockUseLocationValue.search = searchParam;
if (numberOfSearches > 1) {
state.content.data.blocks[searchBlockId2] = searchBlock;
state.content.data.blocks_layout.items.push(searchBlockId2);
}
return renderHook(({ id, defaultPage }) => usePagination(id, defaultPage), {
initialProps: {
id: searchBlockId,
defaultPage: 1,
},
});
};

describe(`Tests for usePagination, for the block ${searchBlockId}`, () => {
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.mockImplementation((cb) => cb(state));
});

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

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

const param1 = '?page=2';
it(`1 paginated block with params: ${param1} - shoud be 2`, () => {
const { result } = setUp(param1);
expect(result.current.currentPage).toBe(2);
});

const param2 = `?${slugify(`page-${searchBlockId}`)}=2`;
it(`2 paginated blocks with current block in the params: ${param2} - shoud be 2`, () => {
const { result } = setUp(param2, 2);
expect(result.current.currentPage).toBe(2);
});

const param3 = `?${slugify(`page-${searchBlockId2}`)}=2`;
it(`2 paginated blocks with the other block in the params: ${param3} - shoud be 1`, () => {
const { result } = setUp(param3, 2);
expect(result.current.currentPage).toBe(1);
});

const param4 = `?${slugify(`page-${searchBlockId}`)}=2&${slugify(
`page-${searchBlockId2}`,
)}=1`;
it(`2 paginated blocks with both blocks in the params, current 2: ${param4} - shoud be 2`, () => {
const { result } = setUp(param4, 2);
expect(result.current.currentPage).toBe(2);
});

const param5 = `?${slugify(`page-${searchBlockId}`)}=1&${slugify(
`page-${searchBlockId2}`,
)}=2`;
it(`2 paginated blocks with both blocks in the params, current 1: ${param5} - shoud be 1`, () => {
const { result } = setUp(param5, 2);
expect(result.current.currentPage).toBe(1);
});

it(`2 paginated blocks with wrong page param: ${param1} - shoud be 1`, () => {
const { result } = setUp(param1, 2);
expect(result.current.currentPage).toBe(1);
});
});