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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
|
/* eslint-disable max-statements */
import { type FC, Fragment, useRef, useCallback, useId } from 'react';
import { useIntl } from 'react-intl';
import { useIsMounted, useSettings } from '../../../utils/hooks';
import {
Button,
Heading,
type HeadingLevel,
ProgressBar,
Spinner,
List,
ListItem,
} from '../../atoms';
import {
Pagination,
type PaginationProps,
type RenderPaginationItemAriaLabel,
type RenderPaginationLink,
} from '../nav';
import { NoResults } from './no-results';
import styles from './posts-list.module.scss';
import { Summary, type SummaryProps } from './summary';
export type Post = Omit<SummaryProps, 'titleLevel'> & {
/**
* The post id.
*/
id: string | number;
};
export type YearCollection = Record<string, Post[]>;
export type PostsListProps = Pick<PaginationProps, 'siblings'> & {
/**
* The pagination base url.
*/
baseUrl?: string;
/**
* True to display the posts by year. Default: false.
*/
byYear?: boolean;
/**
* Determine if the data is loading.
*/
isLoading?: boolean;
/**
* Load more button handler.
*/
loadMore?: () => void;
/**
* The current page number. Default: 1.
*/
pageNumber?: number;
/**
* The posts data.
*/
posts: Post[];
/**
* Determine if the load more button should be visible.
*/
showLoadMoreBtn?: boolean;
/**
* The posts heading level (hn).
*/
titleLevel?: HeadingLevel;
/**
* The total posts number.
*/
total: number;
};
/**
* Create a collection of posts sorted by year.
*
* @param {Posts[]} data - A collection of posts.
* @returns {YearCollection} The posts sorted by year.
*/
const sortPostsByYear = (data: Post[]): YearCollection => {
const yearCollection: Partial<YearCollection> = {};
data.forEach((post) => {
const postYear = new Date(post.meta.dates.publication)
.getFullYear()
.toString();
yearCollection[postYear] = [...(yearCollection[postYear] ?? []), post];
});
return yearCollection as YearCollection;
};
/**
* PostsList component
*
* Render a list of post summaries.
*/
export const PostsList: FC<PostsListProps> = ({
baseUrl = '',
byYear = false,
isLoading = false,
loadMore,
pageNumber = 1,
posts,
showLoadMoreBtn = false,
siblings,
titleLevel,
total,
}) => {
const intl = useIntl();
const listRef = useRef<HTMLOListElement>(null);
const lastPostRef = useRef<HTMLSpanElement>(null);
const isMounted = useIsMounted(listRef);
const { blog } = useSettings();
const lastPostId = posts.length ? posts[posts.length - 1].id : 0;
const progressBarId = useId();
/**
* Retrieve the list of posts.
*
* @param {Posts[]} allPosts - A collection fo posts.
* @param {HeadingLevel} [headingLevel] - The posts heading level (hn).
* @returns {JSX.Element} The list of posts.
*/
const getList = (
allPosts: Post[],
headingLevel: HeadingLevel = 2
): JSX.Element => (
<List
aria-busy={isLoading}
aria-describedby={progressBarId}
className={styles.list}
hideMarker
isOrdered
ref={listRef}
spacing="md"
>
{allPosts.map(({ id, ...post }) => (
<Fragment key={id}>
<ListItem className={styles.item}>
<Summary {...post} titleLevel={headingLevel} />
</ListItem>
{id === lastPostId && (
<ListItem>
<span ref={lastPostRef} tabIndex={-1} />
</ListItem>
)}
</Fragment>
))}
</List>
);
/**
* Retrieve the list of posts.
*
* @returns {JSX.Element | JSX.Element[]} The posts list.
*/
const getPosts = (): JSX.Element | JSX.Element[] => {
const firstLevel = titleLevel ?? 2;
if (!byYear) return getList(posts, firstLevel);
const postsPerYear = sortPostsByYear(posts);
const years = Object.keys(postsPerYear).reverse();
const nextLevel = (firstLevel + 1) as HeadingLevel;
return years.map((year) => (
<section key={year} className={styles.section}>
<Heading level={firstLevel} className={styles.year}>
{year}
</Heading>
{getList(postsPerYear[year], nextLevel)}
</section>
));
};
const loadedPostsCount =
pageNumber === 1
? posts.length
: pageNumber * blog.postsPerPage + posts.length;
const progressInfo = intl.formatMessage(
{
defaultMessage:
'{articlesCount, plural, =0 {# loaded articles} one {# loaded article} other {# loaded articles}} out of a total of {total}',
description: 'PostsList: loaded articles progress',
id: '9MeLN3',
},
{
articlesCount: loadedPostsCount,
total,
}
);
const loadMoreBody = intl.formatMessage({
defaultMessage: 'Load more articles?',
description: 'PostsList: load more button',
id: 'uaqd5F',
});
const loadingMoreArticles = intl.formatMessage({
defaultMessage: 'Loading more articles...',
description: 'PostsList: loading more articles message',
id: 'xYemkP',
});
/**
* Load more posts handler.
*/
const loadMorePosts = useCallback(() => {
if (lastPostRef.current) {
lastPostRef.current.focus();
}
if (loadMore) loadMore();
}, [loadMore]);
const getProgressBar = () => (
<>
<ProgressBar
aria-label={progressInfo}
className={styles.progress}
current={loadedPostsCount}
id={progressBarId}
isCentered
isLoading={isLoading}
label={progressInfo}
max={total}
/>
{showLoadMoreBtn ? (
<Button
className={styles.btn}
isDisabled={isLoading}
// eslint-disable-next-line react/jsx-no-literals -- Kind allowed.
kind="tertiary"
onClick={loadMorePosts}
>
{loadMoreBody}
</Button>
) : null}
</>
);
const paginationAriaLabel = intl.formatMessage({
defaultMessage: 'Pagination',
description: 'PostsList: pagination accessible name',
id: 'k1aA+G',
});
const renderItemAriaLabel: RenderPaginationItemAriaLabel = useCallback(
({ kind, pageNumber: page, isCurrentPage }) => {
switch (kind) {
case 'backward':
return intl.formatMessage({
defaultMessage: 'Go to previous page',
description: 'PostsList: pagination backward link label',
id: 'PHO94k',
});
case 'forward':
return intl.formatMessage({
defaultMessage: 'Go to next page',
description: 'PostsList: pagination forward link label',
id: 'HaKhih',
});
case 'number':
default:
return isCurrentPage
? intl.formatMessage(
{
defaultMessage: 'Current page, page {number}',
description: 'PostsList: pagination current page label',
id: 'nwDGkZ',
},
{ number: page }
)
: intl.formatMessage(
{
defaultMessage: 'Go to page {number}',
description: 'PostsList: pagination page link label',
id: 'AmHSC4',
},
{ number: page }
);
}
},
[intl]
);
const renderLink: RenderPaginationLink = useCallback(
(page) => `${baseUrl}${page}`,
[baseUrl]
);
const getPagination = () => {
if (total < blog.postsPerPage) return null;
return (
<Pagination
aria-label={paginationAriaLabel}
className={styles.pagination}
current={pageNumber}
renderItemAriaLabel={renderItemAriaLabel}
renderLink={renderLink}
siblings={siblings}
total={Math.round(total / blog.postsPerPage)}
/>
);
};
if (posts.length === 0) return <NoResults />;
return (
<>
{getPosts()}
{isLoading ? <Spinner>{loadingMoreArticles}</Spinner> : null}
{isMounted ? getProgressBar() : getPagination()}
</>
);
};
|