From 33076f2bd53b28cdc2a150d1cbec3d44176882dd Mon Sep 17 00:00:00 2001
From: Vinicius Gabriel Machado <vgm18@inf.ufpr.br>
Date: Fri, 16 Apr 2021 15:02:41 -0300
Subject: [PATCH] Fixing bugs (Validacao MECRED 2021004)

---
 src/Components/ContactForm.js      | 266 +++++++++++++++++------------
 src/Components/Header.js           |   8 +-
 src/Components/MenuBar.js          |  18 +-
 src/Components/MenuBarMobile.js    |  12 ++
 src/Components/MobileDrawerMenu.js |  11 +-
 src/Components/SearchBar.js        |  57 ++++---
 src/Pages/Search.js                |   7 +-
 7 files changed, 223 insertions(+), 156 deletions(-)

diff --git a/src/Components/ContactForm.js b/src/Components/ContactForm.js
index 971001eb..3eb206b9 100644
--- a/src/Components/ContactForm.js
+++ b/src/Components/ContactForm.js
@@ -16,10 +16,19 @@ GNU Affero General Public License for more details.
 You should have received a copy of the GNU Affero General Public License
 along with Plataforma Integrada MEC.  If not, see <http://www.gnu.org/licenses/>.*/
 
-import React, { useState } from 'react';
+import React, {useState, useContext} from 'react'
+import {Store} from '../Store.js'
 import styled from 'styled-components';
 import FormInput from "../Components/FormInput.js"
 import {postRequest} from './HelperFunctions/getAxiosConfig'
