simle-chat

Форк
0
/
AddAndRenameChannel.jsx 
117 строк · 4.5 Кб
1
import { useRef, useEffect } from 'react';
2
import { Modal, Form, Button } from 'react-bootstrap';
3
import { useSelector, useDispatch } from 'react-redux';
4
import { useTranslation } from 'react-i18next';
5
import { toast } from 'react-toastify';
6
import { useFormik } from 'formik';
7
import leoProfanity from 'leo-profanity';
8
import * as yup from 'yup';
9
import axios from 'axios';
10

11
import { getCurrentChannelsNames, getActiveChannelId } from '../../selectors/chatSelectors';
12
import { getChangeableСhannelId, getChangeableСhannelName } from '../../selectors/modalSelectors';
13
import { actions as modalActions } from '../../slices/modalSlice';
14
import { actions as chatActions } from '../../slices/chatSlice';
15
import useAuth from '../../hooks/index';
16
import routes from '../../routes';
17

18
const getValidationSchema = (t, currentChannels) => yup.object({
19
  newChannelName: yup.string().trim()
20
    .min(3, t('validationError.wronglengthName'))
21
    .max(20, t('validationError.wronglengthName'))
22
    .required(t('validationError.requiredField'))
23
    .notOneOf(currentChannels, t('validationError.thisNameExists')),
24
});
25

26
const AddAndRenameChannel = ({ modalType }) => {
27
  const dispatch = useDispatch();
28
  const { t } = useTranslation();
29
  const inputRef = useRef();
30
  const { getAuthHeader } = useAuth();
31

32
  const currentChannelsNames = useSelector(getCurrentChannelsNames);
33
  const activeChannelId = useSelector(getActiveChannelId);
34
  const changeableСhannelId = useSelector(getChangeableСhannelId);
35
  const changeableСhannelName = useSelector(getChangeableСhannelName);
36

37
  const formik = useFormik({
38
    initialValues: { newChannelName: (changeableСhannelName) },
39
    validationSchema: getValidationSchema(t, currentChannelsNames),
40
    onSubmit: async (values) => {
41
      const newChannelName = { name: leoProfanity.clean(values.newChannelName) };
42
      const headers = await getAuthHeader();
43
      const requestPath = (modalType === 'addChannel')
44
        ? routes.dataRequestPath('channels')
45
        : routes.dataRequestPathWithId('channels', changeableСhannelId);
46
      try {
47
        if (modalType === 'addChannel') {
48
          const response = await axios.post(requestPath, newChannelName, { headers });
49
          const { name, id } = response.data;
50
          dispatch(chatActions.setActiveChannel({ name, id }));
51
        }
52
        if (modalType === 'renameChannel') {
53
          const response = await axios.patch(requestPath, newChannelName, { headers });
54
          if (response.data.id === activeChannelId) {
55
            const { name, id } = response.data;
56
            dispatch(chatActions.setActiveChannel({ name, id }));
57
          }
58
        }
59
        dispatch(modalActions.closedModal());
60
        toast.success(t(`toasts.${modalType}.success`));
61
      } catch (error) {
62
        toast.error(t(`toasts.${modalType}.error`));
63
        console.error(error);
64
      }
65
    },
66
  });
67

68
  useEffect(() => {
69
    if (modalType === 'addChannel') inputRef.current.focus();
70
    if (modalType === 'renameChannel') inputRef.current.select();
71
  }, [inputRef, modalType]);
72

73
  return (
74
    <>
75
      <Modal.Header closeButton>
76
        <Modal.Title>{t(`modals.addAndRename.${modalType}`)}</Modal.Title>
77
      </Modal.Header>
78
      <Modal.Body>
79
        <Form onSubmit={formik.handleSubmit}>
80
          <Form.Group controlId="newChannelName">
81
            <Form.Control
82
              ref={inputRef}
83
              onChange={formik.handleChange}
84
              onBlur={formik.handleBlur}
85
              value={formik.values.newChannelName}
86
              name="newChannelName"
87
              isInvalid={formik.touched.newChannelName && formik.errors.newChannelName}
88
              disabled={formik.isSubmitting}
89
            />
90
            <Form.Label className="visually-hidden">{t('modals.addAndRename.inputPlaceholder')}</Form.Label>
91
            <Form.Control.Feedback type="invalid">
92
              {formik.errors.newChannelName}
93
            </Form.Control.Feedback>
94
            <div className="mt-3 d-flex justify-content-end">
95
              <Button
96
                onClick={() => dispatch(modalActions.closedModal())}
97
                variant="secondary"
98
                className="me-2"
99
              >
100
                {t('modals.cancelButton')}
101
              </Button>
102
              {' '}
103
              <Button
104
                type="submit"
105
                variant="primary"
106
              >
107
                {t('modals.addAndRename.button')}
108
              </Button>
109
            </div>
110
          </Form.Group>
111
        </Form>
112
      </Modal.Body>
113
    </>
114
  );
115
};
116

117
export default AddAndRenameChannel;
118

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.