comment_field.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import { url } from "../../App";
  2. import './style.scss'
  3. import {
  4. IconButton,
  5. Typography,
  6. Box,
  7. TextField,
  8. Popover
  9. } from '@mui/material'
  10. import {
  11. SentimentSatisfiedAlt
  12. } from '@mui/icons-material/'
  13. import EmojiPicker from 'emoji-picker-react';
  14. import { useState } from "react";
  15. import { useDispatch, useSelector } from "react-redux";
  16. import { actionFullAddComment } from "../redux/thunks";
  17. import { useParams } from "react-router-dom";
  18. import { CommentContext } from "./comments";
  19. import { useContext } from "react";
  20. function CommentField() {
  21. // console.log('id: ', id)
  22. const { postId } = useParams()
  23. const dispatch = useDispatch()
  24. // контекст для изменения поля добавления комментария
  25. const [comment, setComment] = useContext(CommentContext)
  26. // открытие поповера emoji
  27. const [openPopover, setOpenPopover] = useState(null);
  28. const openEmoji = (event) => {
  29. setOpenPopover(event.currentTarget);
  30. }
  31. const closeEmoji = () => {
  32. setOpenPopover(null);
  33. }
  34. const open = Boolean(openPopover);
  35. const emojiField = open ? 'simple-popover' : undefined;
  36. // отслеживаем все комментарии в реальном времени для проверки имени пользователя в поле комментария при ответе на комментарий
  37. const allComments = useSelector(state => state?.promise?.FindComments?.payload)
  38. // запрос на создание комментария
  39. function uploadComment() {
  40. // проверка на то, осталось ли в поле вводе комментария логин пользователя, которому нужно ответить. если нет, тогда удаляем из объекта ключ answerTo и диспатчим запрос с именем CreateComment, потому что это уже коммент к посту
  41. const idToFind = comment?.answerTo?._id
  42. const findLogin = allComments.find(user => user?._id === idToFind)
  43. let isInclude
  44. (comment.text).includes(findLogin?.owner?.login) && (isInclude = true)
  45. // удаляем ключ answerTo, если нет в строке ввода комментария логина
  46. if (!isInclude) {
  47. delete comment.answerTo
  48. }
  49. // определяем, какое имя дать запросу
  50. let nameOfPromise = (isInclude && ('answerTo' in comment)) ? 'CreateCommentTo' : 'CreateComment'
  51. // отправляем запрос на создание комментария с нужным именем
  52. dispatch(actionFullAddComment(nameOfPromise, comment, postId))
  53. // и чистим поле ввода комментария после отправки запроса
  54. setComment({ ...comment, text: '' })
  55. }
  56. return (
  57. <Box
  58. sx={{
  59. display: 'flex',
  60. alignItems: 'flex-end',
  61. justifyContent: 'space-between',
  62. width: '100%'
  63. }}
  64. >
  65. <TextField
  66. id='addCommentField'
  67. variant="standard"
  68. multiline
  69. placeholder='Комментировать...'
  70. size="small"
  71. color="info"
  72. sx={{
  73. margin: 1,
  74. width: '100%',
  75. }}
  76. value={comment.text}
  77. onChange={e => setComment({ ...comment, text: e.target.value })}
  78. InputProps={{
  79. startAdornment:
  80. <Box>
  81. <IconButton
  82. aria-describedby={emojiField}
  83. onClick={openEmoji}
  84. >
  85. <SentimentSatisfiedAlt
  86. fontSize='small'
  87. />
  88. </IconButton>
  89. <Popover
  90. id={emojiField}
  91. open={open}
  92. anchorEl={openPopover}
  93. onClose={closeEmoji}
  94. anchorOrigin={{
  95. vertical: 'top',
  96. horizontal: 'right',
  97. }}
  98. transformOrigin={{
  99. vertical: 'bottom',
  100. horizontal: 'left',
  101. }}
  102. >
  103. <EmojiPicker
  104. searchPlaceHolder='Найти'
  105. emojiStyle='apple'
  106. width={300}
  107. height={450}
  108. onEmojiClick={
  109. e => setComment({ ...comment, text: comment.text + e.emoji })
  110. }
  111. />
  112. </Popover>
  113. </Box>,
  114. endAdornment:
  115. <Box>
  116. {comment.text !== '' && <Typography
  117. variant='subtitle2'
  118. color="primary.main"
  119. align='center'
  120. sx={{
  121. alignSelf: 'center',
  122. cursor: 'pointer',
  123. margin: '0 8px'
  124. }}
  125. onClick={uploadComment}
  126. >
  127. Отправить
  128. </Typography>}
  129. </Box>
  130. }}
  131. />
  132. </Box>
  133. )
  134. }
  135. export default CommentField