aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/templates/page/page-comments.tsx
blob: 01c4eeaf88ef2ff8ef8e52ae2ae6539abf730ec6 (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
import {
  type ForwardRefRenderFunction,
  type HTMLAttributes,
  forwardRef,
  type ReactNode,
  useCallback,
} from 'react';
import { useIntl } from 'react-intl';
import {
  createComment,
  type CreateCommentInput,
} from '../../../services/graphql';
import { COMMENTS_SECTION_ID } from '../../../utils/constants';
import { Heading, Link, Section } from '../../atoms';
import { Card, CardBody } from '../../molecules';
import {
  type CommentData,
  CommentsList,
  type CommentsListProps,
} from '../../organisms/comments-list';
import { CommentForm, type CommentFormSubmit } from '../../organisms/forms';
import styles from './page.module.scss';

const link = (chunks: ReactNode) => (
  // eslint-disable-next-line react/jsx-no-literals
  <Link href="#comment-form-section">{chunks}</Link>
);

export type PageCommentsProps = Omit<
  HTMLAttributes<HTMLDivElement>,
  'children' | 'id' | 'onSubmit'
> &
  Pick<CommentsListProps, 'depth'> & {
    /**
     * Should the comments form be removed from the page?
     *
     * @default false
     */
    areCommentsClosed?: boolean;
    /**
     * The page comments.
     */
    comments: CommentData[];
    /**
     * The database page id.
     */
    pageId: number;
  };

const PageCommentsWithRef: ForwardRefRenderFunction<
  HTMLDivElement,
  PageCommentsProps
> = (
  {
    areCommentsClosed = false,
    className = '',
    comments,
    depth,
    pageId,
    ...props
  },
  ref
) => {
  const wrapperClass = `${styles.comments} ${className}`;
  const commentsCount =
    comments.length +
    comments.reduce(
      (accumulator, currentValue) =>
        accumulator + (currentValue.replies?.length ?? 0),
      0
    );
  const intl = useIntl();
  const commentsListTitle = intl.formatMessage(
    {
      defaultMessage:
        '{commentsCount, plural, =0 {No comments} one {# comment} other {# comments}}',
      description: 'PageComments: the section title of the comments list',
      id: 'H4pKJP',
    },
    { commentsCount }
  );
  const commentFormSectionTitle = intl.formatMessage({
    defaultMessage: 'Leave a comment',
    description: 'PageComments: the section title of the comment form',
    id: 'Y7XdNp',
  });
  const commentFormTitle = intl.formatMessage({
    defaultMessage: 'Comment form',
    description: 'PageComments: an accessible name for the comment form',
    id: 'o+wCJz',
  });
  const noCommentsYet = intl.formatMessage<ReactNode>(
    {
      defaultMessage: 'No comments yet. <link>Be the first!</link>',
      id: 'w+BpPg',
      description: 'PageComments: no comments text',
    },
    {
      link,
    }
  );

  const saveComment: CommentFormSubmit = useCallback(
    async (data) => {
      const commentData: CreateCommentInput = {
        author: data.author,
        authorEmail: data.email,
        authorUrl: data.website ?? '',
        clientMutationId: 'comment',
        commentOn: pageId,
        content: data.comment,
        parent: data.parentId,
      };
      const { comment, success } = await createComment(commentData);
      const successPrefix = intl.formatMessage({
        defaultMessage: 'Thanks, your comment was successfully sent.',
        description: 'PageComments: comment form success message',
        id: 'ZcFroC',
      });
      const successMessage = comment?.approved
        ? intl.formatMessage({
            defaultMessage: 'It has been approved.',
            id: 'UgJwSU',
            description: 'PageComments: comment approved.',
          })
        : intl.formatMessage({
            defaultMessage: 'It is now awaiting moderation.',
            id: '/EfcyW',
            description: 'PageComments: comment awaiting moderation',
          });

      return {
        messages: {
          success: `${successPrefix} ${successMessage}`,
        },
        validator: () => success,
      };
    },
    [intl, pageId]
  );

  return (
    <div {...props} className={wrapperClass} id={COMMENTS_SECTION_ID} ref={ref}>
      <Section className={styles.comments__body}>
        <Heading className={styles.heading} level={2}>
          {commentsListTitle}
        </Heading>
        {comments.length ? (
          <CommentsList
            areRepliesForbidden={areCommentsClosed}
            comments={comments}
            depth={depth}
            onSubmit={saveComment}
          />
        ) : (
          <Card variant={2}>
            <CardBody>{noCommentsYet}</CardBody>
          </Card>
        )}
      </Section>
      {areCommentsClosed ? null : (
        <Section
          className={styles.comments__body}
          // eslint-disable-next-line react/jsx-no-literals
          id="comment-form-section"
        >
          <Heading className={styles.heading} level={2}>
            {commentFormSectionTitle}
          </Heading>
          <CommentForm
            aria-label={commentFormTitle}
            className={styles.form}
            onSubmit={saveComment}
          />
        </Section>
      )}
    </div>
  );
};

export const PageComments = forwardRef(PageCommentsWithRef);