summaryrefslogtreecommitdiffstats
path: root/src/components/atoms/headings/heading.test.tsx
blob: 6b6789a48e6ad70c0868861cf051706442a012d0 (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
import { render, screen } from '@test-utils';
import Heading from './heading';

describe('Heading', () => {
  it('renders a h1', () => {
    render(<Heading level={1}>Level 1</Heading>);
    expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(
      'Level 1'
    );
  });

  it('renders a h2', () => {
    render(<Heading level={2}>Level 2</Heading>);
    expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent(
      'Level 2'
    );
  });

  it('renders a h3', () => {
    render(<Heading level={3}>Level 3</Heading>);
    expect(screen.getByRole('heading', { level: 3 })).toHaveTextContent(
      'Level 3'
    );
  });

  it('renders a h4', () => {
    render(<Heading level={4}>Level 4</Heading>);
    expect(screen.getByRole('heading', { level: 4 })).toHaveTextContent(
      'Level 4'
    );
  });

  it('renders a h5', () => {
    render(<Heading level={5}>Level 5</Heading>);
    expect(screen.getByRole('heading', { level: 5 })).toHaveTextContent(
      'Level 5'
    );
  });

  it('renders a h6', () => {
    render(<Heading level={6}>Level 6</Heading>);
    expect(screen.getByRole('heading', { level: 6 })).toHaveTextContent(
      'Level 6'
    );
  });

  it('renders a text with heading styles', () => {
    render(
      <Heading isFake={true} level={2}>
        Fake heading
      </Heading>
    );
    expect(screen.queryByRole('heading', { level: 2 })).not.toBeInTheDocument();
    expect(screen.getByText('Fake heading')).toHaveClass('heading');
  });
});
t .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
import Link from '@components/atoms/links/link';
import SocialLink, {
  type SocialWebsite,
} from '@components/atoms/links/social-link';
import Spinner from '@components/atoms/loaders/spinner';
import ResponsiveImage from '@components/molecules/images/responsive-image';
import Code from '@components/molecules/layout/code';
import Gallery from '@components/organisms/images/gallery';
import Overview, {
  type OverviewMeta,
} from '@components/organisms/layout/overview';
import Sharing from '@components/organisms/widgets/sharing';
import { getLayout } from '@components/templates/layout/layout';
import PageLayout, {
  type PageLayoutProps,
} from '@components/templates/page/page-layout';
import styles from '@styles/pages/project.module.scss';
import {
  type NextPageWithLayout,
  type ProjectPreview,
  type Repos,
} from '@ts/types/app';
import { loadTranslation, type Messages } from '@utils/helpers/i18n';
import { getProjectData, getProjectFilenames } from '@utils/helpers/projects';
import {
  getSchemaJson,
  getSinglePageSchema,
  getWebPageSchema,
} from '@utils/helpers/schema-org';
import { capitalize } from '@utils/helpers/strings';
import useBreadcrumb from '@utils/hooks/use-breadcrumb';
import useGithubApi, { type RepoData } from '@utils/hooks/use-github-api';
import useSettings from '@utils/hooks/use-settings';
import { MDXComponents, NestedMDXComponents } from 'mdx/types';
import { GetStaticPaths, GetStaticProps } from 'next';
import Head from 'next/head';
import { useRouter } from 'next/router';
import Script from 'next/script';
import { ComponentType } from 'react';
import { useIntl } from 'react-intl';

type ProjectPageProps = {
  project: ProjectPreview;
  translation: Messages;
};

/**
 * Project page.
 */
const ProjectPage: NextPageWithLayout<ProjectPageProps> = ({ project }) => {
  const { id, intro, meta, title } = project;
  const { cover, dates, license, repos, seo, technologies } = meta;
  const intl = useIntl();
  const { items: breadcrumbItems, schema: breadcrumbSchema } = useBreadcrumb({
    title,
    url: `/projets/${id}`,
  });

  const ProjectContent: ComponentType<MDXComponents> =
    require(`../../content/projects/${id}.mdx`).default;

  const components: NestedMDXComponents = {
    Code: (props) => <Code {...props} />,
    Gallery: (props) => <Gallery {...props} />,
    Image: (props) => <ResponsiveImage withBorders={true} {...props} />,
    Link: (props) => <Link {...props} />,
    pre: ({ children }) => <Code {...children.props} />,
  };

  const { website } = useSettings();
  const { asPath } = useRouter();
  const pageUrl = `${website.url}${asPath}`;

  const headerMeta: PageLayoutProps['headerMeta'] = {
    publication: { date: dates.publication },
    update:
      dates.update && dates.update !== dates.publication
        ? { date: dates.update }
        : undefined,
  };

  /**
   * Retrieve the repositories links.
   *
   * @param {Repos} repos - A repositories object.
   * @returns {JSX.Element[]} - An array of SocialLink.
   */
  const getReposLinks = (repositories: Repos): JSX.Element[] => {
    const links = [];

    for (const [name, url] of Object.entries(repositories)) {
      const socialWebsite = capitalize(name) as SocialWebsite;
      const socialUrl = `https://${name}.com/${url}`;

      links.push(<SocialLink name={socialWebsite} url={socialUrl} />);
    }

    return links;
  };

  const { isError, isLoading, data } = useGithubApi(meta.repos!.github!);

  const getGithubData = (key: keyof RepoData) => {
    if (isError) return 'Error';
    if (isLoading || !data) return <Spinner />;

    switch (key) {
      case 'created_at':
        return data.created_at;
      case 'updated_at':
        return data.updated_at;
      case 'stargazers_count':
        const stars = intl.formatMessage(
          {
            defaultMessage:
              '{starsCount, plural, =0 {No stars on Github} one {# star on Github} other {# stars on Github}}',
            id: 'Gnf1Si',
            description: 'Projets: Github stars count',
          },
          { starsCount: data.stargazers_count }
        );
        return (
          <>
            ⭐&nbsp;
            <Link href={`https://github.com/${repos!.github}/stargazers`}>
              {stars}
            </Link>
          </>
        );
    }
  };

  const overviewData: OverviewMeta = {
    creation: data && { date: getGithubData('created_at') as string },
    update: data && { date: getGithubData('updated_at') as string },
    license,
    popularity: data && getGithubData('stargazers_count'),
    repositories: repos ? getReposLinks(repos) : undefined,
    technologies,
  };

  const webpageSchema = getWebPageSchema({
    description: seo.description,
    locale: website.locales.default,
    slug: asPath,
    title: seo.title,
    updateDate: dates.update,
  });
  const articleSchema = getSinglePageSchema({
    cover: `/projects/${id}.jpg`,
    dates,
    description: intro,
    id: 'project',
    kind: 'page',
    locale: website.locales.default,
    slug: asPath,
    title,
  });
  const schemaJsonLd = getSchemaJson([webpageSchema, articleSchema]);

  return (
    <>
      <Head>
        <title>{`${seo.title} - ${website.name}`}</title>
        <meta name="description" content={seo.description} />
        <meta property="og:url" content={`${pageUrl}`} />
        <meta property="og:type" content="article" />
        <meta property="og:title" content={title} />
        <meta property="og:description" content={intro} />
      </Head>
      <Script
        id="schema-project"
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaJsonLd) }}
      />
      <PageLayout
        title={title}
        intro={intro}
        breadcrumb={breadcrumbItems}
        breadcrumbSchema={breadcrumbSchema}
        headerMeta={headerMeta}
        withToC={true}
        widgets={[
          <Sharing
            key="sharing-widget"
            data={{ excerpt: intro, title, url: pageUrl }}
            media={[
              'diaspora',
              'email',
              'facebook',
              'journal-du-hacker',
              'linkedin',
              'twitter',
            ]}
            className={styles.widget}
          />,
        ]}
      >
        <Overview cover={cover} meta={overviewData} />
        <ProjectContent components={components} />
      </PageLayout>
    </>
  );
};

ProjectPage.getLayout = (page) =>
  getLayout(page, { useGrid: true, withExtraPadding: true });

export const getStaticProps: GetStaticProps<ProjectPageProps> = async ({
  locale,
  params,
}) => {
  const translation = await loadTranslation(locale);
  const { slug } = params!;
  const project = await getProjectData(slug as string);

  return {
    props: {
      project,
      translation,
    },
  };
};

export const getStaticPaths: GetStaticPaths = async () => {
  const filenames = getProjectFilenames();
  const paths = filenames.map((filename) => {
    return {
      params: {
        slug: filename,
      },
    };
  });

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

export default ProjectPage;