Skip to content
Snippets Groups Projects
Select Git revision
  • b679fd884a14187dd3bcd70998eaf006f843ba76
  • main default
2 results

Comments.js

Blame
  • user avatar
    Antoine Gaudron-desjardins authored
    b679fd88
    History
    Comments.js 5.29 KiB
    import React, { useEffect, useRef, useState } from "react";
    import axios from "axios";
    import { AiOutlineInfoCircle } from "react-icons/ai";
    import { BiSend } from "react-icons/bi";
    import { BsChatText } from "react-icons/bs";
    
    import { getSiblings } from "../utils";
    
    import "../styles/Comments.css";
    
    export default function Messages({ place, infos }) {
      const [messages, setMessages] = useState([]);
      const [newComment, setNewComment] = useState("");
      const [loading, setLoading] = useState(true);
      const input = useRef();
      const chat = useRef();
    
      let width = window.innerWidth > 0 ? window.innerWidth : screen.width;
      width = width > 600;
    
      const Submit = (ev) => {
        if (newComment.replace(/\s/g, "").length) {
          ev.preventDefault();
          axios
            .post(`${process.env.REACT_APP_BASE_URL_BACK}/${encodeURIComponent(place)}/comments`, {
              content: newComment,
            })
            .then((res) => {
              if (messages.length) {
                let update = messages.map((_, index) => (index ? messages[index - 1] : res.data));
                update.push(messages[messages.length - 1]);
                setMessages(update);
              } else {
                setMessages([res.data]);
              }
              updateValue("");
            })
            .catch((e) => {
              console.log(e);
              updateValue("");
            });
        }
      };
    
      const updateValue = (value) => {
        setNewComment(value);
        if (input.current) {
          input.current.style.height = "";
          input.current.style.height = `${input.current.scrollHeight + 5}px`;
        }
      };
    
      const OpenSideBar = (ev) => {
        if (!width && ev.target.parentNode.parentNode.className == "comments-side-bar") {
          ev.preventDefault();
          ev.stopPropagation();
          let sidebar = ev.target.parentNode.parentNode;
          if (!parseInt(sidebar.style.width, 10)) {
            let siblings = getSiblings(sidebar);
            for (let sibling of siblings) {
              sibling.style.width = 0;
            }
            if (ev.target.id == "comments-icon-left") {
              let otherIcon = document.getElementById("comments-icon-right");
              otherIcon.style.cssText = "background-color: none";
            } else if (ev.target.id == "comments-icon-right") {
              let otherIcon = document.getElementById("comments-icon-left");
              otherIcon.style.cssText = "background-color: none";
            }
            sidebar.style.width = "100%";
            ev.target.style.cssText = "background-color: white; color: black";
          } else {
            let mainPage = document.getElementById("restaurant-main-page");
            mainPage.style.width = "100%";
            sidebar.style.width = 0;
            ev.target.style.cssText = "background-color: none; color: white";
          }
        }
      };
    
      useEffect(() => {
        axios
          .get(
            `${process.env.REACT_APP_BASE_URL_BACK}/${encodeURIComponent(place)}/${
              infos ? "news" : "comments"
            }`,
          )
          .then((res) => {
            setMessages(res.data);
            setLoading(false);
          })
          .catch((e) => {
            console.log(e);
            setLoading(false);
          });
      }, []);
    
      useEffect(() => {
        if (chat.current) {
          let position = chat.current.scrollHeight - chat.current.clientHeight;
          chat.current.scrollTop = position;
        }
      }, [chat.current]);
    
      useEffect(() => {
        if (input.current) {
          input.current.style.height = "";
          input.current.style.height = `${input.current.scrollHeight + 5}px`;
        }
      }, [newComment]);
    
      return (
        <div className="comments-side-bar">
          <div className="comments-title">
            {infos ? (
              <>
                <AiOutlineInfoCircle id="comments-icon-left" onClick={OpenSideBar} />
                Infos
              </>
            ) : (
              <>
                <BsChatText id="comments-icon-right" onClick={OpenSideBar} />
                Commentaires
              </>
            )}
          </div>
          <div ref={chat} className={`comments-scroll-bar ${infos && "infos-scroll-bar"}`}>
            {!messages.length ? (
              loading ? (
                <div className={`comments-loading ${infos && "infos-loading"}`}>Chargement...</div>
              ) : (
                <div className="no-comments">
                  <div>
                    Il n&apos;y a{" "}
                    {infos
                      ? `aucune information particulière concernant ${place}`
                      : `aucun commentaire sur ${place}`}
                  </div>
                </div>
              )
            ) : (
              messages.map((message, index) => {
                let [date, hour] = message.published_at.split("T");
                let [year, month, day] = date.split("-");
                return (
                  <div key={index} className="comment">
                    <div className="comment-content">{message.content}</div>
                    <div className="comment-date">
                      {`À ${hour.substring(0, 5)} le ${day}/${month}/${year}`}
                    </div>
                  </div>
                );
              })
            )}
          </div>
          {!infos && (
            <div className="comment-input-container">
              <textarea
                className="comments-input"
                ref={input}
                value={newComment}
                onChange={(ev) => updateValue(ev.target.value)}
                placeholder="Ajouter un commentaire"
              />
              <button className="comment-input-button" onClick={Submit}>
                <BiSend />
              </button>
            </div>
          )}
        </div>
      );
    }