-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
use-patterns-paging.js
76 lines (71 loc) · 2.23 KB
/
use-patterns-paging.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* WordPress dependencies
*/
import { useMemo, useState, useEffect } from '@wordpress/element';
import { useAsyncList, usePrevious } from '@wordpress/compose';
import { getScrollContainer } from '@wordpress/dom';
const PAGE_SIZE = 20;
const INITIAL_INSERTER_RESULTS = 5;
/**
* Supplies values needed to page the patterns list client side.
*
* @param {Array} currentCategoryPatterns An array of the current patterns to display.
* @param {string} currentCategory The currently selected category.
* @param {Object} scrollContainerRef Ref of container to to find scroll container for when moving between pages.
* @param {string} currentFilter The currently search filter.
*
* @return {Object} Returns the relevant paging values. (totalItems, categoryPatternsList, numPages, changePage, currentPage)
*/
export default function usePatternsPaging(
currentCategoryPatterns,
currentCategory,
scrollContainerRef,
currentFilter = ''
) {
const [ currentPage, setCurrentPage ] = useState( 1 );
const previousCategory = usePrevious( currentCategory );
const previousFilter = usePrevious( currentFilter );
if (
( previousCategory !== currentCategory ||
previousFilter !== currentFilter ) &&
currentPage !== 1
) {
setCurrentPage( 1 );
}
const totalItems = currentCategoryPatterns.length;
const pageIndex = currentPage - 1;
const categoryPatterns = useMemo( () => {
return currentCategoryPatterns.slice(
pageIndex * PAGE_SIZE,
pageIndex * PAGE_SIZE + PAGE_SIZE
);
}, [ pageIndex, currentCategoryPatterns ] );
const categoryPatternsAsyncList = useAsyncList( categoryPatterns, {
step: INITIAL_INSERTER_RESULTS,
} );
const numPages = Math.ceil( currentCategoryPatterns.length / PAGE_SIZE );
const changePage = ( page ) => {
const scrollContainer = getScrollContainer(
scrollContainerRef?.current
);
scrollContainer?.scrollTo( 0, 0 );
setCurrentPage( page );
};
useEffect(
function scrollToTopOnCategoryChange() {
const scrollContainer = getScrollContainer(
scrollContainerRef?.current
);
scrollContainer?.scrollTo( 0, 0 );
},
[ currentCategory, scrollContainerRef ]
);
return {
totalItems,
categoryPatterns,
categoryPatternsAsyncList,
numPages,
changePage,
currentPage,
};
}