summaryrefslogtreecommitdiffstats
path: root/src/components/PostsList/PostsList.tsx
blob: 3354dd56304de419196cf8d7f462f9e22337c4f0 (plain)
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
import { t } from '@lingui/macro';
import { PostsList as PostsListData } from '@ts/types/blog';
import styles from './PostsList.module.scss';
import PostPreview from '@components/PostPreview/PostPreview';
import { Fragment } from 'react';
import { sortPostsByYear } from '@utils/helpers/sort';

const PostsList = ({
  data,
  showYears,
}: {
  data: PostsListData[];
  showYears: boolean;
}) => {
  const titleLevel = showYears ? 3 : 2;

  const getPostsListByYear = () => {
    const posts = sortPostsByYear(data);
    const years = Object.keys(posts).reverse();

    return years.map((year) => {
      return (
        <section key={year} className={styles.section}>
          {showYears && (
            <h2 className={styles.year}>
              <span className="screen-reader-text">{t`Published in`} </span>
              {year}
            </h2>
          )}
          <ol className={styles.list}>
            {posts[year].map((post) => {
              return (
                <li key={post.id} className={styles.item}>
                  <PostPreview post={post} titleLevel={titleLevel} />
                </li>
              );
            })}
          </ol>
        </section>
      );
    });
  };

  const getPostsList = () => {
    return data.map((page) => {
      if (page.posts.length === 0) {
        return <p key="no-result">{t`No results found.`}</p>;
      } else {
        return (
          <Fragment key={page.pageInfo.endCursor}>
            <ol className={styles.list}>
              {page.posts.map((post) => {
                return (
                  <li key={post.id} className={styles.item}>
                    <PostPreview post={post} titleLevel={titleLevel} />
                  </li>
                );
              })}
            </ol>
          </Fragment>
        );
      }
    });
  };

  return <>{showYears ? getPostsListByYear() : getPostsList()}</>;
};

export default PostsList;