| 1 |
import { useEffect, useState } from "@wordpress/element"; |
| 2 |
import { debounce } from "../../controls/controls"; |
| 3 |
import { jsonStringify } from "../../blocks/shared/helpFn"; |
| 4 |
|
| 5 |
export const usePaginationFn = ({ |
| 6 |
posts, |
| 7 |
postCount, |
| 8 |
attributes, |
| 9 |
observerRef, |
| 10 |
ref, |
| 11 |
currentPage, |
| 12 |
setCurrentPage, |
| 13 |
setLoadMorePagination, |
| 14 |
ajaxLiveFilter = {}, |
| 15 |
loadMorePagination = false, |
| 16 |
}) => { |
| 17 |
const { postLimit, itemsPerPage, loadMoreInfiniteScroll, paginationType, paginationEnable } = attributes; |
| 18 |
// states |
| 19 |
const [allPosts, setAllPosts] = useState([]); |
| 20 |
const [height, setHeight] = useState(""); |
| 21 |
const [loading, setLoading] = useState(false); |
| 22 |
|
| 23 |
const allPostLimit = postLimit > postCount ? postCount : postLimit; |
| 24 |
|
| 25 |
const totalPage = Math.ceil(allPostLimit / itemsPerPage); |
| 26 |
|
| 27 |
const handleScroll = () => { |
| 28 |
const offsetTop = observerRef.current.offsetTop - 1000; |
| 29 |
const scrollXPosition = window.scrollY; |
| 30 |
if (offsetTop < scrollXPosition) { |
| 31 |
setLoading(true); |
| 32 |
setLoadMorePagination(true); |
| 33 |
} |
| 34 |
}; |
| 35 |
|
| 36 |
if (loadMoreInfiniteScroll) { |
| 37 |
window.addEventListener("scroll", debounce(handleScroll, 0)); |
| 38 |
} |
| 39 |
|
| 40 |
useEffect(() => { |
| 41 |
if (loading === true && currentPage < totalPage) { |
| 42 |
setCurrentPage((prev) => prev + 1); |
| 43 |
} |
| 44 |
}, [loading]); |
| 45 |
|
| 46 |
useEffect(() => { |
| 47 |
setAllPosts((prevPosts) => { |
| 48 |
if (loadMorePagination) { |
| 49 |
return [...prevPosts, ...posts]; |
| 50 |
} |
| 51 |
return posts; |
| 52 |
}); |
| 53 |
setLoading(false); |
| 54 |
}, [posts]); |
| 55 |
|
| 56 |
useEffect(() => { |
| 57 |
setAllPosts([]); |
| 58 |
setCurrentPage(1); |
| 59 |
}, [jsonStringify(ajaxLiveFilter)]); |
| 60 |
|
| 61 |
useEffect(() => { |
| 62 |
// if ('load-more' === paginationType) { |
| 63 |
// return |
| 64 |
// }; |
| 65 |
|
| 66 |
const style = ref?.current?.style; |
| 67 |
if ("load-more" !== paginationType && posts?.length > 0) { |
| 68 |
style.height = `${height}px`; |
| 69 |
|
| 70 |
setTimeout(() => { |
| 71 |
style.height = ``; |
| 72 |
}, 60); |
| 73 |
} |
| 74 |
}, [currentPage, height, allPosts]); |
| 75 |
|
| 76 |
useEffect(() => { |
| 77 |
// if ('load-more' === paginationType) return; |
| 78 |
if ("load-more" !== paginationType && posts?.length > 0) { |
| 79 |
setTimeout(() => { |
| 80 |
setHeight(ref.current?.offsetHeight); |
| 81 |
}, 500); |
| 82 |
} |
| 83 |
}, [allPosts]); |
| 84 |
|
| 85 |
return { |
| 86 |
allPosts: paginationEnable ? allPosts : posts, |
| 87 |
currentPage: currentPage, |
| 88 |
height: height, |
| 89 |
loading: loading, |
| 90 |
setCurrentPage: setCurrentPage, |
| 91 |
}; |
| 92 |
}; |
| 93 |
|