aboutsummaryrefslogtreecommitdiffstats
path: root/src/assets/images/icon-arrow-right.svg
blob: 5ddb0b41431f4091eceec04b2fe049df59add317 (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
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   width="64.644997"
   height="23.476"
   viewBox="0 0 64.644997 23.476001"
   version="1.1"
   id="svg4"
   sodipodi:docname="icon-arrow-right.svg"
   inkscape:version="1.1.1 (3bf5ae0d25, 2021-09-20, custom)"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:svg="http://www.w3.org/2000/svg">
  <defs
     id="defs8" />
  <sodipodi:namedview
     id="namedview6"
     pagecolor="#ffffff"
     bordercolor="#666666"
     borderopacity="1.0"
     inkscape:pageshadow="2"
     inkscape:pageopacity="0.0"
     inkscape:pagecheckerboard="0"
     showgrid="false"
     inkscape:zoom="7.3600763"
     inkscape:cx="11.141189"
     inkscape:cy="23.912796"
     inkscape:window-width="1920"
     inkscape:window-height="1019"
     inkscape:window-x="0"
     inkscape:window-y="33"
     inkscape:window-maximized="1"
     inkscape:current-layer="svg4"
     fit-margin-top="0"
     fit-margin-left="0"
     fit-margin-right="0"
     fit-margin-bottom="0" />
  <path
     d="M -1.6784668e-6,15.441 40.007998,15.423 V 8.0349999 l -40.0079996784668,0.142 z"
     id="path2-6"
     sodipodi:nodetypes="ccccc" />
  <path
     d="M 40.007998,23.476 64.644998,11.715 39.844998,-8.3923343e-8 Z"
     id="path2-3"
     sodipodi:nodetypes="cccc" />
</svg>
' href='#n271'>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 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
/* eslint-disable max-statements */
import type { ParsedUrlQuery } from 'querystring';
import type { GetStaticPaths, GetStaticProps } from 'next';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { type FC, useCallback } from 'react';
import { useIntl } from 'react-intl';
import {
  getLayout,
  Heading,
  LinksWidget,
  PostsList,
  Pagination,
  type RenderPaginationLink,
  type RenderPaginationItemAriaLabel,
  Page,
  PageHeader,
  PageBody,
  PageSidebar,
  Spinner,
  Notice,
  LoadingPage,
} from '../../../components';
import {
  convertWPThematicPreviewToPageLink,
  convertWPTopicPreviewToPageLink,
  fetchLastPostCursor,
  fetchPostsCount,
  fetchPostsList,
  fetchThematicsCount,
  fetchThematicsList,
  fetchTopicsCount,
  fetchTopicsList,
} from '../../../services/graphql';
import styles from '../../../styles/pages/blog.module.scss';
import type {
  GraphQLConnection,
  Maybe,
  NextPageWithLayout,
  Nullable,
  WPPostPreview,
  WPThematicPreview,
  WPTopicPreview,
} from '../../../types';
import { CONFIG } from '../../../utils/config';
import {
  ARTICLE_ID,
  PAGINATED_ROUTE_PREFIX,
  ROUTES,
} from '../../../utils/constants';
import {
  getBlogGraph,
  getLinksItemData,
  getPostsWithUrl,
  getSchemaFrom,
  getWebPageGraph,
} from '../../../utils/helpers';
import { loadTranslation, type Messages } from '../../../utils/helpers/server';
import {
  useArticlesList,
  useBreadcrumbs,
  useRedirection,
  useThematicsList,
  useTopicsList,
} from '../../../utils/hooks';

const renderPaginationLink: RenderPaginationLink = (pageNum) =>
  `${ROUTES.BLOG}${PAGINATED_ROUTE_PREFIX}/${pageNum}`;

type BlogPageProps = {
  data: {
    posts: GraphQLConnection<WPPostPreview>;
    thematics: GraphQLConnection<WPThematicPreview>;
    topics: GraphQLConnection<WPTopicPreview>;
  };
  lastCursor: Maybe<Nullable<string>>;
  pageNumber: number;
  translation: Messages;
};

const Blog: FC<Pick<BlogPageProps, 'data' | 'lastCursor' | 'pageNumber'>> = ({
  data,
  lastCursor,
  pageNumber,
}) => {
  const intl = useIntl();
  const {
    articles,
    error,
    firstNewResultIndex,
    isLoading,
    isLoadingMore,
    isRefreshing,
    hasNextPage,
    loadMore,
  } = useArticlesList({
    after: lastCursor,
    fallback: [data.posts],
    perPage: CONFIG.postsPerPage,
  });
  const { isLoading: areThematicsLoading, thematics } = useThematicsList({
    fallback: data.thematics,
    input: { first: data.thematics.pageInfo.total },
  });
  const { isLoading: areTopicsLoading, topics } = useTopicsList({
    fallback: data.topics,
    input: { first: data.topics.pageInfo.total },
  });

  const messages = {
    loading: {
      thematicsList: intl.formatMessage({
        defaultMessage: 'Thematics are loading...',
        description: 'BlogPage: loading thematics message',
        id: 'y37FuH',
      }),
      topicsList: intl.formatMessage({
        defaultMessage: 'Topics are loading...',
        description: 'BlogPage: loading topics message',
        id: 'OsclKU',
      }),
    },
    pageTitle: intl.formatMessage(
      {
        defaultMessage: 'Blog - Page {number}',
        description: 'BlogPage: page title with number',
        id: '8xVO3Y',
      },
      {
        number: pageNumber,
      }
    ),
    pagination: {
      noJS: intl.formatMessage({
        defaultMessage:
          "You can't load more articles without Javascript, please use the pagination instead.",
        description: 'BlogPage: pagination no script message',
        id: 'ZMES/E',
      }),
      title: intl.formatMessage({
        defaultMessage: 'Pagination',
        description: 'BlogPage: pagination accessible name',
        id: 'AXe1Iz',
      }),
    },
    seo: {
      metaDesc: intl.formatMessage(
        {
          defaultMessage:
            "Discover {websiteName}'s writings. He talks about web development, Linux and open source mostly.",
          description: 'BlogPage: SEO - Meta description',
          id: '18h/t0',
        },
        { websiteName: CONFIG.name }
      ),
      title: intl.formatMessage(
        {
          defaultMessage:
            'Blog: development, open source - Page {number} - {websiteName}',
          description: 'BlogPage: SEO - Page title',
          id: 'dG3sT3',
        },
        { number: pageNumber, websiteName: CONFIG.name }
      ),
    },
    widgets: {
      thematicsListTitle: intl.formatMessage({
        defaultMessage: 'Thematics',
        description: 'BlogPage: thematics list widget title',
        id: 'HriY57',
      }),
      topicsListTitle: intl.formatMessage({
        defaultMessage: 'Topics',
        description: 'BlogPage: topics list widget title',
        id: '2D9tB5',
      }),
    },
  };

  const { items: breadcrumbItems, schema: breadcrumbSchema } = useBreadcrumbs(
    messages.pageTitle
  );

  const jsonLd = getSchemaFrom([
    getWebPageGraph({
      breadcrumb: breadcrumbSchema,
      description: messages.seo.metaDesc,
      slug: ROUTES.BLOG,
      title: messages.pageTitle,
    }),
    getBlogGraph({
      description: '',
      posts: articles?.flatMap((page) =>
        page.edges.map(({ node }) => {
          return { '@id': `${node.slug}#${ARTICLE_ID}` };
        })
      ),
      slug: ROUTES.BLOG,
      title: messages.pageTitle,
    }),
  ]);

  const renderPaginationLabel: RenderPaginationItemAriaLabel = useCallback(
    ({ kind, pageNumber: number, isCurrentPage }) => {
      switch (kind) {
        case 'backward':
          return intl.formatMessage(
            {
              defaultMessage: 'Go to previous page, page {number}',
              description: 'BlogPage: previous page label',
              id: 'faO6BQ',
            },
            { number }
          );
        case 'forward':
          return intl.formatMessage(
            {
              defaultMessage: 'Go to next page, page {number}',
              description: 'BlogPage: next page label',
              id: 'oq3BzP',
            },
            { number }
          );
        case 'number':
        default:
          return isCurrentPage
            ? intl.formatMessage(
                {
                  defaultMessage: 'Current page, page {number}',
                  description: 'BlogPage: current page label',
                  id: 'JL6G22',
                },
                { number }
              )
            : intl.formatMessage(
                {
                  defaultMessage: 'Go to page {number}',
                  description: 'BlogPage: page number label',
                  id: 'IVczxR',
                },
                { number }
              );
      }
    },
    [intl]
  );

  const pageUrl = `${CONFIG.url}${ROUTES.BLOG}`;

  return (
    <Page breadcrumbs={breadcrumbItems} isBodyLastChild>
      <Head>
        <title>{messages.seo.title}</title>
        {/*eslint-disable-next-line react/jsx-no-literals -- Name allowed */}
        <meta name="description" content={messages.seo.metaDesc} />
        <meta property="og:url" content={pageUrl} />
        {/*eslint-disable-next-line react/jsx-no-literals -- Content allowed */}
        <meta property="og:type" content="website" />
        <meta property="og:title" content={messages.pageTitle} />
        <meta property="og:description" content={messages.seo.metaDesc} />
        <script
          // eslint-disable-next-line react/no-danger
          dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
          type="application/ld+json"
        />
      </Head>
      <PageHeader
        heading={messages.pageTitle}
        meta={{ total: data.posts.pageInfo.total }}
      />
      <PageBody>
        {articles ? (
          <PostsList
            className={styles['posts-list']}
            firstNewResult={firstNewResultIndex}
            isLoading={isLoading || isLoadingMore || isRefreshing}
            onLoadMore={hasNextPage ? loadMore : undefined}
            posts={getPostsWithUrl(
              articles.flatMap((page) => page.edges.map((edge) => edge.node))
            )}
            sortByYear
            total={data.posts.pageInfo.total}
          />
        ) : null}
        {error ? (
          <Notice
            // eslint-disable-next-line react/jsx-no-literals -- Kind allowed
            kind="error"
          >
            {intl.formatMessage({
              defaultMessage: 'Failed to load.',
              description: 'BlogPage: failed to load text',
              id: 'C/XGkH',
            })}
          </Notice>
        ) : null}
        <noscript>
          <Notice
            // eslint-disable-next-line react/jsx-no-literals
            kind="info"
          >
            {messages.pagination.noJS}
          </Notice>
          <Pagination
            aria-label={messages.pagination.title}
            className={styles.pagination}
            current={pageNumber}
            isCentered
            renderItemAriaLabel={renderPaginationLabel}
            renderLink={renderPaginationLink}
            total={data.posts.pageInfo.total}
          />
        </noscript>
      </PageBody>
      <PageSidebar>
        {areThematicsLoading ? (
          <Spinner>{messages.loading.thematicsList}</Spinner>
        ) : (
          <LinksWidget
            heading={
              <Heading level={2}>{messages.widgets.thematicsListTitle}</Heading>
            }
            items={getLinksItemData(
              thematics.edges.map((edge) =>
                convertWPThematicPreviewToPageLink(edge.node)
              )
            )}
          />
        )}
        {areTopicsLoading ? (
          <Spinner>{messages.loading.topicsList}</Spinner>
        ) : (
          <LinksWidget
            heading={
              <Heading level={2}>{messages.widgets.topicsListTitle}</Heading>
            }
            items={getLinksItemData(
              topics.edges.map((edge) =>
                convertWPTopicPreviewToPageLink(edge.node)
              )
            )}
          />
        )}
      </PageSidebar>
    </Page>
  );
};

/**
 * Blog index page.
 */
const BlogPage: NextPageWithLayout<BlogPageProps> = ({
  data,
  lastCursor,
  pageNumber,
}) => {
  useRedirection({
    isReplacing: true,
    to: ROUTES.BLOG,
    whenPathMatches: (path) =>
      path === `${ROUTES.BLOG}${PAGINATED_ROUTE_PREFIX}/1`,
  });

  const { isFallback } = useRouter();

  return isFallback ? (
    <LoadingPage />
  ) : (
    <Blog data={data} lastCursor={lastCursor} pageNumber={pageNumber} />
  );
};

BlogPage.getLayout = (page) => getLayout(page);

type BlogPageParams = {
  number: string;
} & ParsedUrlQuery;

export const getStaticProps: GetStaticProps<BlogPageProps> = async ({
  locale,
  params,
}) => {
  const pageNumber = Number((params as BlogPageParams).number);

  if (pageNumber === 1)
    return {
      redirect: {
        destination: ROUTES.BLOG,
        permanent: true,
      },
    };

  const lastCursor =
    pageNumber > 1
      ? await fetchLastPostCursor(CONFIG.postsPerPage * (pageNumber - 1))
      : null;
  const posts = await fetchPostsList({
    first: CONFIG.postsPerPage,
    after: lastCursor,
  });
  const totalThematics = await fetchThematicsCount();
  const thematics = await fetchThematicsList({ first: totalThematics });
  const totalTopics = await fetchTopicsCount();
  const topics = await fetchTopicsList({ first: totalTopics });
  const translation = await loadTranslation(locale);

  return {
    props: {
      data: {
        posts: JSON.parse(JSON.stringify(posts)),
        thematics,
        topics,
      },
      lastCursor,
      pageNumber,
      translation,
    },
  };
};

export const getStaticPaths: GetStaticPaths = async () => {
  const totalArticles = await fetchPostsCount();
  const totalPages = Math.ceil(totalArticles / CONFIG.postsPerPage);
  const pagesArray = Array.from(
    { length: totalPages },
    (_, index) => index + 1
  );
  // We remove /blog/page/1 since it is redirected to /blog
  const paths = pagesArray.slice(1).map((number) => {
    return { params: { number: `${number}` } };
  });

  return {
    paths,
    fallback: true,
  };
};

export default BlogPage;