Skip to content

Commit

Permalink
Add current page parameter to the route in the listing and search blo…
Browse files Browse the repository at this point in the history
…ck pagination (#4159)

Co-authored-by: Mikel Larreategi <mlarreategi@codesyntax.com>
Co-authored-by: Víctor Fernández de Alba <sneridagh@gmail.com>
Co-authored-by: ionlizarazu <ilizarazu@codesyntax.com>
  • Loading branch information
4 people authored Apr 5, 2023
1 parent 267181c commit c40e772
Show file tree
Hide file tree
Showing 6 changed files with 193 additions and 20 deletions.
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);
});
});

0 comments on commit c40e772

Please sign in to comment.