aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/molecules/forms/labelled-field.tsx
blob: 6a00a3e2e21b16e069bb9454ad785f349bba52f3 (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
import Field, { type FieldProps } from '@components/atoms/forms/field';
import Label from '@components/atoms/forms/label';
import { forwardRef, ForwardRefRenderFunction } from 'react';
import styles from './labelled-field.module.scss';

export type LabelledFieldProps = FieldProps & {
  /**
   * Visually hide the field label. Default: false.
   */
  hideLabel?: boolean;
  /**
   * The field label.
   */
  label: string;
  /**
   * The label position. Default: top.
   */
  labelPosition?: 'left' | 'top';
};

/**
 * LabelledField component
 *
 * Render a field tied to a label.
 */
const LabelledField: ForwardRefRenderFunction<
  HTMLInputElement,
  LabelledFieldProps
> = (
  { hideLabel = false, id, label, labelPosition = 'top', required, ...props },
  ref
) => {
  const positionModifier = `label--${labelPosition}`;
  const visibilityClass = hideLabel ? 'screen-reader-text' : '';

  return (
    <>
      <Label
        htmlFor={id}
        required={required}
        className={`${visibilityClass} ${styles[positionModifier]}`}
      >
        {label}
      </Label>
      <Field id={id} ref={ref} required={required} {...props} />
    </>
  );
};

export default forwardRef(LabelledField);
{ 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 Notice, { type NoticeKind } from '@components/atoms/layout/notice';
import ContactForm, {
  type ContactFormProps,
} from '@components/organisms/forms/contact-form';
import SocialMedia from '@components/organisms/widgets/social-media';
import { getLayout } from '@components/templates/layout/layout';
import PageLayout from '@components/templates/page/page-layout';
import { meta } from '@content/pages/contact.mdx';
import { sendMail } from '@services/graphql/contact';
import styles from '@styles/pages/contact.module.scss';
import { type NextPageWithLayout } from '@ts/types/app';
import { loadTranslation } from '@utils/helpers/i18n';
import {
  getSchemaJson,
  getSinglePageSchema,
  getWebPageSchema,
} from '@utils/helpers/schema-org';
import useBreadcrumb from '@utils/hooks/use-breadcrumb';
import useSettings from '@utils/hooks/use-settings';
import { GetStaticProps } from 'next';
import Head from 'next/head';
import { useRouter } from 'next/router';
import Script from 'next/script';
import { useState } from 'react';
import { useIntl } from 'react-intl';

const ContactPage: NextPageWithLayout = () => {
  const { dates, intro, seo, title } = meta;
  const intl = useIntl();
  const { items: breadcrumbItems, schema: breadcrumbSchema } = useBreadcrumb({
    title,
    url: `/contact`,
  });

  const socialMediaTitle = intl.formatMessage({
    defaultMessage: 'Find me elsewhere',
    description: 'ContactPage: social media widget title',
    id: 'Qh2CwH',
  });

  const { website } = useSettings();
  const { asPath } = useRouter();
  const webpageSchema = getWebPageSchema({
    description: seo.description,
    locale: website.locales.default,
    slug: asPath,
    title: seo.title,
    updateDate: dates.update,
  });
  const contactSchema = getSinglePageSchema({
    dates,
    description: intro,
    id: 'contact',
    kind: 'contact',
    locale: website.locales.default,
    slug: asPath,
    title,
  });
  const schemaJsonLd = getSchemaJson([webpageSchema, contactSchema]);

  const widgets = [
    <SocialMedia
      key="social-media"
      title={socialMediaTitle}
      level={2}
      media={[
        { name: 'Github', url: 'https://github.com/ArmandPhilippot' },
        { name: 'Gitlab', url: 'https://gitlab.com/ArmandPhilippot' },
        {
          name: 'LinkedIn',
          url: 'https://www.linkedin.com/in/armandphilippot',
        },
      ]}
    />,
  ];

  const [status, setStatus] = useState<NoticeKind>('info');
  const [statusMessage, setStatusMessage] = useState<string>('');

  const submitMail: ContactFormProps['sendMail'] = async (data, reset) => {
    const { email, message, name, subject } = data;
    const messageHTML = message.replace(/\r?\n/g, '<br />');
    const body = `Message received from ${name} <${email}> on ${website.url}.<br /><br />${messageHTML}`;
    const replyTo = `${name} <${email}>`;
    const mailData = {
      body,
      clientMutationId: 'contact',
      replyTo,
      subject,
    };
    const { message: mutationMessage, sent } = await sendMail(mailData);

    if (sent) {
      setStatus('success');
      setStatusMessage(
        intl.formatMessage({
          defaultMessage:
            'Thanks. Your message was successfully sent. I will answer it as soon as possible.',
          description: 'Contact: success message',
          id: '3Pipok',
        })
      );
      reset();
    } else {
      const errorPrefix = intl.formatMessage({
        defaultMessage: 'An error occurred:',
        description: 'Contact: error message',
        id: 'TpyFZ6',
      });
      const error = `${errorPrefix} ${mutationMessage}`;
      setStatus('error');
      setStatusMessage(error);
    }
  };

  return (
    <>
      <Head>
        <title>{`${seo.title} - ${website.name}`}</title>
        <meta name="description" content={seo.description} />
        <meta property="og:url" content={`${website.url}${asPath}`} />
        <meta property="og:type" content="article" />
        <meta property="og:title" content={title} />
        <meta property="og:description" content={intro} />
      </Head>
      <Script
        id="schema-contact"
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaJsonLd) }}
      />
      <PageLayout
        breadcrumb={breadcrumbItems}
        breadcrumbSchema={breadcrumbSchema}
        intro={intro}
        title="Contact"
        widgets={widgets}
      >
        <ContactForm
          sendMail={submitMail}
          Notice={
            <Notice
              kind={status}
              message={statusMessage}
              className={styles.notice}
            />
          }
        />
      </PageLayout>
    </>
  );
};

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

export const getStaticProps: GetStaticProps = async ({ locale }) => {
  const translation = await loadTranslation(locale);

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

export default ContactPage;