+import LoginModal from './LoginModal.js'
+import Snackbar from '@material-ui/core/Snackbar';
+import SignUpModal from './SignUpModal'
+import MuiAlert from '@material-ui/lab/Alert';
+
+function Alert(props) {
+  return <MuiAlert elevation={6} variant="filled" {...props} />;
+}
 
 const Button = styled.button`
 
@@ -95,6 +104,10 @@ const Button = styled.button`
   }
 
   function Formulario (props){
+    const {state} = useContext(Store)
+    const [loginOpen, setLogin] = useState(false)
+    const [successfulLoginOpen, handleSuccessfulLogin] = useState(false)
+    const [signUpOpen, setSignUp] = useState(false)
 
     const [nome, handleNome] = useState(
       {
@@ -119,132 +132,165 @@ const Button = styled.button`
       })
 
 
-  const preencheNome = (e) => {
-    const aux2 = e.target.value
-    const flag = validateNome(aux2)
-    handleNome({...nome, dict : {
-      key : flag,
-      value : e.target.value
-    }})
-    console.log(nome)
-  }
+    const preencheNome = (e) => {
+      const aux2 = e.target.value
+      const flag = validateNome(aux2)
+      handleNome({...nome, dict : {
+        key : flag,
+        value : e.target.value
+      }})
+      console.log(nome)
+    }
 
-  const preencheEmail = (e) => {
-    const aux = e.target.value
-    const flag = validateEmail(aux)
-    handleEmail({...email, dict : {
-      key : flag,
-      value : e.target.value
-    }})
-    console.log(email)
-  }
+    const preencheEmail = (e) => {
+      const aux = e.target.value
+      const flag = validateEmail(aux)
+      handleEmail({...email, dict : {
+        key : flag,
+        value : e.target.value
+      }})
+      console.log(email)
+    }
 
-  const preencheMensagem = (e) => {
-    const msg = e.target.value
-    console.log(msg)
-    let flag = validateMensagem(msg)
-    handleMensagem({...mensagem, dict : {
-      key : flag,
-      value : msg
-    }})
-    console.log(mensagem)
-  }
+    const preencheMensagem = (e) => {
+      const msg = e.target.value
+      console.log(msg)
+      let flag = validateMensagem(msg)
+      handleMensagem({...mensagem, dict : {
+        key : flag,
+        value : msg
+      }})
+      console.log(mensagem)
+    }
 
-  const limpaTudo = () => {
-
-    handleNome({
-      dict : {
-       key: false,
-       value:""
-     }}
-   );
-
-    handleEmail({
-      dict : {
-       key: false,
-       value:""
-     }}
-    )
-
-    handleMensagem({
-      dict : {
-       key: false,
-       value:""
-     }}
-    )
+    const limpaTudo = () => {
 
-  }
+      handleNome({
+        dict : {
+        key: false,
+        value:""
+      }}
+      );
 
+      handleEmail({
+        dict : {
+        key: false,
+        value:""
+      }}
+      )
 
+      handleMensagem({
+        dict : {
+        key: false,
+        value:""
+      }}
+      )
 
-  const onSubmit = (e) => {
-      //on submit we should prevent the page from refreshing
-      e.preventDefault(); //though this is arguable
-      console.log(!(nome.dict.key && email.dict.key && mensagem.dict.key ))
-      // Se não houver erro em nunhum dos campos E nenhum dos campos for vazio: a página faz o contato com o backend e os campos ficam em branco no formulário
-      if (!(nome.dict.key || email.dict.key || mensagem.dict.key )) {
-          let payload = {
-              contact : {
-                  name: nome.dict.value,
-                  email: email.dict.value,
-                  message: mensagem.dict.value
-              }
-            }
-            postRequest(`/contacts`, payload, (data) => {limpaTudo()}, (error) => {console.log(error)})
-  }
-}
+    }
+
+    const handleSignUp = () => {
+      setSignUp(!signUpOpen)
+    }
 
+    const handleLogin = () => {
+      setLogin(!loginOpen)
+    }
+
+    const toggleSnackbar = (event, reason) => {
+      if (reason === 'clickaway') {
+          return;
+      }
 
+        handleSuccessfulLogin(false);
+    }
 
+    const onSubmit = (e) => {
+        //on submit we should prevent the page from refreshing
+        e.preventDefault(); //though this is arguable
+        console.log(!(nome.dict.key && email.dict.key && mensagem.dict.key ))
+        // Se não houver erro em nunhum dos campos E nenhum dos campos for vazio: a página faz o contato com o backend e os campos ficam em branco no formulário
+        if (!(nome.dict.key || email.dict.key || mensagem.dict.key )) {
+            let payload = {
+                contact : {
+                    name: nome.dict.value,
+                    email: email.dict.value,
+                    message: mensagem.dict.value
+                }
+              }
+              postRequest(`/contacts`, payload, (data) => {limpaTudo()}, (error) => {console.log(error)})
+        }
+    }
 
-  return(
 
 
 
-      <form onSubmit={e => onSubmit(e)}>
-        <FormInput
-          inputType={"text"}
-          name={"nome"}
-          value={nome.dict.value}
-          placeholder={"Nome *"}
-          error = {nome.dict.key}
-          help = {nome.dict.key ? "insira seu nome para o contato " : ""}
-          handleChange={e => preencheNome(e)}
-        />
-        <br/>
-        <FormInput
-          inputType={"text"}
-          name={"email"}
-          value={email.dict.value}
-          placeholder={"E-mail *"}
-          error = {email.dict.key}
-          help = {email.dict.key ? "Formato de e-mail incorreto ou vazio, tente : usuario@provedor.com" : ""}
-          handleChange={e => preencheEmail(e)}
+    return(
+      <React.Fragment>
+        <Snackbar open={successfulLoginOpen} autoHideDuration={1000} onClose={toggleSnackbar}
+            anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
+        >
+            <Alert severity="success" style={{ backgroundColor: "#00acc1" }}>Você está conectado(a)!</Alert>
+        </Snackbar>
+        {/*-------------------------------MODALS---------------------------------------*/}
+        <LoginModal open={loginOpen} handleClose={() => setLogin(false)} openSignUp={handleSignUp}
+            openSnackbar={() => { handleSuccessfulLogin(true) }}
         />
-        <br/>
-        <br/>
-        <FormInput
-          inputType={"text"}
-          name={"mensagem"}
-          value={mensagem.dict.value}
-          placeholder={"Mensagem *"}
-          multi = {true}
-          rows = "5"
-          rowsMax = "6"
-          error = {mensagem.dict.key}
-          help = {mensagem.dict.key ? "Faltou escrever sua mensagem de sugestão, crítica ou dúvida." : "Escreva sua mensagem no campo acima."}
-          handleChange={e => preencheMensagem(e)}
-        />
-        <br/>
-        <br/>
-        <div style={{display: "flex", justifyContent: "center"}}>
-          <Button onClick={e => onSubmit(e)} >ENVIAR MENSAGEM</Button>
-        </div>
-      </form>
-
+        <SignUpModal open={signUpOpen} handleClose={handleSignUp} openLogin={handleLogin} />  
+        {/*----------------------------------------------------------------------------*/}
+
+
+        <form onSubmit={e => onSubmit(e)}>                          
+          <FormInput
+            inputType={"text"}
+            name={"nome"}
+            value={nome.dict.value}
+            placeholder={"Nome *"}
+            error = {nome.dict.key}
+            help = {nome.dict.key ? "insira seu nome para o contato " : ""}
+            handleChange={e => preencheNome(e)}
+          />
+          <br/>
+          <FormInput
+            inputType={"text"}
+            name={"email"}
+            value={email.dict.value}
+            placeholder={"E-mail *"}
+            error = {email.dict.key}
+            help = {email.dict.key ? "Formato de e-mail incorreto ou vazio, tente : usuario@provedor.com" : ""}
+            handleChange={e => preencheEmail(e)}
+          />
+          <br/>
+          <br/>
+          <FormInput
+            inputType={"text"}
+            name={"mensagem"}
+            value={mensagem.dict.value}
+            placeholder={"Mensagem *"}
+            multi = {true}
+            rows = "5"
+            rowsMax = "6"
+            error = {mensagem.dict.key}
+            help = {mensagem.dict.key ? "Faltou escrever sua mensagem de sugestão, crítica ou dúvida." : "Escreva sua mensagem no campo acima."}
+            handleChange={e => preencheMensagem(e)}
+          />
+          <br/>
+          <br/>
+          <div style={{display: "flex", justifyContent: "center"}}>
+            {
+              state.currentUser.id !== '' ? (
+                <Button onClick={e => onSubmit(e)} >ENVIAR MENSAGEM</Button>
+              )
+              :
+              (
+                <Button onClick={e => {e.preventDefault(); handleLogin(true);}} >ENVIAR MENSAGEM</Button>
+              )
+            }
+          </div>
+        </form>
+      </React.Fragment>
 
 
-  );
+    );
 }
 
 export default Formulario;
diff --git a/src/Components/Header.js b/src/Components/Header.js
index 3b278a89..57cc42f2 100644
--- a/src/Components/Header.js
+++ b/src/Components/Header.js
@@ -137,7 +137,13 @@ export default function Header(props) {
           )
           :
           (
-            <MenuBarMobile openSignUp={handleSignUp} openLogin={handleLogin} />
+            <React.Fragment>
+              <MenuBarMobile openSearchBar={handleClickSearch} openSignUp={handleSignUp} openLogin={handleLogin} />
+              {
+                state.searchOpen &&
+                <SearchBar />
+              }
+            </React.Fragment>
           )
       }
       <SignUpModal open={signUpOpen} handleClose={handleSignUp} openLogin={handleLogin} />
diff --git a/src/Components/MenuBar.js b/src/Components/MenuBar.js
index 21cc08c7..3f8dae23 100644
--- a/src/Components/MenuBar.js
+++ b/src/Components/MenuBar.js
@@ -130,18 +130,18 @@ export default function MenuBar(props) {
   }
 
   const menuSobre = [
-    { name: "Sobre a Plataforma", href: "sobre" },
-    { name: "Portais Parceiros", href: "sobre#portaisparceiros" },
-    { name: "Termos de Uso", href: "termos" },
-    { name: "Contato", href: "contato" }
+    { name: "Sobre a Plataforma", href: "/sobre" },
+    { name: "Portais Parceiros", href: "/sobre#portaisparceiros" },
+    { name: "Termos de Uso", href: "/termos" },
+    { name: "Contato", href: "/contato" }
   ]
 
   const menuAjuda = [
-    { name: "Central de Ajuda", href: "ajuda" },
-    { name: "Publicando Recursos", href: "publicando-recurso" },
-    { name: "Encontrando Recursos", href: "encontrando-recurso" },
-    { name: "Participando da Rede", href: "participando-da-rede" },
-    { name: "Gerenciando a Conta", href: "gerenciando-conta" }
+    { name: "Central de Ajuda", href: "/ajuda" },
+    { name: "Publicando Recursos", href: "/publicando-recurso" },
+    { name: "Encontrando Recursos", href: "/encontrando-recurso" },
+    { name: "Participando da Rede", href: "/participando-da-rede" },
+    { name: "Gerenciando a Conta", href: "/gerenciando-conta" }
   ]
 
   const minhaArea = buildMyAreaTabs()
diff --git a/src/Components/MenuBarMobile.js b/src/Components/MenuBarMobile.js
index c314ab6a..0e263606 100644
--- a/src/Components/MenuBarMobile.js
+++ b/src/Components/MenuBarMobile.js
@@ -23,6 +23,7 @@ import { Button } from '@material-ui/core'
 import logo from '../img/logo_small.svg'
 import { Link } from 'react-router-dom'
 import MobileDrawerMenu from './MobileDrawerMenu';
+import IconSearch from '@material-ui/icons/Search'
 
 
 export default function MenuBarMobile(props) {
@@ -52,6 +53,9 @@ export default function MenuBarMobile(props) {
                         <img src={logo} alt="logo" style={{ border: "0", verticalAlign: "middle" }} />
                     </Link>
                 </DrawerButtonDiv>
+                <Button style={{ color: "#00bcd4", position: "absolute", right: 0}} onClick={props.openSearchBar}>
+                    <IconSearchStyled/>
+                </Button>
             </OuterDiv>
         </>
     )
@@ -79,3 +83,11 @@ const DrawerButtonDiv = styled.div`
     margin-left:auto;
     margin-right:auto;
 `
+
+const IconSearchStyled = styled(IconSearch)`
+    color: #16b8dd;
+    height : 38px;
+    width : 45.55px;
+    margin-left:auto;
+    margin-right:auto;
+`
\ No newline at end of file
diff --git a/src/Components/MobileDrawerMenu.js b/src/Components/MobileDrawerMenu.js
index 67e0b6cd..0a615f6f 100644
--- a/src/Components/MobileDrawerMenu.js
+++ b/src/Components/MobileDrawerMenu.js
@@ -33,7 +33,6 @@ import DefaultAvatar from '../img/default_profile0.png'
 import SettingsIcon from '@material-ui/icons/Settings';
 import { apiDomain } from '../env.js'
 import { deleteRequest } from './HelperFunctions/getAxiosConfig'
-import SearchIcon from '@material-ui/icons/Search';
 
 export default function MobileDrawerMenu(props) {
     const { state, dispatch } = useContext(Store)
@@ -69,11 +68,11 @@ export default function MobileDrawerMenu(props) {
 
     const menuSobre = [
         { name: "Página Inicial", href: "/", icon: <HomeIcon /> },
-        { name: "Sobre a Plataforma", href: "sobre", icon: <InfoIcon /> },
-        { name: "Contato", href: "contato", icon: <MailOutlineIcon /> },
-        { name: "Central de Ajuda", href: "ajuda", icon: <HelpOutlineIcon /> },
-        { name: "Termos de Uso", href: "termos", icon: <AssignmentIcon /> },
-        { name: "Busca", href: `busca?query=${state.search.query}&search_class=${state.search.class}`, icon: <SearchIcon /> }
+        { name: "Sobre a Plataforma", href: "/sobre", icon: <InfoIcon /> },
+        { name: "Contato", href: "/contato", icon: <MailOutlineIcon /> },
+        { name: "Central de Ajuda", href: "/ajuda", icon: <HelpOutlineIcon /> },
+        { name: "Termos de Uso", href: "/termos", icon: <AssignmentIcon /> },
+        //{ name: "Busca", href: `/busca?query=${state.search.query}&search_class=${state.search.class}`, icon: <SearchIcon /> }
     ]
 
     // {/*used in dynamic css selection*/}
diff --git a/src/Components/SearchBar.js b/src/Components/SearchBar.js
index c3db1516..8dc8b65c 100644
--- a/src/Components/SearchBar.js
+++ b/src/Components/SearchBar.js
@@ -163,34 +163,39 @@ export default function SearchBar(props) {
           <ButtonStyled onClick={handleKeyDown} ><IconSearchStyled /></ButtonStyled>
         </Link>
 
-        <Flex style={{ "justifyContent": 'middle', 'flexDirection': 'column' }}>
-          <div>Pressione "Enter"</div>
-          <div>ou click na lupa</div>
-        </Flex>
-        <DividerVertical />
         {state.windowSize.width >= 900 ?
-          <RadioGroupStyled row={true}
-            aria-label="Tipo"
-            name="types" value={searchClass}
-            onChange={
-              (event) => setSearchClass(event.target.value)
-            }
-          >
-            <FormControlLabelStyled value="LearningObject" control={<RadioStyled />} label="Recursos" />
-            <FormControlLabelStyled value="Collection" control={<RadioStyled />} label="Coleções" />
-            <FormControlLabelStyled value="User" control={<RadioStyled />} label="Usuários" />
-          </RadioGroupStyled>
-          :
-          <FormControl>
-            <SelectStyled
-              value={searchClass}
-              onChange={(event) => setSearchClass(event.target.value)}
+          <React.Fragment>
+            <Flex style={{ "justifyContent": 'middle', 'flexDirection': 'column' }}>
+              <div>Pressione "Enter"</div>
+              <div>ou click na lupa</div>
+            </Flex>
+            <DividerVertical />
+            <RadioGroupStyled row={true}
+              aria-label="Tipo"
+              name="types" value={searchClass}
+              onChange={
+                (event) => setSearchClass(event.target.value)
+              }
             >
-              <MenuItemStyled value="LearningObject" aria-label="Recursos">Recursos</MenuItemStyled>
-              <MenuItemStyled value="Collection" aria-label="Coleções">Coleções</MenuItemStyled>
-              <MenuItemStyled value="User" aria-label="Usuários">Usuários</MenuItemStyled>
-            </SelectStyled>
-          </FormControl>
+              <FormControlLabelStyled value="LearningObject" control={<RadioStyled />} label="Recursos" />
+              <FormControlLabelStyled value="Collection" control={<RadioStyled />} label="Coleções" />
+              <FormControlLabelStyled value="User" control={<RadioStyled />} label="Usuários" />
+            </RadioGroupStyled>
+          </React.Fragment>
+        :
+          <React.Fragment>
+            <DividerVertical />
+            <FormControl>
+              <SelectStyled
+                value={searchClass}
+                onChange={(event) => setSearchClass(event.target.value)}
+              >
+                <MenuItemStyled value="LearningObject" aria-label="Recursos">Recursos</MenuItemStyled>
+                <MenuItemStyled value="Collection" aria-label="Coleções">Coleções</MenuItemStyled>
+                <MenuItemStyled value="User" aria-label="Usuários">Usuários</MenuItemStyled>
+              </SelectStyled>
+            </FormControl>
+          </React.Fragment>
         }
       </Flex>
     </Bar>
diff --git a/src/Pages/Search.js b/src/Pages/Search.js
index 59c24ee3..25252c2b 100644
--- a/src/Pages/Search.js
+++ b/src/Pages/Search.js
@@ -113,9 +113,6 @@ export default function Search(props) {
     const query = urlParams.get("query");
     const searchClass = urlParams.get("search_class");
 
-    console.log(query)
-    console.log(searchClass)
-
     if (state.search.query !== query || state.search.class !== searchClass) {
       dispatch({
         type: "SAVE_SEARCH",
@@ -124,6 +121,8 @@ export default function Search(props) {
           class: searchClass,
         },
       });
+      state.search.query = query
+      state.search.class = searchClass
     }
     currOption = searchClass
     setOption(searchClass)
@@ -135,7 +134,7 @@ export default function Search(props) {
         type: "HANDLE_SEARCH_BAR",
         opened: false,
       });
-  }, [window.history.state.key, state.currentUser.id])
+  }, [window.history.state === null ? true : window.history.state.key, state.currentUser.id])
 
   useEffect(() => {
     setIsLoading(true);
-- 
GitLab