aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/templates/page/page-layout.tsx
blob: 8ea0087cefae1fa4533b75b61ab8cb80979edcb1 (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
/* eslint-disable max-statements */
import Script from 'next/script';
import {
  type FC,
  type HTMLAttributes,
  type ReactNode,
  useRef,
  useCallback,
} from 'react';
import { useIntl } from 'react-intl';
import type { BreadcrumbList } from 'schema-dts';
import { sendComment } from '../../../services/graphql';
import type { SendCommentInput } from '../../../types';
import { useHeadingsTree, useIsMounted } from '../../../utils/hooks';
import { Heading, Sidebar } from '../../atoms';
import {
  PageFooter,
  type PageFooterProps,
  PageHeader,
  type PageHeaderProps,
} from '../../molecules';
import {
  CommentForm,
  CommentsList,
  type CommentsListProps,
  TocWidget,
  Breadcrumbs,
  type BreadcrumbsItem,
  type CommentFormSubmit,
} from '../../organisms';
import styles from './page-layout.module.scss';

export type PageLayoutProps = {
  /**
   * True if the page accepts new comments. Default: false.
   */
  allowComments?: boolean;
  /**
   * Set attributes to the page body.
   */
  bodyAttributes?: HTMLAttributes<HTMLDivElement>;
  /**
   * Set additional classnames to the body wrapper.
   */
  bodyClassName?: string;
  /**
   * The breadcrumb items.
   */
  breadcrumb: BreadcrumbsItem[];
  /**
   * The breadcrumb JSON schema.
   */
  breadcrumbSchema: BreadcrumbList['itemListElement'][];
  /**
   * The main content of the page.
   */
  children: ReactNode;
  /**
   * The page comments
   */
  comments?: CommentsListProps['comments'];
  /**
   * The footer metadata.
   */
  footerMeta?: PageFooterProps['meta'];
  /**
   * The header metadata.
   */
  headerMeta?: PageHeaderProps['meta'];
  /**
   * The page id.
   */
  id?: number;
  /**
   * The page introduction.
   */
  intro?: PageHeaderProps['intro'];
  /**
   * The page title.
   */
  title: PageHeaderProps['title'];
  /**
   * An array of widgets to put in the last sidebar.
   */
  widgets?: ReactNode[];
  /**
   * Show the table of contents. Default: false.
   */
  withToC?: boolean;
};

/**
 * PageLayout component
 *
 * Render the pages layout.
 */
export const PageLayout: FC<PageLayoutProps> = ({
  children,
  allowComments = false,
  bodyAttributes,
  bodyClassName = '',
  breadcrumb,
  breadcrumbSchema,
  comments,
  footerMeta,
  headerMeta,
  id,
  intro,
  title,
  widgets,
  withToC = false,
}) => {
  const intl = useIntl();
  const breadcrumbsLabel = intl.formatMessage({
    defaultMessage: 'Breadcrumb',
    description: 'PageLayout: an accessible name for the breadcrumb nav.',
    id: 'm6a3BD',
  });
  const commentsTitle = intl.formatMessage({
    defaultMessage: 'Comments',
    description: 'PageLayout: comments title',
    id: '+dJU3e',
  });
  const commentFormSectionTitle = intl.formatMessage({
    defaultMessage: 'Leave a comment',
    description: 'PageLayout: comment form title',
    id: 'kzIYoQ',
  });
  const commentFormTitle = intl.formatMessage({
    defaultMessage: 'Comment form',
    description: 'PageLayout: comment form accessible name',
    id: 'l+Jcf6',
  });
  const tocTitle = intl.formatMessage({
    defaultMessage: 'Table of Contents',
    description: 'PageLayout: table of contents title',
    id: 'eys2uX',
  });

  const bodyRef = useRef<HTMLDivElement>(null);
  const isMounted = useIsMounted(bodyRef);
  const headingsTree = useHeadingsTree(bodyRef, { fromLevel: 2 });

  const saveComment: CommentFormSubmit = useCallback(
    async (data) => {
      if (!id) throw new Error('Page id missing. Cannot save comment.');

      const { author, comment: commentBody, email, parentId, website } = data;
      const commentData: SendCommentInput = {
        author,
        authorEmail: email,
        authorUrl: website ?? '',
        clientMutationId: 'comment',
        commentOn: id,
        content: commentBody,
        parent: parentId,
      };
      const { comment, success } = await sendComment(commentData);

      if (success) {
        const successPrefix = intl.formatMessage({
          defaultMessage: 'Thanks, your comment was successfully sent.',
          description: 'PageLayout: comment form success message',
          id: 'B290Ph',
        });
        const successMessage = comment?.approved
          ? intl.formatMessage({
              defaultMessage: 'It has been approved.',
              id: 'g3+Ahv',
              description: 'PageLayout: comment approved.',
            })
          : intl.formatMessage({
              defaultMessage: 'It is now awaiting moderation.',
              id: 'Vmj5cw',
              description: 'PageLayout: comment awaiting moderation',
            });
        return {
          messages: {
            success: `${successPrefix} ${successMessage}`,
          },
          validator: () => success,
        };
      }

      return {
        messages: {
          error: intl.formatMessage({
            defaultMessage: 'An error occurred:',
            description: 'PageLayout: comment form error message',
            id: 'fkcTGp',
          }),
        },
        validator: () => success,
      };
    },
    [id, intl]
  );

  return (
    <>
      <Script
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }}
        id="schema-breadcrumb"
        type="application/ld+json"
      />
      <Breadcrumbs
        aria-label={breadcrumbsLabel}
        className={styles.breadcrumb}
        items={breadcrumb}
      />
      <PageHeader
        className={styles.header}
        intro={intro}
        meta={headerMeta}
        title={title}
      />
      {withToC ? (
        <Sidebar
          aria-label={intl.formatMessage({
            defaultMessage: 'Table of contents sidebar',
            id: 'Q+1GbT',
            description: 'PageLayout: accessible name for ToC sidebar',
          })}
          className={`${styles.sidebar} ${styles['sidebar--first']}`}
        >
          {isMounted && bodyRef.current ? (
            <TocWidget
              heading={<Heading level={3}>{tocTitle}</Heading>}
              tree={headingsTree}
            />
          ) : null}
        </Sidebar>
      ) : null}
      {typeof children === 'string' ? (
        <div
          {...bodyAttributes}
          className={`${styles.body} ${bodyClassName}`}
          dangerouslySetInnerHTML={{ __html: children }}
          ref={bodyRef}
        />
      ) : (
        <div ref={bodyRef} className={`${styles.body} ${bodyClassName}`}>
          {children}
        </div>
      )}
      {footerMeta?.length ? (
        <PageFooter meta={footerMeta} className={styles.footer} />
      ) : null}
      <Sidebar
        aria-label={intl.formatMessage({
          defaultMessage: 'Sidebar',
          id: 'c556Qo',
          description: 'PageLayout: accessible name for the sidebar',
        })}
        className={`${styles.sidebar} ${styles['sidebar--last']}`}
      >
        {widgets}
      </Sidebar>
      {allowComments ? (
        <div className={styles.comments} id="comments">
          <section className={styles.comments__section}>
            <Heading className={styles.comments__title} level={2}>
              {commentsTitle}
            </Heading>
            {comments?.length ? (
              <CommentsList
                comments={comments}
                depth={2}
                onSubmit={saveComment}
              />
            ) : (
              <p className={styles['comments__no-comments']}>
                {intl.formatMessage({
                  defaultMessage: 'No comments.',
                  id: 'sBwfCy',
                  description: 'PageLayout: no comments text',
                })}
              </p>
            )}
          </section>
          <section className={styles.comments__section}>
            <Heading className={styles.comments__title} level={2}>
              {commentFormSectionTitle}
            </Heading>
            <CommentForm
              aria-label={commentFormTitle}
              className={styles.comments__form}
              onSubmit={saveComment}
            />
          </section>
        </div>
      ) : null}
    </>
  );
};