summaryrefslogtreecommitdiffstats
path: root/src/pages/article
diff options
context:
space:
mode:
Diffstat (limited to 'src/pages/article')
-rw-r--r--src/pages/article/[slug].tsx94
1 files changed, 36 insertions, 58 deletions
diff --git a/src/pages/article/[slug].tsx b/src/pages/article/[slug].tsx
index 2878538..c72d48e 100644
--- a/src/pages/article/[slug].tsx
+++ b/src/pages/article/[slug].tsx
@@ -18,6 +18,12 @@ import {
type NextPageWithLayout,
} from '@ts/types/app';
import { loadTranslation, type Messages } from '@utils/helpers/i18n';
+import {
+ getBlogSchema,
+ getSchemaJson,
+ getSinglePageSchema,
+ getWebPageSchema,
+} from '@utils/helpers/schema-org';
import useBreadcrumb from '@utils/hooks/use-breadcrumb';
import usePrism, { type OptionalPrismPlugin } from '@utils/hooks/use-prism';
import useReadingTime from '@utils/hooks/use-reading-time';
@@ -29,7 +35,6 @@ import Script from 'next/script';
import { ParsedUrlQuery } from 'querystring';
import { HTMLAttributes } from 'react';
import { useIntl } from 'react-intl';
-import { Blog, BlogPosting, Graph, WebPage } from 'schema-dts';
import useSWR from 'swr';
type ArticlePageProps = {
@@ -108,64 +113,35 @@ const ArticlePage: NextPageWithLayout<ArticlePageProps> = ({
const { website } = useSettings();
const { asPath } = useRouter();
- const pageUrl = `${website.url}${asPath}`;
- const pagePublicationDate = new Date(dates.publication);
- const pageUpdateDate = dates.update ? new Date(dates.update) : undefined;
-
- const webpageSchema: WebPage = {
- '@id': `${pageUrl}`,
- '@type': 'WebPage',
- breadcrumb: { '@id': `${website.url}/#breadcrumb` },
- lastReviewed: dates.update,
- name: seo.title,
- description: seo.description,
- reviewedBy: { '@id': `${website.url}/#branding` },
- url: `${pageUrl}`,
- isPartOf: {
- '@id': `${website.url}`,
- },
- };
-
- const blogSchema: Blog = {
- '@id': `${website.url}/#blog`,
- '@type': 'Blog',
- blogPost: { '@id': `${website.url}/#article` },
- isPartOf: {
- '@id': `${pageUrl}`,
- },
- license: 'https://creativecommons.org/licenses/by-sa/4.0/deed.fr',
- };
-
- const blogPostSchema: BlogPosting = {
- '@id': `${website.url}/#article`,
- '@type': 'BlogPosting',
- name: title,
+ const webpageSchema = getWebPageSchema({
description: intro,
- articleBody: content,
- author: { '@id': `${website.url}/#branding` },
- commentCount: commentsCount,
- copyrightYear: pagePublicationDate.getFullYear(),
- creator: { '@id': `${website.url}/#branding` },
- dateCreated: pagePublicationDate.toISOString(),
- dateModified: pageUpdateDate && pageUpdateDate.toISOString(),
- datePublished: pagePublicationDate.toISOString(),
- discussionUrl: `${pageUrl}/#comments`,
- editor: { '@id': `${website.url}/#branding` },
- headline: title,
- image: cover?.src,
- inLanguage: website.locales.default,
- isPartOf: {
- '@id': `${website.url}/blog`,
- },
- license: 'https://creativecommons.org/licenses/by-sa/4.0/deed.fr',
- mainEntityOfPage: { '@id': `${pageUrl}` },
- thumbnailUrl: cover?.src,
- };
-
- const schemaJsonLd: Graph = {
- '@context': 'https://schema.org',
- '@graph': [webpageSchema, blogSchema, blogPostSchema],
- };
+ locale: website.locales.default,
+ slug: asPath,
+ title,
+ updateDate: dates.update,
+ });
+ const blogSchema = getBlogSchema({
+ isSinglePage: true,
+ locale: website.locales.default,
+ slug: asPath,
+ });
+ const blogPostSchema = getSinglePageSchema({
+ commentsCount,
+ content,
+ cover: cover?.src,
+ dates,
+ description: intro,
+ id: 'article',
+ kind: 'post',
+ locale: website.locales.default,
+ slug: asPath,
+ title,
+ });
+ const schemaJsonLd = getSchemaJson([
+ webpageSchema,
+ blogSchema,
+ blogPostSchema,
+ ]);
const prismPlugins: OptionalPrismPlugin[] = ['command-line', 'line-numbers'];
const { attributes, className } = usePrism({ plugins: prismPlugins });
@@ -202,6 +178,8 @@ const ArticlePage: NextPageWithLayout<ArticlePageProps> = ({
prismClassNameReplacer
);
+ const pageUrl = `${website.url}${asPath}`;
+
return (
<>
<Head>
l { 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 Fieldset, {
  type FieldsetProps,
} from '@components/molecules/forms/fieldset';
import useStateChange from '@utils/hooks/use-state-change';
import { ChangeEvent, FC, MouseEvent, SetStateAction, useState } from 'react';
import LabelledBooleanField, {
  type LabelledBooleanFieldProps,
} from './labelled-boolean-field';
import styles from './radio-group.module.scss';

export type RadioGroupCallbackProps = {
  choices: {
    new: string;
    prev: string;
  };
  updateChoice: (value: SetStateAction<string>) => void;
};

export type RadioGroupCallback = (props: RadioGroupCallbackProps) => void;

export type RadioGroupOption = Pick<
  LabelledBooleanFieldProps,
  'id' | 'label' | 'name' | 'value'
>;

export type RadioGroupProps = Pick<
  FieldsetProps,
  'bodyClassName' | 'className' | 'legend' | 'legendClassName' | 'Tooltip'
> &
  Pick<LabelledBooleanFieldProps, 'labelPosition' | 'labelSize'> & {
    /**
     * Set additional classnames to the radio group wrapper when kind is toggle.
     */
    groupClassName?: string;
    /**
     * The default option value.
     */
    initialChoice: string;
    /**
     * The radio group kind. Default: regular.
     */
    kind?: 'regular' | 'toggle';
    /**
     * The legend position. Default: inline.
     */
    legendPosition?: FieldsetProps['legendPosition'];
    /**
     * A callback function to execute when choice is changed.
     */
    onChange?: RadioGroupCallback;
    /**
     * A callback function to execute when clicking on a choice.
     */
    onClick?: RadioGroupCallback;
    /**
     * Set additional classnames to the labelled field wrapper.
     */
    optionClassName?: string;
    /**
     * The options.
     */
    options: RadioGroupOption[];
  };

/**
 * RadioGroup component
 *
 * Render a group of labelled radio buttons.
 */
const RadioGroup: FC<RadioGroupProps> = ({
  className,
  groupClassName = '',
  initialChoice,
  kind = 'regular',
  labelPosition,
  labelSize,
  legendPosition = 'inline',
  onChange,
  optionClassName = '',
  options,
  ...props
}) => {
  const [selectedChoice, setSelectedChoice] =
    useStateChange<string>(initialChoice);
  const isToggle = kind === 'toggle';
  const alignmentModifier = `wrapper--${legendPosition}`;
  const toggleModifier = isToggle ? 'wrapper--toggle' : 'wrapper--regular';

  /**
   * Update the selected choice on click or change event.
   */
  const updateChoice = (
    e:
      | ChangeEvent<HTMLInputElement>
      | MouseEvent<HTMLInputElement, globalThis.MouseEvent>
  ) => {
    const input = e.target as HTMLInputElement;
    onChange &&
      onChange({
        choices: { new: input.value, prev: selectedChoice },
        updateChoice: setSelectedChoice,
      });
    if (e.type === 'change') setSelectedChoice(input.value);
  };

  /**
   * Retrieve an array of radio buttons.
   *
   * @returns {JSX.Element[]} The radio buttons.
   */
  const getOptions = (): JSX.Element[] => {
    return options.map((option) => (
      <LabelledBooleanField
        key={option.id}
        checked={selectedChoice === option.value}
        className={`${styles.option} ${optionClassName}`}
        fieldClassName={styles.radio}
        hidden={isToggle}
        labelClassName={styles.label}
        labelPosition={kind === 'toggle' ? 'right' : labelPosition}
        labelSize={labelSize}
        onChange={updateChoice}
        onClick={updateChoice}
        type="radio"
        {...option}
      />
    ));
  };

  return (
    <Fieldset
      className={`${styles.wrapper} ${styles[alignmentModifier]} ${styles[toggleModifier]} ${className}`}
      legendPosition={legendPosition}
      role="radiogroup"
      {...props}
    >
      {isToggle ? (
        <span className={`${styles.toggle} ${groupClassName}`}>
          {getOptions()}
        </span>
      ) : (
        getOptions()
      )}
    </Fieldset>
  );
};

export default RadioGroup;