-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinfiniscroll.ts
166 lines (140 loc) · 5.03 KB
/
infiniscroll.ts
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/**
* https://github.com/ronny/infiniscroll
* Copyright (c) 2021 Ronny Haryanto
* MIT License
*
* The majority of this code is based on the work of Elkfox published at
* https://github.com/Elkfox/Ajaxinate. Original copyright:
* Copyright (c) 2017 Elkfox Co Pty Ltd (elkfox.com)
* MIT License
*/
export default InfiniScroll;
export interface InfiniScrollConfig {
/** selector of repeating content, default: '#InfiniScrollItemsContainer' */
itemsContainerSelector: string;
/** selector of pagination container, default: '#InfiniScrollPaginationContainer' */
paginationContainerSelector: string;
/** number of pixels before the bottom to start loading more on scroll, default: 0 */
offset: number;
/** text shown during loading of next page */
loadingText: string;
/** whether to show debugging messages and errors to console, default: false */
debug: boolean;
/** optional logger, defaults to `console` when `debug` is `true`, NullLogger otherwise */
logger?: Logger;
}
interface InfiniScroll {
start(): Promise<void>;
stop(): Promise<void>;
}
export function InfiniScroll(givenConfig?: Readonly<InfiniScrollConfig>): InfiniScroll {
const DefaultConfig: InfiniScrollConfig = {
itemsContainerSelector: '#InfiniScrollItemsContainer',
paginationContainerSelector: '#InfiniScrollPaginationContainer',
offset: 0,
loadingText: 'Loading…',
debug: false,
};
const config: Readonly<InfiniScrollConfig> = {
...DefaultConfig,
...givenConfig,
};
const log = config.debug ? config.logger ?? console : NullLogger();
const itemsContainerEl = document.querySelector(config.itemsContainerSelector);
const paginationContainerEl = document.querySelector(config.paginationContainerSelector);
const domParser = new window.DOMParser();
return {
start,
stop,
};
async function start(): Promise<void> {
if (!itemsContainerEl) {
log.error(`InfiniScroll itemsContainerSelector ${config.itemsContainerSelector} does not match any element`);
return;
}
if (!paginationContainerEl) {
log.error(
`InfiniScroll paginationContainerSelector ${config.paginationContainerSelector} does not match any element`
);
return;
}
addScrollListeners();
}
async function stop(): Promise<void> {
removeScrollListeners();
}
function addScrollListeners(): void {
if (!paginationContainerEl) {
return;
}
document.addEventListener('scroll', checkIfPaginationInView, { passive: true });
window.addEventListener('resize', checkIfPaginationInView, { passive: true });
window.addEventListener('orientationchange', checkIfPaginationInView, { passive: true });
}
function removeScrollListeners(): void {
document.removeEventListener('scroll', checkIfPaginationInView);
window.removeEventListener('resize', checkIfPaginationInView);
window.removeEventListener('orientationchange', checkIfPaginationInView);
}
function checkIfPaginationInView(): void {
if (!paginationContainerEl) {
return;
}
const paginationBoundingClientRect = paginationContainerEl.getBoundingClientRect();
const top = paginationBoundingClientRect.top - config.offset;
const bottom = paginationBoundingClientRect.bottom + config.offset;
const paginationInView = top <= window.innerHeight && bottom >= 0;
if (paginationInView) {
const nextPageLinkElement = paginationContainerEl.querySelector('a');
removeScrollListeners();
if (nextPageLinkElement) {
nextPageLinkElement.innerText = config.loadingText;
loadNextPage(nextPageLinkElement.href);
}
}
}
async function loadNextPage(url: string): Promise<void> {
if (!itemsContainerEl || !paginationContainerEl) {
return;
}
const response = await fetch(url, {
method: 'GET',
credentials: 'same-origin',
keepalive: true,
redirect: 'follow',
headers: {
Accept: 'text/html',
},
});
if (!response.ok) {
log.error('InfiniScroll: loadNextPage: ', response.status, response.statusText);
return;
}
const doc = domParser.parseFromString(await response.text(), 'text/html');
const nextPageItemsContainer = doc.querySelectorAll(config.itemsContainerSelector)[0];
if (!nextPageItemsContainer) {
log.error(
`InfiniScroll: loadNextPage: next page has no items container matching selector ${config.itemsContainerSelector}`
);
return;
}
itemsContainerEl.insertAdjacentHTML('beforeend', nextPageItemsContainer.innerHTML);
const nextPagePaginationContainer = doc.querySelectorAll(config.paginationContainerSelector)[0];
if (!nextPagePaginationContainer) {
paginationContainerEl.innerHTML = '';
removeScrollListeners();
} else {
paginationContainerEl.innerHTML = nextPagePaginationContainer.innerHTML;
start();
}
}
function NullLogger(): Logger {
return {
// eslint-disable-next-line @typescript-eslint/no-empty-function
error() {},
};
}
}
interface Logger {
error(...args: unknown[]): void;
}