diff --git a/package-lock.json b/package-lock.json index a8fb0106a47c902e2206ec5511f11b2704b751f5..cb6f20995cd7290456862eed47a271e5bc0d3b0b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2538,11 +2538,18 @@ "integrity": "sha512-3YDiu347mtVtjpyV3u5kVqQLP242c06zwDOgpeRnybmXlYYsLbtTrUBUm8i8srONt+FWobl5aibnU1030PeeuA==" }, "axios": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz", - "integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==", + "version": "0.21.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.1.tgz", + "integrity": "sha512-dKQiRHxGD9PPRIUNIWvZhPTPpl1rf/OxTYKsqKUDjBwYylTvV7SjSHJb9ratfyzM6wCdLCOYLzs73qpg5c4iGA==", "requires": { - "follow-redirects": "1.5.10" + "follow-redirects": "^1.10.0" + }, + "dependencies": { + "follow-redirects": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.13.1.tgz", + "integrity": "sha512-SSG5xmZh1mkPGyKzjZP8zLjltIfpW32Y5QpdNJyjcfGxK3qo3NDDkZOZSFiGn1A6SclQxY9GzEwAHQ3dmYRWpg==" + } } }, "axobject-query": { diff --git a/package.json b/package.json index 95bdc57afcd91439c09a529b754a3c8a4e11fb1b..22c837b427c03bfe990bf426d6fcddca56b69ad9 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "@material-ui/lab": "^4.0.0-alpha.57", "@material-ui/styles": "^4.11.2", "@syncfusion/ej2-react-inputs": "^18.3.52", - "axios": "^0.19.2", + "axios": "^0.21.1", "base64-img": "^1.0.4", "binary-extensions": "^2.1.0", "build": "^0.1.4", diff --git a/src/Components/AboutCarousel.css b/src/Components/AboutCarousel.css new file mode 100644 index 0000000000000000000000000000000000000000..92e69e00e308af1fb61fc38c3de4789c8b19dffa --- /dev/null +++ b/src/Components/AboutCarousel.css @@ -0,0 +1,6 @@ +#You-Can-Caroussel > .carousel-root > .carousel-slider > button{ + display:none; +} +.dot{ + border: 1px solid black; +} \ No newline at end of file diff --git a/src/Components/AboutCarousel.js b/src/Components/AboutCarousel.js index 35e68f3a937c6644576eeea533fb4fc8c8d929b9..fc36515228cd3b234058e7e712d5630900be159e 100644 --- a/src/Components/AboutCarousel.js +++ b/src/Components/AboutCarousel.js @@ -21,7 +21,7 @@ import React from 'react'; import "react-responsive-carousel/lib/styles/carousel.min.css"; import { Carousel } from 'react-responsive-carousel'; import styled from 'styled-components'; - +import "./AboutCarousel.css" import Img1 from '../img/carousel/Icone_Grande (1).png' import Img2 from '../img/carousel/Icone_Grande (2).png' @@ -70,7 +70,7 @@ const CarouselAbout = styled(Carousel)` text-align: center; display: block; margin: auto; - padding-inline: 235px + // padding-inline: 235px } } ` @@ -80,50 +80,51 @@ const CarouselAbout = styled(Carousel)` function AboutCarousel(props) { return ( - <CarouselAbout showThumbs= {true} - showStatus= {false} - showIndicators = {false} - interval={8000} - transitionTime={1000} - autoPlay - infiniteLoop - - > - <div> - <img src={Img1} alt="Slide 1"/> - <span>Buscar e Baixar Recursos</span> - <p>São mais de 20 mil recursos educacionais à sua disposição. São recursos de portais parceiros do MEC e de professores que, como você, atuam na Educação Básica!</p> - </div> - <div> - <img src={Img2} alt="Slide 2"/> - <span>Guardar Recursos em Coleções</span> - <p>Guarde e organize em coleções aqueles recursos que você considera ser interessantes para elaborar a sua aula. Aproveite e indique aos colegas pelas redes sociais ou e-mail.</p> - </div> - <div> - <img src={Img3} alt="Slide 3"/> - - <span>Compartilhar suas Experiências</span> - <p>Você pode relatar suas experiências sobre o uso de recursos no seu cotidiano escolar. Aproveite esse espaço para sugerir e conhecer novos usos para um mesmo recurso.</p> - - </div> - <div> - <img src={Img4} alt="Slide 4"/> - - <span>Publicar o seu Recurso</span> - <p>Colabore e ajude a fortalecer a plataforma publicando um recurso educacional desenvolvido por você ou pelo coletivo da escola do qual faz parte. Compartilhe seu conhecimento e dê visibilidade ao seu recurso, torne-o público enriquecendo o conhecimento partilhado!</p> - - - </div> - <div> - <img src={Img5} alt="Slide 5"/> - - <span>Encontrar Materiais de Formação</span> - <p>A plataforma disponibiliza um conjunto de materiais de formação desenvolvidos pelo Ministério da Educação com diversidade de temas e recursos educacionais.</p> - - - </div> - </CarouselAbout> - + <div id={"You-Can-Caroussel"}> + <CarouselAbout showThumbs= {true} + showStatus= {false} + showIndicators = {false} + interval={8000} + transitionTime={1000} + autoPlay + infiniteLoop + + > + <div> + <img src={Img1} alt="Slide 1"/> + <span>Buscar e Baixar Recursos</span> + <p>São mais de 20 mil recursos educacionais à sua disposição. São recursos de portais parceiros do MEC e de professores que, como você, atuam na Educação Básica!</p> + </div> + <div> + <img src={Img2} alt="Slide 2"/> + <span>Guardar Recursos em Coleções</span> + <p>Guarde e organize em coleções aqueles recursos que você considera ser interessantes para elaborar a sua aula. Aproveite e indique aos colegas pelas redes sociais ou e-mail.</p> + </div> + <div> + <img src={Img3} alt="Slide 3"/> + + <span>Compartilhar suas Experiências</span> + <p>Você pode relatar suas experiências sobre o uso de recursos no seu cotidiano escolar. Aproveite esse espaço para sugerir e conhecer novos usos para um mesmo recurso.</p> + + </div> + <div> + <img src={Img4} alt="Slide 4"/> + + <span>Publicar o seu Recurso</span> + <p>Colabore e ajude a fortalecer a plataforma publicando um recurso educacional desenvolvido por você ou pelo coletivo da escola do qual faz parte. Compartilhe seu conhecimento e dê visibilidade ao seu recurso, torne-o público enriquecendo o conhecimento partilhado!</p> + + + </div> + <div> + <img src={Img5} alt="Slide 5"/> + + <span>Encontrar Materiais de Formação</span> + <p>A plataforma disponibiliza um conjunto de materiais de formação desenvolvidos pelo Ministério da Educação com diversidade de temas e recursos educacionais.</p> + + + </div> + </CarouselAbout> + </div> ); } diff --git a/src/Components/AboutCarouselPartner.css b/src/Components/AboutCarouselPartner.css new file mode 100644 index 0000000000000000000000000000000000000000..4ccfbadb16760548c55fdca453e17662174f706a --- /dev/null +++ b/src/Components/AboutCarouselPartner.css @@ -0,0 +1,6 @@ +#Partner-Caroussel > .carousel-root > .carousel-slider > button{ + display:none; +} +.dot{ + border: 1px solid black; +} \ No newline at end of file diff --git a/src/Components/AboutCarouselPartner.js b/src/Components/AboutCarouselPartner.js new file mode 100644 index 0000000000000000000000000000000000000000..eb9c9c2939dedce5bf90673951b2ffe29e6d431d --- /dev/null +++ b/src/Components/AboutCarouselPartner.js @@ -0,0 +1,142 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 from 'react'; +import "react-responsive-carousel/lib/styles/carousel.min.css"; +import { Carousel } from 'react-responsive-carousel'; +import './AboutCarouselPartner.css' + + +import LogoPortalDoProfessor from "../img/logo_parceiros/logo_portaldoprofessor.png"; +import LogoBioe from "../img/logo_parceiros/logo_bioe.png"; +import LogoDominioPublico from "../img/logo_parceiros/logo_dominiopublico.png"; +import LogoTvEscola from "../img/logo_parceiros/logo_tvescola.png"; +import Safer from "../img/logo_parceiros/safer.png"; +import FundacaoLemann from "../img/logo_parceiros/fundacao-lemann.png"; +import InstitutoCrescer from "../img/logo_parceiros/instituto-crescer.png"; +import RedeEscola from "../img/logo_parceiros/redeescola.png"; +import Educagital from "../img/logo_parceiros/educagital.png"; +import EnefAef from "../img/logo_parceiros/ENEF_AEF.png"; +import Impa from "../img/logo_parceiros/impa.png"; +import Futura from "../img/logo_parceiros/futura.png"; +import Impulsiona from "../img/logo_parceiros/impulsiona.png"; +import InstPeninsula from "../img/logo_parceiros/inst-peninsula.png"; +import Telefonica from "../img/logo_parceiros/telefonica.png"; + +function AboutCarouselPartner(props) { + + + const itens = [ + <a href="http://portaldoprofessor.mec.gov.br/index.html" rel="noreferrer" target="_blank"> + <img src={LogoPortalDoProfessor} alt="LogoPortalDoProfessor"/> + </a>, + <a href="http://objetoseducacionais2.mec.gov.br/" rel="noreferrer" target="_blank"> + <img src={LogoBioe} alt="LogoBioe" /> + </a>, + <a href="http://www.dominiopublico.gov.br/pesquisa/PesquisaObraForm.jsp" rel="noreferrer" target="_blank"> + <img src={LogoDominioPublico} alt="LogoDominioPublico" /> + </a>, + <a href="https://tvescola.org.br/" rel="noreferrer" target="_blank"> + <img src={LogoTvEscola} alt="LogoTvEscola" /> + </a>, + <a href="http://www.fundacaolemann.org.br/" rel="noreferrer" target="_blank"> + <img style={{align: "middle"}} src={FundacaoLemann} alt="FundacaoLemann" /> + </a>, + <a href="http://new.safernet.org.br/" rel="noreferrer" target="_blank"> + <img src={Safer} alt="Safer" /> + </a>, + <a href="http://institutocrescer.org.br/" rel="noreferrer" target="_blank"> + <img src={InstitutoCrescer} alt="InstitutoCrescer" /> + </a>, + <a href="http://escoladigital.org.br/" rel="noreferrer" target="_blank"> + <img src={RedeEscola} alt="RedeEscola" /> + </a>, + <a href="http://educadigital.org.br" rel="noreferrer" target="_blank"> + <img src={Educagital} alt="Educagital" /> + </a>, + <a href="http://www.aefbrasil.org.br" rel="noreferrer" target="_blank"> + <img style={{filter: "grayscale(1)"}} src={EnefAef} alt="EnefAef" /> + </a>, + <a href="https://impa.br/" rel="noreferrer" target="_blank"> + <img src={Impa} alt="Impa" /> + </a>, + <a href="http://futura.org.br/" rel="noreferrer" target="_blank"> + <img src={Futura} alt="Futura" /> + </a>, + <a href="http://impulsiona.org.br/" rel="noreferrer" target="_blank"> + <img src={Impulsiona} alt="Impulsiona" /> + </a>, + <a href="http://www.institutopeninsula.org.br/" rel="noreferrer" target="_blank"> + <img src={InstPeninsula} alt="InstPeninsula" /> + </a>, + <a href="http://fundacaotelefonica.org.br/" rel="noreferrer" target="_blank"> + <img src={Telefonica} alt="Telefonica" /> + </a> + ] + const partnerPerPage = (()=> { + var pageWidth = window.innerWidth + if (pageWidth >= 1200){ + return 3 + } + else{ + return 1 + } + }) + var rows = [] + var partner_per_page = partnerPerPage() + for(let i = 0; i < 15/partner_per_page; i++){ + rows.push(itens.slice(i*partner_per_page, partner_per_page*(i+1))) + } + + return ( + <div id="Partner-Caroussel"> + <Carousel showThumbs= {false} + showStatus= {false} + showIndicators = {true} + interval={4500} + transitionTime={1000} + autoPlay + infiniteLoop + + > + { + rows.map((row, index) => ( + <div key={(index+1)} style={{display:'inline-flex', paddingTop:100}}> + { + row.map((partner, index2) => ( + <div + key={index + (index2*10)} + style={{marginLeft:10, display: 'flex', maxWidth:300}} + > + { + partner + } + </div> + )) + } + </div> + )) + } + </Carousel> + </div> + + ); +} + +export default AboutCarouselPartner; diff --git a/src/Components/AboutResource.js b/src/Components/AboutResource.js deleted file mode 100644 index 87a0949e185d9dbdaa6f1661f4e6af9de358b7dc..0000000000000000000000000000000000000000 --- a/src/Components/AboutResource.js +++ /dev/null @@ -1,264 +0,0 @@ -/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - -This file is part of Plataforma Integrada MEC. - -Plataforma Integrada MEC is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -Plataforma Integrada MEC is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -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 from 'react'; -import axios from 'axios'; -import {apiUrl} from '../env'; -import {Col,Row} from 'react-grid-system'; -import Paper from '@material-ui/core/Paper'; -import Typography from '@material-ui/core/Typography'; -import CardContent from '@material-ui/core/CardContent'; -import Collapse from '@material-ui/core/Collapse'; -import CardMedia from '@material-ui/core/CardMedia'; -import CardActions from '@material-ui/core/CardActions'; -import Coment from './Coment'; -import Rating from '@material-ui/lab/Rating'; -import Tag from './Tags'; -import { Hidden } from '@material-ui/core'; -import Button from '@material-ui/core/Button'; -import IconButton from '@material-ui/core/IconButton'; -import Menu from '@material-ui/core/Menu'; -import ListItemIcon from '@material-ui/core/ListItemIcon'; -import MenuItem from '@material-ui/core/MenuItem'; -import MoreVertIcon from '@material-ui/icons/MoreVert'; -/*imagens e icones*/ -import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; -import ShareIcon from '@material-ui/icons/Share'; -import ReportIcon from '@material-ui/icons/Error'; -import AddIcon from '@material-ui/icons/CreateNewFolder'; -import FavoriteIcon from '@material-ui/icons/Favorite'; -import GetAppIcon from '@material-ui/icons/GetApp'; -import StarBorderIcon from '@material-ui/icons/StarBorder'; -import RateReviewIcon from '@material-ui/icons/RateReview'; -import VisibilityIcon from '@material-ui/icons/Visibility'; -import SdCardIcon from '@material-ui/icons/SdCard'; -import TranslateIcon from '@material-ui/icons/Translate'; -import InsertDriveFileIcon from '@material-ui/icons/InsertDriveFile'; -import DateRangeIcon from '@material-ui/icons/DateRange'; -import UpdateIcon from '@material-ui/icons/Update'; -import AssignmentOutlinedIcon from '@material-ui/icons/AssignmentOutlined'; -import OpenIcon from '@material-ui/icons/CallMade'; -import { TextField, FormControl } from '@material-ui/core'; - -import noAvatar from "../img/default_profile.png"; -import styled from 'styled-components' - - - -const TypographyStyled = styled(Typography)` - padding: 5px; -` - -const CardActionsStyled = styled(CardActions)` - padding:0px 0px 10px 0px; - align-items: center; -` - -const PaperStyled = styled(Paper)` - margin: 2em 0em 2em 0em; - padding: 2em 2em 0em 2em; - @media only screen and (min-width :500px ) { - margin: 2em 10% 2em 10%; - } -` -const elevateStyle = 3; - -const Overlay = styled.div` - display: inline; - background: linear-gradient(transparent,transparent,#fff),transparent; - bottom: 0; - cursor: pointer; - left: 0; - opacity: .8; - filter: alpha(opacity=80); - position: absolute; - right: 0; - top: 0; - height: inherit; - -` -async function getResource(id){ - let res = await axios.get(`${apiUrl}/learning_objects/${id}`); - let data = res.data; - return(data); -} - -export default function AboutResource() { - - var display = getResource(19133); - console.log(display); - const [anchorEl, setAnchorEl] = React.useState(null); - - function handleClick(event) { - setAnchorEl(event.currentTarget); - } - - function handleClose() { - setAnchorEl(null); - } - return ( - <div style={{backgroundColor: "#f4f4f4", padding: "2em 0em 2em 0em"}}> - <PaperStyled elevation={elevateStyle}> - <CardMedia image={noAvatar}/> - <CardContent style={{padding: "0em"}}> - <Typography variant="h5" color="textSecondary" component="h3"> - {display.name} - </Typography> - <CardActionsStyled > - <IconButton style={{padding: "0px"}}aria-label="Favoritar"> - <FavoriteIcon /> - </IconButton> - <Rating - name="customized-empty" - value={2} - precision={0.5} - emptyIcon={<StarBorderIcon fontSize="inherit" />} - /> - <Hidden smDown> - <IconButton aria-label="Relatar"> - <RateReviewIcon/> - </IconButton> - RELATAR - </Hidden> - </CardActionsStyled> - <CardContent style={{padding: "0em"}}> - <TypographyStyled component="p" color="textSecondary"> - Tipo de Recurso: - </TypographyStyled> - <TypographyStyled component="p" color="textSecondary"> - Componentes Curriculares: - </TypographyStyled> - <TypographyStyled component="p" color="textSecondary"> - Outras Temáticas: - </TypographyStyled> - <TypographyStyled component="p" color="textSecondary"> - Etapas de Ensino: - </TypographyStyled> - </CardContent> - <Row > - <Col md={4} sm={12}><VisibilityIcon style={{verticalAlign: "middle"}}/>Visualizações:</Col> - <Col md={5} sm={12}><GetAppIcon style={{verticalAlign: "middle"}}/>Baixados/Acessados:</Col> - </Row> - <CardActions disableSpacing style={{fontSize: "0.7rem", borderRadius: "2px", justifyContent: "space-between", paddingTop: "2em"}}> - <Hidden smDown> - <Button aria-label="Reportar" size="small"> - <ReportIcon /> REPORTAR ABUSO OU ERRO </Button> - <Button aria-label="Compartilhar"> - <ShareIcon /> COMPARTILHAR </Button> - </Hidden> - <Button aria-label="Guardar"> - <AddIcon /> GUARDAR </Button> - <Button variant="contained" color="secondary"> - <OpenIcon/> Abrir Recurso </Button> - <Hidden mdUp> - <Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick}> - <MoreVertIcon/> - </Button> - <Menu - id="simple-menu" - anchorEl={anchorEl} - keepMounted - open={Boolean(anchorEl)} - onClose={handleClose} - > - <MenuItem onClick={handleClose}> - <ListItemIcon> - <ShareIcon /> - </ListItemIcon> - Compartilhar</MenuItem> - <MenuItem onClick={handleClose}> - <ListItemIcon> - <ReportIcon /> - </ListItemIcon> - Reportar</MenuItem> - </Menu> - </Hidden> - </CardActions> - </CardContent> - </PaperStyled> - <PaperStyled elevation={elevateStyle}> - <Row style={{padding: "15px"}}> - <Col md={8} sm={12}> - <Typography variant="h5" color="textSecondary" component="h3"> - Sobre o Recurso - </Typography> - <Typography component="p" color="textSecondary"> - Paper can be used to build surface or other elements for your application. - </Typography> - <div style={{paddingTop: "4em"}}> - <Typography variant="h5" color="textSecondary" component="h3"> - Informações Adicionais</Typography> - <Tag name="teste"/> - <Typography component="p" color="textSecondary"> - <SdCardIcon/>Tamanho: - </Typography> - <Typography component="p" color="textSecondary"> - <TranslateIcon/>Idioma: - </Typography> - <Typography component="p" color="textSecondary"> - <InsertDriveFileIcon/>Formato: - </Typography> - <Typography component="p" color="textSecondary"> - <DateRangeIcon/>Data de Envio: - </Typography> - <Typography component="p" color="textSecondary"> - <UpdateIcon/>Modificado em: - </Typography> - <Typography component="p" color="textSecondary"> - <AssignmentOutlinedIcon/>Tipo de Licença: - </Typography> - </div> - </Col> - <Col md={4} sm={12}> - <div style={{borderLeft:"1px solid #e5e5e5"}}> - <Typography> - Enviado por: - </Typography><br/> - <img style={{padding: "2em" }} alt="Avatar" src={noAvatar} height="100em"/> - </div> - </Col> - </Row> - - - </PaperStyled> - <PaperStyled elevation={elevateStyle}> - <CardContent> - Conte sua experiência com o Recurso - <Rating - name="customized-color" - value={0} - precision={0.5} - /> - <Row> - <Col md={10} sm={12}> - <TextField fullWidth="true" multiline="true" required="true" placeholder="Escreva aqui sua experiência com o recurso *"/> - </Col> - <Col> - <Button variant="contained" color="primary">submit </Button> - </Col> - </Row> - - </CardContent> - <CardContent> - <Typography variant="h5" component="p" color="textSecondary">Relatos sobre o uso do Recurso</Typography> - <Coment author="jorginho" coment="muito bom gostei mto bom msm"/> - </CardContent> - </PaperStyled> - </div> - ); -} diff --git a/src/Components/AcessibilityBar.js b/src/Components/AcessibilityBar.js deleted file mode 100644 index 7546ea2f92646dc4ee8da27a1f5550d8fc702a2a..0000000000000000000000000000000000000000 --- a/src/Components/AcessibilityBar.js +++ /dev/null @@ -1,60 +0,0 @@ -/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - -This file is part of Plataforma Integrada MEC. - -Plataforma Integrada MEC is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -Plataforma Integrada MEC is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -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, {Component} from 'react'; -import {Row, Col, Container} from 'react-grid-system'; -import Bt from './Button.js' - -const acessibilityBar ={ - width: '100%', - color: 'gray', - fontFamily: '"Roboto", Sans-Serif', - whiteSpace: 'nowrap', - fontSize: '0.7vw', - textAlign: 'right' - -} - -class AcessibilityBar extends Component{ - renderBt(name, link=undefined){ - return <Bt name={name} link={link}/> - } - render(){ - return( - <Container fluid={true}> - <Row style={acessibilityBar}> - <Col md={6} xs={6} lg={6} style={{textAlign: 'left'}}> - {this.renderBt("Ir para conteúdo 1", "texto1")} - {this.renderBt("Ir para menu 2", "texto2")} - {this.renderBt("Ir para menu 3", "texto3")} - {this.renderBt("Ir para rodapé 4", "texto4")} - </Col> - <Col md={6} xs={6} lg={6} style={{textAlign: 'right'}}> - Tamanho do Texto: {this.renderBt("A+")} - {this.renderBt("A-")} - {this.renderBt("A")} - {this.renderBt("Contraste")} - {this.renderBt("Acessibilidade")} - {this.renderBt("Mapa do Site")} - </Col> - </Row> - </Container> - ); - } -} -export default AcessibilityBar; diff --git a/src/Components/ActivityListItem.js b/src/Components/ActivityListItem.js index 00def5db6b3f1cd7e3ca5ed49e8a5f187a829dfe..e6d9d2b7d0de16dbcad37d965ba11c4ed394f2c6 100644 --- a/src/Components/ActivityListItem.js +++ b/src/Components/ActivityListItem.js @@ -34,6 +34,7 @@ import ReportIcon from '@material-ui/icons/Report'; import CloudUploadIcon from '@material-ui/icons/CloudUpload'; import ThumbDownIcon from '@material-ui/icons/ThumbDown'; import DeleteIcon from '@material-ui/icons/Delete'; +import {Link} from 'react-router-dom' const GetObjectColor = (tag) => { return ObjectColor[tag] @@ -137,7 +138,7 @@ export default function ActivityListItem (props) { secondary = { <div> <span> - <a href={props.ownerHref} className="owner-name-a" >{props.ownerName}</a> {activity.text} <a href={props.recipientHref} className="recipient-name-a">{props.recipientName}</a> {activity.text2} + <Link to={props.ownerHref} className="owner-name-a" >{props.ownerName}</Link> {activity.text} <Link to={props.recipientHref} className="recipient-name-a">{props.recipientName}</Link> {activity.text2} </span> </div> } diff --git a/src/Components/AreasSubPages.js b/src/Components/AreasSubPages.js index f6b59bb2d31d904f2663f644951380405dd1bb0d..b8d429a946ea7f27d93034d0baddef361cfc3582 100644 --- a/src/Components/AreasSubPages.js +++ b/src/Components/AreasSubPages.js @@ -17,8 +17,6 @@ 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, { Component } from "react"; -import axios from "axios"; -import { apiUrl } from "../env"; import "./carousel.css"; import { Col, Row, Container, Hidden, Visible } from "react-grid-system"; import MaterialCard from "./MaterialCard"; @@ -27,20 +25,13 @@ import { Carousel } from "react-responsive-carousel"; import recursos from "../img/ilustra_recursos_digitais.png"; import materiais from "../img/ilustra_materiais.png"; import colecoes from "../img/ilustra_colecoes.png"; -import Grid from "@material-ui/core/Grid"; import ResourceCardFunction from "./ResourceCardFunction.js"; import CollectionCardFunction from "./CollectionCardFunction.js"; +import colecoes_obj from './FormationMaterialsResources/formationMaterials'; +import ExpandedMaterial from './ExpandedMaterials'; +import {getRequest} from './HelperFunctions/getAxiosConfig.js' -const areaStyle = { - paddingTop: "5px", - fontSize: "16px", - textAlign: "left", - backgroundColor: "inherit", - width: "1000px", - margin: "auto", - padding: "20px", - minHeight: "190px", -}; +const materials = colecoes_obj(); class ReqResources extends Component { constructor(props) { @@ -49,84 +40,60 @@ class ReqResources extends Component { resources: [], }; } + componentDidMount() { - axios - .get(`${apiUrl}/learning_objects?limit=12&sort=["published_at", "desc"]`) - .then((res) => { - this.setState({ resources: res.data }); - console.log(res.data); - }); + const url = `/learning_objects?limit=12&sort=["published_at", "desc"]` + getRequest(url, (data) => {this.setState({ resources: data })}, (error) => {console.log(error)}) + } + + resourcesPerPage() { + var pageWidth = window.innerWidth + if (pageWidth >= 1200) { + return 3 + } + else { + if (pageWidth > 766) { + return 2 + } + else { + return 1 + } + } } + render() { - var row1 = this.state.resources.slice(0, 4); - var row2 = this.state.resources.slice(4, 8); - var row3 = this.state.resources.slice(8, 13); + var rows = [] + var resources_per_page = this.resourcesPerPage() + for (let i = 0; i < 12 / resources_per_page; i++) { + rows.push(this.state.resources.slice(i * resources_per_page, resources_per_page * (i + 1))) + } return ( + <Carousel showThumbs={false} infiniteLoop={true} showStatus={false}> - <Row style={{ paddingBottom: "5px" }}> - {row1.map((card) => ( - <Col md={3} sm={6} key={card.id}> - <ResourceCardFunction - avatar={card.publisher.avatar} - id={card.id} - thumbnail={card.thumbnail} - type={card.object_type ? card.object_type : "Outros"} - title={card.name} - published={card.state === "published" ? true : false} - likeCount={card.likes_count} - liked={card.liked} - rating={card.review_average} - // author={card.author} - author={card.publisher.name} - tags={card.educational_stages} - href={"/recurso/" + card.id} - downloadableLink={card.default_attachment_location} - /> - </Col> + { + rows.map((row, index) => ( + <Row style={{ paddingBottom: "5px", margin: '0 auto', width: "80%", justifyContent: "center" }} key={(index + 1)}> + {row.map((card) => ( + <div style={{ marginLeft: 10, display: 'flex' }} key={card.id * (index + 1)}> + <ResourceCardFunction + avatar={card.publisher.avatar} + id={card.id} + thumbnail={card.thumbnail} + type={card.object_type ? card.object_type : "Outros"} + title={card.name} + published={card.state === "published" ? true : false} + likeCount={card.likes_count} + liked={card.liked} + rating={card.review_average} + author={card.publisher.name} + tags={card.tags} + href={"/recurso/" + card.id} + downloadableLink={card.default_attachment_location} + /> + </div> + ))} + </Row> ))} - </Row> - <Row> - {row2.map((card) => ( - <Col md={3} sm={6} key={card.id}> - <ResourceCardFunction - avatar={card.publisher.avatar} - id={card.id} - thumbnail={card.thumbnail} - type={card.object_type ? card.object_type : "Outros"} - title={card.name} - published={card.state === "published" ? true : false} - likeCount={card.likes_count} - liked={card.liked} - rating={card.review_average} - author={card.publisher.name} - tags={card.educational_stages} - href={"/recurso/" + card.id} - downloadableLink={card.default_attachment_location} - /> - </Col> - ))} - </Row> - <Row> - {row3.map((card) => ( - <Col md={3} sm={6} key={card.id}> - <ResourceCardFunction - avatar={card.publisher.avatar} - id={card.id} - thumbnail={card.thumbnail} - type={card.object_type ? card.object_type : "Outros"} - title={card.name} - published={card.state === "published" ? true : false} - likeCount={card.likes_count} - liked={card.liked} - rating={card.review_average} - author={card.publisher.name} - tags={card.educational_stages} - href={"/recurso/" + card.id} - downloadableLink={card.default_attachment_location} - /> - </Col> - ))} - </Row> </Carousel> ); } @@ -140,100 +107,94 @@ class ReqCollections extends Component { }; } componentDidMount() { - axios - .get(`${apiUrl}/collections?limit=12&sort=["updated_at", "desc"]`) - .then((res) => { - this.setState({ collections: res.data }); - console.log(res.data); - }); + const url = `/collections?limit=12&sort=["updated_at", "desc"]` + + getRequest(url, (data) => {this.setState({ collections: data })}, (error) => {console.log(error)}) } + collectionsPerPage() { + var pageWidth = window.innerWidth + if (pageWidth >= 1200) { + return 3 + } + else { + if (pageWidth > 766) { + return 2 + } + else { + return 1 + } + } + } + render() { - var row1 = this.state.collections.slice(0, 4); - var row2 = this.state.collections.slice(4, 8); - var row3 = this.state.collections.slice(8, 13); + var rows = [] + var collections_per_page = this.collectionsPerPage() + for (let i = 0; i < 12 / collections_per_page; i++) { + rows.push(this.state.collections.slice(i * collections_per_page, collections_per_page * (i + 1))) + } return ( <Carousel showThumbs={false} infiniteLoop={true} showStatus={false}> - <Row style={{ paddingBottom: "5px" }}> - {row1.map((card) => ( - <Col md={3} sm={6} key={card.id}> - <CollectionCardFunction - name={card.name} - rating={card.score} - id={card.id} - author={card.owner.name} - description={card.description} - thumbnails={card.items_thumbnails} - avatar={card.owner.avatar} - likeCount={card.likes_count} - /> - </Col> - ))} - </Row> - <Row> - {row2.map((card) => ( - <Col md={3} sm={6} key={card.id}> - <CollectionCardFunction - name={card.name} - id={card.id} - rating={card.score} - author={card.owner.name} - description={card.description} - thumbnails={card.items_thumbnails} - avatar={card.owner.avatar} - likeCount={card.likes_count} - /> - </Col> + { + rows.map((row, index) => ( + <Row style={{ paddingBottom: "5px", margin: '0 auto', width: "80%", justifyContent: "center" }} key={(index + 1)}> + {row.map((card) => ( + <div style={{ marginLeft: 10, display: 'flex' }} key={card.id * (index + 1)}> + <CollectionCardFunction + name={card.name} + tags={card.tags} + rating={card.score} + id={card.id} + author={card.owner.name} + description={card.description} + thumbnails={card.items_thumbnails} + avatar={card.owner.avatar} + likeCount={card.likes_count} + followed={card.followed} + liked={card.liked} + collections={card.collection_items} + authorID={card.owner.id} + /> + </div> + ))} + </Row> ))} - </Row> - <Row> - {row3.map((card) => ( - <Col md={3} sm={6} key={card.id}> - <CollectionCardFunction - name={card.name} - id={card.id} - rating={card.score} - author={card.owner.name} - description={card.description} - thumbnails={card.items_thumbnails} - avatar={card.owner.avatar} - likeCount={card.likes_count} - /> - </Col> - ))} - </Row> </Carousel> ); } } class SubPages extends Component { + constructor(props) { + super(props); + this.state = { + currMaterial: { + open: false, + material: {} + }, + }; + } + areaRender() { switch (this.props.banner) { case "Recursos": return ( <React.Fragment> - <div style={{ backgroundColor: "#ff7f00" }}> - <Container style={areaStyle}> - <Grid container style={{ display: "flex" }} spacing={5}> - <Grid item xs={3}> - <img - src={recursos} - alt="aba recursos" - height="155" - style={{ float: "right" }} - /> - </Grid> - <Grid item xs={9}> - <p style={{ textAlign: "justify", color: "#fff" }}> - Nesta área, você tem acesso a Recursos Educacionais - Digitais, isto é, a vídeos, animações e a outros recursos - destinados à educação. São Recursos de portais parceiros - do MEC e de professores que, como você, atuam na Educação - Básica! + <div style={{ backgroundColor: "#ff7f00", position: "relative" }}> + <div style={{ textAlign: "justify", color: "#fff", minHeight: 195, paddingLeft: 10, paddingRight: 10, paddingTop: 20, paddingBottom: 20 }}> + <img + src={recursos} + alt="aba recursos" + height="155" + style={{ float: "left", marginRight: 20, marginBottom: 20, marginLeft: window.innerWidth >= 825 ? "25%" : "0px" }} + /> + <p style={{ textAlign: "justify", color: "#fff", marginRight: window.innerWidth >= 825 ? "25%" : "0px" }}> + Nesta área, você tem acesso a Recursos Educacionais + Digitais, isto é, a vídeos, animações e a outros recursos + destinados à educação. São Recursos de portais parceiros + do MEC e de professores que, como você, atuam na Educação + Básica! </p> - </Grid> - </Grid> - </Container> + </div> </div> <Container style={{ padding: "20px" }}> <p @@ -255,30 +216,43 @@ class SubPages extends Component { </React.Fragment> ); case "Materiais": + + const HandleExpandMaterial = (id) => { + if (id !== this.state.currMaterial.material.id) + this.setState({ + currMaterial: { + open: true, + material: { ...materials[id] } + } + }) + else + this.setState({ + currMaterial: { + open: false, + material: {} + } + }) + } + + return ( <React.Fragment> - <div style={{ backgroundColor: "#e81f4f" }}> - <Container style={areaStyle}> - <Grid container spacing={5}> - <Grid item xs={3}> - <img - src={materiais} - alt="aba materiais" - height="165" - style={{ float: "right" }} - /> - </Grid> - <Grid item xs={9}> - <p style={{ textAlign: "justify", color: "#fff" }}> - Nesta área, você acessa livremente materiais completos de - formação, como cursos já oferecidos pelo MEC e seus - parceiros. São conteúdos elaborados por equipes - multidisciplinares e de autoria de pesquisadores e - educadores renomados nas áreas. + <div style={{ backgroundColor: "#e81f4f", position: "relative" }}> + <div style={{ textAlign: "justify", color: "#fff", minHeight: 195, paddingLeft: 10, paddingRight: 10, paddingTop: 20, paddingBottom: 20 }}> + <img + src={materiais} + alt="aba recursos" + height="155" + style={{ float: "left", marginRight: 20, marginBottom: 20, marginLeft: window.innerWidth >= 825 ? "25%" : "0px" }} + /> + <p style={{ textAlign: "justify", color: "#fff", marginRight: window.innerWidth >= 825 ? "25%" : "0px" }}> + Nesta área, você acessa livremente materiais completos de + formação, como cursos já oferecidos pelo MEC e seus + parceiros. São conteúdos elaborados por equipes + multidisciplinares e de autoria de pesquisadores e + educadores renomados nas áreas. </p> - </Grid> - </Grid> - </Container> + </div> </div> <Container style={{ padding: "20px" }}> <p @@ -298,47 +272,51 @@ class SubPages extends Component { showStatus={false} > <Row> - <Col md={3}> - <MaterialCard name="oioi" /> - </Col> - <Col md={3}> - <MaterialCard name="oioi" /> - </Col> - <Col md={3}> - <MaterialCard name="oioi" /> - </Col> - <Col md={3}> - <MaterialCard name="oioi" /> - </Col> + { + materials.map((material, index) => { + return ( + <Col md={3} key={index}> + <MaterialCard + name={material.name} + thumb={material.img} + score={material.score} + modules={material.topics} + handleExpand={HandleExpandMaterial} + id={index} + /> + </Col> + ) + }) + } </Row> </Carousel> + { + this.state.currMaterial.open ? + <ExpandedMaterial material={this.state.currMaterial.material} /> + : + null + } </Container> - </React.Fragment> + </React.Fragment > ); case "Colecoes": return ( <React.Fragment> - <div style={{ backgroundColor: "#673ab7" }}> - <Container style={areaStyle}> - <Grid container spacing={5}> - <Grid item xs={3}> - <img - src={colecoes} - alt="aba coleções" - width="180" - style={{ float: "right" }} - /> - </Grid> - <Grid item xs={9}> - <p style={{ textAlign: "justify", color: "#fff" }}> - Nesta área, você tem acesso às coleções criadas e - organizadas pelos usuários da plataforma. É mais uma - possibilidade de buscar recursos educacionais para sua - aula! + <div style={{ backgroundColor: "#673ab7", position: "relative" }}> + <div style={{ textAlign: "justify", color: "#fff", minHeight: 195, paddingLeft: 10, paddingRight: 10, paddingTop: 20, paddingBottom: 20 }}> + <img + src={colecoes} + alt="aba recursos" + height="155" + style={{ float: "left", marginRight: 20, marginBottom: 20, marginLeft: window.innerWidth >= 825 ? "25%" : "0px" }} + /> + <p style={{ textAlign: "justify", color: "#fff", marginRight: window.innerWidth >= 825 ? "25%" : "0px" }}> + Nesta área, você tem acesso às coleções criadas e + organizadas pelos usuários da plataforma. É mais uma + possibilidade de buscar recursos educacionais para sua + aula! </p> - </Grid> - </Grid> - </Container> + </div> </div> <Container style={{ padding: "20px" }}> <p @@ -363,4 +341,6 @@ class SubPages extends Component { return <div>{this.areaRender()}</div>; } } + + export default SubPages; diff --git a/src/Components/Button.js b/src/Components/Button.js deleted file mode 100644 index afe4acadacfa68b9e44d0c98b042352108c9305d..0000000000000000000000000000000000000000 --- a/src/Components/Button.js +++ /dev/null @@ -1,75 +0,0 @@ -/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - -This file is part of Plataforma Integrada MEC. - -Plataforma Integrada MEC is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -Plataforma Integrada MEC is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -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, {Component} from 'react'; - -class Bt extends Component{ - constructor(props){ - super(props); - - this.state ={ - color: "white", - hover: "#F0F0F0", - iddle: "white" - }; - } - componentWillMount(){ - if (this.props.backhover){ - this.setState({hover: this.props.backhover}) - } - if (this.props.iddle){ - this.setState({color:this.props.background, - iddle: this.props.background}) - } - } - onHover(){ - this.setState({color: this.state.hover}) - } - onIddle(){ - this.setState({color: this.state.iddle}) - } - onClick(){ - if(this.props.link === undefined){ - } - if(this.props.method !== undefined ){ - console.log(this.props.parameter) - this.props.method(this.props.parameter) - } - else { - alert(`goto ${this.props.link}`) - } - } - - render(){ - const acessibilityBt = { - borderStyle: 'none', - padding: '10px', - textAlign: 'center', - display: 'inline-block', - backgroundColor: this.state.color, - color: "#ababab" - }; - return( - <span id={this.props.name +"-Button"} style={acessibilityBt} onMouseEnter={this.onHover.bind(this)} onMouseOut={this.onIddle.bind(this)} onClick={this.onClick.bind(this)}> - {this.props.name} - </span> - ); - } -} - -export default Bt; diff --git a/src/Components/ButtonGuardarColecao.js b/src/Components/ButtonGuardarColecao.js index 65ae71a2ab7c2de703e21e81679c32f7c4454481..4d8865f7cb57e8c35ece36587f77922b0d0ab48a 100644 --- a/src/Components/ButtonGuardarColecao.js +++ b/src/Components/ButtonGuardarColecao.js @@ -1,30 +1,67 @@ -import React, {useState, useContext} from 'react' -import {Store} from '../Store.js' +import React, { useState, useContext } from 'react' +import { Store } from '../Store.js' import Button from '@material-ui/core/Button'; import styled from 'styled-components' import CreateNewFolderIcon from '@material-ui/icons/CreateNewFolder'; import GuardarModal from './GuardarModal' +import SignUpModal from './SignUpModal' +import LoginModal from './LoginModal.js' +import Snackbar from '@material-ui/core/Snackbar'; +import MuiAlert from '@material-ui/lab/Alert'; -export default function ButtonGuardarColecao (props) { - const {state} = useContext(Store) +export default function ButtonGuardarColecao(props) { + const { state } = useContext(Store) const [saveToCol, toggleSave] = useState(false) const handleGuardar = () => { - if(state.currentUser.id === '') { - console.log('abrir login modal'); + if (!state.currentUser.id) { + handleLogin() } else { toggleSave(true); } } + const handleSignUp = () => { + setSignUp(!signUpOpen) + } + + const handleLogin = () => { + setLogin(!loginOpen) + } + + function Alert(props) { + return <MuiAlert elevation={6} variant="filled" {...props} />; + } + + function toggleLoginSnackbar(reason) { + if (reason === 'clickaway') { + return; + } + handleSuccessfulLogin(false); + } + + const [signUpOpen, setSignUp] = useState(false) + const [loginOpen, setLogin] = useState(false) + const [successfulLoginOpen, handleSuccessfulLogin] = useState(false) + return ( <> - <GuardarModal open={saveToCol} handleClose={() => {toggleSave(false)}} - thumb={props.thumb} title={props.title} recursoId={props.learningObjectId} - /> - <StyledButton onClick={handleGuardar}> - <CreateNewFolderIcon/> GUARDAR - </StyledButton> + <SignUpModal open={signUpOpen} handleClose={handleSignUp} openLogin={handleLogin} + /> + <LoginModal open={loginOpen} handleClose={() => setLogin(false)} openSignUp={handleSignUp} + openSnackbar={() => { handleSuccessfulLogin(true) }} + /> + <Snackbar open={successfulLoginOpen} autoHideDuration={1000} onClose={toggleLoginSnackbar} + anchorOrigin={{ vertical: 'top', horizontal: 'center' }} + > + <Alert severity="success" style={{ backgroundColor: "#00acc1" }}>Você está conectado(a)!</Alert> + </Snackbar> + <GuardarModal open={saveToCol} handleClose={() => { toggleSave(false) }} + thumb={props.thumb} title={props.title} recursoId={props.learningObjectId} + /> + <StyledButton onClick={handleGuardar}> + <CreateNewFolderIcon /> GUARDAR + </StyledButton> </> ) } diff --git a/src/Components/Card.js b/src/Components/Card.js deleted file mode 100644 index e721b5504a51eb1a24130c0028bba39da9ee6555..0000000000000000000000000000000000000000 --- a/src/Components/Card.js +++ /dev/null @@ -1,105 +0,0 @@ -/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - -This file is part of Plataforma Integrada MEC. - -Plataforma Integrada MEC is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -Plataforma Integrada MEC is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -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, {Component} from 'react'; -import {Container} from 'react-grid-system'; -import Card from '@material-ui/core/Card'; -import CardContent from '@material-ui/core/CardContent'; -import CardActions from '@material-ui/core/CardActions'; -import IconButton from '@material-ui/core/IconButton'; -import Typography from '@material-ui/core/Typography'; -import FavoriteIcon from '@material-ui/icons/Favorite'; -import StarRatings from 'react-star-ratings'; -import animacao from "../img/laranja/ANIMACAO_SIMULACAO.jpg"; -import apresentacao from "../img/laranja/APRESENTACAO.jpg"; -import aplicativo from "../img/laranja/APP.jpg"; -import audio from "../img/laranja/AUDIO.jpg"; -import vazio from "../img/laranja/EMPTY.jpg"; -import imagem from "../img/laranja/IMAGEM.jpg"; -import grafico from "../img/laranja/INFOGRAFICO.jpg"; -import jogo from "../img/laranja/JOGO.jpg"; -import livro from "../img/laranja/LIVRO_DIGITAL.jpg"; -import mapa from "../img/laranja/MAPA.jpg"; -import outros from "../img/laranja/OUTROS.jpg"; -import software from "../img/laranja/SOFTWARE.jpg"; -import texto from "../img/laranja/TEXTO.jpg"; -import video from "../img/laranja/VIDEO.jpg"; - -import AddIcon from '@material-ui/icons/CreateNewFolder'; -import Options from './CardOptions' -import Video from '@material-ui/icons/OndemandVideo'; - -var types = [{label: "Animação", thumb: animacao}, {label: "Apresentação", thumb: apresentacao}, -{label: "Aplicativo" , thumb: aplicativo}, {label: "Áudio", thumb: audio}, {label: "Vazio", thumb: vazio}, {label: "Imagem", thumb: imagem}, {label: "Gráfico", thumb: grafico}, {label: "Jogo", thumb: jogo}, {label: "Livro", thumb: livro}, {label: "Mapa", thumb: mapa}, {label: "Outros", thumb: outros}, {label: "Software", thumb:software}, {label: "Texto", thumb:texto}, {label: "Vídeo", thumb:video}] -class ResourceCard extends Component{ - constructor(props){ - super(props); - this.state = { - hover: false, - thumbnail: null, - isVideo: false, - }; - }; - decide(){ - var aux = this.props.thumbnail; - if (!aux) { - aux = types.find(function(element){ return element.label === (this.props.type)}); - } - this.setState({thumbnail: aux.thumb}); - console.log(this.state.thumbnail); - (this.props.type === "Vídeo")? this.setState({isvideo:true}) : this.setState({isvideo:false}); -}; - render(){ - {this.decide()} - return ( - <Card> - <img src={this.state.thumbnail} alt="thumbnail do recurso"/> - <CardContent style={{height: "60%", textAlign: "left", paddingBottom: "0px"}}> - <Typography variant="body2" color="textSecondary" component="p" style={{height:"45px", overflow: "hidden", fontSize: "0.8em"}}> - {this.props.name} - </Typography> - </CardContent> - <Container style={{textAlign: "left"}}> - <StarRatings - rating={this.props.rating*100} - starRatedColor="ff7f00" - starDimension="20px" - starSpacing="2px" - starHoverColor="red" - /> - </Container> - <CardActions style={{justifyContent: "space-between"}}> - { this.state.isVideo - ? <Video style={{color:"#ff7f00"}} /> - : <br/>} - <IconButton aria-label="Favoritar" size="small"> - <FavoriteIcon /> - </IconButton> - </CardActions> - <CardActions style={{borderTop:"1px solid #e5e5e5", justifyContent: "space-between"}}> - - <IconButton aria-label="Guardar" size="small"> - <AddIcon /> - </IconButton> - <Options/> - </CardActions> - </Card> - );} -} - -export default ResourceCard; diff --git a/src/Components/ColCardPublicOptions.js b/src/Components/ColCardPublicOptions.js index 53c8e8a3b85234b22a1cac61948777cbfbbf9911..48a7bab2be1d264fb8681bb3e79637c68d08894f 100644 --- a/src/Components/ColCardPublicOptions.js +++ b/src/Components/ColCardPublicOptions.js @@ -27,81 +27,105 @@ import MoreVertIcon from '@material-ui/icons/MoreVert'; import styled from 'styled-components' import ErrorIcon from '@material-ui/icons/Error'; import ReportModal from './ReportModal.js' -import {getAxiosConfig} from '../Components/HelperFunctions/getAxiosConfig' -import axios from 'axios' -import {apiUrl} from '../env'; +import ReportProblemIcon from '@material-ui/icons/ReportProblem'; +import OpenInBrowserIcon from '@material-ui/icons/OpenInBrowser'; +import {deleteRequest} from '../Components/HelperFunctions/getAxiosConfig' export default function ColCardPublicOptions (props) { const [anchorEl, setAnchorEl] = React.useState(null); - function handleClick(event) { - setAnchorEl(event.currentTarget); - } + function handleClick(event) { + setAnchorEl(event.currentTarget); + } - function handleClose() { - setAnchorEl(null); - } + function handleClose() { + setAnchorEl(null); + } - const [reportModalOpen, toggleReportModal] = useState(false) - const handleReportModal = (value) => {toggleReportModal(value)} + const [reportModalOpen, toggleReportModal] = useState(false) + const handleReportModal = (value) => {toggleReportModal(value)} - const handleUnfollow = () => { - let config = getAxiosConfig() - let payload = {} + const handleUnfollow = () => { - axios.put( (`${apiUrl}/collections/` + props.id + '/follow'),payload, config).then( - (response) => { - console.log(response.data) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - }, (error) => {console.log(error)}) - } + deleteRequest(`/collections/${props.id}/follow`, (data) => {console.log(data)}, (error) => {console.log(error)}) + } - return ( - <> - <ReportModal open={reportModalOpen} handleClose={() => handleReportModal(false)} - form="colecao" complainableId={props.id} - complainableType={"Collection"} - /> - <div style={{fontSize: "12px"}}> - <Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick} style={{color : "#666"}}> - <MoreVertIcon style={{color : "inherit"}}/> - </Button> - <Menu - id="simple-menu" - anchorEl={anchorEl} - keepMounted - open={Boolean(anchorEl)} - onClose={handleClose} - > - <StyledMenuItem> - <Link to={"/colecao-do-usuario/" + props.id}> - <ListItemIcon><OpenIcon /></ListItemIcon>Abrir - </Link> - </StyledMenuItem> - - <StyledMenuItem onClick={handleUnfollow}> - <ListItemIcon><ErrorIcon /></ListItemIcon>Deixar de Seguir - </StyledMenuItem> - - <StyledMenuItem onClick={() => {handleReportModal(true)}}> - <ListItemIcon><ErrorIcon /></ListItemIcon>Reportar - </StyledMenuItem> - </Menu> - </div> + return ( + <> + <ReportModal + open={reportModalOpen} + handleClose={() => handleReportModal(false)} + form="colecao" + complainableId={props.id} + complainableType={"Collection"} + /> + <div style={{ fontSize: "12px" }}> + <Button + aria-controls="simple-menu" + aria-haspopup="true" + onClick={handleClick} + style={{ color: "#666" }} + > + <MoreVertIcon style={{ color: "inherit" }} /> + </Button> + <Menu + id="simple-menu" + anchorEl={anchorEl} + keepMounted + open={Boolean(anchorEl)} + onClose={handleClose} + > + <StyledMenuItem> + <Link to={"/colecao-do-usuario/" + props.id}> + <ListItemIcon> + <OpenIcon /> + </ListItemIcon> + Abrir + </Link> + </StyledMenuItem> + + <StyledMenuItem + onClick={() => + window.open("/colecao-do-usuario/" + props.id, "_blank") + } + > + <ListItemIcon> + <OpenInBrowserIcon /> + </ListItemIcon> + Abrir em nova guia + </StyledMenuItem> + + <StyledMenuItem onClick={handleUnfollow}> + <ListItemIcon> + <ErrorIcon /> + </ListItemIcon> + Deixar de Seguir + </StyledMenuItem> + + <StyledMenuItem + onClick={() => { + handleReportModal(true); + }} + > + <ListItemIcon> + <ReportProblemIcon /> + </ListItemIcon> + Reportar + </StyledMenuItem> + </Menu> + </div> </> - ) + ); } export const StyledMenuItem = styled(MenuItem)` - color : #666 !important; + color: #666 !important; - .MuiSvgIcon-root { - vertical-align : middle !important; - } - a { - text-decoration : none !important; - color : #666 !important; - } -` + .MuiSvgIcon-root { + vertical-align: middle !important; + } + a { + text-decoration: none !important; + color: #666 !important; + } +`; diff --git a/src/Components/CollectionCardFunction.js b/src/Components/CollectionCardFunction.js index 5b015705196ea7e9faa7915548e304270969ca99..de9bb18ce27f388c031c9bf7e40b104ea61d359f 100644 --- a/src/Components/CollectionCardFunction.js +++ b/src/Components/CollectionCardFunction.js @@ -16,15 +16,15 @@ 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, useContext} from 'react'; +import React, {useState, useContext, useEffect} from 'react'; import {Store} from '../Store.js' -import {apiDomain, apiUrl} from '../env'; +import {apiDomain} from '../env'; import noAvatar from "../img/default_profile.png"; import Button from '@material-ui/core/Button'; import styled from 'styled-components' import Slide from '@material-ui/core/Slide'; import Grid from '@material-ui/core/Grid'; -import {StyledCard, CardDiv, CardReaDiv, Footer, LikeCounter, ButtonNoWidth, EnviadoPor, TagContainer} from './ResourceCardFunction.js' +import { StyledCard, CardDiv, CardReaDiv, Footer, LikeCounter, ButtonNoWidth, EnviadoPor, TagContainer, HeaderContainer, AvatarDiv } from './ResourceCardFunction.js' import Rating from '@material-ui/lab/Rating'; import StarBorderIcon from '@material-ui/icons/StarBorder'; import FolderIcon from '@material-ui/icons/Folder'; @@ -34,86 +34,129 @@ import CheckIcon from '@material-ui/icons/Check'; import LockIcon from '@material-ui/icons/Lock'; import ColCardOwnerOptions from './ColCardOwnerOptions.js' import ColCardPublicOptions from './ColCardPublicOptions' -import {Link} from 'react-router-dom'; -import axios from 'axios' -import {getAxiosConfig} from '../Components/HelperFunctions/getAxiosConfig' - -export default function CollectionCardFunction (props) { - const {state} = useContext(Store) +import { Link } from 'react-router-dom'; +import {putRequest} from '../Components/HelperFunctions/getAxiosConfig' +import { saveHeaders } from '../Components/HelperFunctions/saveTokens'; +import SignUpModal from './SignUpModal' +import LoginModal from './LoginModal.js' +import Snackbar from '@material-ui/core/Snackbar'; +import MuiAlert from '@material-ui/lab/Alert'; + +export default function CollectionCardFunction(props) { + // console.log(props); + const { state } = useContext(Store) // eslint-disable-next-line const [userAvatar] = useState(props.avatar ? (`${apiDomain}` + props.avatar) : noAvatar) - const [userFollowingCol, toggleUserFollowingCol] = useState(props.followed) - const handleToggleUserFollowingCol = () => {toggleUserFollowingCol(!userFollowingCol)} + const [userFollowingCol, toggleUserFollowingCol] = useState(props.followed ? props.followed : false) + const handleToggleUserFollowingCol = () => { toggleUserFollowingCol(!userFollowingCol) } const [likesCount, setLikesCount] = useState(props.likeCount) const [liked, toggleLiked] = useState(props.liked) + + const [signUpOpen, setSignUp] = useState(false) + const [loginOpen, setLogin] = useState(false) + const [successfulLoginOpen, handleSuccessfulLogin] = useState(false) + + + function handleSuccessLike (data) { + toggleLiked(!liked) + setLikesCount(data.count) + } const handleLike = () => { - let payload = {} - let config = getAxiosConfig() - - axios.put( (`${apiUrl}/collections/` + props.id + '/like'),payload, config - ).then( - (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - toggleLiked(!liked) - setLikesCount(response.data.count) - }, - (error) => {console.log(error)} - ) + putRequest(`/collections/${props.id}/like`, {}, handleSuccessLike, (error) => {console.log(error)}) } const [followingHover, handleFollowingHover] = useState(false) - const toggleFollowingHover = (value) => {handleFollowingHover(value)} + const toggleFollowingHover = (value) => { handleFollowingHover(value) } const [slideIn, setSlide] = useState(false) - const controlSlide = () => {setSlide(!slideIn)} + const controlSlide = () => { setSlide(!slideIn) } + function handleSuccessFollow (data) { + handleToggleUserFollowingCol() + } const handleFollow = () => { - let config = getAxiosConfig() - let payload = {} - - axios.put( (`${apiUrl}/collections/` + props.id + '/follow'),payload, config).then( - (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response.data) - handleToggleUserFollowingCol() - }, - (error) => {console.log(error)} - ) + putRequest(`/collections/${props.id}/follow`, {}, handleSuccessFollow, (error) => {console.log(error)}) } const RenderFollowButton = () => { return ( <FollowButton onClick={handleFollow}> - <AddIcon/><span>SEGUIR</span> + <AddIcon /><span>SEGUIR</span> </FollowButton> ) } + useEffect(() => { + // setTimeout(function () { + // if (state.currentUser.id) { + // const config = getAxiosConfig(); + // axios({ + // method: 'get', + // url: `${apiUrl}/users/${state.currentUser.id}/following/Collection`, + // headers: config.headers + // }).then( + // (response) => { + // const data = response.data + // for (let i = 0; i < data.length; i++) + // if (data[i].followable.id === props.id) + // toggleUserFollowingCol(true) + // saveHeaders(response) + // }) + // } + // else { + // toggleLiked(false); + // toggleUserFollowingCol(false); + // } + // }, 1000); + + // setTimeout(function () { + // if (state.currentUser.id) { + // const config = getAxiosConfig(); + // axios({ + // method: 'get', + // url: `${apiUrl}/users/${state.currentUser.id}/collections/liked`, + // headers: config.headers + // }).then( + // (response) => { + // const data = response.data + // for (let i = 0; i < data.length; i++) + // if (data[i].id === props.id) + // toggleLiked(true) + // saveHeaders(response) + // }) + // } + // else { + // toggleLiked(false); + // toggleUserFollowingCol(false); + // } + // }, 2000); + if (!state.currentUser.id) { + toggleLiked(false); + toggleUserFollowingCol(false); + } + }, [state.currentUser.id]) + const RenderFollowingButton = () => { return ( <FollowingButton onMouseOver={() => toggleFollowingHover(true)} onMouseLeave={() => toggleFollowingHover(false)} onClick={handleFollow}> { followingHover ? - ( - [ - <span>DEIXAR DE SEGUIR</span> - ] - ) - : - ( - [ - <React.Fragment> - <CheckIcon/><span>SEGUINDO</span> - </React.Fragment> - ] - ) + ( + [ + <span>DEIXAR DE SEGUIR</span> + ] + ) + : + ( + [ + <React.Fragment> + <CheckIcon /><span>SEGUINDO</span> + </React.Fragment> + ] + ) } </FollowingButton> ) @@ -122,171 +165,182 @@ export default function CollectionCardFunction (props) { const SlideAnimationContent = () => { return ( <SlideContentDiv> - <div style={{display:"flex", flex:"1"}}>{/*marginBottom:10px*/} - <SlideAvatarDiv> - <img className="img" src={userAvatar} alt="user avatar"/> - </SlideAvatarDiv> - <EnviadoPor> + <HeaderContainer container="row" justify="flex-start" alignItems="center"> + <AvatarDiv item xs={2}> + <img className="img" src={userAvatar} alt="user avatar" /> + </AvatarDiv> + <EnviadoPor item xs={10}> Enviado por: - <br/> + <br /> <p>{props.author}</p> </EnviadoPor> - </div> - { - props.tags && - <TagContainer> - <Grid container spacing={1} justify='safe' style={{height : "inherit"}}> + </HeaderContainer> + <TagContainer container direction="row"> { - props.tags.map( (tag) => + props.tags.map((tag) => <Grid item key={tag.id}> - <span key={tag.id}>{tag.name}</span> + <span >{tag.name}</span> </Grid> ) } - </Grid> </TagContainer> - } </SlideContentDiv> ) } - return ( - <StyledCard> - <CardDiv> - <CardReaDiv> - <Header onMouseEnter={controlSlide} onMouseLeave={controlSlide}> - {/*slide animation and content*/} - <Slide direction="right" in={slideIn} timeout={300}> - <Link to={"/colecao-do-usuario/" + props.id} className="text"> - {/* <a href={"/colecao-do-usuario/" + props.id} className="text"> */} - {SlideAnimationContent()} - </Link> - </Slide> - <Slide direction="left" in={!slideIn} timeout={700}> - <a href={"/colecao-do-usuario/" + props.id}> - - <UserInfo> - <AvatarDiv> - <img src={userAvatar} alt="user avatar"/> - </AvatarDiv> - <UserAndTitle> - <span>{props.author}</span> - <span className={"col-name"}>{props.name}</span> - </UserAndTitle> - </UserInfo> + const handleSignUp = () => { + setSignUp(!signUpOpen) + } + const handleLogin = () => { + setLogin(!loginOpen) + } + + function Alert(props) { + return <MuiAlert elevation={6} variant="filled" {...props} />; + } + + function toggleLoginSnackbar(reason) { + if (reason === 'clickaway') { + return; + } + handleSuccessfulLogin(false); + } + return ( + <> + <SignUpModal open={signUpOpen} handleClose={handleSignUp} openLogin={handleLogin} + /> + <LoginModal open={loginOpen} handleClose={() => setLogin(false)} openSignUp={handleSignUp} + openSnackbar={() => { handleSuccessfulLogin(true) }} + /> + <Snackbar open={successfulLoginOpen} autoHideDuration={1000} onClose={toggleLoginSnackbar} + anchorOrigin={{ vertical: 'top', horizontal: 'center' }} + > + <Alert severity="success" style={{ backgroundColor: "#00acc1" }}>Você está conectado(a)!</Alert> + </Snackbar> + <StyledCard> + <CardDiv> + <CardReaDiv> + <Header onMouseEnter={controlSlide} onMouseLeave={controlSlide}> + <Slide direction="left" in={slideIn} timeout={1000}> + <div className={`slideContentLinkAfterActive${slideIn}`} style={{ width: '100%', height: "100%" }}> + <Link to={"/colecao-do-usuario/" + props.id} className="text" style={{ textDecoration: "none" }} > + {SlideAnimationContent()} + </Link> + </div> + </Slide> + <div className={`slideContentLinkBeforeActive${slideIn}`} style={{ width: '100%', height: '100%' }}> + <UserInfo> + {/* I(Luis) dont know why, but if i use styled components, sometimes the avatar will be deconfigured */} + <img src={userAvatar} alt="user avatar" style={{ + height: "70px", width: "70px", borderRadius: "50%", + zIndex: 1, border: "2px solid white", + boxShadow: "0 1px 3px rgba(0,0,0,.45)" + + }} /> + <UserAndTitle> + <span>{props.author}</span> + <span className={"col-name"}>{props.name}</span> + </UserAndTitle> + </UserInfo> <StyledGrid container direction="row"> { - props.thumbnails.map( (thumb) => - <Grid item xs={props.thumbnails <= 4 && props.thumbnails > 0 ? 12/props.thumbnails.length : 6}> - <div style={{backgroundImage : `url(${ `${apiDomain}` + thumb})`, height : "100%", width : "100%", backgroundSize : "cover", backgroundPosition : "center"}}/> + props.thumbnails.map((thumb) => + <Grid item xs={props.thumbnails <= 4 && props.thumbnails > 0 ? 12 / props.thumbnails.length : 6}> + <div style={{ backgroundImage: `url(${`${apiDomain}` + thumb})`, height: "100%", width: "100%", backgroundSize: "cover", backgroundPosition: "center" }} /> </Grid> ) } </StyledGrid> - </a> - </Slide> - </Header> - - <Description> {/*renders rating, number of learning objects and likes count*/} - { - props.authorID !== state.currentUser.id && - <Rating - name="customized-empty" - value={props.rating*10} - precision={0.5} - style={{color:"#666"}} - emptyIcon={<StarBorderIcon fontSize="inherit" />} - /> - } - - <Footer> - <Type> - <FolderIcon /> - <span style={{fontWeight:"bold"}}>{props.thumbnails.length} </span> - <span>{props.thumbnails.length !== 1 ? "Recursos" : "Recurso"}</span> - </Type> - <LikeCounter> - <span>{likesCount}</span> - <ButtonNoWidth onClick={handleLike}> - <FavoriteIcon style={{color : liked ? "red" : "#666" }}/> - </ButtonNoWidth> - </LikeCounter> - </Footer> - </Description> - - </CardReaDiv> + </div> + </Header> + + <Description> {/*renders rating, number of learning objects and likes count*/} + { + props.authorID !== state.currentUser.id && + <Rating + name="customized-empty" + value={props.rating} + readOnly + style={{ color: "#666" }} + emptyIcon={<StarBorderIcon fontSize="inherit" />} + /> + } + + <Footer> + <Type> + <FolderIcon /> + <span style={{ fontWeight: "bold" }}>{props.collections.length} </span> + <span>{props.collections.length !== 1 ? "Recursos" : "Recurso"}</span> + </Type> + <LikeCounter> + <span>{likesCount}</span> + <ButtonNoWidth onClick={handleLike}> + <FavoriteIcon style={{ color: liked ? "red" : "#666" }} /> + </ButtonNoWidth> + </LikeCounter> + </Footer> + </Description> + + </CardReaDiv> - { - props.authorID === state.currentUser.id ? - ( - <CardReaFooter style={{justifyContent : "space-between"}}> {/*renders following/unfollow and follow button*/} - <Grid container> - <Grid item xs={6} style={{display : "flex", justifyContent : "center"}}> - { - props.privacy === 'private' && - <LockIcon style={{color : "#666"}}/> - } - </Grid> - <Grid item xs={6} style={{display : "flex", justifyContent : "flex-end"}}> - <ColCardOwnerOptions - id={props.id} - /> - </Grid> - </Grid> - </CardReaFooter> - ) - : - ( - <CardReaFooter> {/*renders following/unfollow and follow button*/} - { - userFollowingCol ? + { + props.authorID === state.currentUser.id ? ( - [ - RenderFollowingButton() - ] + <CardReaFooter style={{ justifyContent: "space-between" }}> {/*renders following/unfollow and follow button*/} + <Grid container> + <Grid item xs={6} style={{ display: "flex", justifyContent: "center" }}> + { + props.privacy === 'private' && + <LockIcon style={{ color: "#666" }} /> + } + </Grid> + <Grid item xs={6} style={{ display: "flex", justifyContent: "flex-end" }}> + <ColCardOwnerOptions + id={props.id} + /> + </Grid> + </Grid> + </CardReaFooter> ) : ( - [ - RenderFollowButton() - ] + <CardReaFooter> {/*renders following/unfollow and follow button*/} + { + userFollowingCol ? + ( + [ + RenderFollowingButton() + ] + ) + : + ( + [ + RenderFollowButton() + ] + ) + } + <ColCardPublicOptions + id={props.id} + /> + </CardReaFooter> ) - } - <ColCardPublicOptions - id={props.id} - /> - </CardReaFooter> - ) - } + } - </CardDiv> - </StyledCard> + </CardDiv> + </StyledCard> + </> ) } -const SlideAvatarDiv = styled.div` - vertical-align : middle; - border : 0; - img { - height : 40px !important; - width : 40px !important; - border : 0; - vertical-align : middle; - border-radius : 50%; - } -` const SlideContentDiv = styled.div` background-color : #7e57c2; padding : 10px; width : 100%; height : 100%; - position : absolute; - display : flex; - flex-direction : column; ` const UserAndTitle = styled.div` @@ -317,19 +371,19 @@ const UserAndTitle = styled.div` } ` -const AvatarDiv = styled.div` - z-index : 5; - overflow : hidden; - - img { - border-radius : 50%; - height : 70px; - width : 70px; - border : 2px solid #fff !important; - background-color : #fff; - box-shadow : 0 1px 3px rgba(0,0,0,.45); - } -` +// const AvatarDiv = styled.div` +// z-index : 5; +// overflow : hidden; + +// img { +// border-radius : 50%; +// height : 70px; +// width : 70px; +// border : 2px solid #fff !important; +// background-color : #fff; +// box-shadow : 0 1px 3px rgba(0,0,0,.45); +// } +// ` const UserInfo = styled.div` position : absolute; diff --git a/src/Components/CollectionCommentSection.js b/src/Components/CollectionCommentSection.js index 9351596e1a34daabddd03f45fbe1cb9d80cea73f..ccc7f079dae76494734addd6116bdaf6a331ae5d 100644 --- a/src/Components/CollectionCommentSection.js +++ b/src/Components/CollectionCommentSection.js @@ -22,13 +22,12 @@ import Card from '@material-ui/core/Card'; import Button from '@material-ui/core/Button'; import EditIcon from '@material-ui/icons/Edit'; import styled from 'styled-components'; -import axios from 'axios'; -import { apiUrl } from '../env'; import CommentForm from './ResourcePageComponents/CommentForm.js'; import Comment from './Comment.js'; import Snackbar from '@material-ui/core/Snackbar'; import MuiAlert from '@material-ui/lab/Alert'; import Comentario from '../img/comentarios.png'; +import {getRequest} from '../Components/HelperFunctions/getAxiosConfig' export default function CollectionCommentSection(props) { const [post_snack_open, setPostSnackOpen] = useState(false); @@ -36,9 +35,9 @@ export default function CollectionCommentSection(props) { const [render_state, setRenderState] = useState(false); const [reviews, setReviews] = useState([]); const comment_ref = useRef(null); - + const forceUpdate = () => { setRenderState(!render_state); } - + const handlePostSnackbar = () => { setPostSnackOpen(!post_snack_open); } @@ -74,7 +73,7 @@ export default function CollectionCommentSection(props) { ` return ( <NoCommentsContainer> - <Image src={Comentario} /> + <Image src={Comentario} style={{width:"100%", maxWidth:234}}/> <BlueTitle>Compartilhe sua opinião com a rede!</BlueTitle> <Secondary>Gostou desta coleção? Comente e compartilhe com a rede sua opinião. Interagindo com a rede, você contribui para que mais coleções como esta sejam criadas.</Secondary> <Button @@ -114,10 +113,7 @@ export default function CollectionCommentSection(props) { } useEffect(() => { - axios.get(apiUrl+'/collections/'+props.id+'/reviews') - .then(res => { - setReviews(res.data); - }); + getRequest(`/collections/${props.id}/reviews`, (data) => {setReviews(data)}, (error) => {console.log(error)}) }, [render_state]); return ( diff --git a/src/Components/CollectionReview.js b/src/Components/CollectionReview.js index c1b2d4f0472483c8ebd564d56ee51c49f77b42ed..10cc202c3ff6f3908aeb09c7d0d4fb567505fddb 100644 --- a/src/Components/CollectionReview.js +++ b/src/Components/CollectionReview.js @@ -23,12 +23,11 @@ import IconButton from '@material-ui/core/IconButton'; import StarBorderIcon from '@material-ui/icons/StarBorder'; import FavoriteIcon from '@material-ui/icons/Favorite'; import InfoIcon from '@material-ui/icons/Info'; -import axios from 'axios'; -import { apiUrl } from '../env'; import { Store } from '../Store.js' import ReportModal from './ReportModal.js'; import SignUpModal from './SignUpModal.js'; import LoginModal from './LoginModal.js'; +import {putRequest, getRequest} from './HelperFunctions/getAxiosConfig.js' export default function CollectionReview(props) { const [likes, setLikes] = useState(0); @@ -39,61 +38,31 @@ export default function CollectionReview(props) { const [log_in_open, setLoginOpen] = useState(false); const { state } = useContext(Store); + function handleSuccessfulGet (data) { + setLikes(Number(data.likes_count)); + setLiked(data.liked); + } + useEffect(() => { - axios.get(apiUrl + '/collections/' + props.id) - .then(res => { - setLikes(Number(res.data.likes_count)); - setLiked(res.data.liked); - }); + const url = `/collections/${props.id}` + + getRequest(url, handleSuccessfulGet, (error) => {console.log(error)}) + }, [props.id]); const handleClickReport = () => { setReportOpen(true); } - const SaveNewHeaders = (response) => { - if ( - (response.headers['access-token'] === undefined || response.headers['access-token'] === null) && - (response.headers.client === undefined || response.headers.client === null) - ) { - - } else { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - sessionStorage.setItem('@portalmec/clientToken', response.headers.client) - console.log('saved') - } - } + function handleSuccess (data) { + setLiked(!liked) + setLikes(data.count) + } const handleLikeClick = () => { if (state.currentUser.id) { - const url = apiUrl + '/collections/' + props.id + '/like'; - if (!liked) - axios({ - method: 'put', - url: url, - headers: { - 'Accept': 'application/json', - 'Content-Type': 'application/json; charset=utf-8', - 'access-token': sessionStorage.getItem('@portalmec/accessToken'), - 'client': sessionStorage.getItem('@portalmec/clientToken'), - 'uid': sessionStorage.getItem('@portalmec/uid'), - 'If-None-Match': null - }, - }).then(response => { - if(response.status === 201) - { - setLiked(true) - setLikes(response.data.count); - } - else - { - setLiked(false); - setLikes(response.data.count); - } - SaveNewHeaders(response) - }) - else - setLiked(!liked); + const url = `/collections/${props.id}/like` + putRequest(url, {}, handleSuccess, (error) => {console.log(error)}) } else setSignUpOpen(true); } diff --git a/src/Components/Coment.js b/src/Components/Coment.js deleted file mode 100644 index f76cbf7fc21d321d7ce4155f57d4580f00190c75..0000000000000000000000000000000000000000 --- a/src/Components/Coment.js +++ /dev/null @@ -1,27 +0,0 @@ -import React, {Component} from 'react'; -import CardContent from '@material-ui/core/CardContent'; -import Typography from '@material-ui/core/Typography'; -import StarRatings from 'react-star-ratings'; - - -class Coment extends Component { - constructor(props) { - super(props); - - } -render(){ - return( - <CardContent> - <StarRatings - rating={2} - starRatedColor="ff7f00" - starDimension="20px" - starSpacing="2px" - /> - <Typography component="p" varitant="srOnly" style={{color: "orange"}}> {this.props.author}:{this.props.coment}</Typography> - </CardContent> - ); -} - -} -export default Coment; diff --git a/src/Components/Comment.js b/src/Components/Comment.js index 51850497b9898ee2030d7ccfa7e3416e2bf3065f..09b66d5ad2f83e4ad3f10994de899960ca4f1b49 100644 --- a/src/Components/Comment.js +++ b/src/Components/Comment.js @@ -28,11 +28,10 @@ import Rating from '@material-ui/lab/Rating'; import StarBorderIcon from '@material-ui/icons/StarBorder'; import EditIcon from '@material-ui/icons/Edit'; import TextField from "@material-ui/core/TextField"; -import axios from 'axios' -import {apiUrl} from '../env'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@material-ui/core/MenuItem'; import ModalExcluir from './ModalExcluirComentario.js' +import {putRequest, deleteRequest} from './HelperFunctions/getAxiosConfig' export default function Comment (props) { @@ -75,18 +74,16 @@ export default function Comment (props) { setComment({...comment, error : flag, value : userInput}) } + function handleOnSuccessfulComment (data) { + setDisplayedComment(comment.value) + setEditando(false) + props.handleSnackbar(2) + } + const updateComment = () => { const finalComment = comment if (!finalComment.error) { - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid'), - } - } + let payload = { "review" : { "name":null, @@ -96,35 +93,19 @@ export default function Comment (props) { "review_ratings_attributes" : props.reviewRatings } } + putRequest(`/learning_objects/${props.objectID}/reviews/`, payload, handleOnSuccessfulComment, (error) => {console.log(error)}) - axios.put( (`${apiUrl}/learning_objects/` + props.objectID + '/reviews/' + props.reviewID),payload, config - ).then((response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - setDisplayedComment(finalComment.value) - setEditando(false) - props.handleSnackbar(2) - }, (error) => {console.log(error)}) } } + function handleSuccessDeleteComment (data) { + props.rerenderCallback() + props.handleSnackbar(3) + } + const deleteComment = () => { - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid'), - } - } - axios.delete( (`${apiUrl}/learning_objects/` + props.objectID + '/reviews/' + props.reviewID), config).then((response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - props.rerenderCallback(); props.handleSnackbar(3)}, (error) => {console.log(error)}) + + deleteRequest(`/learning_objects/${props.objectID}/reviews/${props.reviewID}`, handleSuccessDeleteComment, (error) => {console.log(error)}) toggleModal(false) @@ -327,4 +308,3 @@ const AvatarDiv = styled.div` vertical-align : middle; } ` - diff --git a/src/Components/ContactButtons/FollowButton.js b/src/Components/ContactButtons/FollowButton.js index 4faddda7cfb471ce5d58f4e433f75d44b24b1171..5594fa6619ba288e50f997c8f449039a0f0b828b 100644 --- a/src/Components/ContactButtons/FollowButton.js +++ b/src/Components/ContactButtons/FollowButton.js @@ -20,32 +20,19 @@ import React from 'react' import PersonAddIcon from '@material-ui/icons/PersonAdd'; import styled from 'styled-components' import Button from '@material-ui/core/Button'; -import axios from 'axios' -import {apiUrl} from '../../env'; -import {getAxiosConfig} from '../HelperFunctions/getAxiosConfig' +import {putRequest} from '../HelperFunctions/getAxiosConfig' export default function FollowButton (props) { - const handleFollow = (followerID) => { - const id = followerID - console.log('id: ', id) - - let payload = {} - const header = getAxiosConfig() - - axios.put((`${apiUrl}/users/` + id + '/follow'), payload, header).then( - (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - props.toggleFollowed() - }, - (error) => { - console.log(error) - } - ) + function handleSuccess (data) { + props.toggleFollowed() + } + const handleFollow = (followerID) => { + if (followerID !== undefined) { + const url = `/users/${followerID}/follow/` + putRequest(url, {}, handleSuccess, (error) => {console.log(error)}) + } } return ( @@ -62,24 +49,9 @@ export default function FollowButton (props) { export function NoIcon (props) { const handleFollow = (followerID) => { - const id = followerID - console.log('id: ', id) - - if (id !== undefined) { - let payload = {} - const header = getAxiosConfig() - - axios.put((`${apiUrl}/users/` + id + '/follow'), payload, header).then( - (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - }, - (error) => { - console.log(error) - } - ) + if (followerID !== undefined) { + const url = `/users/${followerID}/follow/` + putRequest(url, {}, (data) => {console.log(data)}, (error) => {console.log(error)}) } } diff --git a/src/Components/ContactButtons/FollowingButton.js b/src/Components/ContactButtons/FollowingButton.js index 6fa7464a760885e617f37a1028aafc496b2b2610..b2d22f248597fa5fd15f9289f7ea538ec2a8b2b5 100644 --- a/src/Components/ContactButtons/FollowingButton.js +++ b/src/Components/ContactButtons/FollowingButton.js @@ -21,9 +21,7 @@ import styled from 'styled-components' import Button from '@material-ui/core/Button'; import FollowingIcon from '../../img/how_to_reg-24px.png' import ModalConfirmarUnfollow from '../ModalConfirmarUnfollow.js' -import axios from 'axios' -import {apiUrl} from '../../env'; -import {getAxiosConfig} from '../HelperFunctions/getAxiosConfig' +import {putRequest} from '../HelperFunctions/getAxiosConfig' export default function FollowingButton (props) { @@ -38,26 +36,15 @@ export default function FollowingButton (props) { toggleModal(true) } - const handleUnfollowPartTwo = () => { - const id = unfollowID - console.log('id: ', id) - let payload = {} - const header = getAxiosConfig() + function handleSuccess (data) { + props.toggleFollowed() + toggleModal(false) + } + const handleUnfollowPartTwo = () => { + const url = `/users/${unfollowID}/follow/` - axios.put((`${apiUrl}/users/` + id + '/follow'), payload, header).then( - (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - props.toggleFollowed() - toggleModal(false) - }, - (error) => { - console.log(error) - } - ) + putRequest(url, {}, handleSuccess, (error) => {console.log(error)}) } return ( diff --git a/src/Components/ContactCard.js b/src/Components/ContactCard.js index b1c26823e9ecb88f646b57c2f540bde466c93049..b5719d71e54a6eeb2ebaa30844b0a8e1ac6b10f3 100644 --- a/src/Components/ContactCard.js +++ b/src/Components/ContactCard.js @@ -71,18 +71,32 @@ export default function ImgMediaCard(props) { { followedBoolean ? ( - [ - <FollowingButton followedID={props.followerID} toggleFollowed={toggleFollowed}/> - ] + <React.Fragment> + <FollowingButton + followedID={props.followerID ? props.followerID : props.followedID} + toggleFollowed={toggleFollowed}/> + + <Options + followableID={props.followerID ? props.followerID : props.followedID} + followed={followedBoolean} + toggleFollowed={toggleFollowed}/> + </React.Fragment> ) : ( - [ - <FollowButton followerID={props.followerID} toggleFollowed={toggleFollowed}/> - ] + <React.Fragment> + <FollowButton + followerID={props.followedID ? props.followedID : props.followerID} + toggleFollowed={toggleFollowed}/> + + <Options + followableID={props.followedID ? props.followedID : props.followerID} + followed={followedBoolean} + toggleFollowed={toggleFollowed}/> + </React.Fragment> ) } - <Options followableID={props.followerID} followed={followedBoolean}/> + </div> </UserInfo> </CardContent> diff --git a/src/Components/ContactCardOptions.js b/src/Components/ContactCardOptions.js index 99de8ca99da13b42dc6025a128d15f3c5a531473..deb12ba4e7a9c4a68785e59986ed3b85d3a05065 100644 --- a/src/Components/ContactCardOptions.js +++ b/src/Components/ContactCardOptions.js @@ -26,9 +26,7 @@ import MoreVertIcon from '@material-ui/icons/MoreVert'; import OpenIcon from '@material-ui/icons/OpenInNew'; import ReportIcon from '@material-ui/icons/Error'; import PersonAddIcon from '@material-ui/icons/PersonAdd'; -import axios from 'axios' -import {apiUrl} from '../env'; -import {getAxiosConfig} from './HelperFunctions/getAxiosConfig' +import {putRequest} from './HelperFunctions/getAxiosConfig' import ReportModal from './ReportModal.js' import {Link} from 'react-router-dom' @@ -43,34 +41,20 @@ export default function SimpleMenu(props) { function handleClose() { setAnchorEl(null); } + const handleFollow = (followerID) => { - const id = followerID - console.log('id: ', id) - - let payload = {} - const header = getAxiosConfig() - axios.put((`${apiUrl}/users/` + id + '/follow'), payload, header).then( - (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - }, - (error) => { - console.log(error) - } - ) + + putRequest(`/users/${followerID}/follow`, {}, (data) => { + console.log(data); + props.toggleFollowed() + }, (error) => {console.log(error)}) + + handleClose(); } const [reportModal, toggleReportModal] = useState(false) const handleModal = (value) => { toggleReportModal(value) - // {/*if (state.currentUser.id) { - // toggleReportModal(!reportModal) - // } - // else { - // toggleLoginModal(true) - // }*/} } return ( @@ -102,13 +86,13 @@ export default function SimpleMenu(props) { { props.followed ? ( - <StyledMenuItem onClick={() => {handleFollow(props.followableID);handleClose()}}> + <StyledMenuItem onClick={() => {handleFollow(props.followableID)}}> <ListItemIcon><ReportIcon /></ListItemIcon>Deixar de Seguir </StyledMenuItem> ) : ( - <StyledMenuItem onClick={() => {handleFollow(props.followableID);handleClose()}}> + <StyledMenuItem onClick={() => {handleFollow(props.followableID)}}> <ListItemIcon><PersonAddIcon /></ListItemIcon>Seguir </StyledMenuItem> ) diff --git a/src/Components/ContactForm.js b/src/Components/ContactForm.js index b00d2f3219e0c699e134a8455d7c41716e88442d..971001ebc2f52aad912ac0d9deb1791aafd68396 100644 --- a/src/Components/ContactForm.js +++ b/src/Components/ContactForm.js @@ -19,11 +19,7 @@ along with Plataforma Integrada MEC. If not, see <http://www.gnu.org/licenses/> import React, { useState } from 'react'; import styled from 'styled-components'; import FormInput from "../Components/FormInput.js" -import axios from 'axios' -import {apiUrl} from '../env'; - - - +import {postRequest} from './HelperFunctions/getAxiosConfig' const Button = styled.button` @@ -187,27 +183,16 @@ const Button = styled.button` 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 )) { - - axios.post(`${apiUrl}/contacts`, - { + let payload = { contact : { - name: nome.dict.value, - email: email.dict.value, - message: mensagem.dict.value + name: nome.dict.value, + email: email.dict.value, + message: mensagem.dict.value } - - } - ).then() - - - - limpaTudo(); - - } - - - + } + postRequest(`/contacts`, payload, (data) => {limpaTudo()}, (error) => {console.log(error)}) } +} diff --git a/src/Components/CriarColecaoForm.js b/src/Components/CriarColecaoForm.js index 9eada322aa34fcccdb8736709414874c3f137bba..ea8c05070f21519b8594a13c03897d69481b2556 100644 --- a/src/Components/CriarColecaoForm.js +++ b/src/Components/CriarColecaoForm.js @@ -25,8 +25,7 @@ import RadioGroup from '@material-ui/core/RadioGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import TextField from '@material-ui/core/TextField'; -import axios from 'axios' -import {apiUrl} from '../env'; +import {postRequest} from './HelperFunctions/getAxiosConfig' export default function CriarColecaoForm (props) { const {state} = useContext(Store) @@ -59,6 +58,9 @@ export default function CriarColecaoForm (props) { }) } + function handleSuccess (data) { + props.finalize(data.id) + } const formSubmit = (e) => { e.preventDefault() @@ -66,7 +68,6 @@ export default function CriarColecaoForm (props) { const finalRadioValue = value === 'pública' ? 'public' : 'private' const finalColName = colName - console.log(finalRadioValue, finalColName.value) if(!(finalColName.key)) { let payload = { "collection" : { @@ -76,25 +77,8 @@ export default function CriarColecaoForm (props) { "privacy" : finalRadioValue } } - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid') - } - } + postRequest( `/collections/`, payload, handleSuccess, (error) =>{console.log(error)}) - axios.post( (`${apiUrl}/collections/`), payload, config - ).then( - (response) => { - console.log(response) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - props.finalize(response.data.id) - }, (error) =>{console.log(error)}) } } diff --git a/src/Components/Dropdown.js b/src/Components/Dropdown.js index a379b826b8df5498957d0b84ffe0645a20ca0b18..31d7047d63cfd5d837734ebbf0cd057bfbc4430f 100644 --- a/src/Components/Dropdown.js +++ b/src/Components/Dropdown.js @@ -95,7 +95,7 @@ function Dropdown(props) { <MenuList> { props.items.map((item)=> - <Link key={item.name} to={item.href} ><MenuItem>{item.name}</MenuItem></Link> + <Link key={`${item.name}_${new Date().toString()}` } to={item.href} ><MenuItem>{item.name}</MenuItem></Link> ) } </MenuList> diff --git a/src/Components/EditarColecaoForm.js b/src/Components/EditarColecaoForm.js index a078b1af975a3d44d2d517faccc8e38dd7cd75f9..9191ee7d51b329f0739e0b3d410baddf7437e7e4 100644 --- a/src/Components/EditarColecaoForm.js +++ b/src/Components/EditarColecaoForm.js @@ -25,31 +25,28 @@ import RadioGroup from '@material-ui/core/RadioGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import TextField from '@material-ui/core/TextField'; -import axios from 'axios' -import {apiUrl} from '../env'; -import {getAxiosConfig} from './HelperFunctions/getAxiosConfig' +import {getRequest, putRequest} from './HelperFunctions/getAxiosConfig' export default function EditarColecaoForm (props) { const {state} = useContext(Store) + function handleSuccessfulGet (data) { + setColName({key : false, value : data.name}) + setValue( data.privacy === 'public' ? 'pública' : 'privada') + handleColDescription(data.description) + } + useEffect(() => { - axios.get(`${apiUrl}/collections/${props.id}`).then( - (res) => { - setColName({key : false, value : res.data.name}) - setValue( res.data.privacy === 'public' ? 'pública' : 'privada') - handleColDescription(res.data.description) - }, - (err) => {console.log(err)} - ) + getRequest(`/collections/${props.id}`, handleSuccessfulGet, (error) => {console.log(error)}) }, []) const [value, setValue] = useState(-1); /*values are set according to backend complaint id*/ - const [options] = useState([ + const [options] = [ {value : "pública", text :'Pública (Sua coleção estará disponível para todos)'}, {value : "privada", text : 'Privada (Somente você poderá visualizar esta coleção)'} - ]) + ] const handleChange = (event) => { setValue(event.target.value); @@ -71,6 +68,9 @@ export default function EditarColecaoForm (props) { }) } + function handleSuccessfulSubmit (data) { + props.finalize(data.id) + } const formSubmit = (e) => { e.preventDefault() @@ -78,7 +78,6 @@ export default function EditarColecaoForm (props) { const finalRadioValue = value === 'pública' ? 'public' : 'private' const finalColName = colName - console.log(finalRadioValue, finalColName.value) if(!(finalColName.key)) { let payload = { "collection" : { @@ -88,17 +87,8 @@ export default function EditarColecaoForm (props) { "privacy" : finalRadioValue } } - let config = getAxiosConfig() - - axios.put( (`${apiUrl}/collections/${props.id}`), payload, config - ).then( - (response) => { - console.log(response) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - props.finalize(response.data.id) - }, (error) =>{console.log(error)}) + + putRequest(`/collections/${props.id}/`, payload, handleSuccessfulSubmit, (error) =>{console.log(error)}) } } diff --git a/src/Components/ExpandedMaterials.js b/src/Components/ExpandedMaterials.js new file mode 100644 index 0000000000000000000000000000000000000000..603ec4ed4f8053d3c72d8ed36527fec9cb221bc9 --- /dev/null +++ b/src/Components/ExpandedMaterials.js @@ -0,0 +1,129 @@ +import React from 'react'; +import { makeStyles } from '@material-ui/core/styles'; +import styled from 'styled-components'; +import Chip from '@material-ui/core/Chip'; +import Grid from '@material-ui/core/Grid'; +import Button from '@material-ui/core/Button'; +import TopicCard from './TopicCard'; +import Paper from '@material-ui/core/Paper'; +import Library from '@material-ui/icons/LibraryBooks'; +import { Link } from 'react-router-dom'; + +const useStyles = makeStyles((theme) => ({ + root: { + display: 'flex', + flexWrap: 'wrap', + '& > *': { + margin: theme.spacing(0.5), + }, + }, +})); + +const ExpandedMaterial = (props) => { + const material = { ...props.material }; + const classes = useStyles(); + + return ( + <Paper elevation={3} style={{ backgroundColor: "#444444", padding: "20px" }}> + <Grid container direction="row" spacing={2}> + <Grid item direction="column" xs={12} md={4}> + <Grid item> + <Title variant="body2"> + { + material.name + } + </Title> + </Grid> + <SizedHeightBox /> + <Grid item> + <ChipsDiv className={classes.root}> + { + material.tags.map((tag, index) => { + return ( + <Chip color="default" label={tag.name} key={index} style={{ padding: "0.5px" }} /> + ) + }) + } + </ChipsDiv> + </Grid> + <SizedHeightBox2 /> + <Grid item direction="column" style={{ color: '#E5E7E9', fontWeight: "500" }}> + <DevelopedByDiv> + { + `Desenvolvido por: ${material.developed}` + } + </DevelopedByDiv> + <SizedHeightBox3 /> + <StyledLink to={`/colecao?colecao=${material.id}`}> + <Button variant="contained" color="secondary"> + Ver todos + </Button> + </StyledLink> + </Grid> + </Grid> + <Grid item direction="column" xs={12} md={8}> + <Grid container direction="row"> + <Library style={{ color: "White" }} /> + <SizedWidthBox /> + <Title> + {material.topics.length} módulos + </Title> + </Grid> + <SizedHeightBox /> + <Grid container direction="row" justify="center" alignItems="center" spacing={3}> + <Grid item md={4}> + <TopicCard + topic={material.topics[0]} + colecao_id={material.id} + /> + </Grid> + <Grid item md={4}> + <TopicCard + topic={material.topics[1]} + colecao_id={material.id} + /> + </Grid> + <Grid item md={4}> + <TopicCard + topic={material.topics[2]} + colecao_id={material.id} + /> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> + ); +} + +const Title = styled.h3` + color: White; + font-weight: 500; + padding : 0; + margin : 0; +` +const DevelopedByDiv = styled.div` +` + +const ChipsDiv = styled.div` + margin-left : -5px; +` +const SizedHeightBox = styled.div` + height : 3em; +` +const SizedHeightBox2 = styled.div` + height : 2em; +` +const SizedHeightBox3 = styled.div` + height : 0.5em; +` +const SizedWidthBox = styled.div` + width : 5px; +` +const StyledLink = styled(Link)` + text-decoration: none !important; + color: inherit !important; +` + + +export default ExpandedMaterial; \ No newline at end of file diff --git a/src/Components/ExpansionPanels.js b/src/Components/ExpansionPanels.js index a16fa9047664d2e79573d0169ba9f2d834ab9210..9a242d21a3b8616c70c6ed7b419f24e133194aec 100644 --- a/src/Components/ExpansionPanels.js +++ b/src/Components/ExpansionPanels.js @@ -454,7 +454,7 @@ export default function SimpleExpansionPanel() { <Grid item xs={12} md={4}> <div style={{color:"#00BCD4",fontSize:"18px"}}> <p>BASICAMENTE,</p> - <p>O usuário poderá reportar, utilizando a funcionalidade “Reportar” ou pelo formulário de “Contato”, qualquer tipo de conteúdo publicado na Plataforma MEC RED que viole os direitos dos usuários, de terceiros ou a legislação aplicável.</p> + <p>O usuário poderá reportar,utilizando a funcionalidade “Reportar” ou pelo formulário de “Contato”, qualquer tipo de conteúdo publicado na Plataforma MEC RED que viole os direitos dos usuários, de terceiros ou a legislação aplicável.</p> </div> </Grid> </Grid> diff --git a/src/Components/Firulas.js b/src/Components/Firulas.js index 526ff7abdc28b1de5666ba4e573060edb5413902..6a368a11cf553166280ec8d85dd9ede03562e781 100644 --- a/src/Components/Firulas.js +++ b/src/Components/Firulas.js @@ -1,29 +1,19 @@ import React, {useState} from 'react' -import axios from 'axios' -import {apiUrl} from '../env'; import styled from 'styled-components' import Rating from '@material-ui/lab/Rating'; import StarBorderIcon from '@material-ui/icons/StarBorder'; import {LikeCounter, ButtonNoWidth} from '../Components/ResourceCardFunction.js' import FavoriteIcon from '@material-ui/icons/Favorite'; +import {putRequest} from './HelperFunctions/getAxiosConfig' export default function Firulas (props) { const [liked, setLiked] = useState(props.liked) + function handleSuccess (data) { + setLiked(!liked) + } const handleLike = () => { - let payload = {} - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid'), - } - } - - axios.put( (`${apiUrl}/learning_objects/` + props.recursoId + '/like'),payload, config - ).then( (response) => {setLiked(!liked)}, (error) => {console.log(error)}) + putRequest(`/learning_objects/${props.recursoId}/like/`, {}, handleSuccess, (error) => {console.log(error)}) } return ( diff --git a/src/Components/FollowCollectionButton.js b/src/Components/FollowCollectionButton.js index cf7d7323ccd935207d581b0c0dd690faa621d130..be01ad44329cfe45b7ca167a4111d721cd8f7e7a 100644 --- a/src/Components/FollowCollectionButton.js +++ b/src/Components/FollowCollectionButton.js @@ -22,8 +22,7 @@ import CheckIcon from '@material-ui/icons/Check'; import AddIcon from '@material-ui/icons/Add'; import styled from 'styled-components'; import SignUpModal from './SignUpModal.js'; -import axios from 'axios'; -import { apiUrl } from '../env'; +import {getRequest, putRequest} from './HelperFunctions/getAxiosConfig' export default function FollowCollectionButton(props) { const [icon, setIcon] = useState(<AddIcon fontSize="large" />); @@ -32,34 +31,21 @@ export default function FollowCollectionButton(props) { const [sign_up_open, setSignUpOpen] = useState(false); const [following, setFollowing] = useState(false); //user following collection + function handleSuccessGet (data) { + if(data) + data.map((e) => { + if (e["followable"]["id"] === Number(props.collection_id)){ + setVariant("contained"); + setButtonText("Seguindo"); + setIcon(<CheckIcon fontSize="large" />) + setFollowing(true); + } + return undefined + }) + } useEffect(() => { - const url = apiUrl + '/users/' + props.user_id + '/following/Collection'; - console.log("props: ", props); - axios({ - method: 'get', - url: url, - headers: { - 'Accept': 'application/json', - 'Content-Type': 'application/json; charset=utf-8', - 'access-token': sessionStorage.getItem('@portalmec/accessToken'), - 'client': sessionStorage.getItem('@portalmec/clientToken'), - 'uid': sessionStorage.getItem('@portalmec/uid'), - 'If-None-Match': null - }, - }).then(response => { - const data = [...response.data]; - if(data) - data.map((e) => { - if (e["followable"]["id"] === Number(props.collection_id)){ - setVariant("contained"); - setButtonText("Seguindo"); - setIcon(<CheckIcon fontSize="large" />) - setFollowing(true); - } - return undefined - }) - SaveNewHeaders(response) - }) + const url = `/users/${props.user_id}/following/Collection` + getRequest(url, handleSuccessGet, (error) => console.log(error)) }, []); //handleMouse{Enter, Leave} only do anything when user follows given collection: @@ -79,70 +65,27 @@ export default function FollowCollectionButton(props) { } } - const SaveNewHeaders = (response) => { - if ( - (response.headers['access-token'] === undefined || response.headers['access-token'] === null) && - (response.headers.client === undefined || response.headers.client === null) - ) { - - } else { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - sessionStorage.setItem('@portalmec/clientToken', response.headers.client) - console.log('saved') - } - } - + function handleSuccessfulFollow (data) { + setVariant("contained"); + setButtonText("Seguindo"); + setIcon(<CheckIcon fontSize="large" />) + setFollowing(true); + } + function handleSuccessfulUnfollow (data) { + setVariant("outlined"); + setButtonText("Seguir Coleção"); + setIcon(<AddIcon fontSize="large" />); + setFollowing(false); + } const handleClick = () => { + const url = `/collections/${props.collection_id}/follow` + if (!props.user_id) setSignUpOpen(true); else if (!following) { - const url = apiUrl + '/collections/' + props.collection_id + '/follow'; - setVariant("contained"); - setButtonText("Seguindo"); - setIcon(<CheckIcon fontSize="large" />) - setFollowing(true); - axios({ - method: 'put', - url: url, - headers: { - 'Accept': 'application/json', - 'Content-Type': 'application/json; charset=utf-8', - 'access-token': sessionStorage.getItem('@portalmec/accessToken'), - 'client': sessionStorage.getItem('@portalmec/clientToken'), - 'uid': sessionStorage.getItem('@portalmec/uid'), - 'If-None-Match': null - }, - }).then(response => { - if (response.status === 201) - setFollowing(true); - else if (response.status === 200) - setFollowing(false); - SaveNewHeaders(response) - }) + putRequest(url, {}, handleSuccessfulFollow, (error) => {console.log(error)}) } else { - const url = apiUrl + '/collections/' + props.collection_id + '/follow'; - setVariant("outlined"); - setButtonText("Seguir Coleção"); - setIcon(<AddIcon fontSize="large" />); - setFollowing(false); - axios({ - method: 'put', - url: url, - headers: { - 'Accept': 'application/json', - 'Content-Type': 'application/json; charset=utf-8', - 'access-token': sessionStorage.getItem('@portalmec/accessToken'), - 'client': sessionStorage.getItem('@portalmec/clientToken'), - 'uid': sessionStorage.getItem('@portalmec/uid'), - 'If-None-Match': null - }, - }).then(response => { - if (response.status === 201) - setFollowing(true); - else if (response.status === 200) - setFollowing(false); - SaveNewHeaders(response) - }) + putRequest(url, {}, handleSuccessfulUnfollow, (error) => {console.log(error)}) } }; diff --git a/src/Components/FormationMaterialDescription.js b/src/Components/FormationMaterialDescription.js index ab8b6b4a70dd32d649c8b49051b9355725ef53ff..5771aef3448785bc86fc45db7f65a3a10e353bdc 100644 --- a/src/Components/FormationMaterialDescription.js +++ b/src/Components/FormationMaterialDescription.js @@ -21,87 +21,84 @@ export default function FormationMaterialDescription(props) { const colecao_obj = props.colecao_obj; const topico_obj = props.topico_obj; - return ( + return ( <WrappingCard> <Grid container direction="row" justify="flex-start" alignItems="center" > - <Grid item xs={9}> - <HeightAdjustment> + <Grid item xs={12} md={8}> <TextContainer> <Title> - { colecao ? - "Sobre o Material" - : "Resumo do "+props.colecao_obj.topic_name.slice(0, -1) + {colecao ? + "Sobre o Material" + : "Resumo do " + props.colecao_obj.topic_name.slice(0, -1) } </Title> <Description> - { colecao ? + {colecao ? colecao_obj.description : topico_obj.description } </Description> - { colecao ? - <SubTitle>Histórico do Curso</SubTitle> - : <Strong>Autoria (autores):</Strong> - } + {colecao ? + <SubTitle>Histórico do Curso</SubTitle> + : <Strong>Autoria (autores):</Strong> + } <Description> - { colecao ? + {colecao ? colecao_obj.historic : topico_obj.author } </Description> </TextContainer> - </HeightAdjustment> </Grid> - <Grid item xs={3}> - <HeightAdjustment> + <Grid item xs={12} md={3}> <IconList> <IconItem> - <LibraryBooksIcon/> + <LibraryBooksIcon /> <Strong>Tipo de recurso: </Strong> Material de Formação - <br/> + <br /> </IconItem> <IconItem> - <MoveToInboxIcon/> + <MoveToInboxIcon /> <Strong>Ano de publicação: </Strong> - { colecao ? + {colecao ? colecao_obj.created_at.split('-')[0] : topico_obj.created_at.split('-')[0] } - <br/> + <br /> </IconItem> - { [0, 1, 2].map(i => { - const content = colecao ? - (colecao_obj.language[i] ? - colecao_obj.language[i].name - : '') - : (topico_obj.language[i] ? - topico_obj.language[i].name - : '') - return ( - <IconItem> - <TranslateIcon/> - <Strong>Idioma: </Strong> - { content } - <br/> - </IconItem> - ); - })} + {[0, 1, 2].map(i => { + const content = colecao ? + (colecao_obj.language[i] ? + colecao_obj.language[i].name + : '') + : (topico_obj.language[i] ? + topico_obj.language[i].name + : '') + return ( + <IconItem> + <TranslateIcon /> + <Strong>Idioma: </Strong> + {content} + <br /> + </IconItem> + ); + })} <IconItem> - <Strong>{ colecao ? "Criado" : "Enviado" } por:</Strong> - <br/> + <Strong>{colecao ? "Criado" : "Enviado"} por:</Strong> + <br /> <StyledAnchor href={colecao_obj.developedurl}> { - colecao_obj.id === 3 ? <LongUserIcon src="img/logo_parceiros/ic_peninsula.png" /> - : <div> - <UserIcon src="img/logo_parceiros/ic_nute.png"/> + colecao_obj.id === 3 ? <LongUserIcon src={require("../img/logo_parceiros/ic_peninsula.png")} /> + : <div> + <UserIcon src={require("../img/logo_parceiros/ic_nute.png")} /> <Red> {colecao_obj.developed} </Red> @@ -110,67 +107,76 @@ export default function FormationMaterialDescription(props) { </StyledAnchor> </IconItem> </IconList> - </HeightAdjustment> </Grid> </Grid> </WrappingCard> - ); + ); } -const Title=styled.h1` +const Title = styled.h1` font-weight: 100; color: rgb(102, 102, 102); ` -const SubTitle=styled.h3` +const SubTitle = styled.h3` font-weight: 900; padding-top: 10px; color: rgb(102, 102, 102); ` -const UserIcon=styled.img` +const UserIcon = styled.img` width: 50px; height: 50px; border-radius: 100px; margin: 10px 5px 10px 10px; ` -const LongUserIcon=styled.img` +const LongUserIcon = styled.img` width: 90px; margin: 10px; ` -const Description=styled.p` +const Description = styled.p` color: #666; ` -const TextContainer=styled.div` +const TextContainer = styled.div` margin: 15px; height: 100%; - border-right: solid 1px #e5e5e5; -` -const HeightAdjustment=styled.div` - height: 450px; + @media screen and (max-width: 768px) { + border-bottom: solid 1px #e5e5e5; + padding : 0 0 10px 0 + } + @media screen and (max-width: 990px) { + border-bottom: solid 1px #e5e5e5; + padding : 0 0 10px 0 + } + @media screen and (min-width: 992px) { + border-right: solid 1px #e5e5e5; + padding : 0 15px 0 0 + + } + @media screen and (min-width: 1200px) { + border-right: solid 1px #e5e5e5; + padding : 0 15px 0 0 + } ` -const WrappingCard=styled(Card)` + +const WrappingCard = styled(Card)` border-radius: 0; - height: 500px !important; margin-right : auto; margin-left : auto; margin-bottom: 30px; @media screen and (max-width: 768px) { width : 100% !important; - height: 600px !important; } @media screen and (min-width: 992px) { width : 770px; - height: 600px !important; } @media screen and (min-width: 1200px) { width : 970px !important; - height: 600px !important; } ` -const IconList=styled.div` - margin-top: 50px; +const IconList = styled.div` + margin: 15px; ` -const IconItem=styled.span` +const IconItem = styled.span` width: 100%; display: inline-block; margin-bottom: 15px; @@ -185,18 +191,15 @@ const IconItem=styled.span` vertical-align: middle } - span { - margin-left : 2%; - } ` -const Strong=styled.span` +const Strong = styled.span` font-weight: bold; color: #666; ` -const Red=styled.span` +const Red = styled.span` color: #e81f4f; ` -const StyledAnchor=styled.a` +const StyledAnchor = styled.a` text-decoration: none !important; color: inherit !important; ` diff --git a/src/Components/FormationMaterialHeader.js b/src/Components/FormationMaterialHeader.js index 03a81692c80016028802bb1005eeebd15ca85b14..0c49772337828e81ec2ccfb9b045d3cb4f7ef2b9 100644 --- a/src/Components/FormationMaterialHeader.js +++ b/src/Components/FormationMaterialHeader.js @@ -4,119 +4,131 @@ import styled from 'styled-components' import Grid from '@material-ui/core/Grid'; import Card from '@material-ui/core/Card'; import Button from '@material-ui/core/Button'; +import Chip from '@material-ui/core/Chip'; +import { makeStyles } from '@material-ui/core/styles'; + +const useStyles = makeStyles((theme) => ({ + root: { + display: 'flex', + flexWrap: 'wrap', + '& > *': { + margin: theme.spacing(0.5), + }, + }, +})); + export default function FormationMaterialHeader(props) { const colecao = props.colecao; const colecao_obj = props.colecao_obj; const topico_obj = props.topico_obj; + const classes = useStyles(); + const get_title = () => { return colecao ? - colecao_obj.name - : (topico_obj.pre_title + topico_obj.title); + colecao_obj.name + : (topico_obj.pre_title + topico_obj.title); } const get_subtitle = () => { return colecao ? - colecao_obj.topics.length+' '+colecao_obj.topic_name - : colecao_obj.name; + colecao_obj.topics.length + ' ' + colecao_obj.topic_name + : colecao_obj.name; } - return ( + const getThumb = () => { + return colecao ? + require(`../../public/${colecao_obj.img}`) + : require(`../../public/${topico_obj.img}`) + } + + return ( <WrappingCard> - <Grid container - direction="row" + <Grid container + direction="row" + justify="flex-start" + alignItems="stretch" + > + <Grid item xs={12} lg={5}> + <Img src={getThumb()} /> + </Grid> + <Grid item xs={12} lg={7} + direction="column" justify="flex-start" alignItems="stretch" + style={{ padding: "8px 10px" }} > - <Grid item xs={5}> - <Img src={colecao_obj.img}/> + <Grid item> + <Title>{get_title()}</Title> + </Grid> + <Grid item> + <SubTitle> + {colecao ? + get_subtitle() + : <StyledLink to={'/colecao?id=' + colecao_obj.id}>{get_subtitle()}</StyledLink>} + </SubTitle> </Grid> - <Grid item container xs={7} - direction="column" - justify="flex-start" - alignItems="stretch" - > - <Grid item> - <Title>{get_title()}</Title> - </Grid> - <Grid item> - <SubTitle> - { colecao ? - get_subtitle() - : <StyledLink to={'/colecao?id='+colecao_obj.id}>{get_subtitle()}</StyledLink> } - </SubTitle> - </Grid> - <Grid item> - <TagList> - {colecao_obj.tags.map((t) => { - return (<Badge>{t.name}</Badge>); - })} - </TagList> - </Grid> - <Grid item> - { colecao ? - <Button - variant="contained" - color="secondary" - style={{marginLeft: '15px'}} - onClick={props.handleClick} - > - { props.colecao ? "Ver todos os módulos" : "Iniciar leitura" } - </Button> - : - <StyledLink to={'/iframe-colecao?colecao='+colecao_obj.id+'&topico='+topico_obj.id}> - <Button - variant="contained" - color="secondary" - style={{marginLeft: '15px'}} - onClick={props.handleClick} - > - { props.colecao ? "Ver todos os módulos" : "Iniciar leitura" } - </Button> - </StyledLink> - } - </Grid> + <Grid item> + <ChipsDiv className={classes.root}> + {colecao_obj.tags.map((t, index) => { + return (<Chip color="default" label={t.name} key={index} style={{ padding: "0.5px" }} />); + })} + </ChipsDiv> + </Grid> + <Grid item> + {colecao ? + <Button + variant="contained" + color="secondary" + style={{ marginLeft: '15px' }} + onClick={props.handleClick} + > + {props.colecao ? "Ver todos os módulos" : "Iniciar leitura"} + </Button> + : + <StyledLink to={'/iframe-colecao?colecao=' + colecao_obj.id + '&topico=' + topico_obj.id}> + <Button + variant="contained" + color="secondary" + style={{ marginLeft: '15px', marginTop: '10px' }} + onClick={props.handleClick} + > + {props.colecao ? "Ver todos os módulos" : "Iniciar leitura"} + </Button> + </StyledLink> + } </Grid> </Grid> + </Grid> </WrappingCard> - ); + ); } -const Badge=styled.span` - background-color: #e5e5e5; - color: #666; - border-radius: 15px; - margin-left: 5px; - padding: 3px 7px; - line-height: 1.2em; - font-size: 0.7em; - display: inline-block; -` -const TagList=styled.div` +const ChipsDiv = styled.div` margin-bottom: 10px; width: 100%; margin-left: 10px; ` -const Img=styled.img` - max-width: 100%; +const Img = styled.img` + width: 100%; + height: 100%; + display: block; /* remove extra space below image */ background-color: #e5e5e5; - display: inline-block; ` -const Title=styled.h1` +const Title = styled.h2` font-weight: 100; margin: 15px; color: rgb(102, 102, 102); ` -const SubTitle=styled.h3` - font-weight: 100; +const SubTitle = styled.h4` + font-weight: 50; margin: 15px;; margin-top: 0; color: rgb(102, 102, 102); ` -export const WrappingCard=styled(Card)` +export const WrappingCard = styled(Card)` border-radius: 0; - height: 250px !important; margin-right : auto; margin-left : auto; margin-bottom: 30px; @@ -132,7 +144,8 @@ export const WrappingCard=styled(Card)` width : 970px !important; } ` + const StyledLink = styled(Link)` text-decoration: none !important; - color: inherit !important; + color: #e81f4f !important; ` diff --git a/src/Components/GuardarModal.js b/src/Components/GuardarModal.js index 8d4fc7ff48724e4bedf559b41cef9d8c555bf48b..3a231ac260b33ab13c140f17acb59693910e7817 100644 --- a/src/Components/GuardarModal.js +++ b/src/Components/GuardarModal.js @@ -23,14 +23,14 @@ import Backdrop from '@material-ui/core/Backdrop'; import Fade from '@material-ui/core/Fade'; import styled from 'styled-components' import {Store} from '../Store.js' -import axios from 'axios' -import {apiUrl, apiDomain} from '../env'; +import {apiDomain} from '../env'; import CloseIcon from '@material-ui/icons/Close'; import PublicIcon from '@material-ui/icons/Public'; import LockIcon from '@material-ui/icons/Lock'; import LoadingSpinner from './LoadingSpinner.js' import CriarColecaoForm from './CriarColecaoForm.js' import SnackbarComponent from './SnackbarComponent' +import {getRequest, postRequest} from './HelperFunctions/getAxiosConfig' function CloseModalButton (props) { return ( @@ -40,60 +40,42 @@ function CloseModalButton (props) { ) } -function getConfig () { - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid') - } - } - return config -} - export default function ReportModal (props) { const {state} = useContext(Store) const [collsArr, setcolls] = useState([]) const [loading, toggleLoading] = useState(true) const [creatingCol, setCreating] = useState(false) + + function handleSuccessGetCols (data) { + setcolls(data) + toggleLoading(false) + } const getCols = () => { if (collsArr.length === 0) { const id = state.currentUser.id - const config = getConfig() - - axios.get( (`${apiUrl}/users/` + id + '/collections'), config - ).then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - setcolls(response.data) - toggleLoading(false) - }, (error) => {console.log('error')}) + + const url = `/users/${id}/collections/` + + getRequest(url, handleSuccessGetCols, (error) => {console.log('error')}) } } + + function handleSuccessPostToCol (data) { + toggleSnackbar(true) + setCreating(false) + props.handleClose() + } const postToCol = (colId) => { - const config = getConfig() + const url = `/collections/${colId}/items` const payload = { "collection" : { "items" : [ {"id":props.recursoId, "type":"LearningObject"} ] } } + postRequest( url, payload, handleSuccessPostToCol, (error) => {console.log(error)}) - axios.post( (`${apiUrl}/collections/` + colId + '/items'), payload, config - ).then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - toggleSnackbar(true) - setCreating(false) - props.handleClose() - }, (error) => {console.log(error)}) } const [snackbarOpen, toggleSnackbar] = useState(false) diff --git a/src/Components/Header.js b/src/Components/Header.js index 14025e28280949a3f8d37107cf49dc74d057e6e5..a0eb0c727f385d59854a25bc5aac5d91b41a1f11 100644 --- a/src/Components/Header.js +++ b/src/Components/Header.js @@ -17,8 +17,6 @@ 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, { useContext, useState, useEffect } from 'react' -import axios from 'axios' -import {apiUrl} from '../env' import MenuBar from './MenuBar' import SearchBar from './SearchBar' import SignUpModal from './SignUpModal' @@ -27,15 +25,16 @@ import { Store } from '../Store'; import ColaborarModal from './ColaborarModal.js' import Snackbar from '@material-ui/core/Snackbar'; import MuiAlert from '@material-ui/lab/Alert'; -import {useLocation} from 'react-router-dom' +import { useLocation } from 'react-router-dom' import MenuBarMobile from './MenuBarMobile.js' +import {validateGoogleLoginToken} from './HelperFunctions/getAxiosConfig' //const StyledButton = styled(Button)` // background : #ffa54c !important; // boxShadow :none; //` function Alert(props) { - return <MuiAlert elevation={6} variant="filled" {...props} />; + return <MuiAlert elevation={6} variant="filled" {...props} />; } @@ -46,47 +45,41 @@ export default function Header(props){ const [successfulLoginOpen, handleSuccessfulLogin] = useState(false) const [modalColaborar, setModalColaborar] = useState(false) - const validateToken = (config) => { - axios.get(`${apiUrl}/auth/validate_token/`, config).then( - (response) => { - console.log(response.data) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - dispatch ({ - type: "USER_LOGGED_IN", - userLoggedIn: !state.userIsLoggedIn, - login: response.data.data - } - ) - - sessionStorage.setItem('@portalmec/id', response.data.data.id) - sessionStorage.setItem('@portalmec/username', response.data.data.name) - sessionStorage.setItem('@portalmec/uid', response.data.data.uid) - - - let headers = { - client:response.headers.client, - "access-token":response.headers['access-token'], - "token-type": "Bearer", - expiry:response.headers.expiry, - uid:response.data.data.uid - } - sessionStorage.setItem('@portalmec/auth_headers', JSON.stringify(headers)) - }, - (err) => { - console.log(err) + function handleSuccessValidateToken (data) { + dispatch ({ + type: "USER_LOGGED_IN", + userLoggedIn: !state.userIsLoggedIn, + login: data.data } - ) + ) } - useEffect( () => { +/* useEffect( () => { if (sessionStorage.getItem('@portalmec/auth_headers')) { let config = { headers : JSON.parse(sessionStorage.getItem('@portalmec/auth_headers'))} - validateToken(config) + validateToken(config, handleSuccessValidateToken, (error) => {console.log(error)}) + } + }, [])*/ + + let loc = useLocation() + useEffect(() => { + let query = new URLSearchParams(loc.search) + + if(query.get("auth_token")) { + let config = { + headers : { + "access-token" : query.get("auth_token"), + "client" : query.get("client_id"), + "uid" : query.get("uid"), + "expiry" : query.get("expiry"), + "token-type" : 'Bearer' + } + } + validateGoogleLoginToken(config, handleSuccessValidateToken, (error) => {console.log(error)}) + redirect() } - }, []) + }, [loc]) useEffect ( () => { if (state.currentUser.askTeacherQuestion === true) { @@ -101,26 +94,6 @@ export default function Header(props){ props.history.push('/') } - let loc = useLocation() - useEffect(() => { - let query = new URLSearchParams(loc.search) - - console.log(query.getAll("auth_token")) - if(query.get("auth_token")) { - let config = { - headers : { - "access-token" : query.get("auth_token"), - "client" : query.get("client_id"), - "uid" : query.get("uid"), - "expiry" : query.get("expiry"), - "token-type" : 'Bearer' - } - } - validateToken(config) - redirect() - } - }, [loc]) - const toggleSnackbar = (event, reason) => { if (reason === 'clickaway') { return; @@ -152,32 +125,32 @@ export default function Header(props){ windowWidth > 990 && <AcessibilityBar/> */} - <Snackbar open={successfulLoginOpen} autoHideDuration={1000} onClose={toggleSnackbar} - anchorOrigin = {{ vertical:'top', horizontal:'center' }} - > - <Alert severity="success" style={{backgroundColor:"#00acc1"}}>Você está conectado(a)!</Alert> - </Snackbar> - { - windowWidth > 990 ? - ( - <React.Fragment> - <MenuBar openSearchBar={handleClickSearch} openSignUp = {handleSignUp} openLogin = {handleLogin}/> - { - state.searchOpen && - <SearchBar/> - } - </React.Fragment> - - ) - : - ( - <MenuBarMobile openSignUp = {handleSignUp} openLogin = {handleLogin}/> - ) - } - <SignUpModal open={signUpOpen} handleClose={handleSignUp} openLogin={handleLogin}/> - <LoginModal open={loginOpen} handleClose={() => setLogin(false)} openSignUp={handleSignUp} - openSnackbar={() => {handleSuccessfulLogin(true)}}/> - <ColaborarModal open={modalColaborar} handleClose={() => {setModalColaborar(!modalColaborar)}} /> - </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> + { + windowWidth > 990 ? + ( + <React.Fragment> + <MenuBar openSearchBar={handleClickSearch} openSignUp={handleSignUp} openLogin={handleLogin} /> + { + state.searchOpen && + <SearchBar /> + } + </React.Fragment> + + ) + : + ( + <MenuBarMobile openSignUp={handleSignUp} openLogin={handleLogin} /> + ) + } + <SignUpModal open={signUpOpen} handleClose={handleSignUp} openLogin={handleLogin} /> + <LoginModal open={loginOpen} handleClose={() => setLogin(false)} openSignUp={handleSignUp} + openSnackbar={() => { handleSuccessfulLogin(true) }} /> + <ColaborarModal open={modalColaborar} handleClose={() => { setModalColaborar(!modalColaborar) }} /> + </React.Fragment> + ) } diff --git a/src/Components/HelpCenter/Cards/CardEncontrando.js b/src/Components/HelpCenter/Cards/CardEncontrando.js index f989352e13a40ded76308ec44c830f27d0ec0080..173f179d24445dcc8aebdab0ef5ab7bfb59d3eda 100644 --- a/src/Components/HelpCenter/Cards/CardEncontrando.js +++ b/src/Components/HelpCenter/Cards/CardEncontrando.js @@ -75,7 +75,7 @@ const CardAjuda = styled.div` height: 360px; margin-bottom: 20px; - + width: 100% .card { height: 280px; @@ -84,7 +84,7 @@ const CardAjuda = styled.div` font-size: 14px; background-color:#fff; box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); - + margin-top:30px h3 { font-size: 23px; font-weight: 400; diff --git a/src/Components/HelpCenter/Cards/CardGerenciando.js b/src/Components/HelpCenter/Cards/CardGerenciando.js index 3cc9506ab3f75de0f0ee1d8298fa714e6a07f6c4..d3e1daa3299815d50e1c948ce1810d172d49c9ae 100644 --- a/src/Components/HelpCenter/Cards/CardGerenciando.js +++ b/src/Components/HelpCenter/Cards/CardGerenciando.js @@ -93,7 +93,7 @@ const CardAjuda = styled.div` height: 360px; margin-bottom: 20px; - + width: 100% .card { height: 280px; @@ -102,6 +102,7 @@ const CardAjuda = styled.div` font-size: 14px; background-color:#fff; box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); + margin-top:30px h3 { font-size: 23px; diff --git a/src/Components/HelpCenter/Cards/CardParticipando.js b/src/Components/HelpCenter/Cards/CardParticipando.js index 9dfdbf1a8c0553adc760fc14bf3fd27dcd76f1d0..5091e9908cf3a52399f0ce08907601f24b93618a 100644 --- a/src/Components/HelpCenter/Cards/CardParticipando.js +++ b/src/Components/HelpCenter/Cards/CardParticipando.js @@ -66,7 +66,8 @@ const CardAjuda = styled.div` height: 360px; margin-bottom: 20px; - + width: 100% + .card { height: 280px; @@ -75,6 +76,8 @@ const CardAjuda = styled.div` font-size: 14px; background-color:#fff; box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); + margin-top:30px + h3 { font-size: 23px; diff --git a/src/Components/HelpCenter/Cards/CardPublicando.js b/src/Components/HelpCenter/Cards/CardPublicando.js index 673c7d153a5ae2fe6e75f0fd21b3739d17a5cba3..c5fb0a3ff925d87a602f30ff467daf95182bc8b9 100644 --- a/src/Components/HelpCenter/Cards/CardPublicando.js +++ b/src/Components/HelpCenter/Cards/CardPublicando.js @@ -74,7 +74,7 @@ const CardAjuda = styled.div` height: 360px; margin-bottom: 20px; - +width: 100% .card { height: 280px; @@ -83,7 +83,7 @@ margin-bottom: 20px; font-size: 14px; background-color:#fff; box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); - + margin-top:30px h3 { font-size: 23px; font-weight: 400; diff --git a/src/Components/FormValidationFunction.js b/src/Components/HelperFunctions/FormValidationFunction.js similarity index 100% rename from src/Components/FormValidationFunction.js rename to src/Components/HelperFunctions/FormValidationFunction.js diff --git a/src/Components/HelperFunctions/getAxiosConfig.js b/src/Components/HelperFunctions/getAxiosConfig.js index 63a4ff6e53a5e6763eafdc8d0146f1c426c8ec00..7841d441bbf4c7085d8b965fe76f0d17863dbf99 100644 --- a/src/Components/HelperFunctions/getAxiosConfig.js +++ b/src/Components/HelperFunctions/getAxiosConfig.js @@ -1,14 +1,257 @@ +import {apiUrl} from '../../env.js' +import axios from 'axios' -export const getAxiosConfig = () => { +export function getAxiosConfigFromJSON () { let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', + headers : JSON.parse(sessionStorage.getItem('@portalmec/auth_headers')) + } + return config +} + +export function updateHeaders (newHeaders) { + + sessionStorage.setItem('@portalmec/accessToken', newHeaders['access-token']) + + let auth_headers = JSON.parse(sessionStorage.getItem('@portalmec/auth_headers')) + if (auth_headers) { + auth_headers['access-token'] = newHeaders['access-token'] + } + else { + auth_headers = { + client: newHeaders.client, + "access-token": newHeaders['access-token'], + uid: newHeaders.uid, + expiry: newHeaders.expiry, + "token-type": "Bearer" } } - config.headers["Access-Token"] = sessionStorage.getItem('@portalmec/accessToken'); - config.headers.Client = sessionStorage.getItem('@portalmec/clientToken') - config.headers.Uid = sessionStorage.getItem('@portalmec/uid') + sessionStorage.setItem('@portalmec/auth_headers', JSON.stringify(auth_headers)) +} + +function fetchHeaders () { + let auth_headers = JSON.parse(sessionStorage.getItem('@portalmec/auth_headers')) + + if (auth_headers) { + const myHeaders = new Headers(auth_headers) + return myHeaders + } + else { + return {} + } +} + +function checkPreviousTokens (new_token) { + + let prev_tokens = JSON.parse(sessionStorage.getItem('@portalmec/tokens')) + + if (prev_tokens) { + if (!prev_tokens.hasOwnProperty(new_token)) { + prev_tokens[new_token] = 1 + sessionStorage.setItem('@portalmec/tokens', JSON.stringify(prev_tokens)) + return true + } + else { + return false + } + } + else { + let tokens = {} + tokens[new_token] = 1 + sessionStorage.setItem('@portalmec/tokens', JSON.stringify(tokens)) + return true + } + +} + +function updateAccessToken (newAccessToken) { + + if (checkPreviousTokens(newAccessToken)) { + + sessionStorage.setItem('@portalmec/accessToken', newAccessToken) + + let auth_headers = JSON.parse(sessionStorage.getItem('@portalmec/auth_headers')) + + if (auth_headers) { + auth_headers['access-token'] = newAccessToken + } + + sessionStorage.setItem('@portalmec/auth_headers', JSON.stringify(auth_headers)) + } +} + +export const getRequest = (url, onSuccess, onError) => { + fetch((`${apiUrl}${url}`), { + headers : fetchHeaders() + }) + .then(response => { + if (response.headers.has('access-token')) { + updateAccessToken(response.headers.get('access-token')) + } + return response.json().catch(err => { + return {}; + }) + }) + .then(data => { + console.log(data) + onSuccess(data) + }) + .catch(error => { + onError(error) + }) +} + +export const deleteRequest = (url, onSuccess, onError) => { + fetch((`${apiUrl}${url}`), { + method : 'DELETE', + headers : fetchHeaders() + }) + .then(response => { + if (response.headers.has('access-token')) { + updateAccessToken(response.headers.get('access-token')) + } + return response.json().catch(err => { + return {}; + }) + }) + .then(data => { + console.log(data) + onSuccess(data) + }) + .catch(error => { + onError(error) + }) +} + +export const putRequest = (url, payload, onSuccess, onError) => { + let newHeaders = fetchHeaders() + if (payload instanceof FormData) { + newHeaders.append('Content-Type', 'multipart/form-data') + } + else { + newHeaders.append('Content-Type', 'application/json') + } + + fetch((`${apiUrl}${url}`), { + method : 'PUT', + headers : newHeaders, + body: payload instanceof FormData ? payload : JSON.stringify(payload) + }) + .then(response => { + if (response.headers.has('access-token')) { + updateAccessToken(response.headers.get('access-token')) + } + return response.json().catch(err => { + return {}; + }) + }) + .then(data => { + console.log(data) + onSuccess(data) + }) + .catch(error => { + onError(error) + }) +} + +export const postRequest = (url, payload, onSuccess, onError) => { + let newHeaders = fetchHeaders() + if (payload instanceof FormData) { + newHeaders.append('Content-Type', 'multipart/form-data') + } + else { + newHeaders.append('Content-Type', 'application/json') + } + + fetch((`${apiUrl}${url}`), { + method : 'POST', + headers : newHeaders, + body: payload instanceof FormData ? payload : JSON.stringify(payload) + }) + .then(response => { + if (response.headers.has('access-token')) { + updateAccessToken(response.headers.get('access-token')) + } + return response.json().catch(err => { + return {}; + }) + }) + .then(data => { + console.log(data) + onSuccess(data) + }) + .catch(error => { + onError(error) + }) +} + +export const fetchAllRequest = (urls, onSuccess, onError) => { + Promise.all( urls.map( url => fetch(`${apiUrl}${url}`, { + headers : fetchHeaders() + }))).then( (responses) => { + for(let res of responses) { + console.log(res) + if (res.headers.has('access-token') && res.status !== 304) { + console.log(res) + updateAccessToken(res.headers.get('access-token')) + } + } + return Promise.all(responses.map( (response) => response.json().catch(err => { + return {}; + }))) + }).then( (data) => { + onSuccess(data) + }).catch((error) => { + onError(error) + }) +} + +export const validateGoogleLoginToken = (config, onSuccess, onError) => { + axios.get( (`${apiUrl}/auth/validate_token/`), config ).then( + (response) => { + + if ( response.headers['access-token'] ) { + updateHeaders(response.headers) + } + + onSuccess(response.data) + }, + (error) => { + onError(error) + } + ) +} + +export const authentication = (url, payload, onSuccess, onError) => { + let formData = new FormData() + for (const [key, value] of Object.entries(payload)) { + formData.append(`${key}`,value); + } + + fetch((`${apiUrl}${url}`), { + method : 'POST', + body: formData + }) + .then(response => { + const auth_headers = { + client: response.headers.get('client'), + "access-token": response.headers.get('access-token'), + uid: response.headers.get('uid'), + expiry: response.headers.get('expiry'), + "token-type": "Bearer" + } + + sessionStorage.setItem('@portalmec/auth_headers', JSON.stringify(auth_headers)) + + return response.json().catch(err => { + return {}; + }) + }) + .then(data => { + console.log(data) + onSuccess(data) + }) + .catch(error => { + onError(error) + }) - return config } diff --git a/src/Components/HelperFunctions/saveTokens.js b/src/Components/HelperFunctions/saveTokens.js new file mode 100644 index 0000000000000000000000000000000000000000..15b89b05f5779c53cfdd209a8e33418e3074b944 --- /dev/null +++ b/src/Components/HelperFunctions/saveTokens.js @@ -0,0 +1,6 @@ +export const saveHeaders = (response) => { + if (response.headers['access-token']) + sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) + if (response.headers.client) + sessionStorage.setItem('@portalmec/clientToken', response.headers.client) +} \ No newline at end of file diff --git a/src/Components/IframeOverlay/DrawerContent.js b/src/Components/IframeOverlay/DrawerContent.js index 8bd7e483f68d011d783a7f944cfd9e96872cce71..38907d688fab7632769096ecf825394c7c817573 100644 --- a/src/Components/IframeOverlay/DrawerContent.js +++ b/src/Components/IframeOverlay/DrawerContent.js @@ -1,21 +1,24 @@ import React, { useState, useEffect } from 'react'; import styled from 'styled-components'; -import axios from 'axios'; import Grid from '@material-ui/core/Grid'; import SearchInput from './SearchInput.js'; import ResourceCard from './ResourceCard.js'; -import { apiUrl } from '../../env'; import SmallFooter from './SmallFooter.js'; +import CircularProgress from '@material-ui/core/CircularProgress'; +import {getRequest} from '../HelperFunctions/getAxiosConfig' export default function DrawerContent(props) { const [resources, setResources] = useState([]); + const [isLoading, setIsLoading] = useState(false); + function handleSuccess(data) { + setResources(data) + } const search = (query) => { - axios.get(`${apiUrl}/search? - page=0&results_per_page=5&query=${query}&search_class=LearningObject`) - .then(res => { - setResources(res.data); - }); + const url = `/search? + page=0&results_per_page=5&query=${query}&search_class=LearningObject` + + getRequest(url, handleSuccess, (error) => {console.log(error)}) } useEffect(() => { @@ -34,19 +37,24 @@ export default function DrawerContent(props) { > <Grid item xs={11}> <SearchInput stdin={props.tag} search={search}/> - </Grid> + </Grid> <Grid item xs={11}> <Description> Recursos Relacionados na Plataforma MEC: </Description> </Grid> - {resources.map(r => { + + { + isLoading ? <CircularProgress style={{color : 'white'}}/> + : + resources.map((r, index) => { return( - <Grid item xs={11}> + <Grid item xs={11} key={index}> <ResourceCard id={r.id} name={r.name} likes={r.likes_count} + thumb={r.thumbnail} /> </Grid> );} diff --git a/src/Components/IframeOverlay/ResourceCard.js b/src/Components/IframeOverlay/ResourceCard.js index 57f2b5be670911f2f5916362409e1b087867d10e..365ea9a3d6574cd63503c060bf94d08308be7748 100644 --- a/src/Components/IframeOverlay/ResourceCard.js +++ b/src/Components/IframeOverlay/ResourceCard.js @@ -6,10 +6,17 @@ import Grid from '@material-ui/core/Grid'; import WhiteAreaOfCard from './WhiteAreaOfCard.js'; export default function ResourceCard(props) { + + const getThumb = () => { + return props.thumb ? + `https://api.portalmec.c3sl.ufpr.br${props.thumb}` + : require('../../img/laranja/IMAGEM.jpg'); + + } + return( <Anchor - to={'/recurso?id='+props.id - +'&name='+props.name} + to={'/recurso/'+props.id} > <CardPaper elevation={3}> <Grid container @@ -18,7 +25,7 @@ export default function ResourceCard(props) { alignItems="center" > <Grid item> - <Img src="https://api.portalmec.c3sl.ufpr.br/system/learning_objects/thumbnails/000/032/128/original/1427119781385_thumb_w300_h160.jpg?1544253610" /> + <Img src={getThumb()} /> </Grid> <Grid item> <WhiteAreaOfCard name={props.name} likes={props.likes} /> diff --git a/src/Components/IframeOverlay/SearchInput.js b/src/Components/IframeOverlay/SearchInput.js index f201d3143be7501aa4631ecacdecfd972a985130..3fd246cb70a501f5d0c091df2e133ce8c2ac3f80 100644 --- a/src/Components/IframeOverlay/SearchInput.js +++ b/src/Components/IframeOverlay/SearchInput.js @@ -5,6 +5,8 @@ import IconButton from '@material-ui/core/IconButton'; import OutlinedInput from '@material-ui/core/OutlinedInput'; import InputAdornment from '@material-ui/core/InputAdornment'; import FormControl from '@material-ui/core/FormControl'; +import Divider from '@material-ui/core/Divider'; +import CloseRoundedIcon from '@material-ui/icons/CloseRounded'; export default function SearchInput(props) { const [text, setText] = useState(props.stdin); @@ -17,31 +19,56 @@ export default function SearchInput(props) { props.search(text); } + const handleCleanInput = () => { + setText(""); + } + + const handleKeyUp = (event) => { + if (event.key === "Enter") + handleClickSearch() + } + return ( <Wrapper> - <FormControl variant="outlined" style={{width: '100%'}}> + <FormControl variant="outlined" style={{ width: '100%' }}> <OutlinedInput type="text" value={text} + placeholder="O quê você está buscando?" onChange={handleChange} + onKeyUp={handleKeyUp} endAdornment={ - <InputAdornment position="end"> - <IconButton - onClick={handleClickSearch} - edge="end" - > - <SearchIcon /> - </IconButton> - </InputAdornment> + <> + <InputAdornment position="end"> + <IconButton + onClick={handleCleanInput} + edge="end" + > + <CloseRoundedIcon /> + </IconButton> + </InputAdornment> + <SizedWidhtBox /> + <Divider orientation="vertical" flexItem /> + <InputAdornment position="end"> + <IconButton + onClick={handleClickSearch} + edge="end" + > + <SearchIcon style={{ fill: "#00bcd4" }} /> + </IconButton> + </InputAdornment> + </> } /> </FormControl> </Wrapper> ); } -const Wrapper=styled.div` +const Wrapper = styled.div` background-color: white; border-radius: 5px; margin: 20px; - +` +const SizedWidhtBox = styled.div` + margin-right : 22px; ` diff --git a/src/Components/IllegalContentModal.js b/src/Components/IllegalContentModal.js index 135270c2fbbb96658225e24962830f5f6e1c1c50..976bb5d8728791502ced2db51534bf6b4cc5b703 100644 --- a/src/Components/IllegalContentModal.js +++ b/src/Components/IllegalContentModal.js @@ -81,24 +81,12 @@ const StyledDivContainer = styled.div` export default function IllegalContentModal (props) { const {state} = useContext(Store) - // const func = () => { - // let name = '' - // axios.get(`${apiUrl}/users/:id`,{ - // - // } - // ).then ( (response) => { - // name = response.name - // }, (error) => { - // console.log(':(') - // }) - // } - return ( <StyledModal aria-labelledby="transition-modal-title" aria-describedby="transition-modal-description" open={props.open} - + centered="true" onClose={props.handleClose} closeAfterTransition diff --git a/src/Components/LoginContainerFunction.js b/src/Components/LoginContainerFunction.js index 33b7ff15dd065bfb9df5f1beed06701286107f7f..8534da0ad3bbe1154612b62b1eeff24f4f26cbfc 100644 --- a/src/Components/LoginContainerFunction.js +++ b/src/Components/LoginContainerFunction.js @@ -25,7 +25,7 @@ import {device} from './device.js' import LabeledCheckbox from './Checkbox.js' import FormInput from "./FormInput.js" import GoogleLogo from "../img/logo_google.svg" -import ValidateUserInput from '../Components/FormValidationFunction.js' +import ValidateUserInput from './HelperFunctions/FormValidationFunction.js' import {Link} from 'react-router-dom' import {apiUrl} from '../env.js' diff --git a/src/Components/LoginModal.js b/src/Components/LoginModal.js index 18b5e7e6fb67bf3a36a94de27f3e422132ec6495..b18ab1cc252bd0598aae745c41997bd67678c41d 100644 --- a/src/Components/LoginModal.js +++ b/src/Components/LoginModal.js @@ -23,10 +23,10 @@ import Zoom from '@material-ui/core/Fade'; import styled from 'styled-components' import LoginContainer from './LoginContainerFunction.js' import {Store} from '../Store.js' -import axios from 'axios' -import {apiUrl} from '../env'; import Snackbar from '@material-ui/core/Snackbar'; import MuiAlert from '@material-ui/lab/Alert'; +import {authentication} from './HelperFunctions/getAxiosConfig' + const StyledLogin = styled(Modal)` margin : 0 !important; margin-left : 0 !important; @@ -55,45 +55,36 @@ export default function LoginModal (props){ handleSnackbar(false); } + function renameKeys (obj) { + if (obj.avatar_file_name) { + Object.defineProperty(obj, 'avatar', + Object.getOwnPropertyDescriptor(obj, 'avatar_file_name')); + delete obj['avatar_file_name']; + } + } + + function handleSuccess (data) { + renameKeys(data.data) + dispatch ({ + type: "USER_LOGGED_IN", + userLoggedIn: !state.userIsLoggedIn, + login: data.data + } + ) + props.handleClose(); + props.openSnackbar(); + } + function handleError (error) { + handleSnackbar(true) + } const handleLoginInfo = (login) => { - axios.post(`${apiUrl}/auth/sign_in`, - { + const url = `/auth/sign_in` + const payload = { email : login.email, password : login.senha } - ).then( (response) => { - console.log(response) - dispatch ({ - type: "USER_LOGGED_IN", - userLoggedIn: !state.userIsLoggedIn, - login: response.data.data - } - ) - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - sessionStorage.setItem('@portalmec/clientToken', response.headers.client) - sessionStorage.setItem('@portalmec/id', response.data.data.id) - sessionStorage.setItem('@portalmec/username', response.data.data.name) - sessionStorage.setItem('@portalmec/uid', response.data.data.uid) - - let headers = { - client:response.headers.client, - "access-token":response.headers['access-token'], - "token-type": "Bearer", - expiry:response.headers.expiry, - uid:response.data.data.uid - } - sessionStorage.setItem('@portalmec/auth_headers', JSON.stringify(headers)) - - if (login.checkboxChecked) { - localStorage.setItem('@portalmec/auth_headers', JSON.stringify(headers)) - } - props.handleClose(); - props.openSnackbar(); - }, (error) => { - handleSnackbar(true) - } - ) + authentication(url, payload, handleSuccess, handleError) } @@ -123,6 +114,7 @@ export default function LoginModal (props){ /> </Zoom> </StyledLogin> + </> ) } diff --git a/src/Components/MaterialCard.js b/src/Components/MaterialCard.js index c5353a918fd0f5aafdf7b2e532c82cfa93cb4b85..33cf3d8ddccf32591fdb77753956331d3ec87b51 100644 --- a/src/Components/MaterialCard.js +++ b/src/Components/MaterialCard.js @@ -16,40 +16,102 @@ 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, {Component} from 'react'; +import React from 'react'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import CardActions from '@material-ui/core/CardActions'; import Typography from '@material-ui/core/Typography'; -import livro from "../img/laranja/LIVRO_DIGITAL.jpg"; import Library from '@material-ui/icons/LibraryBooks'; +import Rating from '@material-ui/lab/Rating'; +import StarBorderIcon from '@material-ui/icons/StarBorder'; +import Grid from '@material-ui/core/Grid'; +import styled from 'styled-components'; +import Button from '@material-ui/core/Button'; +import ExpandMoreRoundedIcon from '@material-ui/icons/ExpandMoreRounded'; +import {Link} from 'react-router-dom'; +export default function MaterialCard(props) { -class MaterialCard extends Component { - constructor(props) { - super(props); - this.state={ - thumbnail: livro, - }; - } - render(){ - return ( - <Card> - <img src={this.state.thumbnail} alt="thumbnail do recurso"/> - <CardContent style={{height: "60%", textAlign: "left", paddingBottom: "0px"}}> - <Typography variant="body2" color="textSecondary" component="p" style={{overflow: "hidden", fontSize: "0.8em"}}> - {this.props.name} - </Typography> - </CardContent> - <CardActions style={{justifyContent: "space-between"}}> - <Library style={{color:"#e81f4f"}} /> - </CardActions> - <CardActions style={{borderTop:"1px solid #e5e5e5", justifyContent: "space-between"}}> - <Typography>Expandir??</Typography> - </CardActions> - </Card> - );} - } - - -export default MaterialCard; + const thumb = require(`../../public/${props.thumb}`) + + const HandleButtonPressed = () => { + props.handleExpand(props.id); + } + + const width = window.innerWidth; + + return ( + <Card> + <img src={thumb} alt="thumbnail do recurso" /> + <CardContent style={{ height: "60px", textAlign: "left", paddingBottom: "0px", width: "100%" }}> + <Title> + {props.name} + </Title> + </CardContent> + <CardActions> + <Grid container direction="column" justify="flex-start" alignItems="flex-start" style={{ marginLeft: "5px" }}> + <Grid item> + <Rating + name="customized-empty" + value={props.score} + precision={0.5} + style={{ color: "#666" }} + emptyIcon={<StarBorderIcon fontSize="inherit" />} + readOnly + /> + </Grid> + <Grid container direction="row" alignItems="center"> + <Library style={{ color: "#e81f4f" }} /> + <SizedBox /> + <Typography variant="body2" color="textSecondary" component="p" style={{ overflow: "hidden", fontSize: "0.8em" }}> + {props.modules.length} módulos + </Typography> + </Grid> + </Grid> + </CardActions> + <CardActions style={{ borderTop: "1px solid #e5e5e5", justifyContent: "center" }}> + { + width <= 767 ? + <StyledLink to={`/colecao?colecao=${props.id}`}> + <Button + color="secondary" + endIcon={<ExpandMoreRoundedIcon />} + > + + Ver módulos + </Button> + </StyledLink> + : + <Button + color="secondary" + endIcon={<ExpandMoreRoundedIcon />} + onClick={HandleButtonPressed} + > + + Ver módulos + </Button> + } + </CardActions> + </Card > + ) +} + +const SizedBox = styled.div` + width : 5px; +` +const Title = styled(Typography)` + font-weight: 500; + color: rgb(102, 102, 102); + font-size: 0.9em; + margin-left: 10px; + margin-right: 10px; + + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +` +const StyledLink = styled(Link)` + text-decoration: none ; + color: inherit ; +` \ No newline at end of file diff --git a/src/Components/MenuBarMobile.js b/src/Components/MenuBarMobile.js index ea3196dd0c45a6658adb77cc48c2358665beb616..4590e9dd578da0ed15a585e37982710e33cfced0 100644 --- a/src/Components/MenuBarMobile.js +++ b/src/Components/MenuBarMobile.js @@ -19,13 +19,13 @@ along with Plataforma Integrada MEC. If not, see <http://www.gnu.org/licenses/> import React from 'react' import MenuIcon from '@material-ui/icons/Menu'; import styled from 'styled-components' -import {Button} from '@material-ui/core' +import { Button } from '@material-ui/core' import logo from '../img/logo_small.svg' -import {Link} from 'react-router-dom' +import { Link } from 'react-router-dom' import Grid from '@material-ui/core/Grid'; import MobileDrawerMenu from './MobileDrawerMenu'; -export default function MenuBarMobile (props) { +export default function MenuBarMobile(props) { const [drawerOpen, setDrawerStatus] = React.useState(false); @@ -37,45 +37,40 @@ export default function MenuBarMobile (props) { }; return ( - <OuterDiv> - <Grid container> - <Grid item xs={3} style={{display : "flex"}}> - <Button style={{color : "#00bcd4"}} onClick={toggleDrawer(true)}> - <MenuIcon className="icon"/> - </Button> - </Grid> - - <Grid item xs={9} justify={'center'}> - <div className="logo"> - <Link to="/"> - <img src={logo} alt={"Plataforma Integrada"}/> - </Link> - </div> - </Grid> - </Grid> + <> <MobileDrawerMenu anchor={'left'} open={drawerOpen} onClose={toggleDrawer(false)} - openSignUp = {props.openSignUp} openLogin = {props.openLogin} - /> - </OuterDiv> + openSignUp={props.openSignUp} openLogin={props.openLogin} + /> + <OuterDiv> + <DrawerButtonDiv style={{justifySelf : "flex-start", position : "absolute", left : 0}}> + <Button style={{ color: "#00bcd4" }} onClick={toggleDrawer(true)}> + <MenuIcon className="icon" /> + </Button> + </DrawerButtonDiv> + <div className="logo"> + <Link to="/"> + <img src={logo} alt={"Plataforma Integrada"} /> + </Link> + </div> + </OuterDiv> + </> ) } -const OuterDiv = styled.div ` +const OuterDiv = styled.div` height : 48px; - margin : 5px 2px; + width : 100%; display : flex; - flex-direction : column; - align-content : stretch; + flex-direction : row; + align-items : center; justify-content : center; + position : relative; .logo { - height : 50px; - width : 150px; - padding : 5px; - padding-top : 15px; + align-content : center; + justify-self : center; text-align : center; - img { height : 38px; overflow : hidden; @@ -98,3 +93,8 @@ const OuterDiv = styled.div ` color : inherit !important; } ` +const DrawerButtonDiv = styled.div` + justify-self : center; + position : absolute; + left : 0; +` \ No newline at end of file diff --git a/src/Components/MenuList.js b/src/Components/MenuList.js index 6ec3f5c91f5c11b2323c92583da9f302f2cd7926..643b4b04a72b14cda85a328c8f14ee572a13be83 100644 --- a/src/Components/MenuList.js +++ b/src/Components/MenuList.js @@ -26,9 +26,8 @@ import ExitToAppIcon from '@material-ui/icons/ExitToApp'; import { Store } from '../Store'; import Profile from '../img/default_profile0.png' import styled from 'styled-components' -import {apiDomain, apiUrl} from '../env.js' -import {getAxiosConfig} from './HelperFunctions/getAxiosConfig' -import axios from 'axios' +import {apiDomain} from '../env.js' +import {deleteRequest} from './HelperFunctions/getAxiosConfig' const OverrideButton = styled(Button)` @@ -47,30 +46,15 @@ export default function MenuList(props) { setAnchorEl(null); }; + function handleSuccessSignOut (data) { + dispatch( { + type: 'USER_LOGGED_OUT', + userLoggedOut: !state.userIsLoggedIn, + }) + } const handleLogout = () => { - let config = getAxiosConfig() - axios.delete(`${apiUrl}/auth/sign_out`, config).then( - () => { - - localStorage.removeItem('@portalmec/username'); - sessionStorage.removeItem('@portalmec/uid'); - sessionStorage.removeItem('@portalmec/senha'); - dispatch( { - type: 'USER_LOGGED_OUT', - userLoggedOut: !state.userIsLoggedIn, - login: { - username : '', - email : '', - accessToken : '', - client : '' - } - }) - }, - (err) => { - console.log(err) - } - ) - + const url = `/auth/sign_out` + deleteRequest(url, handleSuccessSignOut, (error) => {console.log(error)}) } return ( @@ -84,13 +68,13 @@ export default function MenuList(props) { > <div style={{borderRadius: "50%", border: "2px solid #fff", background: "#fff", overflow: "hidden", maxWidth : "50px", maxHeight : "50px"}}> { - state.currentUser.avatar_file_name === '' || state.currentUser.avatar_file_name === null ? + state.currentUser.avatar === '' || state.currentUser.avatar === null || state.currentUser.avatar === undefined ? ( <img src={Profile} alt={'user avatar'} style={{width:"100%", height:"100%", verticalAlign : "middle", marginLeft : "0"}}/> ): ( - <img src={apiDomain + state.currentUser.avatar_file_name} alt={'user avatar'} style={{width:"100%", height:"100%", verticalAlign : "middle", marginLeft : "0"}}/> + <img src={apiDomain + state.currentUser.avatar} alt={'user avatar'} style={{width:"100%", height:"100%", verticalAlign : "middle", marginLeft : "0"}}/> ) } </div> diff --git a/src/Components/MobileDrawerMenu.js b/src/Components/MobileDrawerMenu.js index 2b15988246f8298895220ca06267b1d70d6228fa..f872b4583c995b8ec6da6dad2d1d1c62b13d4b14 100644 --- a/src/Components/MobileDrawerMenu.js +++ b/src/Components/MobileDrawerMenu.js @@ -36,9 +36,9 @@ import HistoryIcon from '@material-ui/icons/History'; import FavoriteBorderIcon from '@material-ui/icons/FavoriteBorder'; import FolderOpenIcon from '@material-ui/icons/FolderOpen'; import SettingsIcon from '@material-ui/icons/Settings'; -import {apiDomain, apiUrl} from '../env.js' -import {getAxiosConfig} from './HelperFunctions/getAxiosConfig' -import axios from 'axios' +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) @@ -48,6 +48,7 @@ export default function MobileDrawerMenu (props) { { name : "Sobre a Plataforma", href : "sobre", icon : <InfoIcon/>}, { name : "Contato", href : "contato", icon : <MailOutlineIcon/>}, { name : "Central de Ajuda", href : "ajuda", icon : <HelpOutlineIcon/>}, + { name: "Busca", href: `/busca?query=${state.search.query}&search_class=${state.search.class}`, icon : <SearchIcon/>}, { name : "Termos de Uso", href : "termos", icon : <AssignmentIcon/>}, ] @@ -58,11 +59,11 @@ export default function MobileDrawerMenu (props) { }; const getUserAvatar = () => { - if (state.currentUser.avatar_file_name === '' || state.currentUser.avatar_file_name == null) { + if (state.currentUser.avatar === '' || state.currentUser.avatar == null) { return DefaultAvatar } else { - return apiDomain + state.currentUser.avatar_file_name + return apiDomain + state.currentUser.avatar } } @@ -75,30 +76,16 @@ export default function MobileDrawerMenu (props) { { name: "Coleções", href: "/perfil", icon : <FolderOpenIcon/>, value : '3'}, ] - // {/*dispatches log out actions to Store.js*/} - const handleLogout = () => { - let config = getAxiosConfig() - axios.delete(`${apiUrl}/auth/sign_out`, config).then( - (res) => { - localStorage.removeItem('@portalmec/username'); - sessionStorage.removeItem('@portalmec/uid'); - sessionStorage.removeItem('@portalmec/senha'); - dispatch( { - type: 'USER_LOGGED_OUT', - userLoggedOut: !state.userIsLoggedIn, - login: { - username : '', - email : '', - accessToken : '', - client : '' - } - }) - }, - (err) => { - console.log(err) - } - ) + function handleSuccessSignOut (data) { + dispatch( { + type: 'USER_LOGGED_OUT', + userLoggedOut: !state.userIsLoggedIn, + }) + } + const handleLogout = () => { + const url = `/auth/sign_out` + deleteRequest(url, handleSuccessSignOut, (error) => {console.log(error)}) } return ( diff --git a/src/Components/ModalAlterarAvatar/ComponentAlterarAvatar.js b/src/Components/ModalAlterarAvatar/ComponentAlterarAvatar.js index 4895cf29c01b5fde32ebeb1f1519b4b25f6a2036..8936af0a751bcd2d139c08bf631e489415688a24 100644 --- a/src/Components/ModalAlterarAvatar/ComponentAlterarAvatar.js +++ b/src/Components/ModalAlterarAvatar/ComponentAlterarAvatar.js @@ -20,12 +20,11 @@ import React, {useContext, useState} from 'react'; import { Button } from '@material-ui/core'; import styled from 'styled-components' import {Store} from '../../Store.js' -import axios from 'axios' -import {apiUrl, apiDomain} from '../../env'; +import {apiDomain} from '../../env'; import CloseIcon from '@material-ui/icons/Close'; import Profile from '../../img/default_profile0.png' import Cropper from '../Cropper.js' - +import {putRequest} from '../HelperFunctions/getAxiosConfig' function ChooseImage (props) { return ( @@ -65,21 +64,6 @@ function ChooseImage (props) { ) } -const GetHeaderConfig = () => { - - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid'), - } - } - // {/*'Host': 'api.portalmec.c3sl.ufpr.br', - // 'Cookie': ''*/} - return config -} export default function ComponentAlterarAvatar (props) { const {state, dispatch} = useContext(Store) @@ -103,28 +87,23 @@ export default function ComponentAlterarAvatar (props) { aspect: 1 }); + function handleSuccess(data) { + const target = state.currentUser + const source = {userAvatar : data.avatar} + dispatch({ + type : 'USER_CHANGED_COVER', + currUser : Object.assign(target, source) + }) + } + const completeSelection = () => { - console.log(newAvatar) + const url = `/users/${props.id}` + //newAvatar is a base64 encoded image file let fdAvatar = new FormData() fdAvatar.set('user[avatar]', newAvatar) - axios.put( (`${apiUrl}/users/` + props.id ), - fdAvatar, - GetHeaderConfig() - ).then( (response) => { - console.log(response) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - const target = state.currentUser - const source = {userAvatar : response.data.avatar} - dispatch({ - type : 'USER_CHANGED_COVER', - currUser : Object.assign(target, source) - }) - }, (error) => {console.log(error)} - ) + putRequest(url, fdAvatar, handleSuccess, (error) => {console.log(error)}) } return ( diff --git a/src/Components/ModalAlterarCover/ComponentAlterarCover.js b/src/Components/ModalAlterarCover/ComponentAlterarCover.js index caf408d482af065ceeba81a1e601efdf5544a602..99a5f5493eca3735ae00b5a2431934ed5b9f8201 100644 --- a/src/Components/ModalAlterarCover/ComponentAlterarCover.js +++ b/src/Components/ModalAlterarCover/ComponentAlterarCover.js @@ -20,27 +20,9 @@ import React, {useContext, useState} from 'react'; import { Button } from '@material-ui/core'; import styled from 'styled-components' import {Store} from '../../Store.js' -import axios from 'axios' -import {apiUrl} from '../../env'; import CloseIcon from '@material-ui/icons/Close'; import Cropper from '../Cropper.js' - - -const GetHeaderConfig = () => { - - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid'), - } - } - // {/*'Host': 'api.portalmec.c3sl.ufpr.br', - // 'Cookie': ''*/} - return config -} +import {putRequest} from '../HelperFunctions/getAxiosConfig' export default function ComponentAlterarCover (props) { const {state, dispatch} = useContext(Store) @@ -55,27 +37,23 @@ export default function ComponentAlterarCover (props) { aspect: 16 / 9 }); + function handleSuccess (data) { + const target = state.currentUser + const source = {userCover : data.cover} + dispatch({ + type : 'USER_CHANGED_COVER', + currUser : Object.assign(target, source) + }) + } + const completeSelection = () => { - console.log(newCover) + const url = `/users/${props.id}` + //newCover is a base64 encoded image file. let fdCover = new FormData() fdCover.set('user[cover]', newCover) - axios.put( (`${apiUrl}/users/` + props.id ), - fdCover, - GetHeaderConfig() - ).then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - const target = state.currentUser - const source = {userCover : response.data.cover} - dispatch({ - type : 'USER_CHANGED_COVER', - currUser : Object.assign(target, source) - }) - }, (error) => {console.log(error)} - ) + putRequest(url, fdCover, handleSuccess, (error) => {console.log(error)}) } return ( diff --git a/src/Components/ModalConfirmarCuradoria.js b/src/Components/ModalConfirmarCuradoria.js index b654338cadf3dd573689ce0102179377ca6282e6..4687b1876be5b3ae5376901a97eb2e00aca3df66 100644 --- a/src/Components/ModalConfirmarCuradoria.js +++ b/src/Components/ModalConfirmarCuradoria.js @@ -22,10 +22,8 @@ import Modal from '@material-ui/core/Modal'; import Backdrop from '@material-ui/core/Backdrop'; import Fade from '@material-ui/core/Fade'; import styled from 'styled-components' -import axios from 'axios' -import {apiUrl} from '../env'; import CloseModalButton from './CloseModalButton' -import {getAxiosConfig} from './HelperFunctions/getAxiosConfig' +import {postRequest} from './HelperFunctions/getAxiosConfig' export default function ModalConfirmarCuradoriaOpen (props) { @@ -42,8 +40,11 @@ export default function ModalConfirmarCuradoriaOpen (props) { return newArr } + function handleSuccess (data) { + props.finalizeCuratorshipFlow() + } const handleConfirmation = () => { - let config = getAxiosConfig() + const url = `/submissions/${props.recursoId}/answer` let payload = { "submission" : { @@ -51,16 +52,7 @@ export default function ModalConfirmarCuradoriaOpen (props) { "answers" : transformReportCriteria(props.reportCriteria) } } - - axios.post( (`${apiUrl}/submissions/` + props.recursoId + '/answer'), payload, config).then( - (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response.data) - props.finalizeCuratorshipFlow() - }, (error) => {console.log(error)} - ) + postRequest(url, payload, handleSuccess, (error) => {console.log(error)}) } return ( diff --git a/src/Components/ModalExcluirColecao.js b/src/Components/ModalExcluirColecao.js index 914aa74f2ce58c00699144802eb7c364cbc11faa..879112aebb46690447dcc1b3cdecb62e90adbbff 100644 --- a/src/Components/ModalExcluirColecao.js +++ b/src/Components/ModalExcluirColecao.js @@ -21,28 +21,22 @@ import Modal from '@material-ui/core/Modal'; import Backdrop from '@material-ui/core/Backdrop'; import Fade from '@material-ui/core/Fade'; import styled from 'styled-components' -import axios from 'axios' -import {apiUrl} from '../env'; import GreyButton from './GreyButton.js' import PurpleButton from './PurpleButton.js' -import {getAxiosConfig} from '../Components/HelperFunctions/getAxiosConfig' import SnackbarComponent from './SnackbarComponent' +import {deleteRequest} from './HelperFunctions/getAxiosConfig' export default function ModalExcluirColecao (props) { const [snackbarOpen, toggleSnackbar] = useState(false) + function handleDeleteSuccess (data) { + toggleSnackbar(true) + props.handleClose() + } const handleDelete = () => { - let config = getAxiosConfig() - - axios.delete( (`${apiUrl}/collections/` + props.id), config - ).then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - toggleSnackbar(true) - props.handleClose() - }, (error) => {console.log(error);}) + const url = `/collections/${props.id}` + + deleteRequest(url, handleDeleteSuccess, (error) => {console.log(error)}) } return ( diff --git a/src/Components/ModalVideoApresentacao.js b/src/Components/ModalVideoApresentacao.js index 3b83f173cd56e4a3724ca7d71003c55d88fc9d49..286cdf69dd9c4bf42c8e94c9a84a8010d0f4091e 100644 --- a/src/Components/ModalVideoApresentacao.js +++ b/src/Components/ModalVideoApresentacao.js @@ -52,9 +52,8 @@ export default function ModalVideoApresentacao (props) { const VideoContainer = styled.div` position : relative; - width : 100%; - height : 0; - padding-bottom : 56.25%; + width : 70%; + height : 70%; .video { width : 100%; diff --git a/src/Components/Notifications.js b/src/Components/Notifications.js index d8df9e70914342207aa0ceba0cc989c54e75aa86..cf8a2f055f3fc17d46b9ba856d05c3bfa96b7b8d 100644 --- a/src/Components/Notifications.js +++ b/src/Components/Notifications.js @@ -21,10 +21,9 @@ import { Button } from '@material-ui/core'; import Badge from '@material-ui/core/Badge'; import styled from 'styled-components' import Menu from '@material-ui/core/Menu'; -import {apiDomain, apiUrl} from '../env.js' -import axios from 'axios' +import {apiDomain} from '../env.js' import ActivityListItem from './ActivityListItem.js' -import {getAxiosConfig} from './HelperFunctions/getAxiosConfig.js' +import {getRequest} from './HelperFunctions/getAxiosConfig.js' import { withStyles } from '@material-ui/core/styles'; import {Link} from 'react-router-dom' @@ -77,27 +76,23 @@ export default function Notification (props) { const [notifications, setNotifications] = useState([]); // eslint-disable-next-line const [notificatonsLength, setLength] = useState(0); - useEffect(() => { - setTimeout(() => { - let config = getAxiosConfig() - axios.get(`${apiUrl}/feed?offset=0&limit=30`, config) - .then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } + function handleAxiosSuccess (data) { + setNotifications(data) + setLength(data.length) + } + + function handleAxiosError (error) { + console.log('error getNotifications') + console.log(error) + } + + + useEffect(() => { + getRequest('/feed?offset=0&limit=30', handleAxiosSuccess, handleAxiosError) + }, []) - console.log('atividades response: ', response) - setNotifications(response.data) - setLength(response.data.length) - }, - (error) => { - console.log('error while running getNotifications') - } - ) - }, 1000); - }, [sessionStorage.getItem('@portalmec/uid')]) function handleClick(event) { console.log('event.currentTarget: ', event.currentTarget) setAnchorEl(event.currentTarget); diff --git a/src/Components/NotificationsInner.js b/src/Components/NotificationsInner.js index 5b80924a112447925393c4d6a3117aa9826d7e58..4630287968d81ff709a2fb3d4dd46e88ab70d38e 100644 --- a/src/Components/NotificationsInner.js +++ b/src/Components/NotificationsInner.js @@ -1,30 +1,21 @@ import React, {useState, useContext, useEffect} from 'react' import styled from 'styled-components' -import {apiDomain, apiUrl} from '../env.js' -import axios from 'axios' +import {apiDomain} from '../env.js' import ActivityListItem from './ActivityListItem.js' -import {getAxiosConfig} from './HelperFunctions/getAxiosConfig.js' +import {getRequest} from './HelperFunctions/getAxiosConfig' export default function NotificationInner (props) { const [notifications, setNotifications] = useState([]); const [notificatonsLength, setLength] = useState(0); - useEffect(() => { - let config = getAxiosConfig() - axios.get(`${apiUrl}/feed?offset=0&limit=30`, config) - .then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log('atividades response: ', response) - setNotifications(response.data) - setLength(response.data.length) + function handleSuccess (data) { + setNotifications(data) + setLength(data.length) + } + useEffect(() => { + const url = `/feed?offset=0&limit=30` - }, - (error) => { - console.log('error while running getNotifications') - } - ) + getRequest(url, handleSuccess, (error) => {console.log('error while running getNotifications')}) }, []) return ( diff --git a/src/Components/PageProfessorComponents/PartOne.js b/src/Components/PageProfessorComponents/PartOne.js index 6fe3e70cb933c64da77e923804f69fe375fbc580..ad8fcf9a72464421bb2a467cd1c4b32aa9244db0 100644 --- a/src/Components/PageProfessorComponents/PartOne.js +++ b/src/Components/PageProfessorComponents/PartOne.js @@ -88,7 +88,6 @@ export default function PartOne (props) { } const handleSubmit = () => { - console.log('handle submit : ', uf.abbreviation, uf.name, municipio.name, codigoINEP.value) props.handleBuscar(uf.abbreviation, uf.name, municipio.name, codigoINEP.value) } diff --git a/src/Components/PublicationPermissionsContent.js b/src/Components/PublicationPermissionsContent.js index 533993c1c89990ec78de3a59cd34a93db0119132..ddccba30f8c1ec5f98349ae1e9589c2a90554dca 100644 --- a/src/Components/PublicationPermissionsContent.js +++ b/src/Components/PublicationPermissionsContent.js @@ -8,8 +8,7 @@ import Radio from '@material-ui/core/Radio'; import FormControl from '@material-ui/core/FormControl'; import Grid from '@material-ui/core/Grid'; import { withStyles } from '@material-ui/core/styles'; -import axios from 'axios' -import {apiUrl} from '../env'; +import {getRequest} from './HelperFunctions/getAxiosConfig' const StyledFormControl = styled(FormControl)` display: "block ruby"; @@ -31,16 +30,14 @@ export default function PublicationPermissionsContent (props) { const [questionsArr, setQuestionsArr] = useState([]) const handleSetQuestionsArr = (newArr) => {setQuestionsArr(newArr)} + function handleSuccess (data) { + handleSetQuestionsArr(data) + } + useEffect(() => { - axios.get(`${apiUrl}/questions/`).then( - (response) => { - console.log(response) - handleSetQuestionsArr(response.data) - }, - (error) => { - console.log('falhou em get questions') - } - ) + const url = `/questions/` + + getRequest(url, handleSuccess, (error) => {console.log(error)}) }, []) diff --git a/src/Components/ReportModal.js b/src/Components/ReportModal.js index be2248dfa1b53d92cea76d45c82c246934ed66bf..079ca75fd3dd6454d6e26263767ac33d3ad3b556 100644 --- a/src/Components/ReportModal.js +++ b/src/Components/ReportModal.js @@ -16,19 +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, {useContext} from 'react'; +import React, {useContext, useState} from 'react'; import { Button } from '@material-ui/core'; import Modal from '@material-ui/core/Modal'; import Backdrop from '@material-ui/core/Backdrop'; import Fade from '@material-ui/core/Fade'; import styled from 'styled-components' import {Store} from '../Store.js' -import axios from 'axios' -import {apiUrl} from '../env'; import CloseIcon from '@material-ui/icons/Close'; import ReportUserForm from './ReportUserForm.js' import ReportRecursoForm from './ReportRecursoForm.js' import ReportColecaoForm from './ReportColecaoForm.js' +import {postRequest} from './HelperFunctions/getAxiosConfig' +import SnackbarComponent from './SnackbarComponent.js' function CloseModalButton (props) { return ( @@ -40,11 +40,10 @@ function CloseModalButton (props) { export default function ReportModal (props) { const {state} = useContext(Store) + const [snackbarOpen, handleSnackbar] = useState(false) const handleSubmit = (complaint_reason_id, description) => { - console.log('complaint_reason_id: ', complaint_reason_id) - console.log('description: ', description) - + const url = `/complaints/` const payload = { "complaint" : { "user_id" : state.currentUser.id, @@ -54,18 +53,13 @@ export default function ReportModal (props) { "complaint_reason_id" : complaint_reason_id } } - console.log(payload) - axios.post(`${apiUrl}/complaints`, - { - "complaint" : { - "user_id" : state.currentUser.id, - "description" : description, - "complainable_id" : props.complainableId, - "complainable_type" : props.complainableType, - "complaint_reason_id" : complaint_reason_id - } - }).then( (response) => {console.log(response)}, (error) => {console.log(error)}) + postRequest(url, payload, (data) => { + console.log(data) + props.handleClose(); + handleSnackbar(true); + }, (error) => {console.log(error)}) + } const renderForm = (formType) => { @@ -85,49 +79,40 @@ export default function ReportModal (props) { } } - /* const renderForm = (formType) => { - switch (formType) { - case 'colecao': - return ( - <ReportCollectionForm - handleClose={props.handleClose} - handleSubmit={handleSubmit} - /> - ); - break; - } - } */ - return ( - <StyledModal - aria-labelledby="transition-modal-title" - aria-describedby="transition-modal-description" - open={props.open} - - centered="true" - onClose={props.handleClose} - closeAfterTransition - BackdropComponent={Backdrop} - BackdropProps={{ - timeout: 500, - }} - > - <Fade in={props.open}> - <ReportContainer> - <Header> - <span style={{width:"32px"}}/> - <h2>O que está acontecendo?</h2> - <CloseModalButton handleClose={props.handleClose}/> - </Header> - - <Content> - { - renderForm(props.form) - } - </Content> - </ReportContainer> - </Fade> - </StyledModal> + <React.Fragment> + <SnackbarComponent snackbarOpen={snackbarOpen} severity={"success"} handleClose={() => {handleSnackbar(false)}} text={"Sua reclamação foi recebida."} + /> + <StyledModal + aria-labelledby="transition-modal-title" + aria-describedby="transition-modal-description" + open={props.open} + + centered="true" + onClose={props.handleClose} + closeAfterTransition + BackdropComponent={Backdrop} + BackdropProps={{ + timeout: 500, + }} + > + <Fade in={props.open}> + <ReportContainer> + <Header> + <span style={{width:"32px"}}/> + <h2>O que está acontecendo?</h2> + <CloseModalButton handleClose={props.handleClose}/> + </Header> + + <Content> + { + renderForm(props.form) + } + </Content> + </ReportContainer> + </Fade> + </StyledModal> + </React.Fragment> ) } diff --git a/src/Components/ResourceCard.js b/src/Components/ResourceCard.js index 03576afd0ada0fd7794198681c73cda37cdf68b1..2e76e5fc66116d288e3be56b7af41c85ef77878e 100644 --- a/src/Components/ResourceCard.js +++ b/src/Components/ResourceCard.js @@ -25,6 +25,7 @@ import CardActions from "@material-ui/core/CardActions"; import IconButton from "@material-ui/core/IconButton"; import Typography from "@material-ui/core/Typography"; import FavoriteIcon from "@material-ui/icons/Favorite"; +import styled from 'styled-components'; import animacao from "../img/laranja/ANIMACAO_SIMULACAO.jpg"; import apresentacao from "../img/laranja/APRESENTACAO.jpg"; import aplicativo from "../img/laranja/APP.jpg"; @@ -74,7 +75,7 @@ const slideStyle = { const publisherStyle = { color: "white", paddinLeft: "30px", - fontSize: "15px" + fontSize: "15px", }; class ResourceCard extends Component { @@ -86,16 +87,16 @@ class ResourceCard extends Component { userAvatar: null }; } - renderType(type){ - if (!this.state.thumbnail) { - if(!this.props.thumbnail) { - const aux = types.find(function(element){return element.label === type}); - this.setState({thumbnail: aux.thumb}); - } - else{ - this.setState({thumbnail: `${apiDomain}` + this.props.thumbnail}); - } + renderType(type) { + if (!this.state.thumbnail) { + if (!this.props.thumbnail) { + const aux = types.find(function (element) { return element.label === type }); + this.setState({ thumbnail: aux.thumb }); } + else { + this.setState({ thumbnail: `${apiDomain}` + this.props.thumbnail }); + } + } // {/*if (!this.state.thumbnail && !this.props.thumbnail ) { // var aux = types.find(function(element){ return element.label === type}); // this.setState({thumbnail: aux.thumb}); @@ -135,10 +136,10 @@ class ResourceCard extends Component { > <div className={this.state.userStyle}> <img style={slideStyle} src={this.state.userAvatar} alt="Avatar" /> - <Typography style={publisherStyle}> + <StyledPublisher style={publisherStyle}> Enviado por: <br /> {this.props.author} - </Typography> + </StyledPublisher> </div> <img src={this.state.thumbnail} @@ -163,6 +164,7 @@ class ResourceCard extends Component { name="customized-empty" value={this.props.rating * 10} precision={0.5} + readOnly emptyIcon={<StarBorderIcon fontSize="inherit" />} /> </Container> @@ -172,8 +174,8 @@ class ResourceCard extends Component { {this.props.type === "Vídeo" ? ( <Video style={{ color: "#ff7f00" }} /> ) : ( - <br /> - )} + <br /> + )} <IconButton aria-label="Favoritar" size="small"> <FavoriteIcon /> </IconButton> @@ -194,4 +196,11 @@ class ResourceCard extends Component { } } +const StyledPublisher = styled(Typography)` + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +` + export default ResourceCard; diff --git a/src/Components/ResourceCardFunction.js b/src/Components/ResourceCardFunction.js index 8113aa671694a725dce337672825b74f56bf6970..08d07b6190f283703263cbbabf3e676737425bc3 100644 --- a/src/Components/ResourceCardFunction.js +++ b/src/Components/ResourceCardFunction.js @@ -16,10 +16,9 @@ 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, useEffect} from 'react'; +import React, { useState, useEffect } from 'react'; import Card from '@material-ui/core/Card'; -import axios from 'axios' -import {apiDomain, apiUrl} from '../env'; +import {apiDomain} from '../env'; import ResourceCardOptions from './ResourceCardOptions' import noAvatar from "../img/default_profile.png"; // import { makeStyles } from '@material-ui/core/styles'; @@ -48,27 +47,23 @@ import FavoriteIcon from '@material-ui/icons/Favorite'; import ButtonGuardarColecao from './ButtonGuardarColecao.js' import Slide from '@material-ui/core/Slide'; import Grid from '@material-ui/core/Grid'; -import {Link} from 'react-router-dom'; -import {getDefaultThumbnail} from './HelperFunctions/getDefaultThumbnail' +import { Link } from 'react-router-dom'; +import { getDefaultThumbnail } from './HelperFunctions/getDefaultThumbnail' import GetIconByName from './UploadPageComponents/GetIconByName' -import {getAxiosConfig} from './HelperFunctions/getAxiosConfig' - import "./ResourceCard.css"; +import {putRequest} from './HelperFunctions/getAxiosConfig' -// const types = [{label: "Animação", thumb: animacao}, {label: "Apresentação", thumb: apresentacao}, -// {label: "Aplicativo" , thumb: aplicativo}, {label: "Áudio", thumb: audio}, {label: "Vazio", thumb: vazio}, {label: "Imagem", thumb: imagem}, {label: "Gráfico", thumb: grafico}, {label: "Jogo", thumb: jogo}, {label: "Livro", thumb: livro}, {label:"Livro digital", thumb: livro}, {label: "Mapa", thumb: mapa}, {label: "Outros", thumb: outros}, {label: "Software Educacional", thumb:software}, {label: "Software", thumb:software}, {label: "Texto", thumb:texto}, {label: "Vídeo", thumb:video}] - -export default function ResourceCardFunction (props) { +export default function ResourceCardFunction(props) { const [thumbnail, setThumbnail] = useState(null) // eslint-disable-next-line const [label, setLabel] = useState(props.type) const [userAvatar, setUserAvatar] = useState(noAvatar) const [slideIn, setSlide] = useState(false) - const controlSlide = () => {setSlide(!slideIn)} + const controlSlide = () => { setSlide(!slideIn) } const [liked, toggleLiked] = useState(props.liked) const [likesCount, setLikesCount] = useState(props.likeCount) - useEffect( () => { + useEffect(() => { //decide which thumbnail to use if (props.thumbnail) { setThumbnail(`${apiDomain}` + props.thumbnail) @@ -80,52 +75,47 @@ export default function ResourceCardFunction (props) { if (props.avatar) { setUserAvatar(`${apiDomain}` + props.avatar) } + else { + setUserAvatar(require('../img/logo_parceiros/ic_default.png')) + } }, []) + function handleSuccessLike (data) { + toggleLiked(!liked) + setLikesCount(data.count) + } + const handleLike = () => { - let payload = {} - let config = getAxiosConfig() - - axios.put( (`${apiUrl}/learning_objects/` + props.id + '/like'),payload, config - ).then( - (response) => { - console.log(response.data) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - toggleLiked(!liked) - setLikesCount(response.data.count) + const url = `/learning_objects/${props.id}/like/` - }, - (error) => {console.log(error)} - ) + putRequest(url, {}, handleSuccessLike, (error) => {console.log(error)}) } const SlideAnimationContent = () => { return ( <SlideContentDiv> - <div style={{display:"flex", flex:"1"}}>{/*marginBottom:10px*/} - <AvatarDiv> - <img className="img" src={userAvatar} alt="user avatar"/> - </AvatarDiv> - <EnviadoPor> - Enviado por: - <br/> - <p>{props.author}</p> - </EnviadoPor> + <div style={{padding : 7}}> + <HeaderContainer container="row" justify="flex-start" alignItems="center" >{/*marginBottom:10px*/} + <AvatarDiv item xs={2}> + <img className="img" src={userAvatar} alt="user avatar" /> + </AvatarDiv> + <EnviadoPor item xs={10}> + Enviado por: + <br /> + <p>{props.author}</p> + </EnviadoPor> + </HeaderContainer> + <TagContainer container direction="row"> + { + props.tags.map((tag) => + <Grid item key={tag.id}> + <span >{tag.name}</span> + </Grid> + ) + } + </TagContainer> </div> - <TagContainer> - <Grid container spacing={1} justify='safe' style={{height : "inherit"}}> - { - props.tags.map( (tag) => - <Grid item key={tag.id}> - <span key={tag.id}>{tag.name}</span> - </Grid> - ) - } - </Grid> - </TagContainer> </SlideContentDiv> ) } @@ -136,54 +126,47 @@ export default function ResourceCardFunction (props) { <CardReaDiv> <Header onMouseEnter={controlSlide} onMouseLeave={controlSlide}> { - props.published && - <Slide direction="left" in={slideIn} timeout={500}> - <div className={`slideContentLinkAfterActive${slideIn}`} style={{}}> + <Slide direction="left" in={slideIn} timeout={1000}> + <div className={`slideContentLinkAfterActive${slideIn}`}> <Link to={props.href} className="text" > {SlideAnimationContent()} </Link> - </div> </Slide > } - <div className={`slideContentLinkBeforeActive${slideIn}`} style={{}}> - + <div className={`slideContentLinkBeforeActive${slideIn}`} style={{ height: '100%' }}> <Link to={props.href}> - <img className="img-cover" src={thumbnail} alt="learning object thumbnail"/> + <img className="img-cover" src={thumbnail} alt="learning object thumbnail" style={{ width: "272.5px" }} /> </Link> </div> </Header> - <Description> - <Link to={props.href} className="text"> {/*add link to learningObject*/} - <span> + <Link to={props.href} className="text" style={{ height: '45px' }}> {/*add link to learningObject*/} + <Title> {props.title} - </span> + </Title> </Link> - { props.published && <Rating - name="customized-empty" - value={props.rating} - precision={0.5} - style={{color:"#666"}} - emptyIcon={<StarBorderIcon fontSize="inherit" />} + name="customized-empty" + value={props.rating} + readOnly + style={{ color: "#666" }} + emptyIcon={<StarBorderIcon fontSize="inherit" />} /> } - <Footer> <Type> {GetIconByName(label)} <span>{label}</span> </Type> - { props.published && <LikeCounter> <span>{likesCount}</span> <ButtonNoWidth onClick={handleLike}> - <FavoriteIcon style={{color : liked ? "red" : "#666" }}/> + <FavoriteIcon style={{ color: liked ? "red" : "#666" }} /> </ButtonNoWidth> </LikeCounter> } @@ -194,16 +177,16 @@ export default function ResourceCardFunction (props) { { props.published && <CardReaFooter> - <div style={{display : "flex", height : "100%"}}> + <div style={{ display: "flex", height: "100%" }}> <ButtonGuardarColecao thumb={props.thumbnail} title={props.title} recursoId={props.id} - /> + /> </div> <ResourceCardOptions learningObjectId={props.id} - downloadableLink = {props.downloadableLink} + downloadableLink={props.downloadableLink} thumb={props.thumbnail} title={props.title} - /> + /> </CardReaFooter> } </CardDiv> @@ -211,27 +194,34 @@ export default function ResourceCardFunction (props) { ) } /*---------- USED IN SLIDE DIV ONLY -----------*/ -export const TagContainer = styled.div` - display : flex; - flex-direction : row; - width : 100%; - overflow : hidden; - flex : 2; - height : 120px; +export const HeaderContainer = styled(Grid)` + +` +export const TagContainer = styled(Grid)` + margin-top: 0.5em; + height : 120px ; + overflow-y : hidden; + ${'' /* border : 2px solid red; */} span { + word-wrap: break-word; background-color : #fff; - height : 20px; + display : flex; + justify-content : center; + align-items : center; + height : 22px; + tet-align : center; + margin: 3px; + -webkit-box-direction: normal; overflow : hidden; - margin : 2px; - padding : 3px 8px; + padding : 1px 8px; border-radius : 10px; color : #666; font-size : 11px; } ` -export const EnviadoPor = styled.div` +export const EnviadoPor = styled(Grid)` display : inline-block; padding-left : 10px; overflow : hidden; @@ -239,20 +229,21 @@ export const EnviadoPor = styled.div` padding-right : 1em; p { - text-overflow : ellipsis; - overflow : hidden; - white-space : nowrap; margin : 0; + display: -webkit-box; + -webkit-line-clamp: 1; + -webkit-box-orient: vertical; + overflow: hidden; } ` -const AvatarDiv = styled.div` +export const AvatarDiv = styled(Grid)` vertical-align : middle; border : 0; - width : 45px; + width : 40px; + height : 40px; img { - width : 45px; - height : 40px !important; - width : 40px !important; + max-height: 100%; + max-width: 100%; border : 0; vertical-align : middle; border-radius : 50%; @@ -261,12 +252,9 @@ const AvatarDiv = styled.div` const SlideContentDiv = styled.div` background-color : #ff9226; - padding : 10px; - width : 100%; - height : 100%; - // position : absolute; - // display : flex; - // flex-direction : column; + ${'' /* padding : 10px; */} + width : 272.5px; + height : 189px; ` /*--------------------------------------------*/ @@ -341,6 +329,7 @@ export const Footer = styled.div` display : flex; flex-direction : row; justify-content : space-between; + margin-top : 5px; ` const Description = styled.div` @@ -355,16 +344,13 @@ const Description = styled.div` text-decoration : none !important; color : inherit; } - - .title { - text-overflow : ellipsis; - overflow : hidden; - margin-bottom : 10px; - font-size : 1.2em; - line-height : 1.1; - max-height : 46px; - color : #666; - } +` +const Title = styled.span` + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + color : #666; ` export const Header = styled.div` @@ -382,7 +368,7 @@ export const CardReaDiv = styled.div` display : flex; flex-direction : column; height : 320px; - width : 272.5px; + ${'' /* width : 272.5px; */} margin : 0 auto; .img-cover { @@ -393,7 +379,7 @@ export const CardReaDiv = styled.div` display : block; background-position : center; background-size : cover; - width : 100%; + ${'' /* width : 100%; */} } ` @@ -409,7 +395,7 @@ export const StyledCard = styled(Card)` max-height : 380px; margin-top : 10px; margin-bottom : 10px; - max-width : 345px; + ${'' /* max-width : 345px; */} border-radius : 0; box-shadow : 0 0 5px 0 rgba(0,0,0,.25); ` diff --git a/src/Components/ResourceCardOptions.js b/src/Components/ResourceCardOptions.js index 7503fec2c073b37341548b355a7fc3f23e81ebbf..44bc52df18fd48f3deeeae344a8457ff06e6a8b6 100644 --- a/src/Components/ResourceCardOptions.js +++ b/src/Components/ResourceCardOptions.js @@ -16,8 +16,8 @@ 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, {useContext, useState} from 'react'; -import {Store} from '../Store.js' +import React, { useContext, useState } from 'react'; +import { Store } from '../Store.js' import styled from 'styled-components' import Button from '@material-ui/core/Button'; import Menu from '@material-ui/core/Menu'; @@ -27,16 +27,22 @@ import MoreVertIcon from '@material-ui/icons/MoreVert'; import OpenIcon from '@material-ui/icons/OpenInNew'; import ReportIcon from '@material-ui/icons/Error'; import ReportModal from './ReportModal.js' -import {Link} from 'react-router-dom' +import { Link } from 'react-router-dom' import DownloadIcon from '@material-ui/icons/CloudDownload'; import ShareIcon from '@material-ui/icons/Share'; import AddIcon from '@material-ui/icons/CreateNewFolder'; import GuardarModal from './GuardarModal' import ShareModal from './ShareModal' import SnackbarComponent from './SnackbarComponent' - -export default function ResourceCardOptions (props) { - const {state} = useContext(Store) +import OpenInBrowserIcon from '@material-ui/icons/OpenInBrowser'; +import Tooltip from '@material-ui/core/Tooltip'; +import SignUpModal from './SignUpModal' +import LoginModal from './LoginModal.js' +import Snackbar from '@material-ui/core/Snackbar'; +import MuiAlert from '@material-ui/lab/Alert'; + +export default function ResourceCardOptions(props) { + const { state } = useContext(Store) const [anchorEl, setAnchorEl] = React.useState(null); function handleClick(event) { @@ -60,8 +66,8 @@ export default function ResourceCardOptions (props) { const [saveToCol, toggleSave] = useState(false) const handleGuardar = () => { - if(state.currentUser.id === '') { - console.log('abrir login modal'); + if (!state.currentUser.id) { + handleLogin(); } else { toggleSave(true); @@ -78,8 +84,8 @@ export default function ResourceCardOptions (props) { const [shareOpen, toggleShare] = useState(false) const handleShare = () => { - if(state.currentUser.id === '') { - console.log('abrir login modal'); + if (!state.currentUser.id) { + handleLogin() } else { toggleShare(true); @@ -87,65 +93,109 @@ export default function ResourceCardOptions (props) { handleClose() } const getShareablePageLink = () => { - return (window.location.href + "/recurso/" + props.learningObjectId) + return (window.origin + "/recurso/" + props.learningObjectId) + } + + const handleSignUp = () => { + setSignUp(!signUpOpen) + } + + const handleLogin = () => { + setLogin(!loginOpen) + } + + function Alert(props) { + return <MuiAlert elevation={6} variant="filled" {...props} />; + } + + function toggleLoginSnackbar(reason) { + if (reason === 'clickaway') { + return; + } + handleSuccessfulLogin(false); } const [snackbarOpen, toggleSnackbar] = useState(false) + const [signUpOpen, setSignUp] = useState(false) + const [loginOpen, setLogin] = useState(false) + const [successfulLoginOpen, handleSuccessfulLogin] = useState(false) return ( - <React.Fragment> - <ReportModal open={reportModal} handleClose={() => handleModalReportar(false)} - form="recurso" complainableId={props.learningObjectId} - complainableType={"LearningObject"} - {...props} - /> - <GuardarModal open={saveToCol} handleClose={() => {toggleSave(false)}} - thumb={props.thumb} title={props.title} recursoId={props.learningObjectId} - /> - <ShareModal open={shareOpen} handleClose={() => {toggleShare(false)}} - thumb={props.thumb} title={props.title} link={getShareablePageLink()} - /> - <SnackbarComponent snackbarOpen={snackbarOpen} severity={"info"} handleClose={() => {toggleSnackbar(false)}} text={"Baixando o Recurso... Lembre-se de relatar sua experiência após o uso do Recurso!"} - /> - <div style={{fontSize: "12px", display : "flex", flexDirection : "column", justifyContent : "center"}}> - <ButtonNoWidth aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick} style={{color : "#666"}}> - <MoreVertIcon style={{color : "#666"}}/> - </ButtonNoWidth> - <Menu - id="simple-menu" - anchorEl={anchorEl} - keepMounted - open={Boolean(anchorEl)} - onClose={handleClose} - > - <StyledMenuItem onClick={handleClose}> - <Link to={"/recurso/" + props.learningObjectId}> - <ListItemIcon><OpenIcon /></ListItemIcon>Abrir - </Link> - </StyledMenuItem> - - { - props.downloadableLink && - <StyledMenuItem onClick={() => {enableDownload(); handleClose()}}> - <ListItemIcon><DownloadIcon /></ListItemIcon>Baixar - </StyledMenuItem> - } - - <StyledMenuItem onClick={handleShare}> - <ListItemIcon><ShareIcon /></ListItemIcon>Compartilhar - </StyledMenuItem> - - <StyledMenuItem onClick={handleGuardar}> - <ListItemIcon><AddIcon /></ListItemIcon>Guardar - </StyledMenuItem> - - <StyledMenuItem onClick={() => {handleModalReportar(true); handleClose()}}> - <ListItemIcon><ReportIcon /></ListItemIcon>Reportar - </StyledMenuItem> - </Menu> - </div> - </React.Fragment> - ); + <> + + <React.Fragment> + <ReportModal open={reportModal} handleClose={() => handleModalReportar(false)} + form="recurso" complainableId={props.learningObjectId} + complainableType={"LearningObject"} + {...props} + /> + <GuardarModal open={saveToCol} handleClose={() => { toggleSave(false) }} + thumb={props.thumb} title={props.title} recursoId={props.learningObjectId} + /> + <ShareModal open={shareOpen} handleClose={() => { toggleShare(false) }} + thumb={props.thumb} title={props.title} link={getShareablePageLink()} + /> + <SnackbarComponent snackbarOpen={snackbarOpen} severity={"info"} handleClose={() => { toggleSnackbar(false) }} text={"Baixando o Recurso... Lembre-se de relatar sua experiência após o uso do Recurso!"} + /> + <SignUpModal open={signUpOpen} handleClose={handleSignUp} openLogin={handleLogin} + /> + <LoginModal open={loginOpen} handleClose={() => setLogin(false)} openSignUp={handleSignUp} + openSnackbar={() => { handleSuccessfulLogin(true) }} + /> + <Snackbar open={successfulLoginOpen} autoHideDuration={1000} onClose={toggleLoginSnackbar} + anchorOrigin={{ vertical: 'top', horizontal: 'center' }} + > + <Alert severity="success" style={{ backgroundColor: "#00acc1" }}>Você está conectado(a)!</Alert> + </Snackbar> + <div style={{ fontSize: "12px", display: "flex", flexDirection: "column", justifyContent: "center" }}> + <ButtonNoWidth aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick} style={{ color: "#666" }}> + <MoreVertIcon style={{ color: "#666" }} /> + </ButtonNoWidth> + <Menu + id="simple-menu" + anchorEl={anchorEl} + keepMounted + open={Boolean(anchorEl)} + onClose={handleClose} + > + <Tooltip title="Não preserva filtro" arrow> + <StyledMenuItem onClick={handleClose}> + <Link to={"/recurso/" + props.learningObjectId}> + <ListItemIcon><OpenIcon /></ListItemIcon>Abrir + </Link> + </StyledMenuItem> + </Tooltip> + + <Tooltip title="Preserva filtro" arrow> + <StyledMenuItem onClick={() => window.open("/recurso/" + props.learningObjectId, "_blank")}> + <ListItemIcon><OpenInBrowserIcon /></ListItemIcon> Abrir em nova guia + </StyledMenuItem> + </Tooltip> + + { + props.downloadableLink && + <StyledMenuItem onClick={() => { enableDownload(); handleClose() }}> + <ListItemIcon><DownloadIcon /></ListItemIcon>Baixar + </StyledMenuItem> + } + + <StyledMenuItem onClick={handleShare}> + <ListItemIcon><ShareIcon /></ListItemIcon>Compartilhar + </StyledMenuItem> + + <StyledMenuItem onClick={handleGuardar}> + <ListItemIcon><AddIcon /></ListItemIcon>Guardar + </StyledMenuItem> + + <StyledMenuItem onClick={() => { handleModalReportar(true); handleClose() }}> + <ListItemIcon><ReportIcon /></ListItemIcon>Reportar + </StyledMenuItem> + + </Menu> + </div> + </React.Fragment> + </> + ); } const ButtonNoWidth = styled(Button)` diff --git a/src/Components/ResourceList.js b/src/Components/ResourceList.js index 77c3ce1d67be2751618ee39477a3c6cd8651a756..79d0936ac7ea15277dc989882dc63ae29364495d 100644 --- a/src/Components/ResourceList.js +++ b/src/Components/ResourceList.js @@ -31,15 +31,14 @@ import MuiAlert from '@material-ui/lab/Alert'; import { apiUrl } from '../env.js'; function Alert(props) { - return <MuiAlert elevation={6} variant="filled" {...props} />; + return <MuiAlert elevation={6} variant="filled" {...props} />; } export default function ResourceList(props) { - console.log(props); const [selected, setSelected] = useState(Array.apply( - null, {length: props.resources.length}).map(i => false)); + null, { length: props.resources.length }).map(i => false)); const [selectable, setSelectable] = useState(false); const [download_url, setDownloadUrl] = useState(''); const [snackbar_open, setSnackbarOpen] = useState(false); @@ -68,31 +67,32 @@ export default function ResourceList(props) { let i = 0; while (i < props.resources.length) { if (selected[i]) - resources.push({"type": "LearningObject", "id": props.resources[i].id}); + resources.push({ "type": "LearningObject", "id": props.resources[i].id }); i++; } const body = { "package": { "object": resources - }}; + } + }; if (resources.length) axios - .post(apiUrl+'/package', body) + .post(apiUrl + '/package', body) .catch(err => { if (err.response && err.response.status === 302) { - setDownloadUrl(apiUrl.slice().replace('/v1', '')+'/'+err.response.data.url); + setDownloadUrl(apiUrl.slice().replace('/v1', '') + '/' + err.response.data.url); } }); } }, [selected, selectable]); - + console.log("CARD >>", props.resources) return ( <ResourceListContainer> <Grid container direction="row" justify="space-around" alignItems="center"> <Grid item> <Title> - {props.resources.length ? - props.resources.length+" recurso"+(props.resources.length === 1 ? "" : "s") + {props.resources.length ? + props.resources.length + " recurso" + (props.resources.length === 1 ? "" : "s") : "Carregando coleção"} </Title> </Grid> @@ -105,10 +105,10 @@ export default function ResourceList(props) { </Grid> <Grid item> <UnstyledAnchor href={download_url}> - <Button - color="primary" + <Button + color="primary" variant="outlined" - startIcon={<GetAppIcon fontSize="large"/>} + startIcon={<GetAppIcon fontSize="large" />} onClick={handleDownloadSelection} > <PanelButtonText>baixar seleção</PanelButtonText> @@ -117,33 +117,36 @@ export default function ResourceList(props) { </Grid> </Grid> <Grid container direction="row" justify="flex-start" alignItems="center"> - {props.resources.map((r) => { + {props.resources.map((card) => { return ( - <ResourceGrid item key={r.title}> + <ResourceGrid item key={card.title}> <ResourceCardFunction - type={r.type} - author={r.author} - tags={r.tags} - published={r.published} - title={r.title} - rating={r.rating} - likeCount={r.likeCount} - liked={r.liked} - thumbnail={r.thumbnail} - href={"/recurso/" + r.id} + avatar={card.avatar} + id={card.id} + thumbnail={card.thumbnail} + type={card.type ? card.type : "Outros"} + title={card.title} + published={card.state === "published" ? true : false} + likeCount={card.likeCount} + liked={card.liked} + rating={card.rating} + author={card.publisher} + tags={card.tags} + href={"/recurso/" + card.id} + downloadableLink={card.downloadableLink} /> - {selectable ? + {selectable ? (<SelectButton variant="outline" color="primary" - startIcon={checkBoxIcon(selected[props.resources.indexOf(r)])} - onClick={() => updateSelected(props.resources.indexOf(r))} + startIcon={checkBoxIcon(selected[props.resources.indexOf(card)])} + onClick={() => updateSelected(props.resources.indexOf(card))} > Selecionar </SelectButton>) : <span></span>} - + </ResourceGrid> ); })} @@ -152,35 +155,35 @@ export default function ResourceList(props) { open={snackbar_open} autoHideDuration={6000} onClose={() => setSnackbarOpen(false)} - anchorOrigin={{vertical: 'top', horizontal: 'right'}} + anchorOrigin={{ vertical: 'top', horizontal: 'right' }} > <Alert onClose={() => setSnackbarOpen(false)} severity="info"> Os recursos serão baixados </Alert> </Snackbar> - <FloatingDownloadButton url={download_url} empty={selected.indexOf(true) === -1}/> + <FloatingDownloadButton url={download_url} empty={selected.indexOf(true) === -1} /> </ResourceListContainer> ); } -const ResourceListContainer=styled.div` +const ResourceListContainer = styled.div` margin-left: 20; margin-right: 20; ` -const Title=styled.p` +const Title = styled.p` color: rgb(102, 102, 102); font-size: 2em; font-weigth: 300; ` -const SelectButton=styled(Button)` +const SelectButton = styled(Button)` width: 100%; ` -const PanelButtonText=styled.span` +const PanelButtonText = styled.span` font-weight: 900; ` -const ResourceGrid=styled(Grid)` +const ResourceGrid = styled(Grid)` padding-right: 7px; ` -const UnstyledAnchor=styled.a` +const UnstyledAnchor = styled.a` text-decoration: none !important; ` diff --git a/src/Components/ResourcePageComponents/CommentForm.js b/src/Components/ResourcePageComponents/CommentForm.js index 1859e116c0028088fcbab5378ce49776151dfd0b..0b1c38ba693b98b03c689f18035a6f81478d9cd9 100644 --- a/src/Components/ResourcePageComponents/CommentForm.js +++ b/src/Components/ResourcePageComponents/CommentForm.js @@ -4,10 +4,9 @@ import Rating from '@material-ui/lab/Rating'; import StarIcon from '@material-ui/icons/Star'; import TextField from "@material-ui/core/TextField"; import { Button } from '@material-ui/core'; -import axios from 'axios' -import {apiUrl} from '../../env'; import EditIcon from '@material-ui/icons/Edit'; import Grid from '@material-ui/core/Grid'; +import {postRequest} from '../HelperFunctions/getAxiosConfig' export default function CommentForm (props) { const [rating, setRating] = useState({ @@ -27,22 +26,19 @@ export default function CommentForm (props) { const [attemptedSubmit, setAttempt] = useState(false) + function handleSuccess (data) { + props.handleSnackbar(1) + props.rerenderCallback() + } const handleSubmit = (e) => { e.preventDefault() const finalRating = rating const finalComment = comment - if (!(finalRating.error || finalComment.error)) { - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid'), - } - } + let type = props.recurso ? 'learning_objects' : 'collections' + const url = `/${type}/${props.recursoId}/reviews` + let payload = { "review" : { "description" : finalComment.value, @@ -54,17 +50,8 @@ export default function CommentForm (props) { ] } } - let type = props.recurso ? 'learning_objects/' : 'collections/' - console.log(payload) - axios.post( (`${apiUrl}/` + type + props.recursoId + '/reviews'), payload, config - ).then((response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response.data); - props.handleSnackbar(1); - props.rerenderCallback()}, - (error) => {console.log(error)}) + + postRequest(url, payload, handleSuccess, (error) => {console.log(error)}) } else { setAttempt(true) @@ -90,7 +77,7 @@ export default function CommentForm (props) { <div className="star-alert" style={attemptedSubmit ? {visibility : "visible"} : {visibility : "hidden" }}>{props.recurso ? "Avalie se o recurso foi útil." : "Avalie se esta coleção foi útil."}</div> <Grid container> - <Grid item xs={10}> + <Grid item xs={12} md={9}> <StyledTextField colecao={!props.recurso} value={comment.value} @@ -103,22 +90,22 @@ export default function CommentForm (props) { help = {comment.error ? (props.recurso ? "Escreva aqui a sua experiência com este Recurso" : "Escreva aqui a sua experiência com esta Coleção") : ''} /> </Grid> - <Grid item xs={2}> + <Grid item xs={12} md={3}> <div style={{height : "100%", display : "flex", flexDirection : "column", justifyContent : "flex-end"}}> - { - props.recurso ? - ( - <OrangeButton type="submit">Publicar</OrangeButton> - ) - : - ( - <PurpleButton type="submit"><EditIcon/>Enviar</PurpleButton> - ) - } - </div> - </Grid> + { + props.recurso ? + ( + <OrangeButton type="submit">Publicar</OrangeButton> + ) + : + ( + <PurpleButton type="submit"><EditIcon/>Enviar</PurpleButton> + ) + } + </div> + </Grid> - <div className="campos-obrigatorios">* Campos obrigatórios.</div> + <div className="campos-obrigatorios">* Campos obrigatórios.</div> </Grid > </StyledForm> ) diff --git a/src/Components/ResourcePageComponents/CommentsArea.js b/src/Components/ResourcePageComponents/CommentsArea.js index fdabf83639c62c34221ad6d5d3d093c5c1a7dba1..10a9482f73b5e49ac3e7089453cee29378fca290 100644 --- a/src/Components/ResourcePageComponents/CommentsArea.js +++ b/src/Components/ResourcePageComponents/CommentsArea.js @@ -23,10 +23,10 @@ import Grid from '@material-ui/core/Grid'; import { Button } from '@material-ui/core'; import ExitToAppIcon from '@material-ui/icons/ExitToApp'; import Comentarios from '../../img/comentarios.png' -import {apiUrl, apiDomain} from '../../env'; +import {apiDomain} from '../../env'; import CommentForm from './CommentForm.js' -import axios from 'axios' import Comment from '../Comment.js' +import {getRequest} from '../HelperFunctions/getAxiosConfig' export default function CommentsArea (props) { const {state} = useContext(Store) @@ -34,15 +34,14 @@ export default function CommentsArea (props) { const [gambiarra, setState] = useState(0) const forceUpdate = () => {setState(gambiarra + 1)} + function handleSuccess (data) { + setComentarios(data.sort((a, b) => a.updated_at > b.updated_at ? -1 : 1)) + } + useEffect( () => { - axios.get( (`${apiUrl}/learning_objects/` + props.recursoId + '/reviews') - ).then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - setComentarios(response.data.sort((a, b) => a.updated_at > b.updated_at ? -1 : 1)) - }, (error) => {console.log(error)}) + const url = `/learning_objects/${props.recursoId}/reviews` + + getRequest(url, handleSuccess, (error) => {console.log(error)}) }, [gambiarra]) return ( @@ -55,7 +54,7 @@ export default function CommentsArea (props) { <h3>Conte sua experiência com o Recurso</h3> <Grid container style={{paddingTop : "20px"}}> <Grid item xs={2} style={{paddingLeft : "15px", paddingRight : "15px"}}> - <img src={apiDomain + state.currentUser.avatar_file_name} className="minha-imagem" alt="user avatar"/> + <img src={apiDomain + state.currentUser.avatar} className="minha-imagem" alt="user avatar"/> </Grid> <Grid item xs={10}> <CommentForm diff --git a/src/Components/ResourcePageComponents/Sobre.js b/src/Components/ResourcePageComponents/Sobre.js index 0ff18fa7343d7125f803e2cdd9467c6ab11d7ee1..7cf58bf7c28f6f1a67ad359dbcd39c6b3e41347c 100644 --- a/src/Components/ResourcePageComponents/Sobre.js +++ b/src/Components/ResourcePageComponents/Sobre.js @@ -270,7 +270,6 @@ const SobreDiv = styled.div` .tags-container { padding : 0; width : 100%; - display : flex; flex-direction : row; align-items : center; font-size : .8em; diff --git a/src/Components/ResourcePageComponents/TextoObjeto.js b/src/Components/ResourcePageComponents/TextoObjeto.js index 5b5bc3cdefe384f9a579681ba24fc6f5d637018d..1554cc9ebd70387fd72cb155f749232133f1b5c0 100644 --- a/src/Components/ResourcePageComponents/TextoObjeto.js +++ b/src/Components/ResourcePageComponents/TextoObjeto.js @@ -29,9 +29,7 @@ import Button from '@material-ui/core/Button'; import {Link, Redirect} from 'react-router-dom' import Alert from '../Alert.js'; import Snackbar from '@material-ui/core/Snackbar'; -import {getAxiosConfig} from '../HelperFunctions/getAxiosConfig' -import axios from 'axios' -import {apiUrl} from '../../env'; +import {deleteRequest} from '../HelperFunctions/getAxiosConfig' export default function TextoObjeto (props) { const {state} = useContext(Store) @@ -81,21 +79,13 @@ export default function TextoObjeto (props) { const [snackbarOpen, toggleSnackbar] = useState(false) const [publisherDeletedObject, toggleDeleted] = useState(false) + function handleSuccess (data) { + toggleSnackbar(true) + toggleDeleted(true) + } const handleDelete = () => { - let config = getAxiosConfig() - axios.delete((`${apiUrl}/learning_objects/` + props.recursoId), config).then( - (response) => { - toggleSnackbar(true) - console.log(response.data) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - toggleDeleted(true) - }, - (error) => { - console.log(error) - } - ) + const url = `/learning_objects/${props.recursoId}` + deleteRequest(url, handleSuccess, (error) => {console.log(error)}) } const checkAccessLevel = (levelToCheck) => { diff --git a/src/Components/SearchExpansionPanel/ExpansionPanel.css b/src/Components/SearchExpansionPanel/ExpansionPanel.css new file mode 100644 index 0000000000000000000000000000000000000000..f97d0f5758cf640c3153e4667c95627fea39a888 --- /dev/null +++ b/src/Components/SearchExpansionPanel/ExpansionPanel.css @@ -0,0 +1,14 @@ +.MuiAccordionActions-root{ + display: block !important; +} +.MuiListItemIcon-root{ + min-width: 30px !important; +} + +.MuiListItem-secondaryAction { + padding-right: 0px !important; +} + +.MuiListItem-gutters { + padding-left: 10px !important; +} \ No newline at end of file diff --git a/src/Components/SearchExpansionPanel/SearchExpansionPanel.js b/src/Components/SearchExpansionPanel/SearchExpansionPanel.js index 31ce7434630c75d5f12fb8b9a2044f6eb7697281..ca65cb10c67872ac3d7e44c0b0f560b5cfa32a0a 100644 --- a/src/Components/SearchExpansionPanel/SearchExpansionPanel.js +++ b/src/Components/SearchExpansionPanel/SearchExpansionPanel.js @@ -1,8 +1,8 @@ import React, { useState } from "react"; import { withStyles } from "@material-ui/core/styles"; -import MuiExpansionPanel from "@material-ui/core/ExpansionPanel"; -import MuiExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary"; -import MuiExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails"; +import MuiExpansionPanel from "@material-ui/core/Accordion"; +import MuiExpansionPanelSummary from "@material-ui/core/AccordionSummary"; +import MuiExpansionPanelDetails from "@material-ui/core/AccordionActions"; import Typography from "@material-ui/core/Typography"; import ExpandMoreIcon from "@material-ui/icons/ExpandMore"; import SearchEPCompCurriculum from "./SearchEPCompCurriculum"; @@ -13,6 +13,8 @@ import { TextField } from "@material-ui/core"; import Grid from '@material-ui/core/Grid'; import CircularProgress from '@material-ui/core/CircularProgress'; +import './ExpansionPanel.css' + const ExpansionPanel = withStyles({ root: { border: "1px solid rgba(0, 0, 0, .125)", @@ -62,7 +64,7 @@ const TesteTypography = withStyles({ const ExpansionPanelDetails = withStyles(theme => ({ root: { - padding: theme.spacing(2) + // padding: theme.spacing(2) } }))(MuiExpansionPanelDetails); @@ -96,12 +98,12 @@ export default function SearchExpansionPanel(props) { direction="row" justify="space-between" > - <Grid item> + <Grid item > <Typography style={{ fontSize: "18px", textTransform: "uppercase", - fontWeight: "500" + fontWeight: "500", }} > Filtros @@ -126,9 +128,9 @@ export default function SearchExpansionPanel(props) { <TesteTypography>Componentes Curriculares</TesteTypography> </ExpansionPanelSummary> <ExpansionPanelDetails> - <Typography> + <div> <SearchEPCompCurriculum onChange={props.onChange} /> - </Typography> + </div> </ExpansionPanelDetails> </ExpansionPanel> diff --git a/src/Components/SearchSection.js b/src/Components/SearchSection.js index fac1acb0fc1bbf0423cc56a59eb93d6b4d4ca957..228d72b41c9762d19fc62fe0d73676ed36fc643a 100644 --- a/src/Components/SearchSection.js +++ b/src/Components/SearchSection.js @@ -84,7 +84,7 @@ class SearchSection extends Component{ <FaRegPlayCircle size="20px" style={{verticalAlign: "middle", paddingRight : "5px"}}/>VÍDEO DE APRESENTAÇÃO </span> </div> - <Row justify="center"> + <Row justify="center" style={{marginLeft:0, marginRight:0}}> <button style={{...buttonStyle, ...{backgroundColor: "#ff7f00",fontSize:"1.14em", outline:"none"}}} onClick={()=> {this.props.function("Recursos")}}>Recursos Educacionais Digitais</button> <button style={{...buttonStyle, ...{backgroundColor: "#e81f4f",fontSize:"1.14em", outline:"none"}}} onClick={()=> {this.props.function("Materiais")}}>Materiais de Formação</button> <button style={{...buttonStyle, ...{backgroundColor: "#673ab7",fontSize:"1.14em", outline:"none"}}} onClick={()=> {this.props.function("Colecoes")}}>Coleções dos Usuários</button> diff --git a/src/Components/ShareModal.js b/src/Components/ShareModal.js index 4089314b3fb30149b211bd7b3d83a4e1b016c033..93eb4828efc78e5cf0b8216caa8297d3c5c4331c 100644 --- a/src/Components/ShareModal.js +++ b/src/Components/ShareModal.js @@ -73,7 +73,7 @@ export default function ReportModal (props) { {/*Share to facebook*/} <Grid item xs={4}> - <a + <StyledLink href={"https://www.facebook.com/sharer/sharer.php?u=" + props.link} rel="noreferrer" target="_blank"> @@ -81,12 +81,12 @@ export default function ReportModal (props) { <img src={Facebook} alt="facebook-logo"/> <p>FACEBOOK</p> </ShareButton> - </a> + </StyledLink> </Grid> {/*Share to Twitter*/} <Grid item xs={4}> - <a + <StyledLink href={"https://www.twitter.com/intent/tweet?url=" + props.link} rel="noreferrer" target="_blank"> @@ -94,7 +94,7 @@ export default function ReportModal (props) { <img src={Twitter} alt="twitter-logo"/> <p>TWITTER</p> </ShareButton> - </a> + </StyledLink> </Grid> {/*Get shareable link*/} @@ -242,3 +242,6 @@ const Container = styled.div` height : 100%; } ` +const StyledLink = styled.a` + text-decoration : none; +` \ No newline at end of file diff --git a/src/Components/SignUpContainerFunction.js b/src/Components/SignUpContainerFunction.js index 19ec20363c139c803bfd66c9f5807f83ce52a35e..d336d3417c5075122c4090f03be9695458746620 100644 --- a/src/Components/SignUpContainerFunction.js +++ b/src/Components/SignUpContainerFunction.js @@ -26,7 +26,7 @@ import FormInput from "./FormInput.js" import {StyledCloseModalButton, DialogContentDiv, DialogHeaderStyled, SocialConnectDiv, H3Div} from './LoginContainerFunction.js' import {apiUrl} from '../env.js' import {GoogleLoginButton} from './LoginContainerFunction' -import ValidateUserInput from '../Components/FormValidationFunction.js' +import ValidateUserInput from './HelperFunctions/FormValidationFunction.js' import GoogleLogo from "../img/logo_google.svg" async function handleGoogleAttempt () { diff --git a/src/Components/SignUpModal.js b/src/Components/SignUpModal.js index d5d26a54fbe21f8e5d33be7c9514376a81f2bcc3..d3ed47c79a2b85273ff94601d99092d6e52bbacc 100644 --- a/src/Components/SignUpModal.js +++ b/src/Components/SignUpModal.js @@ -22,32 +22,22 @@ import Fade from '@material-ui/core/Fade'; import styled from 'styled-components' import SignUpContainer from './SignUpContainerFunction.js' import {Store} from '../Store.js' -import axios from 'axios' -import {apiUrl} from '../env'; - -const StyledModalSignUp = styled(Modal)` - .djXaxP{ - margin : 0 !important; - } - - display : flex; - align-items: center; - justify-content : center; - text-align : center; - padding : 10px !important; - border-radius : 4px; - -` - - +import {authentication} from './HelperFunctions/getAxiosConfig' export default function SignUpModal (props) { const { state, dispatch } = useContext(Store) + function handleSuccess (data) { + dispatch ({ + type: 'USER_SIGNED_UP', + userLoggedIn: !state.userIsLoggedIn, + user: data.data + }) + props.handleClose() + } const handleLoginInfo = (newLogin) => { - // {/*console.log(state.currentUser)*/} - axios.post(`${apiUrl}/auth`, - { + const url = `/auth` + const payload = { name : newLogin.name, email: newLogin.email, password : newLogin.password, @@ -55,37 +45,9 @@ export default function SignUpModal (props) { terms_of_service:true, avatar: "" } - ).then( (response) => { - dispatch ( { - type: 'USER_SIGNED_UP', - userLoggedIn: !state.userIsLoggedIn, - user: response.data.data - } - ) - localStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - localStorage.setItem('@portalmec/clientToken', response.headers.client,) - localStorage.setItem('@portalmec/id', response.data.data.id) - localStorage.setItem('@portalmec/username', response.data.data.name) - localStorage.setItem('@portalmec/uid', response.data.data.uid) - - let headers = { - client:response.headers.client, - "access-token":response.headers['access-token'], - "token-type": "Bearer", - expiry:response.headers.expiry, - uid:response.data.data.uid - } - sessionStorage.setItem('@portalmec/auth_headers', JSON.stringify(headers)) - - props.handleClose() - }, (error) => { - console.log(':(') - } - ) + authentication(url, payload, handleSuccess, (error) => {console.log(error)}) } - //useEffect(()=>{console.log(state.currentUser)},[state.currentUser]) - return ( <StyledModalSignUp aria-labelledby="transition-modal-title" @@ -110,3 +72,17 @@ export default function SignUpModal (props) { </StyledModalSignUp> ) } + +const StyledModalSignUp = styled(Modal)` + .djXaxP{ + margin : 0 !important; + } + + display : flex; + align-items: center; + justify-content : center; + text-align : center; + padding : 10px !important; + border-radius : 4px; + +` diff --git a/src/Components/StatsBar.js b/src/Components/StatsBar.js index 0572d3f89199ec0096cfb582b681888cf02e9168..0cdde4942b065244271cb8e5c82f44e0e96d36d2 100644 --- a/src/Components/StatsBar.js +++ b/src/Components/StatsBar.js @@ -18,6 +18,8 @@ along with Plataforma Integrada MEC. If not, see <http://www.gnu.org/licenses/> import React, {Component} from 'react'; import {Col,Row, Container} from 'react-grid-system'; +import { apiUrl } from "../env"; +import axios from "axios"; import mapaBrasil from '../img/mapa-brasil-line-icon.svg'; const brasilStyle={ backgroundColor: "#00bcd4", @@ -41,6 +43,21 @@ const statistcStyle={ }; class StatsBar extends Component{ + constructor(props){ + super(props) + this.state ={ + available_resources: 0, + month_publications:0, + month_downloads:0 + } + } + componentDidMount(){ + // https://api.portalmec.c3sl.ufpr.br/v1/statistics + axios.get(`${apiUrl}/statistics`).then((res) => { + this.setState({available_resources:res.data.count, month_publications:res.data.month_publications, month_downloads:res.data.month_downloads}) + }) + } + render(){ return( <div style={brasilStyle}> @@ -50,7 +67,7 @@ class StatsBar extends Component{ <img src={mapaBrasil} height="83px" alt="mapa do brasil"/> <span style={statistcStyle}> <span style={numberStyle}> - 31061 + {this.state.available_resources} </span> <span> Recursos disponíveis @@ -62,13 +79,13 @@ class StatsBar extends Component{ ESSE MÊS: <span style={statistcStyle}> <span style={numberStyle}> - 10 + {this.state.month_downloads} </span> Baixados </span> <span style={statistcStyle}> <span style={numberStyle}> - 1 + {this.state.month_publications} </span> Publicados </span> diff --git a/src/Components/TabPanels/Breadcrumbs.js b/src/Components/TabPanels/Breadcrumbs.js index 00d547825993a8dd803b6d3a7f89617e71fd2714..1d208986d7bd89b210da95806d101796301a36d9 100644 --- a/src/Components/TabPanels/Breadcrumbs.js +++ b/src/Components/TabPanels/Breadcrumbs.js @@ -1,3 +1,22 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 from 'react' import styled from 'styled-components' import Breadcrumbs from '@material-ui/core/Breadcrumbs'; @@ -12,8 +31,8 @@ export default function CustomizedBreadcrumbs (props) { Página Inicial </Link> { - props.values.map( (value) => - <span> + props.values.map( (value, i) => + <span key={i}> {value} </span> ) diff --git a/src/Components/TabPanels/PanelComponents/TemplateColecao.js b/src/Components/TabPanels/PanelComponents/TemplateColecao.js index dfb193fc5a5db0774c39c7df8095153eedc36c59..3b1e029ae45caa45f28068cd95693796a6331a86 100644 --- a/src/Components/TabPanels/PanelComponents/TemplateColecao.js +++ b/src/Components/TabPanels/PanelComponents/TemplateColecao.js @@ -21,17 +21,18 @@ import Grid from '@material-ui/core/Grid'; import NoContent from './NoContent.js' import CollectionCardFunction from '../../CollectionCardFunction.js' import Title from './PanelTitle.js' -import {WhiteContainer, StyledGrid} from '../StyledComponents.js' -import {ButtonsAreaColecao} from './ButtonsArea' +import { WhiteContainer, StyledGrid } from '../StyledComponents.js' +import { ButtonsAreaColecao } from './ButtonsArea' -export default function PanelTemplateColecao (props) { +export default function PanelTemplateColecao(props) { const RenderFollowedColCard = (card, followerBoolean) => { if (followerBoolean) { return ( <CollectionCardFunction - name={card.followable.name} - rating={card.followable.score} + name={card.name} + collections={card.followable.collection_items} + rating={card.followable.review_average} type={card.followable.object_type} description={card.followable.description} author={card.followable.owner.name} @@ -43,27 +44,27 @@ export default function PanelTemplateColecao (props) { followed={card.followable.followed} privacy={card.followable.privacy} id={card.followable.id} - /> + tags={card.followable.tags} + /> ) } else { return ( <CollectionCardFunction - name={card.name} - rating={card.score} - type={card.object_type} - description={card.description} - author={card.owner.name} - avatar={card.owner.avatar} - authorID={card.owner.id} - thumbnails={card.items_thumbnails} - likeCount={card.likes_count} - privacy={card.privacy} - liked={card.liked} - followed={card.followed} - tags={card.tags} - id={card.id} - /> + name={card.name} + tags={card.tags} + rating={card.review_average} + id={card.id} + author={card.owner.name} + description={card.description} + thumbnails={card.items_thumbnails} + avatar={card.owner.avatar} + likeCount={card.likes_count} + followed={card.followed} + liked={card.liked} + collections={card.collection_items} + authorID={card.owner.id} + /> ) } } @@ -78,24 +79,21 @@ export default function PanelTemplateColecao (props) { { props.length === 0 ? ( - [ - <NoContent text={props.noContentText}/> - ] + <NoContent text={props.noContentText}/> ) : ( - [ <React.Fragment> - <StyledGrid container spacing={1} style={{paddingLeft : "30px", paddingRight : "15px"}}> - { - props.sliceArr.map( (card) => - <Grid item md={3} xs={12} key={card.id}> - {RenderFollowedColCard(card, props.followed)} - </Grid> - ) - } - </StyledGrid> + <StyledGrid container spacing={1} style={{ paddingLeft: "30px", paddingRight: "15px" }}> + { + props.sliceArr.map((card) => + <Grid item md={3} xs={12} key={card.id}> + {RenderFollowedColCard(card, props.followed)} + </Grid> + ) + } + </StyledGrid> <ButtonsAreaColecao sliceLength={props.sliceArr.length} @@ -104,7 +102,6 @@ export default function PanelTemplateColecao (props) { showAll={() => props.showAll()} /> </React.Fragment> - ] ) } diff --git a/src/Components/TabPanels/PanelComponents/TemplateCuradoria.js b/src/Components/TabPanels/PanelComponents/TemplateCuradoria.js index 132b96efa8ba381fa3ad1eb5cdfc0fb66611965f..28390ab44fedca9c8e18c95af860496f2317ca55 100644 --- a/src/Components/TabPanels/PanelComponents/TemplateCuradoria.js +++ b/src/Components/TabPanels/PanelComponents/TemplateCuradoria.js @@ -21,10 +21,11 @@ import Grid from '@material-ui/core/Grid'; import NoContent from './NoContent.js' import ResourceCardFunction from '../../ResourceCardFunction.js' import Title from './PanelTitle.js' -import {WhiteContainer, StyledGrid} from '../StyledComponents.js' -import {ButtonsAreaRecurso} from './ButtonsArea' +import { WhiteContainer, StyledGrid } from '../StyledComponents.js' +import { ButtonsAreaRecurso } from './ButtonsArea' -export default function Template (props) { +export default function Template(props) { + console.log(props.sliceArr); return ( <WhiteContainer> <Title @@ -34,44 +35,48 @@ export default function Template (props) { { props.length === 0 ? - ( - [ - <NoContent text={props.noContentText}/> - ] - ) - : - ( - [ - <React.Fragment> - <StyledGrid container spacing={1} style={{paddingLeft : "30px", paddingRight : "15px"}}> - { - props.sliceArr.map( (card) => - <Grid item md={3} xs={12} key={card.id}> - <ResourceCardFunction - id={card.learning_object.id} - avatar = {card.submitter.avatar} - thumbnail = {card.learning_object.thumbnail} - type = {card.learning_object.object_type ? card.learning_object.object_type : "Outros"} - title={card.learning_object.name} - published={false} - tags={card.educational_stages} - href={"/recurso/" + card.learning_object.id} - downloadableLink={card.default_attachment_location} - /> - </Grid> - ) - } - </StyledGrid> + ( + [ + <NoContent text={props.noContentText} /> + ] + ) + : + ( + [ + <React.Fragment> + <StyledGrid container spacing={1} style={{ paddingLeft: "30px", paddingRight: "15px" }}> + { + props.sliceArr.map((card) => + <Grid item md={3} xs={12} key={card.id}> + <ResourceCardFunction + avatar={card.submitter.avatar} + id={card.learning_object.id} + thumbnail={card.learning_object.thumbnail} + type={card.learning_object.object_type ? card.learning_object.object_type : "Outros"} + title={card.learning_object.name} + published={false} + likeCount={card.learning_object.likes_count} + liked={card.learning_object.liked} + rating={card.learning_object.review_average} + author={card.submitter.name} + tags={card.learning_object.tags} + href={"/recurso/" + card.learning_object.id} + downloadableLink={card.default_attachment_location} + /> + </Grid> + ) + } + </StyledGrid> - <ButtonsAreaRecurso - sliceLength={props.sliceArr.length} - length={props.length} - showMore={() => props.showMore()} - showAll={() => props.showAll()} - /> - </React.Fragment> - ] - ) + <ButtonsAreaRecurso + sliceLength={props.sliceArr.length} + length={props.length} + showMore={() => props.showMore()} + showAll={() => props.showAll()} + /> + </React.Fragment> + ] + ) } </WhiteContainer> diff --git a/src/Components/TabPanels/PanelComponents/TemplateRecurso.js b/src/Components/TabPanels/PanelComponents/TemplateRecurso.js index 6d46e423e6c596efbff5a2725d7ba5d8bb26feab..7fe23657690955daee2580a278001f1605b9c7e0 100644 --- a/src/Components/TabPanels/PanelComponents/TemplateRecurso.js +++ b/src/Components/TabPanels/PanelComponents/TemplateRecurso.js @@ -21,10 +21,10 @@ import Grid from '@material-ui/core/Grid'; import NoContent from './NoContent.js' import ResourceCardFunction from '../../ResourceCardFunction.js' import Title from './PanelTitle.js' -import {WhiteContainer, StyledGrid} from '../StyledComponents.js' -import {ButtonsAreaRecurso} from './ButtonsArea' +import { WhiteContainer, StyledGrid } from '../StyledComponents.js' +import { ButtonsAreaRecurso } from './ButtonsArea' -export default function Template (props) { +export default function Template(props) { return ( <WhiteContainer> <Title @@ -34,48 +34,49 @@ export default function Template (props) { { props.length === 0 ? - ( - [ - <NoContent text={props.noContentText}/> - ] - ) - : - ( - [ - <React.Fragment> - <StyledGrid container spacing={1} style={{paddingLeft : "30px", paddingRight : "15px"}}> - { - props.slice.map( (card) => - <Grid item md={3} xs={12} key={card.id}> - <ResourceCardFunction - avatar = {card.publisher.avatar} - id={card.id} - thumbnail = {card.thumbnail} - type = {card.object_type !== null? card.object_type : "Outros"} - title={card.name} - published={card.state === "published" ? true : false} - likeCount={card.likes_count} - liked={card.liked} - rating={card.review_average} - tags={card.educational_stages} - href={"/recurso/" + card.id} - downloadableLink={card.default_attachment_location} + ( + [ + <NoContent text={props.noContentText} /> + ] + ) + : + ( + [ + <React.Fragment> + <StyledGrid container spacing={1} style={{ paddingLeft: "30px", paddingRight: "15px" }}> + { + props.slice.map((card) => + <Grid item md={3} xs={12} key={card.id}> + <ResourceCardFunction + avatar={card.publisher.avatar} + id={card.id} + thumbnail={card.thumbnail} + type={card.object_type ? card.object_type : "Outros"} + title={card.name} + published={card.state === "published" ? true : false} + likeCount={card.likes_count} + liked={card.liked} + rating={card.review_average} + author={card.publisher.name} + tags={card.tags} + href={"/recurso/" + card.id} + downloadableLink={card.default_attachment_location} - /> - </Grid> - ) - } - </StyledGrid> + /> + </Grid> + ) + } + </StyledGrid> - <ButtonsAreaRecurso - sliceLength={props.slice.length} - length={props.length} - showMore={() => props.showMore()} - showAll={() => props.showAll()} - /> - </React.Fragment> - ] - ) + <ButtonsAreaRecurso + sliceLength={props.slice.length} + length={props.length} + showMore={() => props.showMore()} + showAll={() => props.showAll()} + /> + </React.Fragment> + ] + ) } </WhiteContainer> diff --git a/src/Components/TabPanels/PanelComponents/TemplateRede.js b/src/Components/TabPanels/PanelComponents/TemplateRede.js index b4ded29ef208c343697b8828481bf517abacd27c..e92a49db31b72e4b5d89a91f4e26658c520ba66a 100644 --- a/src/Components/TabPanels/PanelComponents/TemplateRede.js +++ b/src/Components/TabPanels/PanelComponents/TemplateRede.js @@ -13,8 +13,8 @@ export default function PanelTemplateRede (props) { return ( <ContactCard name = {card.follower.name} - avatar = {card.follower.avatar ? apiDomain + card.follower.avatar : null} - cover={card.follower.cover ? apiDomain + card.follower.cover : null} + avatar = {card.follower.avatar !== undefined && card.follower.avatar !== ""? apiDomain + card.follower.avatar : null} + cover={card.follower.cover !== undefined && card.follower.cover !== "" ? apiDomain + card.follower.cover : null} numCollections = {card.follower.collections_count} numLearningObjects = {card.follower.learning_objects_count} follow_count={card.follower.follows_count} @@ -28,8 +28,8 @@ export default function PanelTemplateRede (props) { return ( <ContactCard name = {card.followable.name} - avatar = {card.followable.avatar ? apiDomain + '/' + card.followable.avatar : null} - cover={apiDomain + card.followable.cover} + avatar = {card.followable.avatar !== undefined && card.followable.avatar !== "" ? apiDomain + '/' + card.followable.avatar : null} + cover={card.followable.cover !== undefined && card.followable.cover !== "" ? apiDomain + card.followable.cover : null} numCollections = {card.followable.collections_count} numLearningObjects = {card.followable.learning_objects_count} follow_count={card.followable.follows_count} diff --git a/src/Components/TabPanels/PublicUserPageTabs/LastCollections.js b/src/Components/TabPanels/PublicUserPageTabs/LastCollections.js index 3aab2492a7eb15ad72766c1a8506520d3489ae5c..553b9788dc860e290de3b72bf1acdfd7e06b1730 100644 --- a/src/Components/TabPanels/PublicUserPageTabs/LastCollections.js +++ b/src/Components/TabPanels/PublicUserPageTabs/LastCollections.js @@ -1,11 +1,29 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 from 'react' import Grid from '@material-ui/core/Grid'; -import {HeaderGrid, StyledGrid} from '../StyledComponents.js' -import {NoContent} from './TabInicio.js' +import { HeaderGrid, StyledGrid } from '../StyledComponents.js' +import { NoContent } from './TabInicio.js' import CollectionCardFunction from '../../CollectionCardFunction.js' import NoCol from '../../../img/Pagina_vazia_colecao.png' -export default function LastCols (props) { +export default function LastCols(props) { return ( <React.Fragment> <HeaderGrid container> @@ -16,47 +34,48 @@ export default function LastCols (props) { { - props.count === 0 || props.collections.length === 0? - ( - [ - <Grid container> - <Grid item xs={12}> - <NoContent - image={NoCol} - text1={props.username + " ainda não disponibilizou nenhuma coleção."} - text2={"Quando disponibilizar, elas aparecerão aqui."} - /> + props.count === 0 || props.collections.length === 0 ? + ( + [ + <Grid container> + <Grid item xs={12}> + <NoContent + image={NoCol} + text1={props.username + " ainda não disponibilizou nenhuma coleção."} + text2={"Quando disponibilizar, elas aparecerão aqui."} + /> + </Grid> </Grid> - </Grid> - ] - ) - : - ( - [ - <StyledGrid container spacing={1} style={{paddingLeft : "0.5em"}}> - { - props.collections.slice(0,4).map( (card) => - <Grid item md={3} xs={12} key={card.id}> - <CollectionCardFunction - name={card.name} - rating={card.score} - type={card.object_type} - description={card.description} - author={card.owner.name} - avatar={card.owner.avatar} - thumbnails={card.items_thumbnails} - likeCount={card.likes_count} - liked={card.liked} - followed={card.followed} - tags={card.tags} - id={card.id} - /> - </Grid> - ) - } - </StyledGrid> - ] - ) + ] + ) + : + ( + [ + <StyledGrid container spacing={1} style={{ paddingLeft: "0.5em" }}> + { + props.collections.slice(0, 4).map((card) => + <Grid item md={3} xs={12} key={card.id}> + <CollectionCardFunction + name={card.name} + tags={card.tags} + rating={card.review_average} + id={card.id} + author={card.owner.name} + description={card.description} + thumbnails={card.items_thumbnails} + avatar={card.owner.avatar} + likeCount={card.likes_count} + followed={card.followed} + liked={card.liked} + collections={card.collection_items} + authorID={card.owner.id} + /> + </Grid> + ) + } + </StyledGrid> + ] + ) } </React.Fragment> ) diff --git a/src/Components/TabPanels/PublicUserPageTabs/LastLearnObj.js b/src/Components/TabPanels/PublicUserPageTabs/LastLearnObj.js index 044ebc5bf03964c7290da1c41bc5fc1d7a1c62d0..705faa8d77e70cdeee8b6bbf4ea9e65ead1313fc 100644 --- a/src/Components/TabPanels/PublicUserPageTabs/LastLearnObj.js +++ b/src/Components/TabPanels/PublicUserPageTabs/LastLearnObj.js @@ -1,18 +1,36 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 from 'react' import Grid from '@material-ui/core/Grid'; import ResourceCardFunction from '../../ResourceCardFunction.js' import NoPub from '../../../img/Pagina_vazia_Sem_publicar.png' -import {HeaderGrid, StyledGrid} from '../StyledComponents.js' -import {NoContent} from './TabInicio.js' +import { HeaderGrid, StyledGrid } from '../StyledComponents.js' +import { NoContent } from './TabInicio.js' -export default function LastLearnObjs (props) { +export default function LastLearnObjs(props) { return ( <React.Fragment> <HeaderGrid container> <Grid item xs={9}> <h3>Últimos Recursos Publicados</h3> </Grid> - <Grid item xs={3} style={{textAlign : "end"}}> + <Grid item xs={3} style={{ textAlign: "end" }}> {props.count > 4 && <span> VER MAIS @@ -23,47 +41,48 @@ export default function LastLearnObjs (props) { { props.count === 0 ? - ( - [ - <Grid container> - <Grid item xs={12}> - <NoContent - image={NoPub} - text1={props.username + " ainda não disponibilizou nenhum recurso."} - text2={"Quando disponibilizar, eles aparecerão aqui."} - /> + ( + [ + <Grid container> + <Grid item xs={12}> + <NoContent + image={NoPub} + text1={props.username + " ainda não disponibilizou nenhum recurso."} + text2={"Quando disponibilizar, eles aparecerão aqui."} + /> + </Grid> </Grid> - </Grid> - ] - ) - : - ( - [ - <StyledGrid container spacing={1} style={{paddingLeft : "0.5em"}}> - { - props.learningObjs.slice(0,4).map( (card) => - <Grid item md={3} xs={12} key={card.id}> - <ResourceCardFunction - avatar = {card.publisher.avatar} - id={card.id} - thumbnail = {card.thumbnail} - type = {card.object_type !== null? card.object_type : "Outros"} - title={card.name} - published={card.state === "published" ? true : false} - likeCount={card.likes_count} - liked={card.liked} - rating={card.review_average} - tags={card.educational_stages} - href={"/recurso/" + card.id} - downloadableLink={card.default_attachment_location} + ] + ) + : + ( + [ + <StyledGrid container spacing={1} style={{ paddingLeft: "0.5em" }}> + { + props.learningObjs.slice(0, 4).map((card) => + <Grid item md={3} xs={12} key={card.id}> + <ResourceCardFunction + avatar={card.publisher.avatar} + id={card.id} + thumbnail={card.thumbnail} + type={card.object_type ? card.object_type : "Outros"} + title={card.name} + published={card.state === "published" ? true : false} + likeCount={card.likes_count} + liked={card.liked} + rating={card.review_average} + author={card.publisher.name} + tags={card.tags} + href={"/recurso/" + card.id} + downloadableLink={card.default_attachment_location} - /> - </Grid> - ) - } - </StyledGrid> - ] - ) + /> + </Grid> + ) + } + </StyledGrid> + ] + ) } </React.Fragment> ) diff --git a/src/Components/TabPanels/PublicUserPageTabs/TabColecoes.js b/src/Components/TabPanels/PublicUserPageTabs/TabColecoes.js index 3622356c42741f668544d26565a31a3825848ae4..2b81757d34ee93379d60a8165bac6f6f31216f2e 100644 --- a/src/Components/TabPanels/PublicUserPageTabs/TabColecoes.js +++ b/src/Components/TabPanels/PublicUserPageTabs/TabColecoes.js @@ -1,17 +1,35 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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, useEffect} from 'react' import {HeaderGrid, ContainerStyled, Carregados} from '../StyledComponents.js' import Grid from '@material-ui/core/Grid'; import CollectionCardFunction from '../../CollectionCardFunction.js' -import {ButtonMostrarMaisColecao} from '../PanelComponents/ButtonsArea.js' +import { ButtonMostrarMaisColecao } from '../PanelComponents/ButtonsArea.js' -export default function TabRecursos (props) { +export default function TabRecursos(props) { const [arr, setArr] = useState([]) const [colsSlice, setSlice] = useState([]) - const handleSlice = (newArr) => {setSlice(newArr)} + const handleSlice = (newArr) => { setSlice(newArr) } - useEffect( () => { + useEffect(() => { setArr(props.collections) - setSlice(props.collections.slice(0,4)) + setSlice(props.collections.slice(0, 4)) }, []) const showMore = (quantity) => { @@ -20,31 +38,32 @@ export default function TabRecursos (props) { } return ( - <ContainerStyled style={{flexDirection : "column"}}> + <ContainerStyled style={{ flexDirection: "column" }}> <HeaderGrid container> <Grid item xs={12}> - <h3>Coleções públicas <b style={{fontWeight:"500"}}>({props.count})</b></h3> + <h3>Coleções públicas <b style={{ fontWeight: "500" }}>({props.count})</b></h3> </Grid> </HeaderGrid> - <Grid container spacing={1} style={{paddingLeft : "0.5em"}}> + <Grid container spacing={1} style={{ paddingLeft: "0.5em" }}> { - colsSlice.map( (card) => + colsSlice.map((card) => <Grid item md={3} xs={12} key={card.id}> <CollectionCardFunction name={card.name} - rating={card.score} - type={card.object_type} - description={card.description} + tags={card.tags} + rating={card.review_average} + id={card.id} author={card.owner.name} - avatar={card.owner.avatar} + description={card.description} thumbnails={card.items_thumbnails} + avatar={card.owner.avatar} likeCount={card.likes_count} - liked={card.liked} followed={card.followed} - tags={card.tags} - id={card.id} + liked={card.liked} + collections={card.collection_items} + authorID={card.owner.id} /> </Grid> ) @@ -52,19 +71,19 @@ export default function TabRecursos (props) { </Grid> <Carregados> - <p style={{margin:"0 0 10px", fontSize:"14px"}}> + <p style={{ margin: "0 0 10px", fontSize: "14px" }}> Carregados {colsSlice.length} de {arr.length} </p> { props.count > 5 && <React.Fragment> - <ButtonMostrarMaisColecao onClick={() => {showMore(4)}}> - <span style={{color:"#fff", fontSize:"14px", fontWeight:"500"}}>MOSTRAR MAIS 4</span> + <ButtonMostrarMaisColecao onClick={() => { showMore(4) }}> + <span style={{ color: "#fff", fontSize: "14px", fontWeight: "500" }}>MOSTRAR MAIS 4</span> </ButtonMostrarMaisColecao> - <ButtonMostrarMaisColecao onClick={() => {showMore(20)}}> - <span style={{color:"#fff", fontSize:"14px", fontWeight:"500"}}>MOSTRAR MAIS 20</span> + <ButtonMostrarMaisColecao onClick={() => { showMore(20) }}> + <span style={{ color: "#fff", fontSize: "14px", fontWeight: "500" }}>MOSTRAR MAIS 20</span> </ButtonMostrarMaisColecao> </React.Fragment> } diff --git a/src/Components/TabPanels/PublicUserPageTabs/TabInicio.js b/src/Components/TabPanels/PublicUserPageTabs/TabInicio.js index 9e3cd80b7343218d3110cf687e0b96bce7ee55bd..0663a44c4412e545429c7b560bf9eb2ca9e88126 100644 --- a/src/Components/TabPanels/PublicUserPageTabs/TabInicio.js +++ b/src/Components/TabPanels/PublicUserPageTabs/TabInicio.js @@ -1,3 +1,21 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 from 'react' import styled from 'styled-components' import UserDescription from './UserDescription.js' diff --git a/src/Components/TabPanels/PublicUserPageTabs/TabRecursos.js b/src/Components/TabPanels/PublicUserPageTabs/TabRecursos.js index 6f2a08ba5c7ac1aadb39eb24550d70000b652f87..bf677ebd921dd7f91ffe469a49c4800686843191 100644 --- a/src/Components/TabPanels/PublicUserPageTabs/TabRecursos.js +++ b/src/Components/TabPanels/PublicUserPageTabs/TabRecursos.js @@ -1,50 +1,83 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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, useEffect} from 'react' import {HeaderGrid, ContainerStyled, Carregados} from '../StyledComponents.js' import Grid from '@material-ui/core/Grid'; import ResourceCardFunction from '../../ResourceCardFunction.js' import {ButtonMostrarMaisRecurso} from '../PanelComponents/ButtonsArea' +import {getRequest} from '../../HelperFunctions/getAxiosConfig' -export default function TabRecursos (props) { +export default function TabRecursos(props) { const [arr, setArr] = useState([]) const [objsSlice, setSlice] = useState([]) - const handleSlice = (newArr) => {setSlice(newArr)} + const handleSlice = (newArr) => { setSlice(newArr) } - useEffect( () => { + useEffect(() => { setArr(props.learningObjs) - setSlice(props.learningObjs.slice(0,4)) + setSlice(props.learningObjs.slice(0, 4)) }, []) + function handleSuccess (data) { + setArr(data) + setSlice(data) + } const showMore = (quantity) => { var sliceLength = objsSlice.length - handleSlice(arr.slice(0, sliceLength + quantity)) + var newLength = sliceLength + quantity + + if (newLength > 12) { + const url = `/users/${props.id}/learning_objects?limit=${newLength}$offset=4` + getRequest(url,handleSuccess,(error) => {console.log(error)}) + } + else { + handleSlice(arr.slice(0, sliceLength + quantity)) + } + } return ( - <ContainerStyled style={{flexDirection : "column"}}> + <ContainerStyled style={{ flexDirection: "column" }}> <HeaderGrid container> <Grid item xs={12}> - <h3>Recursos Publicados <b style={{fontWeight:"500"}}>({props.count})</b></h3> + <h3>Recursos Publicados <b style={{ fontWeight: "500" }}>({props.count})</b></h3> </Grid> </HeaderGrid> - <Grid container spacing={1} style={{paddingLeft : "0.5em"}}> + <Grid container spacing={1} style={{ paddingLeft: "0.5em" }}> { - objsSlice.map( (card) => + objsSlice.map((card) => <Grid item md={3} xs={12} key={card.id}> <ResourceCardFunction - avatar = {card.publisher.avatar} + avatar={card.publisher.avatar} id={card.id} - thumbnail = {card.thumbnail} - type = {card.object_type ? card.object_type : "Outros"} + thumbnail={card.thumbnail} + type={card.object_type ? card.object_type : "Outros"} title={card.name} published={card.state === "published" ? true : false} likeCount={card.likes_count} liked={card.liked} rating={card.review_average} - tags={card.educational_stages} + author={card.publisher.name} + tags={card.tags} + href={"/recurso/" + card.id} downloadableLink={card.default_attachment_location} - /> </Grid> ) @@ -52,19 +85,19 @@ export default function TabRecursos (props) { </Grid> <Carregados> - <p style={{margin:"0 0 10px", fontSize:"14px"}}> + <p style={{ margin: "0 0 10px", fontSize: "14px" }}> Carregados {objsSlice.length} de {arr.length} </p> { props.count > 5 && <React.Fragment> - <ButtonMostrarMaisRecurso onClick={() => {showMore(4)}}> - <span style={{color:"#fff", fontSize:"14px", fontWeight:"500"}}>MOSTRAR MAIS 4</span> + <ButtonMostrarMaisRecurso onClick={() => { showMore(4) }}> + <span style={{ color: "#fff", fontSize: "14px", fontWeight: "500" }}>MOSTRAR MAIS 4</span> </ButtonMostrarMaisRecurso> - <ButtonMostrarMaisRecurso onClick={() => {showMore(20)}}> - <span style={{color:"#fff", fontSize:"14px", fontWeight:"500"}}>MOSTRAR MAIS 20</span> + <ButtonMostrarMaisRecurso onClick={() => { showMore(20) }}> + <span style={{ color: "#fff", fontSize: "14px", fontWeight: "500" }}>MOSTRAR MAIS 20</span> </ButtonMostrarMaisRecurso> </React.Fragment> } diff --git a/src/Components/TabPanels/PublicUserPageTabs/TabRede.js b/src/Components/TabPanels/PublicUserPageTabs/TabRede.js index b3dea17eb8b0c7943b3be4e8c7506c7f162c6004..c173dc195d4000acbeda628ffbbef127d1934339 100644 --- a/src/Components/TabPanels/PublicUserPageTabs/TabRede.js +++ b/src/Components/TabPanels/PublicUserPageTabs/TabRede.js @@ -1,20 +1,24 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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, useEffect} from 'react' -import axios from 'axios' -import {apiUrl} from '../../../env'; import PanelTemplateRede from '../PanelComponents/TemplateRede.js' - -const getConfig = () => { - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type':'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid') - } - } - return config -} +import {fetchAllRequest} from '../../HelperFunctions/getAxiosConfig' export default function TabRede (props) { const [followers, setFollowers] = useState([]) @@ -34,26 +38,19 @@ export default function TabRede (props) { } const showAllFollowing = () => {setFollowingSlice(following)} + function handleSuccess (responseArr) { + setFollowers(responseArr[0]) + setFollowersSlice(responseArr[0].slice(0,4)) + + setFollowing(responseArr[1]) + setFollowingSlice(responseArr[1].slice(0,4)) + } + useEffect( () => { - axios.all([ - axios.get((`${apiUrl}/users/` + props.id + '/followers'), getConfig()), - axios.get((`${apiUrl}/users/` + props.id + '/following/User'), getConfig()) - ]) - .then( (responseArr) => { - console.log('responseArr Rede: ', responseArr) - if (responseArr[0].headers['access-token']) { - sessionStorage.setItem('@portalmec/accessToken', responseArr[0].headers['access-token']) - } - setFollowers(responseArr[0].data) - setFollowersSlice(responseArr[0].data.slice(0,4)) - setFollowing(responseArr[1].data) - setFollowingSlice(responseArr[1].data.slice(0,4)) - }, - (error) => { - console.log('error while running axios all') - } - ) + const urls = [`/users/${props.id}/followers`, `/users/${props.id}/following/User`] + + fetchAllRequest(urls, handleSuccess, (error) => {console.log(error)}) }, []) return ( diff --git a/src/Components/TabPanels/PublicUserPageTabs/UserDescription.js b/src/Components/TabPanels/PublicUserPageTabs/UserDescription.js index 495e60e37f549d330c9281f2f86c71d73590367f..4fcc273f0a0b3e8ed984f1d831488d8002a978dd 100644 --- a/src/Components/TabPanels/PublicUserPageTabs/UserDescription.js +++ b/src/Components/TabPanels/PublicUserPageTabs/UserDescription.js @@ -1,3 +1,21 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 from 'react' import styled from 'styled-components' diff --git a/src/Components/TabPanels/StyledComponents.js b/src/Components/TabPanels/StyledComponents.js index 9816407c1b6108c9b4193f2f193c02370aa31021..d77966a39660501c93ccc687a52056cd301b1eb2 100644 --- a/src/Components/TabPanels/StyledComponents.js +++ b/src/Components/TabPanels/StyledComponents.js @@ -184,11 +184,11 @@ export const UserProfileInfoDiv = styled.div` ` export const CheckTeacherDiv = styled.div` - @media screen and (min-width: 500px) { - padding-top : 10px; - padding-left : 250px; - margin-bottom : -10px; - } + padding-top : 10px; + padding-left : 250px; + margin-bottom : -10px; + display : absolute; + p { margin : 0 0 10px; font-family: Roboto; @@ -206,9 +206,6 @@ export const CheckTeacherDiv = styled.div` } } } - @media screen and (max-width: 499px) { - display : none; - } ` export const StyledTabs = styled(Tabs)` diff --git a/src/Components/TabPanels/TabPanelStatusEConquistas.js b/src/Components/TabPanels/TabPanelStatusEConquistas.js index 2617f8a7884e503a540010e73c0a41101a373b39..d9e0c20762cb1387ee0ab460f27fe5aeffd2dc07 100644 --- a/src/Components/TabPanels/TabPanelStatusEConquistas.js +++ b/src/Components/TabPanels/TabPanelStatusEConquistas.js @@ -1,3 +1,22 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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, {useContext, useState, useEffect} from 'react' import { Store } from '../../Store.js' import styled from 'styled-components' @@ -68,7 +87,7 @@ export default function TabPanelStatusEConquistas (props) { src={a.imgsrc} requirements={a.requirements} /> - + </Grid> )} )} diff --git a/src/Components/TabPanels/UserPageTabs/ModalExcluirConta.js b/src/Components/TabPanels/UserPageTabs/ModalExcluirConta.js index 05c08553ec5aa93fbc965266cf89dacf0f59bbd0..1d4410498bd71d489e4d8ccd9a3284bb8f890662 100644 --- a/src/Components/TabPanels/UserPageTabs/ModalExcluirConta.js +++ b/src/Components/TabPanels/UserPageTabs/ModalExcluirConta.js @@ -23,15 +23,13 @@ import Modal from '@material-ui/core/Modal'; import Backdrop from '@material-ui/core/Backdrop'; import Fade from '@material-ui/core/Fade'; import styled from 'styled-components' -import axios from 'axios' -import {apiUrl} from '../../../env.js' import CloseIcon from '@material-ui/icons/Close'; import ExcluirAvatar from '../../../img/Excluir.png' import GreyButton from '../../GreyButton' import FormInput from '../../FormInput' import {Link} from 'react-router-dom' import SnackbarComponent from '../../SnackbarComponent.js' -import {getAxiosConfig} from '../../HelperFunctions/getAxiosConfig' +import {deleteRequest} from '../../HelperFunctions/getAxiosConfig' function CloseModalButton (props) { return ( @@ -64,20 +62,16 @@ export default function ModalExcluirConta (props) { const deletedAccountText = `A conta ${state.currentUser.email} foi deletada com sucesso` + function handleSuccess (data) { + toggleSnackbar(true) + dispatch({ + type: "USER_DELETED_ACCOUNT", + }); + props.handleClose() + } const deleteAccount = () => { - let config = getAxiosConfig() - - axios.delete( (`${apiUrl}/auth/`), config - ).then( (response) => { - console.log(response) - toggleSnackbar(true) - - dispatch({ - type: "USER_DELETED_ACCOUNT", - }); - - props.handleClose() - }, (error) => {console.log(error);}) + const url = `/auth` + deleteRequest(url, handleSuccess, (error) => {console.log(error)}) } return ( diff --git a/src/Components/TabPanels/UserPageTabs/PanelAtividades.js b/src/Components/TabPanels/UserPageTabs/PanelAtividades.js index 0c9d8da9915f980bbc58bae8ca3db6329852fbad..d43ce0da3f4f9023da4def6794f69cadf3195c3e 100644 --- a/src/Components/TabPanels/UserPageTabs/PanelAtividades.js +++ b/src/Components/TabPanels/UserPageTabs/PanelAtividades.js @@ -20,13 +20,12 @@ import React, {useState, useEffect} from 'react' import styled from 'styled-components' import Paper from '@material-ui/core/Paper'; import Button from '@material-ui/core/Button'; -import axios from 'axios' -import {apiUrl, apiDomain} from '../../../env'; +import {apiDomain} from '../../../env'; import Bolo from '../../../img/Bolo.png' import LoadingSpinner from '../../LoadingSpinner.js' import ActivityListItem from '../../ActivityListItem.js' import List from '@material-ui/core/List'; -import {getAxiosConfig} from '../../HelperFunctions/getAxiosConfig.js' +import {getRequest} from '../../HelperFunctions/getAxiosConfig.js' export default function TabPanelAtividades (props) { const [loading, handleLoading] = useState(true) @@ -40,25 +39,18 @@ export default function TabPanelAtividades (props) { setNotificationsSlice(notifications.slice(0, sliceLength + offset)) } - useEffect( () => { - let config = getAxiosConfig() + function handleSuccess (data) { + setNotifications(data) + setNotificationsSlice(data.slice(0,30)) + setLength(data.length) - axios.get(`${apiUrl}/feed?offset=0&limit=30`, config) - .then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } + handleLoading(false) + } + useEffect( () => { + const url = `/feed?offset=0&limit=30` - setNotifications(response.data) - setNotificationsSlice(response.data.slice(0,30)) - setLength(response.data.length) + getRequest(url, handleSuccess, (error) => {console.log(error)}) - handleLoading(false) - }, - (error) => { - console.log(error) - } - ) }, []) return ( @@ -224,4 +216,4 @@ const DivTitulo = styled.div` line-height: 1.2em; margin : 0; border-bottom: 1px solid #eee; -` \ No newline at end of file +` diff --git a/src/Components/TabPanels/UserPageTabs/PanelColecoes.js b/src/Components/TabPanels/UserPageTabs/PanelColecoes.js index f7883396f3359173d24eace08e1826429bdd8210..a6ec0c91cf89e1e6fd8ee9afed41d9c250be1d1a 100644 --- a/src/Components/TabPanels/UserPageTabs/PanelColecoes.js +++ b/src/Components/TabPanels/UserPageTabs/PanelColecoes.js @@ -16,24 +16,22 @@ 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, useEffect} from 'react' +import React, { useState, useEffect } from 'react' import styled from 'styled-components' import Grid from '@material-ui/core/Grid'; import LoadingSpinner from '../../LoadingSpinner.js' -import axios from 'axios' -import {apiUrl} from '../../../env'; import PanelTemplateColecao from '../PanelComponents/TemplateColecao.js' import PaginaVaziaColecao from '../../../img/Pagina_vazia_colecao.png' - import NoContent from '../PanelComponents/NoContent.js' -import {WhiteContainer, StyledGrid} from '../StyledComponents.js' +import { WhiteContainer, StyledGrid } from '../StyledComponents.js' import CreateNewFolderIcon from '@material-ui/icons/CreateNewFolder'; import Title from '../PanelComponents/PanelTitle.js' import CollectionCardFunction from '../../CollectionCardFunction.js' -import {ButtonsAreaColecao} from '../PanelComponents/ButtonsArea' +import { ButtonsAreaColecao } from '../PanelComponents/ButtonsArea' import CriarColecaoModal from '../../CriarColecaoModal.js' +import {fetchAllRequest} from '../../HelperFunctions/getAxiosConfig' -export default function TabPanelColecoes (props) { +export default function TabPanelColecoes(props) { const [loading, handleLoading] = useState(true) const [userCollections, setUserCollections] = useState([]) @@ -42,33 +40,21 @@ export default function TabPanelColecoes (props) { const [followedCollections, setFollowedCollections] = useState([]) const [followedCollectionsSlice, setFollowedCollectionsSlice] = useState([]) - const getInfo = () => { - axios.all([ - axios.get((`${apiUrl}/users/` + props.id + '/collections'), props.config), - axios.get((`${apiUrl}/users/` + props.id + '/following/Collection'), props.config), - ]) - .then( (responseArr) => { - console.log('responseArr Colecoes: ', responseArr) - if (responseArr[1].headers['access-token']) { - sessionStorage.setItem('@portalmec/accessToken', responseArr[1].headers['access-token']) - } - - handleLoading(false) - setUserCollections(responseArr[0].data) - setUserCollectionsSlice(responseArr[0].data.slice(0,3)) + function handleSuccess (responseArr) { + handleLoading(false) + setUserCollections(responseArr[0]) + setUserCollectionsSlice(responseArr[0].slice(0,3)) - setFollowedCollections(responseArr[1].data) - setFollowedCollectionsSlice(responseArr[1].data.slice(0,4)) + setFollowedCollections(responseArr[1]) + setFollowedCollectionsSlice(responseArr[1].slice(0,4)) + } - }, - (error) => { - handleLoading(false) - console.log('error while running axios all') - } - ) + const getInfo = () => { + const urls = [`/users/${props.id}/collections`, `/users/${props.id}/following/Collection`] + fetchAllRequest(urls, handleSuccess, (error) => {console.log(error)}) } - useEffect( () => { + useEffect(() => { getInfo() }, []) @@ -77,86 +63,86 @@ export default function TabPanelColecoes (props) { setUserCollectionsSlice(userCollections.slice(0, sliceLength + 4)) } - const showAllUserCollections = () => {setUserCollectionsSlice(userCollections)} + const showAllUserCollections = () => { setUserCollectionsSlice(userCollections) } const showMoreFollowedCollections = () => { var sliceLength = followedCollectionsSlice.length setFollowedCollectionsSlice(followedCollections.slice(0, sliceLength + 4)) } - const showAllFollowedCollections = () => {setFollowedCollectionsSlice(followedCollections)} + const showAllFollowedCollections = () => { setFollowedCollectionsSlice(followedCollections) } return ( <> - { - loading ? - ( - <LoadingSpinner text={'CARREGANDO COLEÇÕES'}/> - - ) - : - ( - [ - <React.Fragment> - <Tentativa - title={"Minhas Coleções"} - length={userCollections.length} - noContentText={ - <div> - <img src={PaginaVaziaColecao} alt="PaginaVaziaColecao" style={{height:"150px",width:"150px", verticalAlign:"middle", border:"0"}}/> - <br/> - <span style={{fontFamily:"Roboto", fontWeight:"lighter", fontSize:"24px"}}> - Criamos a sua primeira Coleção! + { + loading ? + ( + <LoadingSpinner text={'CARREGANDO COLEÇÕES'} /> + + ) + : + ( + [ + <React.Fragment> + <Tentativa + title={"Minhas Coleções"} + length={userCollections.length} + noContentText={ + <div> + <img src={PaginaVaziaColecao} alt="PaginaVaziaColecao" style={{ height: "150px", width: "150px", verticalAlign: "middle", border: "0" }} /> + <br /> + <span style={{ fontFamily: "Roboto", fontWeight: "lighter", fontSize: "24px" }}> + Criamos a sua primeira Coleção! </span> - <p style={{fontFamily:"Roboto", fontSize:"16px", margin:"10px 0 0", fontWeight : "normal"}}> - Adicione nela recursos que você queira acessar mais tarde. - <br/> + <p style={{ fontFamily: "Roboto", fontSize: "16px", margin: "10px 0 0", fontWeight: "normal" }}> + Adicione nela recursos que você queira acessar mais tarde. + <br /> Crie novas coleções clicando no cartão roxo "Criar Colecão". </p> - </div> - } - sliceArr={userCollectionsSlice} - showMore={showMoreUserCollections} - showAll={showAllUserCollections} - callback={getInfo} - /> - - <PanelTemplateColecao - title={"Coleções que eu sigo"} - length={followedCollections.length} - noContentText={"Você ainda não segue nenhuma coleção."} - sliceArr={followedCollectionsSlice} - showMore={showMoreFollowedCollections} - showAll={showAllFollowedCollections} - followed={true} - /> - </React.Fragment> - ] - ) - } + </div> + } + sliceArr={userCollectionsSlice} + showMore={showMoreUserCollections} + showAll={showAllUserCollections} + callback={getInfo} + /> + + <PanelTemplateColecao + title={"Coleções que eu sigo"} + length={followedCollections.length} + noContentText={"Você ainda não segue nenhuma coleção."} + sliceArr={followedCollectionsSlice} + showMore={showMoreFollowedCollections} + showAll={showAllFollowedCollections} + followed={true} + /> + </React.Fragment> + ] + ) + } </> ) } -function Tentativa (props) { +function Tentativa(props) { const [modalOpen, toggleModal] = useState(false) - const handleModal = () => {toggleModal(!modalOpen)}; + const handleModal = () => { toggleModal(!modalOpen) }; return ( <WhiteContainer> - <CriarColecaoModal open={modalOpen} handleClose={() => {handleModal(); props.callback()}}/> + <CriarColecaoModal open={modalOpen} handleClose={() => { handleModal(); props.callback() }} /> <Title title={props.title} length={props.length} /> - <StyledGrid container spacing={1} style={{paddingLeft : "30px", paddingRight : "15px"}}> + <StyledGrid container spacing={1} style={{ paddingLeft: "30px", paddingRight: "15px" }}> <Grid item md={3} xs={12}> - <CardDiv onClick={()=>{handleModal()}}> - <div style={{backgroundColor:"#673ab7", height:"250px", display:"flex", justifyContent:"center", alignItems:"center"}}> - <CreateNewFolderIcon style={{color:"#fff", fontSize:"70px"}}/> - <p style={{fontSize:"16px", margin:"0 0 10px", color : "#fff"}}> + <CardDiv onClick={() => { handleModal() }}> + <div style={{ backgroundColor: "#673ab7", height: "250px", display: "flex", justifyContent: "center", alignItems: "center" }}> + <CreateNewFolderIcon style={{ color: "#fff", fontSize: "70px" }} /> + <p style={{ fontSize: "16px", margin: "0 0 10px", color: "#fff" }}> CRIAR COLEÇÃO </p> </div> @@ -165,53 +151,52 @@ function Tentativa (props) { { props.length === 0 ? - ( - [ - <Grid item lg={6} md={4} sm={6} xs={12}> - <NoContent text={props.noContentText}/> - </Grid> - ] - ) - : - ( - [ - <React.Fragment> - { - props.sliceArr.map( (card) => - <Grid item md={3} xs={12} key={card.id}> - <CollectionCardFunction - name={card.name} - rating={card.score} - type={card.object_type} - description={card.description} - author={card.owner.name} - avatar={card.owner.avatar} - authorID={card.owner.id} - thumbnails={card.items_thumbnails} - likeCount={card.likes_count} - liked={card.liked} - followed={card.followed} - tags={card.tags} - privacy={card.privacy} - id={card.id} - /> + ( + [ + <Grid item lg={6} md={4} sm={6} xs={12}> + <NoContent text={props.noContentText} /> </Grid> - ) - } - </React.Fragment> - ] - ) - } - </StyledGrid> - { - props.length > 0 && - <ButtonsAreaColecao - sliceLength={props.sliceArr.length} - length={props.length} - showMore={() => props.showMore()} - showAll={() => props.showAll()} - /> + ] + ) + : + ( + [ + <React.Fragment> + { + props.sliceArr.map((card) => + <Grid item md={3} xs={12} key={card.id}> + <CollectionCardFunction + name={card.name} + tags={card.tags} + rating={card.review_average} + id={card.id} + author={card.owner.name} + description={card.description} + thumbnails={card.items_thumbnails} + avatar={card.owner.avatar} + likeCount={card.likes_count} + followed={card.followed} + liked={card.liked} + collections={card.collection_items} + authorID={card.owner.id} + /> + </Grid> + ) + } + </React.Fragment> + ] + ) } + </StyledGrid> + { + props.length > 0 && + <ButtonsAreaColecao + sliceLength={props.sliceArr.length} + length={props.length} + showMore={() => props.showMore()} + showAll={() => props.showAll()} + /> + } </WhiteContainer> ) } diff --git a/src/Components/TabPanels/UserPageTabs/PanelCuradoria.js b/src/Components/TabPanels/UserPageTabs/PanelCuradoria.js index 06ea8fd64e432c03d9e78cb5c6db9a0e42164c37..796bee8acd0ae4dcf601ff3ebcbd1253199e80cd 100644 --- a/src/Components/TabPanels/UserPageTabs/PanelCuradoria.js +++ b/src/Components/TabPanels/UserPageTabs/PanelCuradoria.js @@ -17,10 +17,9 @@ 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, useEffect} from 'react' -import axios from 'axios' -import {apiUrl} from '../../../env'; import LoadingSpinner from '../../LoadingSpinner.js' import TemplateCuradoria from '../PanelComponents/TemplateCuradoria.js' +import {getRequest} from '../../HelperFunctions/getAxiosConfig' export default function TabPanelCuradoria (props) { const [loading, handleLoading] = useState(true) @@ -35,19 +34,15 @@ export default function TabPanelCuradoria (props) { const showAllSubmissions = () => {setSubmissionsSlice(submissions)} + function handleSuccess (data) { + handleLoading(false) + setSubmissions(data) + setSubmissionsSlice(data.slice(0,4)) + } useEffect( () => { - axios.get( (`${apiUrl}/users/` + props.id + '/submissions?offset=0&status=submitted'), props.config) - .then(response => { - console.log(response) - if (response.headers['access-token']) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - - handleLoading(false) - setSubmissions(response.data) - setSubmissionsSlice(response.data.slice(0,4)) + const url = `/users/${props.id}/submissions?offset=0&status=submitted` - }, error => {console.log('error while running ComponentDidMout on TabPanelCuradoria')}) + getRequest(url, handleSuccess, (error) => {console.log(error)}) }, []) return ( diff --git a/src/Components/TabPanels/UserPageTabs/PanelEditarPerfil.js b/src/Components/TabPanels/UserPageTabs/PanelEditarPerfil.js index 9e0560fdd69027c17e4772c4e47008e41fe44d16..ce61ebca4117fedbbce05de52d8133c7fc6293ef 100644 --- a/src/Components/TabPanels/UserPageTabs/PanelEditarPerfil.js +++ b/src/Components/TabPanels/UserPageTabs/PanelEditarPerfil.js @@ -25,13 +25,13 @@ import IconButton from '@material-ui/core/IconButton'; import PhotoCamera from '@material-ui/icons/PhotoCamera'; import Tooltip from '@material-ui/core/Tooltip'; import FormInput from "../../FormInput.js" -import ValidateUserInput from '../../FormValidationFunction.js' +import ValidateUserInput from '../../HelperFunctions/FormValidationFunction.js' import {apiDomain} from '../../../env.js' - +import ModalAlterarCover from '../../ModalAlterarCover/ModalAlterarCover.js' export default function TabPanelEditarPerfil (props) { // eslint-disable-next-line - const {state, dispatch} = useContext(Store) + const {state} = useContext(Store) const [hoverAlterarFoto, handleAlterarFoto] = React.useState(false) const [formNome, setNome] = useState({ @@ -48,9 +48,16 @@ export default function TabPanelEditarPerfil (props) { handleAlterarFoto(!hoverAlterarFoto) } + const [tempCover, setTempCover] = useState('') + + const [open, toggleOpen] = useState(false) + const controlModal = () => {toggleOpen(!open)} + const updateCover = (selectorFiles) => { - console.log(selectorFiles) - console.log(selectorFiles[0].name) + const objectURL = URL.createObjectURL(selectorFiles[0]) + console.log(objectURL) + setTempCover(objectURL) + controlModal() } const handleChange = (e, type) => { @@ -69,7 +76,7 @@ export default function TabPanelEditarPerfil (props) { key : flag, value : userInput, }) - + } } @@ -98,69 +105,77 @@ export default function TabPanelEditarPerfil (props) { } return ( - <div className="card-config"> - <h1 style={{fontWeight:"300"}}>Editar Perfil </h1> - <div className='content-div'> - <div style={{padding:"0", display:"flex", flexDirection:"column"}}> - <HeaderContainer> - <div style={{position:"relative", height:"100%"}}> - <img src={`${apiDomain}` + state.currentUser.cover_file_name} alt="user cover avatar" style={{width:"100%", height:"100%", objectFit:"cover"}}/> - <input accept="image/*" style = {{display:"none"}} id="icon-button-file" type="file" onChange={(e) => updateCover(e.target.files)}/> - <label htmlFor="icon-button-file"> - <Tooltip title={<span style={{fontSize:"14px", overflow:"hidden", transition:"all .5s ease"}}>ALTERAR CAPA</span>} placement="left"> - <IconButton style={{position:"absolute",right:"0",top:"0",color:"#fff"}}color="primary" aria-label="upload picture" component="span"> - <PhotoCamera /> - </IconButton> - </Tooltip> - </label> - </div> - <ProfileAvatarDiv onMouseEnter={handleHoverAlterarFoto} onMouseLeave={handleHoverAlterarFoto}> - <img src={`${apiDomain}` + state.currentUser.avatar_file_name} alt = "user avatar" style={{border:"0", verticalAlign:"middle"}}/> - <ChangeAvatarDiv style={ {display : hoverAlterarFoto ? 'flex' : 'none'}}> - <span>Alterar Foto</span> - </ChangeAvatarDiv> - </ProfileAvatarDiv> - </HeaderContainer> - <br/> - <br/> - <br/> - <br/> - </div> + <React.Fragment> + <ModalAlterarCover + open = {open} + handleClose={controlModal} + cover={tempCover} + id={state.currentUser.id} + /> + <div className="card-config"> + <h1 style={{fontWeight:"300"}}>Editar Perfil </h1> + <div className='content-div'> + <div style={{padding:"0", display:"flex", flexDirection:"column"}}> + <HeaderContainer> + <div style={{position:"relative", height:"100%"}}> + <img src={`${apiDomain}` + state.currentUser.cover} alt="user cover avatar" style={{width:"100%", height:"100%", objectFit:"cover"}}/> + <input accept="image/*" style = {{display:"none"}} id="icon-button-file" type="file" onChange={(e) => updateCover(e.target.files)}/> + <label htmlFor="icon-button-file"> + <Tooltip title={<span style={{fontSize:"14px", overflow:"hidden", transition:"all .5s ease"}}>ALTERAR CAPA</span>} placement="left"> + <IconButton style={{position:"absolute",right:"0",top:"0",color:"#fff"}}color="primary" aria-label="upload picture" component="span"> + <PhotoCamera /> + </IconButton> + </Tooltip> + </label> + </div> + <ProfileAvatarDiv onMouseEnter={handleHoverAlterarFoto} onMouseLeave={handleHoverAlterarFoto}> + <img src={`${apiDomain}` + state.currentUser.avatar} alt = "user avatar" style={{border:"0", verticalAlign:"middle"}}/> + <ChangeAvatarDiv style={ {display : hoverAlterarFoto ? 'flex' : 'none'}}> + <span>Alterar Foto</span> + </ChangeAvatarDiv> + </ProfileAvatarDiv> + </HeaderContainer> + <br/> + <br/> + <br/> + <br/> + </div> - <div style={{paddingTop:"90px"}}> - <div style={{display:"flex", flexDirection:"row"}}> - <form onSubmit={e => handleSubmit(e)}> - <FormInput - inputType={"text"} - name={"Nome Completo"} - value={formNome.value} - placeholder={"Nome Completo"} - handleChange={e => handleChange(e, 'username')} - required={true} - error={formNome.key} - /> - <FormInput - inputType={"text"} - name={"Sobre Mim"} - value={formAboutMe.value} - multi = {true} - rows="3" - rowsMax = "3" - error={formAboutMe.key} - placeholder={"Sobre Mim"} - handleChange={e => handleChange(e, 'aboutMe')} - required={false} - help = {formAboutMe.value.length + '/160'} - /> - </form> + <div style={{paddingTop:"90px"}}> + <div style={{display:"flex", flexDirection:"row"}}> + <form onSubmit={e => handleSubmit(e)}> + <FormInput + inputType={"text"} + name={"Nome Completo"} + value={formNome.value} + placeholder={"Nome Completo"} + handleChange={e => handleChange(e, 'username')} + required={true} + error={formNome.key} + /> + <FormInput + inputType={"text"} + name={"Sobre Mim"} + value={formAboutMe.value} + multi = {true} + rows="3" + rowsMax = "3" + error={formAboutMe.key} + placeholder={"Sobre Mim"} + handleChange={e => handleChange(e, 'aboutMe')} + required={false} + help = {formAboutMe.value.length + '/160'} + /> + </form> + </div> + <ButtonsDiv> + <Link to="perfil" ><ButtonCancelar ><span>CANCELAR</span></ButtonCancelar></Link> + <ButtonConfirmar onClick={e => handleSubmit(e)}><span>SALVAR ALTERAÇÕES</span></ButtonConfirmar> + </ButtonsDiv> </div> - <ButtonsDiv> - <Link to="perfil" ><ButtonCancelar ><span>CANCELAR</span></ButtonCancelar></Link> - <ButtonConfirmar onClick={e => handleSubmit(e)}><span>SALVAR ALTERAÇÕES</span></ButtonConfirmar> - </ButtonsDiv> - </div> - </div > - </div> + </div > + </div> + </React.Fragment> ) } diff --git a/src/Components/TabPanels/UserPageTabs/PanelFavoritos.js b/src/Components/TabPanels/UserPageTabs/PanelFavoritos.js index 75c96c274591601bbae7f9aecdda802ed2b1a56b..4edaf7482aefccfad045c1a43ed26acdcf4e15f1 100644 --- a/src/Components/TabPanels/UserPageTabs/PanelFavoritos.js +++ b/src/Components/TabPanels/UserPageTabs/PanelFavoritos.js @@ -17,11 +17,10 @@ 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, useEffect} from 'react' -import axios from 'axios' -import {apiUrl} from '../../../env'; import LoadingSpinner from '../../LoadingSpinner.js' import Template from '../PanelComponents/TemplateRecurso.js' import PanelTemplateColecao from '../PanelComponents/TemplateColecao.js' +import {fetchAllRequest} from '../../HelperFunctions/getAxiosConfig' export default function TabPanelFavoritos (props) { const [loading, handleLoading] = useState(true) @@ -32,29 +31,21 @@ export default function TabPanelFavoritos (props) { const [likedCollections, setlikedCollections] = useState([]) const [likedCollectionsSlice, setlikedCollectionsSlice] = useState([]) + function handleSuccess (responseArr) { + setlikedLearnObjs(responseArr[0]) + setlikedLearnObjsSlice(responseArr[0].slice(0,4)) + + setlikedCollections(responseArr[1]) + setlikedCollectionsSlice(responseArr[1].slice(0,4)) + + handleLoading(false) + } + useEffect( () => { - axios.all([ - axios.get((`${apiUrl}/users/` + props.id + '/learning_objects/liked'), props.config), - axios.get((`${apiUrl}/users/` + props.id + '/collections/liked'), props.config), - ]) - .then( (responseArr) => { - console.log('responseArr favoritos: ', responseArr) - if (responseArr[0].headers['access-token']) { - sessionStorage.setItem('@portalmec/accessToken', responseArr[0].headers['access-token']) - } - setlikedLearnObjs(responseArr[0].data) - setlikedLearnObjsSlice(responseArr[0].data.slice(0,4)) - - setlikedCollections(responseArr[1].data) - setlikedCollectionsSlice(responseArr[1].data.slice(0,4)) - - handleLoading(false) - }, - (error) => { - handleLoading(false) - console.log('error while running axios all') - } - ) + const urls = [ `/users/${props.id}/learning_objects/liked`, `/users/${props.id}/collections/liked`] + + fetchAllRequest(urls, handleSuccess, (error) => {console.log(error)}) + }, []) const showMoreLikedLearnObj = () => { diff --git a/src/Components/TabPanels/UserPageTabs/PanelGerenciarConta.js b/src/Components/TabPanels/UserPageTabs/PanelGerenciarConta.js index 421cadcd8bc676243b9147e06b3c00b31f545069..0207eb9f2bfe9a7002cb841581fef44b0dab2e41 100644 --- a/src/Components/TabPanels/UserPageTabs/PanelGerenciarConta.js +++ b/src/Components/TabPanels/UserPageTabs/PanelGerenciarConta.js @@ -21,7 +21,7 @@ import Paper from '@material-ui/core/Paper'; import FormInput from "../../FormInput.js" import {CompletarCadastroButton} from './PanelSolicitarContaProfessor.js' import {ButtonCancelar} from './PanelEditarPerfil.js' -import ValidateUserInput from '../../FormValidationFunction.js' +import ValidateUserInput from '../../HelperFunctions/FormValidationFunction.js' import ModalExcluirConta from './ModalExcluirConta.js' export default function TabPanelGerenciarConta (props) { diff --git a/src/Components/TabPanels/UserPageTabs/PanelMeusRecursos.js b/src/Components/TabPanels/UserPageTabs/PanelMeusRecursos.js index 3d9c93d09707c27216f21b79fefc1ba8567b7d48..05668209a684f2c82ba2cadf6f7bd53ceb5da893 100644 --- a/src/Components/TabPanels/UserPageTabs/PanelMeusRecursos.js +++ b/src/Components/TabPanels/UserPageTabs/PanelMeusRecursos.js @@ -17,11 +17,10 @@ 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, useEffect} from 'react' -import axios from 'axios' -import {apiUrl} from '../../../env'; import LoadingSpinner from '../../LoadingSpinner.js' import Template from '../PanelComponents/TemplateRecurso.js' import TemplateCuradoria from '../PanelComponents/TemplateCuradoria.js' +import {fetchAllRequest} from '../../HelperFunctions/getAxiosConfig' export default function TabPanelAtividades (props) { const [loading, handleLoading] = useState(true) @@ -35,34 +34,27 @@ export default function TabPanelAtividades (props) { const [curating, setCurating] = useState([]); const [curatingSlice, setCuratingSlice] = useState([]) + function handleSuccess (responseArr) { + setLearningObjects(responseArr[0]) + setLearningObjectsSlice(responseArr[0].slice(0, 4)) + + setDrafts(responseArr[1]) + setDraftsSlice(responseArr[1].slice(0, 4)) + + setCurating(responseArr[2]) + setCuratingSlice(responseArr[2].slice(0, 4)) + + handleLoading(false) + } + useEffect( () => { - axios.all([ - axios.get((`${apiUrl}/users/` + props.id + '/learning_objects'), props.config), - axios.get((`${apiUrl}/users/` + props.id + '/drafts'), props.config), - axios.get((`${apiUrl}/users/` + props.id + '/submissions?status=submitted'), props.config) - ]) - .then( (responseArr) => { - console.log('responseArr Meus recursos: ', responseArr) - if (responseArr[0].headers['access-token']) { - sessionStorage.setItem('@portalmec/accessToken', responseArr[0].headers['access-token']) - } - - setLearningObjects(responseArr[0].data) - setLearningObjectsSlice(responseArr[0].data.slice(0, 4)) - - setDrafts(responseArr[1].data) - setDraftsSlice(responseArr[1].data.slice(0, 4)) - - setCurating(responseArr[2].data) - setCuratingSlice(responseArr[2].data.slice(0, 4)) - - handleLoading(false) - }, - (error) => { - handleLoading(false) - console.log('error while running axios all') - } - ) + const urls = [ + `/users/${props.id}/learning_objects`, + `/users/${props.id}/drafts`, + `/users/${props.id}/submissions?status=submitted` + ] + + fetchAllRequest(urls, handleSuccess, (error) => {console.log(error)}) }, []) const showMoreLearnObj = () => { diff --git a/src/Components/TabPanels/UserPageTabs/PanelRede.js b/src/Components/TabPanels/UserPageTabs/PanelRede.js index 464b40c3e7d96edc88a9a74882b60c7b71098e3e..fdebcbf9f4f2f85af5f39e26046c9af2cc442e71 100644 --- a/src/Components/TabPanels/UserPageTabs/PanelRede.js +++ b/src/Components/TabPanels/UserPageTabs/PanelRede.js @@ -17,11 +17,10 @@ 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, useEffect} from 'react' -import axios from 'axios' -import {apiUrl} from '../../../env'; import LoadingSpinner from '../../LoadingSpinner.js' import ContainerRedeVazia from './ContainerRedeVazia.js' import PanelTemplateRede from '../PanelComponents/TemplateRede.js' +import {fetchAllRequest} from '../../HelperFunctions/getAxiosConfig' export default function TabPanelRede (props) { const [loading, handleLoading] = useState(true) @@ -44,32 +43,25 @@ export default function TabPanelRede (props) { } const showAllFollowers = () => {setFollowersSlice(followersList)} + function handleSuccess (responseArr) { + console.log(responseArr) + setFollowing(responseArr[0]) + setFollowingSlice(responseArr[0].slice(0,4)) + + + setFollowers(responseArr[1]) + setFollowersSlice(responseArr[1].slice(0,4)) + + handleLoading(false) + } useEffect( () => { - axios.all([ - axios.get((`${apiUrl}/users/` + props.id + '/following/User'), props.config), - axios.get((`${apiUrl}/users/` + props.id + '/followers'), props.config) - ]) - .then( (responseArr) => { - console.log('responseArr Rede: ', responseArr) - if (responseArr[0].headers['access-token']) { - sessionStorage.setItem('@portalmec/accessToken', responseArr[0].headers['access-token']) - } - - setFollowing(responseArr[0].data) - setFollowingSlice(responseArr[0].data.slice(0,4)) - - - setFollowers(responseArr[1].data) - setFollowersSlice(responseArr[1].data.slice(0,4)) - - handleLoading(false) - }, - (error) => { - handleLoading(false) - console.log('error while running axios all') - } - ) + const urls = [ + `/users/${props.id}/following/User`, + `/users/${props.id}/followers` + ] + + fetchAllRequest(urls, handleSuccess, (error) => {console.log(error)}) }, []) return ( @@ -96,7 +88,6 @@ export default function TabPanelRede (props) { ) : ( - [ <React.Fragment> <PanelTemplateRede title={followersList.length === 1 ? "Seguidor" : "Seguidores"} @@ -119,7 +110,6 @@ export default function TabPanelRede (props) { /> </React.Fragment> - ] ) } </> diff --git a/src/Components/TabPanels/UserPageTabs/PanelSolicitarContaProfessor.js b/src/Components/TabPanels/UserPageTabs/PanelSolicitarContaProfessor.js index 769977a5e3fc95490fa1c257a059f9dc1719a073..3e0fe1c7a7382116d02fbab3aeb0c44423393605 100644 --- a/src/Components/TabPanels/UserPageTabs/PanelSolicitarContaProfessor.js +++ b/src/Components/TabPanels/UserPageTabs/PanelSolicitarContaProfessor.js @@ -35,7 +35,6 @@ export default function TabPanelSolicitarContaProfessor (props) { { state.currentUser.submitter_request === 'default' || state.currentUser.submitter_request === 'rejected' ? ( - [ <div style={{paddingLeft:"100px", paddingRight:"101px"}}> <ImageDiv/> <StyledH2>Você é professor(a) da educação básica e gostaria de colaborar com a Plataforma?</StyledH2> @@ -48,28 +47,21 @@ export default function TabPanelSolicitarContaProfessor (props) { </CompletarCadastroButton> </div> </div> - ] ) : ( - [ <> { state.currentUser.submitter_request === 'requested' ? ( - [ <span>Requested</span> - ] ) : ( - [ <span>Professor</span> - ] ) } </> - ] ) } </div> diff --git a/src/Components/TopicCard.js b/src/Components/TopicCard.js index c0f25eaceecafa88bf9d8d07914dbc26dbea6efa..7a1e0e0aa094982d0c03aae4958ddf85c7f0a159 100644 --- a/src/Components/TopicCard.js +++ b/src/Components/TopicCard.js @@ -1,66 +1,74 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 from 'react'; -import { Link } from 'react-router-dom'; -import styled from 'styled-components' import Card from '@material-ui/core/Card'; +import CardContent from '@material-ui/core/CardContent'; import CardActions from '@material-ui/core/CardActions'; +import Typography from '@material-ui/core/Typography'; +import styled from 'styled-components'; +import Button from '@material-ui/core/Button'; +import { Link } from 'react-router-dom'; -export default function TopicCard(props) { - return ( - <CardModel> - <StyledLink to={"topico?colecao="+props.colecao_id+"&topico="+props.topico_obj.id}> - <CardImage src={props.topico_obj.img}/> - <Title> - <BoldTitle> - { props.topico_obj.pre_title } - </BoldTitle> - { props.topico_obj.title } - </Title> - <StyledCardActions> - <StyledLink to={"topico?colecao="+props.colecao_id+"&topico="+props.topico_obj.id}> - <Red><strong>Ver mais</strong></Red> - </StyledLink> - </StyledCardActions> - </StyledLink> - </CardModel> - ); +export default function MaterialCard(props) { + console.log(props); + const thumb = require(`../../public/${props.topic.img}`) + + return ( + <Card style={{ maxHeight: "100%", maxWidth: "300px" }}> + <img style={{ maxHeight: "100%", maxWidth: "100%" }} src={thumb} alt="thumbnail do recurso" /> + <CardContent style={{ height: "50px" }}> + <Title> + <BoldTitle> + {props.topic.pre_title} + </BoldTitle> + {props.topic.title} + </Title> + </CardContent> + <CardActions style={{ borderTop: "1px solid #e5e5e5", justifyContent: "center" }}> + <StyledLink to={"topico?colecao=" + props.colecao_id + "&topico=" + props.topic.id}> + <Button + color="secondary" + > + Ver módulos + </Button> + </StyledLink> + </CardActions> + </Card > + ) } -const Title=styled.h1` - font-weight: 500; +const Title = styled(Typography)` + font-weight: 500; color: rgb(102, 102, 102); font-size: 0.9em; margin-left: 10px; margin-right: 10px; display: -webkit-box; - -webkit-line-clamp: 3; - -webkit-box-orient: vertical; - overflow: hidden; -` -const CardModel=styled(Card)` - position: relative; - width: 18%; - margin-bottom: 30px; - padding: 0; - height: 225px; -` -const CardImage=styled.img` - width: 100%; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; ` -const BoldTitle=styled.span` +const BoldTitle = styled.span` font-weight: bold; ` -const StyledLink=styled(Link)` +const StyledLink = styled(Link)` text-decoration: none !important; color: inherit !important; -` -const Red=styled.span` - color: #e81f4f; - font-size: 14px; -` -const StyledCardActions=styled(CardActions)` - position: absolute; - padding: 10px; - left: 0; - bottom: 0; -` +` \ No newline at end of file diff --git a/src/Components/TopicFooter.js b/src/Components/TopicFooter.js index 2e04b8b1628e7127cd193a5e479e864572ea8884..c6ce8ea42ddf97ec278bc6cd63e779b4cd28ec5e 100644 --- a/src/Components/TopicFooter.js +++ b/src/Components/TopicFooter.js @@ -9,11 +9,11 @@ export default function TopicFooter(props) { <Grid container direction="row" - justify="flex-start" + justify="center" alignItems="center" > <Grid item> - <FormationMaterialImage src={props.src}/> + <FormationMaterialImage src={require(`../../public/${props.src}`)}/> </Grid> <Grid item> <Text> @@ -36,7 +36,6 @@ const Container=styled.div` ` const FormationMaterialImage=styled.img` width: 300px; - display: block; margin-right: 20px; ` const Text=styled.h2` diff --git a/src/Components/TopicList.js b/src/Components/TopicList.js index 77b8e4687255081a5bf4454a88777fafea31b6e3..e965adad1b530fbf96d090fa028b1fc83ebad01a 100644 --- a/src/Components/TopicList.js +++ b/src/Components/TopicList.js @@ -13,23 +13,25 @@ export default function TopicList(props) { setExpanded(!expanded); } - return ( + return ( <Wrapper> <Title>Módulos</Title> <Grid container - direction="row" - justify="space-evenly" + spacing={3} + justify="center" alignItems="center" > - { props.topicos.slice(0, (expanded ? -1 : 5)).map(t => { - return ( - <TopicCard topico_obj={t} colecao_id={props.colecao_id}/> - ); - }) + {props.topicos.slice(0, (expanded ? -1 : 5)).map((t, index) => { + return ( + <Grid item key={index} md={3}> + <TopicCard topic={t} colecao_id={props.colecao_id} /> + </Grid> + ); + }) } </Grid> - { props.topicos.length > 5 ? + {props.topicos.length > 5 ? <Grid container direction="column" justify="flex-start" @@ -37,32 +39,32 @@ export default function TopicList(props) { > <Grid item> <Fab size="medium" color="secondary" aria-label="edit" onClick={handleFabClick}> - {expanded ? <ExpandLessIcon /> : <ExpandMoreIcon /> } + {expanded ? <ExpandLessIcon /> : <ExpandMoreIcon />} </Fab> </Grid> <Grid item> <FabText> - { expanded ? "VER MENOS" : "VER TODOS OS MÓDULOS" } + {expanded ? "VER MENOS" : "VER TODOS OS MÓDULOS"} </FabText> </Grid> </Grid> - : <div></div> + : <div></div> } </Wrapper> - ); + ); } -const FabText=styled.span` +const FabText = styled.span` color: #666; font-weight: 900; line-height: 2em; ` -const Title=styled.h1` +const Title = styled.h1` font-weight: 100; margin-left: 30px; color: rgb(102, 102, 102); ` -const Wrapper=styled.div` +const Wrapper = styled.div` margin-right : auto; margin-left : auto; margin-bottom: 30px; diff --git a/src/Components/UploadPageComponents/ButtonsDiv.js b/src/Components/UploadPageComponents/ButtonsDiv.js index 975017b04f81bfccc588aa30fbc46ee0e35bdcdc..b6aaaa3c829fa41698743a5fe720b9fd82c06148 100644 --- a/src/Components/UploadPageComponents/ButtonsDiv.js +++ b/src/Components/UploadPageComponents/ButtonsDiv.js @@ -21,6 +21,7 @@ import ModalCancelar from './ModalCancelar.js' import { GreyButton, OrangeButton } from './StyledComponents'; import Grid from '@material-ui/core/Grid'; import {Redirect} from 'react-router-dom' + export default function ButtonsDiv (props) { const [modalCancelar, toggleModalCancelar] = useState(false) const [redirectTrue, toggleRedirect] = useState(false) diff --git a/src/Components/UploadPageComponents/DragAndDrop.tsx b/src/Components/UploadPageComponents/DragAndDrop.tsx deleted file mode 100644 index d416b22257648c2c500ef0cb85150e7acfacae20..0000000000000000000000000000000000000000 --- a/src/Components/UploadPageComponents/DragAndDrop.tsx +++ /dev/null @@ -1,153 +0,0 @@ -/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - -This file is part of Plataforma Integrada MEC. - -Plataforma Integrada MEC is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -Plataforma Integrada MEC is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -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, useEffect} from 'react' -import CloudUploadIcon from '@material-ui/icons/CloudUpload'; -import {DottedBox, BlueButton} from './StyledComponents.js'; -import FileToUpload from './FileToUpload' -import {getAxiosConfig} from '../HelperFunctions/getAxiosConfig.js' -import AddAPhotoIcon from '@material-ui/icons/AddAPhoto'; - -type Props = { - draftID : string; -} - -const UploadMediaComponent: React.FC<Props> = ({draftID, children}) => { - const [filesToUpload, setFilesToUpload] = useState<FileToUpload | undefined>(undefined); - - const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => { - const files: FileList | null = e.target.files; - if(!files) return; - - let fileToUpload: FileToUpload = new FileToUpload(files[0], files[0].name, draftID); - - setFilesToUpload(fileToUpload); - if (fileToUpload != undefined){ - console.log(fileToUpload.uploadFile()) - - } - }; - - return ( - <div className="upload-container"> - <h2 className="upload-title">File Uploader</h2> - <div className="upload-form"> - <form id="file_upload"> - <DottedBox - - > - <AddAPhotoIcon className="icon"/> - <input - type="file" - onChange = {onFileChange} - id="upload-file-thumbnail" - style={{display : "none"}} - /> - <BlueButton> - <label htmlFor="upload-file-thumbnail" style={{width : "inherit", cursor : "pointer"}}> - ESCOLHER IMAGEM - </label> - </BlueButton> - <span style={{marginTop : "6px"}}>Ou arrastar e soltar o arquivo aqui</span> - </DottedBox> - </form> - </div> - </div> - ) -} -UploadMediaComponent.displayName = 'UploadMedia'; -export default UploadMediaComponent; - -{/*<div className="upload-file-select"> - <label htmlFor="file_1">Select files for upload</label> - <input id="file_1" type="file" multiple onChange={onFileChange}/> -</div> - -<div className="upload-file-list"> - {filesToUpload.map((f,i) => <div className="upload-file" key={i}>{f.name} - {f.file.size}bytes</div>)} -</div> - -<div className="upload-submit"> - <input type="submit" value="submit"/> -</div>*/} - -{/* - const [dropDepth, setDropDepth] = useState(0) - const [inDropZone, toggleInDropZone] = useState(false) - const [fileList, setFileList] = useState([]) - - const handleDragEnter = e => { - e.preventDefault(); - e.stopPropagation(); - - setDropDepth(dropDepth + 1) - }; - - const handleDragLeave = e => { - e.preventDefault(); - e.stopPropagation(); - - setDropDepth(dropDepth - 1) - if (dropDepth > 0) - toggleInDropZone(true) - }; - - const handleDragOver = e => { - e.preventDefault(); - e.stopPropagation(); - e.dataTransfer.dropEffect = 'copy'; - toggleInDropZone(true) - }; - - const handleDrop = e => { - e.preventDefault(); - e.stopPropagation(); - let files = [...e.dataTransfer.files] - - if (files && files.length > 0) { - props.acceptFile(files[0]) - } - }; - - const handleUpload = (e, selectorFiles : FileList) => { - e.preventDefault(); - props.acceptFile(selectorFiles[0]) - } - - - <DottedBox - onDrop={e => handleDrop(e)} - onDragOver={e => handleDragOver(e)} - onDragEnter={e => handleDragEnter(e)} - onDragLeave={e => handleDragLeave(e)} - > - <CloudUploadIcon className="icon"/> - <input - type="file" - onChange = {(e) => handleUpload(e, e.target.files)} - id="upload-file" - style={{display : "none"}} - /> - <BlueButton> - <label htmlFor="upload-file" style={{width : "inherit", cursor : "pointer"}}> - ESCOLHER O ARQUIVO - </label> - </BlueButton> - <span style={{marginTop : "6px"}}>Ou arrastar e soltar o arquivo aqui</span> -</DottedBox> - */} diff --git a/src/Components/UploadPageComponents/FileToUpload.ts b/src/Components/UploadPageComponents/FileToUpload.ts index 0fba0fc8204700a5e47bdd98516b8aa474e98133..fddbf404078bdb1eed4d04a666955d63ccdbac87 100644 --- a/src/Components/UploadPageComponents/FileToUpload.ts +++ b/src/Components/UploadPageComponents/FileToUpload.ts @@ -1,3 +1,21 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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/>.*/ + export default class FileToUpload { static chunkSize = 262144; readonly request: XMLHttpRequest; diff --git a/src/Components/UploadPageComponents/FileUploadStage.js b/src/Components/UploadPageComponents/FileUploadStage.js index 5419bb3f7ce1dfc0574a3965c32ede36a7fcd425..880ff018ef65d34cdf952b8829dedfd819f647b6 100644 --- a/src/Components/UploadPageComponents/FileUploadStage.js +++ b/src/Components/UploadPageComponents/FileUploadStage.js @@ -21,25 +21,18 @@ import styled from 'styled-components' import {WrapperBox} from './StyledComponents.js' import DoneIcon from '@material-ui/icons/Done'; import DeleteIcon from '@material-ui/icons/Delete'; -import {getAxiosConfig} from '../HelperFunctions/getAxiosConfig.js' -import axios from 'axios' -import {apiUrl} from '../../env'; +import {deleteRequest} from '../HelperFunctions/getAxiosConfig.js' export default function FileUploadStage (props) { const [uploading, toggleUploading] = useState(true) + function handleSuccess (data) { + props.handleNextStage("default") + } const handleDelete = () => { - let config = getAxiosConfig + const url = `/learning_objects/${props.draftID}` - axios.delete( (`${apiUrl}/learning_objects/` + props.draftID), config).then( - (response) => { - console.log(response) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - props.handleNextStage("default") - }, - (error) => {console.log(error)}) + deleteRequest(url, handleSuccess, (error) => {console.log(error)}) } return ( diff --git a/src/Components/UploadPageComponents/ModalCancelar.js b/src/Components/UploadPageComponents/ModalCancelar.js index 5906286e347fc1f1261ca592858f2cecda7d8588..9616436b10e683fdb274387b58ff2aed3c8d788b 100644 --- a/src/Components/UploadPageComponents/ModalCancelar.js +++ b/src/Components/UploadPageComponents/ModalCancelar.js @@ -22,37 +22,23 @@ import Modal from '@material-ui/core/Modal'; import Backdrop from '@material-ui/core/Backdrop'; import Fade from '@material-ui/core/Fade'; import styled from 'styled-components' -import axios from 'axios' -import {apiUrl} from '../../env'; import {Link} from 'react-router-dom' +import {deleteRequest} from '../HelperFunctions/getAxiosConfig.js' export default function ModalCancelar (props) { + + function handleSuccess (data) { + props.handleClose() + console.log('ir pra home') + + } const handleDelete = () => { - console.log(props.draftID) // {/*delete the draft*/} if (props.draftID) { - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid'), - } - } - axios.delete( (`${apiUrl}/learning_objects/` + props.draftID), config).then( - (response) => { - console.log(response) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - }, (error) => {console.log(error)}) - } - // {/*close modal*/} - props.handleClose() - // {/*change current page to home page*/} - console.log('ir pra home') + const url = `/learning_objects/${props.draftID}` + deleteRequest(url, handleSuccess, (error) => {console.log(error)}) + } } return ( diff --git a/src/Components/UploadPageComponents/PartOne.js b/src/Components/UploadPageComponents/PartOne.js index 46540f49752bbf87084cde65ad3c0234a3ca57d4..fbb47cb5b0e325fa01cf5ba7666acd454a398134 100644 --- a/src/Components/UploadPageComponents/PartOne.js +++ b/src/Components/UploadPageComponents/PartOne.js @@ -18,10 +18,7 @@ along with Plataforma Integrada MEC. If not, see <http://www.gnu.org/licenses/> import React, {useState, useEffect} from 'react' import Grid from '@material-ui/core/Grid'; -import axios from 'axios' -import {apiUrl} from '../../env'; import ButtonsDiv from './ButtonsDiv.js' - import SobreORecurso from './Forms/SobreORecurso.js' import NewTitle from './Forms/NewTitle.js' import Keywords from './Forms/Keywords.js' @@ -29,40 +26,20 @@ import Autor from './Forms/Autor.js' import TipoDeRecurso from './Forms/TipoDeRecurso.js' import Idioma from './Forms/Idioma.js' import {SendInfo} from './SendInfo.js' +import {getRequest} from '../HelperFunctions/getAxiosConfig.js' export default function PartOne (props) { // {/*const [subjects, setSubjects] = useState([])*/} const [languages, setLanguages] = useState([]) const [objTypes, setObjTypes] = useState([]) + function handleSuccessGetObjTypes (data) { + setObjTypes(data.sort((a, b) => (a.name) > (b.name) ? 1 : -1)) + } useEffect( () => { - // {/*get the list of subjects*/} - // {/* axios.get(`${apiUrl}/subjects/`).then( - // (response) => { - // console.log(response.data) - // setSubjects(response.data) - // }, (error) => { - // console.log(error) - // } - // )*/} - - // {/*get the list of object_types*/} - axios.get(`${apiUrl}/object_types/`).then( - (response) => { - setObjTypes(response.data.sort((a, b) => (a.name) > (b.name) ? 1 : -1)) - }, (error) => { - console.log(error) - } - ) - - // {/*get the list of languages*/} - axios.get(`${apiUrl}/languages/`).then( - (response) => { - setLanguages(response.data) - }, (error) => { - console.log(error) - } - ) + getRequest(`/object_types/`, handleSuccessGetObjTypes, (error) => {console.log(error)}) + + getRequest(`/languages/`, (data) => {setLanguages(data)}, (error) => {console.log(error)}) }, []) const handleSubmit = () => { diff --git a/src/Components/UploadPageComponents/PartThree.js b/src/Components/UploadPageComponents/PartThree.js index 3a2608c70375de6315c940474c126e1323f233f6..3b4b6b81ecbda32d0fa721e0ffc059e0c47f4cff 100644 --- a/src/Components/UploadPageComponents/PartThree.js +++ b/src/Components/UploadPageComponents/PartThree.js @@ -20,8 +20,7 @@ import React, {useState, useEffect, useContext} from 'react' import {Store} from '../../Store.js' import Grid from '@material-ui/core/Grid'; import styled from 'styled-components' -import axios from 'axios' -import {apiUrl, apiDomain} from '../../env'; +import {apiDomain} from '../../env'; import Stepper from './Stepper.js' import Rating from '@material-ui/lab/Rating'; import StarBorderIcon from '@material-ui/icons/StarBorder'; @@ -34,8 +33,8 @@ import TranslateIcon from '@material-ui/icons/Translate'; import AssignmentIcon from '@material-ui/icons/Assignment'; import { GrayButton, OrangeButton} from './StyledComponents'; import ModalCancelar from './ModalCancelar.js' -import {getAxiosConfig} from '../HelperFunctions/getAxiosConfig.js' import {getDefaultThumbnail} from '../HelperFunctions/getDefaultThumbnail' +import {getRequest} from '../HelperFunctions/getAxiosConfig.js' export default function PartThree (props) { var moment = require('moment') @@ -48,24 +47,22 @@ export default function PartThree (props) { const [description, setDescription] = useState('') const [author, setAuthor] = useState('') + function handleSuccess (data) { + setDraft(data) + /*extract subjects*/ + setSubjects(data.subjects.map((subject)=>(subject.name)).join(', ')) + setTags(data.tags.map(tag => tag.name)) + setDescription(data.description) + setAuthor(data.author) + setLoading(false) + } + useEffect(() => { if (state.currentUser.id !== "") { - const config = getAxiosConfig() - axios.get( (`${apiUrl}/learning_objects/` + props.draftID), config - ).then( (response) => { - console.log(response.data) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - setDraft(response.data) - - /*extract subjects*/ - setSubjects(response.data.subjects.map((subject)=>(subject.name)).join(', ')) - setTags(response.data.tags.map(tag => tag.name)) - setDescription(response.data.description) - setAuthor(response.data.author) - setLoading(false) - }, (error) => {console.log(error)}) + const url = `/learning_objects/${props.draftID}` + + getRequest(url, handleSuccess, (error) => {console.log(error)}) + } }, [state.currentUser.id]) diff --git a/src/Components/UploadPageComponents/PartTwo.js b/src/Components/UploadPageComponents/PartTwo.js index 02a83da82ea0e4a689d8949d7b063afae5a7435d..6ab05cee54ac0f62067fb87aecde4b16e045df1c 100644 --- a/src/Components/UploadPageComponents/PartTwo.js +++ b/src/Components/UploadPageComponents/PartTwo.js @@ -19,8 +19,6 @@ along with Plataforma Integrada MEC. If not, see <http://www.gnu.org/licenses/> import React, {useState, useEffect} from 'react' import Grid from '@material-ui/core/Grid'; import styled from 'styled-components' -import axios from 'axios' -import {apiUrl} from '../../env'; import DragAndDropThumbnail from './PartTwoComponents/DragAndDropThumbnail' import EducationalStage from './PartTwoComponents/EducationalStage' import Licenca from './PartTwoComponents/Licenca' @@ -32,9 +30,9 @@ import ButtonsDiv from './ButtonsDiv.js' import SubjectsAndThemes from './PartTwoComponents/SubjectsAndThemes.js' import {SendInfo} from './SendInfo.js' import EditThumbnail from './PartTwoComponents/EditThumbnail.js' -import {getAxiosConfig} from '../HelperFunctions/getAxiosConfig' import DisplayThumbnail from './PartTwoComponents/DisplayThumbnail.js' import CustomCircularProgress from './PartTwoComponents/CustomCircularProgress'; +import {getRequest, putRequest} from '../HelperFunctions/getAxiosConfig.js' export function LoadingDiv () { return ( @@ -49,21 +47,15 @@ export default function PartTwo (props) { const [subjects, setSubjects] = useState([]) const [themes, setThemes] = useState([]) + function handleSuccess (data) { + setSubjects(data.filter(subject => subject.theme === false).sort((a,b) => a.name > b.name ? 1 : -1)) + setThemes(data.filter(subject => subject.theme === true).sort((a,b) => a.name > b.name ? 1 : -1)) + } + useEffect(() => { - axios.get(`${apiUrl}/educational_stages/`).then( - (response) => {console.log(response); - setEduStages(response.data) - }, - (error) => {console.log(error)} - ) - - axios.get(`${apiUrl}/subjects/`).then( - (response) => {console.log(response); - setSubjects(response.data.filter(subject => subject.theme === false).sort((a,b) => a.name > b.name ? 1 : -1)) - setThemes(response.data.filter(subject => subject.theme === true).sort((a,b) => a.name > b.name ? 1 : -1)) - }, - (error) => {console.log(error)} - ) + getRequest(`/educational_stages/`, (data) => {setEduStages(data)}, (error) => {console.log(error)}) + + getRequest(`/subjects/`, handleSuccess, (error) => {console.log(error)}) }, []) @@ -86,23 +78,17 @@ export default function PartTwo (props) { const updateThumb = (newThumbnail) => { setThumbnail(newThumbnail) console.log(thumbnail) - } + const finalizeThumb = () => { setThumbnailStage('uploading') - let config = getAxiosConfig() + + const url = `/learning_objects/${props.draftID}` + let fdThumb = new FormData() fdThumb.set('learning_object[thumbnail]', thumbnail) - axios.put((`${apiUrl}/learning_objects/` + props.draftID), fdThumb, config).then( - (response) => { - setThumbnailStage('done') - console.log(response.data) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - }, - (error) => {console.log(error)} - ) + + putRequest(url, fdThumb, (data) => {setThumbnailStage('done')}, (error) => {console.log(error)}) } const [thumbnailStage, setThumbnailStage] = useState('default') diff --git a/src/Components/UploadPageComponents/PartTwoComponents/CustomCircularProgress.js b/src/Components/UploadPageComponents/PartTwoComponents/CustomCircularProgress.js index 617a8e70b6a022139e4ecd843fa792117a38515c..2164091858560e3cb63f0c43099de40e2606b741 100644 --- a/src/Components/UploadPageComponents/PartTwoComponents/CustomCircularProgress.js +++ b/src/Components/UploadPageComponents/PartTwoComponents/CustomCircularProgress.js @@ -1,3 +1,21 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 from 'react'; import { makeStyles } from '@material-ui/core/styles'; import CircularProgress from '@material-ui/core/CircularProgress'; diff --git a/src/Components/UploadPageComponents/PartTwoComponents/DisplayThumbnail.js b/src/Components/UploadPageComponents/PartTwoComponents/DisplayThumbnail.js index 261df04c61d83f1820446af0362c8bb51ad791b5..0c07e151670e4a256ed971abb978dad7b3107c5b 100644 --- a/src/Components/UploadPageComponents/PartTwoComponents/DisplayThumbnail.js +++ b/src/Components/UploadPageComponents/PartTwoComponents/DisplayThumbnail.js @@ -1,3 +1,21 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 from 'react' import {StyledFormLabel} from '../StyledComponents.js' import AddAPhotoIcon from '@material-ui/icons/AddAPhoto'; diff --git a/src/Components/UploadPageComponents/PartTwoComponents/EditThumbnail.js b/src/Components/UploadPageComponents/PartTwoComponents/EditThumbnail.js index 35be2ce523737088ba7892dac513b255050d9925..7cce6bf2058f9c6512430053e27d6ed04f479800 100644 --- a/src/Components/UploadPageComponents/PartTwoComponents/EditThumbnail.js +++ b/src/Components/UploadPageComponents/PartTwoComponents/EditThumbnail.js @@ -1,3 +1,21 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 {StyledFormLabel} from '../StyledComponents.js' import Cropper from '../../Cropper' diff --git a/src/Components/UploadPageComponents/ReactFileToUpload.js b/src/Components/UploadPageComponents/ReactFileToUpload.js index d7342d9c1c0b9484c719e1085f2bc43973a81f6c..ffbd6a452bddfe13eb14c996498ca17a897af2de 100644 --- a/src/Components/UploadPageComponents/ReactFileToUpload.js +++ b/src/Components/UploadPageComponents/ReactFileToUpload.js @@ -19,13 +19,13 @@ along with Plataforma Integrada MEC. If not, see <http://www.gnu.org/licenses/> import React, {useState, useEffect} from 'react' import CloudUploadIcon from '@material-ui/icons/CloudUpload'; import {DottedBox, BlueButton} from './StyledComponents.js'; -import {getAxiosConfig} from '../HelperFunctions/getAxiosConfig.js' +import {getAxiosConfigFromJSON, updateHeaders} from '../HelperFunctions/getAxiosConfig.js' import AddAPhotoIcon from '@material-ui/icons/AddAPhoto'; import axios from 'axios' import {apiUrl} from '../../env'; export default function ReactFileToUpload (props) { - const [fileToUpload, setFileToUpload] = useState(null); + const [fileToUpload, setFileToUpload] = useState(null); const chunkSize = 262144 const uploadUrl = `${apiUrl}/learning_objects/` + props.draftID + '/chunk' const [fileName, setFileName] = useState(null) @@ -50,7 +50,7 @@ export default function ReactFileToUpload (props) { for (var i = 0; i < total; i++) { let chunk = newFile.slice(currentChunkStartByte, currentChunkFinalByte) - let config = getAxiosConfig() + let config = getAxiosConfigFromJSON() let formData = new FormData() formData.append('_chunkFilename', newFile.name); formData.append('_chunkIdentifier', chunkIdentifier); @@ -65,7 +65,7 @@ export default function ReactFileToUpload (props) { const response = await axios.post(uploadUrl, formData, config); console.log(response) if (response.headers['access-token']) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) + updateHeaders(response.headers) } remainingBytes = newFile.size - currentChunkFinalByte; if (currentChunkFinalByte === newFile.size) { diff --git a/src/Components/UploadPageComponents/SendInfo.js b/src/Components/UploadPageComponents/SendInfo.js index c931c5ba84cb7af7fa350c6a6aef8afcd5511ba4..ebcb1b95f377fe018e3a178716ff7d1621009dba 100644 --- a/src/Components/UploadPageComponents/SendInfo.js +++ b/src/Components/UploadPageComponents/SendInfo.js @@ -1,9 +1,25 @@ -import axios from 'axios' -import {apiUrl} from '../../env'; +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 {putRequest} from '../HelperFunctions/getAxiosConfig.js' export function SendInfo (fieldName, payload, draftID) { - console.log('fieldName', fieldName, 'payload', payload, 'draftID', draftID) const key = fieldName let value = payload if (key === "tags") { @@ -18,23 +34,8 @@ export function SendInfo (fieldName, payload, draftID) { } } putObject.learning_object[key] = value - console.log(putObject) - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - } - } - config.headers["Access-Token"] = sessionStorage.getItem('@portalmec/accessToken'); - config.headers.Client = sessionStorage.getItem('@portalmec/clientToken') - config.headers.Uid = sessionStorage.getItem('@portalmec/uid') - axios.put((`${apiUrl}/learning_objects/` + draftID), putObject, config) - .then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - } , (error) => {console.log(error)}) + const url = `/learning_objects/${draftID}` + putRequest(url, putObject, (data) => {console.log(data)}, (error) => {console.log(error)}) } diff --git a/src/Components/UploadPageComponents/Stepper.js b/src/Components/UploadPageComponents/Stepper.js index 2c0a1179b5e2b28bd2510183fb7f67ab37ae907c..c1f9d40f55c2e4aafba0c44282ed441077853bf0 100644 --- a/src/Components/UploadPageComponents/Stepper.js +++ b/src/Components/UploadPageComponents/Stepper.js @@ -1,3 +1,21 @@ +/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre +Departamento de Informatica - Universidade Federal do Parana + +This file is part of Plataforma Integrada MEC. + +Plataforma Integrada MEC is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Plataforma Integrada MEC is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +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 from 'react'; import styled from 'styled-components' import PropTypes from 'prop-types'; diff --git a/src/Components/UploadPageComponents/UploadFileWrapper.js b/src/Components/UploadPageComponents/UploadFileWrapper.js index d93e8d47f1d254a40b927f3ade1098d832a90f7e..123512f2dc9e81026f99a2173cd573e1ed0f7e32 100644 --- a/src/Components/UploadPageComponents/UploadFileWrapper.js +++ b/src/Components/UploadPageComponents/UploadFileWrapper.js @@ -21,7 +21,7 @@ import LinkIcon from '../../img/link_icon.svg' import ChooseLink from './ChooseLinkSection.js' import {WrapperBox, BlueButton, GrayButton} from './StyledComponents.js'; import {DottedBox} from './StyledComponents.js'; -import {getAxiosConfig} from '../HelperFunctions/getAxiosConfig.js' +import {getAxiosConfigFromJSON, updateHeaders, deleteRequest, putRequest} from '../HelperFunctions/getAxiosConfig.js' import AddAPhotoIcon from '@material-ui/icons/AddAPhoto'; import axios from 'axios' import {apiUrl} from '../../env'; @@ -71,7 +71,7 @@ export default function UploadFileWrapper (props) { handleNextStage("fileSelected") for (var i = 0; i < total; i++) { let chunk = newFile.slice(currentChunkStartByte, currentChunkFinalByte) - let config = getAxiosConfig() + let config = getAxiosConfigFromJSON() let formData = new FormData() formData.append('_chunkFilename', newFile.name); formData.append('_chunkIdentifier', chunkIdentifier); @@ -86,7 +86,7 @@ export default function UploadFileWrapper (props) { const response = await axios.post(uploadUrl, formData, config); console.log(response) if (response.headers['access-token']) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) + updateHeaders(response.headers) } setProgress(Math.round((currentChunkFinalByte/newFile.size) * 100)) remainingBytes = newFile.size - currentChunkFinalByte; @@ -112,17 +112,9 @@ export default function UploadFileWrapper (props) { const handleDelete = () => { if (attachmentID != null) { + const url = `/learning_objects/${props.draftID}/attachment/${attachmentID}` - let config = getAxiosConfig() - axios.delete( (`${apiUrl}/learning_objects/` + props.draftID + '/attachment/' + attachmentID), config).then( - (response) => { - console.log(response) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - handleNextStage("default") - }, - (error) => {console.log(error)}) + deleteRequest(url, (data) => {handleNextStage("default")}, (error) => {console.log(error)}) } } @@ -148,26 +140,18 @@ export default function UploadFileWrapper (props) { }; const [snackbarOpen, toggleSnackbar] = useState(false) + const handleChooseLink = (link) => { - let config = getAxiosConfig() + const url = `/learning_objects/${props.draftID}` + let payload = { "learning_object" : { "id" : props.draftID, "link" : link } } - axios.put((`${apiUrl}/learning_objects/` + props.draftID), payload, config).then( - (response) => { - console.log(response) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - toggleSnackbar(true) - }, (error) => { - console.log(error) - } - ) + putRequest(url, payload, (data) => {toggleSnackbar(true)}, (error) => {console.log(error)}) } switch (stage) { diff --git a/src/Components/UserCard.js b/src/Components/UserCard.js deleted file mode 100644 index c8cb4a80e14ae5f66c4f7f4a0466a424679d2da9..0000000000000000000000000000000000000000 --- a/src/Components/UserCard.js +++ /dev/null @@ -1,18 +0,0 @@ -/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - -This file is part of Plataforma Integrada MEC. - -Plataforma Integrada MEC is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -Plataforma Integrada MEC is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -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/>.*/ - diff --git a/src/Components/UserPageComponents/Avatar.js b/src/Components/UserPageComponents/Avatar.js index afecba1416e118f4418d68a4bdc388612dd26597..f5ff994f43bd2ed4c480d394b44e1be22132d4b4 100644 --- a/src/Components/UserPageComponents/Avatar.js +++ b/src/Components/UserPageComponents/Avatar.js @@ -26,7 +26,7 @@ export default function ProfileAvatar (props) { // eslint-disable-next-line const {state, dispatch} = useContext(Store) - const [currentAvatar, setAvatar] = useState(state.currentUser.avatar_file_name) + const [currentAvatar, setAvatar] = useState(state.currentUser.avatar) const [hoverBool, toggleHover] = React.useState(false) const handleToggleHover = () => {toggleHover(!hoverBool)} @@ -34,7 +34,7 @@ export default function ProfileAvatar (props) { const [open, toggleOpen] = useState(false) const controlModal = () => {toggleOpen(!open)} - useEffect(() => {setAvatar(state.currentUser.avatar_file_name)}, state.currentUser.avatar_file_name) + useEffect(() => {setAvatar(state.currentUser.avatar)}, state.currentUser.avatar) return ( <> diff --git a/src/Components/UserPageComponents/Cover.js b/src/Components/UserPageComponents/Cover.js index 6fd3c539e020fc7e64bc674b3724f0ca746db932..339c36fd612cb3dc1a595c9a994a775af089c886 100644 --- a/src/Components/UserPageComponents/Cover.js +++ b/src/Components/UserPageComponents/Cover.js @@ -27,6 +27,8 @@ import ModalAlterarCover from '../ModalAlterarCover/ModalAlterarCover.js' export default function Cover (props) { const {state} = useContext(Store) + const WIDTH = window.innerWidth; + const [currentCover, setCoverImg] = useState(state.currentUser.cover_file_name) const [tempCover, setTempCover] = useState('') @@ -41,8 +43,8 @@ export default function Cover (props) { } useEffect( () => { - setCoverImg(state.currentUser.cover_file_name) - }, state.currentUser.cover_file_name) + setCoverImg(state.currentUser.cover) + }, state.currentUser.cover) return ( <> <ModalAlterarCover @@ -55,11 +57,21 @@ export default function Cover (props) { {currentCover && <img src={apiDomain + currentCover} alt = '' style= {{width:"100%", height:"100%", objectFit : "cover" }}/>} <input accept="image/*" style = {{display:"none"}} id="choose-cover-file" type="file" onChange={(e) => updateCover(e.target.files)}/> <label htmlFor="choose-cover-file"> + { + WIDTH >= 545 ? + <Tooltip title={<span style={{fontSize:"14px", overflow:"hidden", transition:"all .5s ease"}}>ALTERAR CAPA</span>} placement="left"> + <IconButton style={{position:"absolute",right:"0",bottom: "0",color:"#fff"}}color="primary" aria-label="upload picture" component="span"> + <PhotoCamera /> + </IconButton> + </Tooltip> + : <Tooltip title={<span style={{fontSize:"14px", overflow:"hidden", transition:"all .5s ease"}}>ALTERAR CAPA</span>} placement="left"> - <IconButton style={{position:"absolute",right:"0",top:"0",color:"#fff"}}color="primary" aria-label="upload picture" component="span"> + <IconButton style={{position:"absolute",left:"0",top: "0",color:"#fff"}}color="primary" aria-label="upload picture" component="span"> <PhotoCamera /> </IconButton> </Tooltip> + } + </label> </CoverContainer> </> diff --git a/src/Components/UserPageComponents/EditProfileButton.js b/src/Components/UserPageComponents/EditProfileButton.js index 4df7df2c7a5a6b4794ca5fd926d7440c77cc3ec1..beaa7137501ba03fc9de6f46d14391c6e7072f13 100644 --- a/src/Components/UserPageComponents/EditProfileButton.js +++ b/src/Components/UserPageComponents/EditProfileButton.js @@ -49,8 +49,8 @@ const EditProfileAnchor = styled(Link)` box-shadow : 0 2px 5px 0 rgba(0,0,0,.26); background-color : #fafafa; position : absolute; - right : 5px; - bottom : 0; + right : 10px; + top : 10px; margin-bottom : 20px; color : #666; padding : 0 10px; diff --git a/src/Pages/AboutPage.js b/src/Pages/AboutPage.js index e8c57d2e26d0b765e23b021e57ff7edd3d4f026a..56b8404129be79f65c0d98f971bb7006e316d1dd 100644 --- a/src/Pages/AboutPage.js +++ b/src/Pages/AboutPage.js @@ -21,6 +21,8 @@ import Grid from '@material-ui/core/Grid'; import styled from 'styled-components'; import Modal from '../Components/ModalAbout'; import AboutCarousel from "../Components/AboutCarousel"; +import AboutCarouselPartner from '../Components/AboutCarouselPartner'; + /*Importação de imagens para o componente*/ import Agpl from "../img/sobre/agpl.svg"; @@ -31,21 +33,6 @@ import Alunos from "../img/sobre/Alunos.png"; import Gestores from "../img/sobre/Gestores.png"; import Comunidade from "../img/sobre/comunidade.png"; -import LogoPortalDoProfessor from "../img/logo_parceiros/logo_portaldoprofessor.png"; -import LogoBioe from "../img/logo_parceiros/logo_bioe.png"; -import LogoDominioPublico from "../img/logo_parceiros/logo_dominiopublico.png"; -import LogoTvEscola from "../img/logo_parceiros/logo_tvescola.png"; -import Safer from "../img/logo_parceiros/safer.png"; -import FundacaoLemann from "../img/logo_parceiros/fundacao-lemann.png"; -import InstitutoCrescer from "../img/logo_parceiros/instituto-crescer.png"; -import RedeEscola from "../img/logo_parceiros/redeescola.png"; -import Educagital from "../img/logo_parceiros/educagital.png"; -import EnefAef from "../img/logo_parceiros/ENEF_AEF.png"; -import Impa from "../img/logo_parceiros/impa.png"; -import Futura from "../img/logo_parceiros/futura.png"; -import Impulsiona from "../img/logo_parceiros/impulsiona.png"; -import InstPeninsula from "../img/logo_parceiros/inst-peninsula.png"; -import Telefonica from "../img/logo_parceiros/telefonica.png"; const Secao1 = styled.div` height: 600px; @@ -54,7 +41,6 @@ const Secao1 = styled.div` const Secao2 = styled.div` - height: 600px; color: #666; text-align: center; font-size: 14px; @@ -63,11 +49,11 @@ const Secao2 = styled.div` .container { height: 100%; - width: 1140px; padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; + padding: 20px 0px; .container-secao { height: 100%; @@ -76,8 +62,8 @@ const Secao2 = styled.div` justify-content: center; - .conteudo-secao { + .conteudo-secao { h2 { text-align: center; font-family: Roboto, sans-serif; @@ -108,23 +94,19 @@ const Secao2 = styled.div` ` const Secao3 = styled.div` - height: auto; padding: 30px 0; background-color: #1ab9de; color: #fff; .container { - height: 100%; - width: 1140px; padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; + padding-left: 20px; .container-secao { - height: 100%; - width: 1110px; padding-right: 15px; padding-left: 15px; display: flex; @@ -184,7 +166,6 @@ const Secao4 = styled.div` .container { height: 100%; - width: 1140px; padding-right: 15px; padding-left: 15px; margin-right: auto; @@ -298,7 +279,6 @@ const Secao5 = styled.div` .container { height: 100%; - width: 1140px; padding-right: 15px; padding-left: 15px; margin-right: auto; @@ -341,8 +321,7 @@ const Secao6 = styled.div` .container { - height: 450px; - width: 1140px; + height: 100%; padding-top:50px padding-right: 15px; padding-left: 15px; @@ -359,7 +338,7 @@ const Secao6 = styled.div` .conteudo-secao { height: 100%; - width: 970px; + width: 100%; h2 { text-align: center; @@ -392,13 +371,12 @@ const Secao6 = styled.div` ` const Secao7 = styled.div` - height: 592px; + height: 100%; background-color: #f4f4f4; .container { height: 100%; - width: 1170px; margin-right: auto; margin-left: auto; @@ -408,6 +386,7 @@ const Secao7 = styled.div` flex-direction: column; justify-content: center; color: #666; + padding: 50px .conteudo-secao { @@ -436,11 +415,11 @@ const Secao7 = styled.div` .card { - height: 270px; + height: 80%; background-color: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); - padding: 50px 20px; + padding: 40px 20px; text-align: center; h3 { @@ -478,7 +457,6 @@ const Secao8 = styled.div` .container { height: 100%; - width: 1140px; padding-right: 15px; padding-left: 15px; margin-right: auto; @@ -572,14 +550,30 @@ const Secao8 = styled.div` export default function AboutPage(props) { - + var pageWidth = window.innerWidth + const calculateMargin = ((pageWidth)=>{ + if (pageWidth > 700 && pageWidth <= 850){ + return "40%" + } + if (pageWidth > 850 && pageWidth <= 900){ + return "25%" + } + if (pageWidth > 900 && pageWidth < 1100){ + return "13%" + } + else{ + return "0%" + } + }) + var marginSet = calculateMargin(pageWidth) + const styleIMGSec3 = {float:"right", width:"80%", maxWidth:475, marginRight:30, marginTop: marginSet} return ( <> <link href="https://fonts.googleapis.com/css?family=Pompiere|Roboto:300,400&display=swap" rel="stylesheet"/> <Secao1> - <iframe title="Vídeo página sobre" src="https://player.vimeo.com/video/231609051" width="100%" height="100%" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe> + <iframe title="Vídeo página sobre" src="https://player.vimeo.com/video/231609051" width="100%" height="100%" frameBorder="0" allow="autoplay; fullscreen" allowFullScreen></iframe> </Secao1> @@ -588,9 +582,7 @@ export default function AboutPage(props) { <div className="container-secao"> <div className="conteudo-secao"> <h2>Um Pouco da História</h2> - <br/> - <br/> - <p> + <p style={{marginLeft:20, marginRight:20, marginBottom:40}}> A partir de uma iniciativa do Ministério da Educação, surge em outubro de 2015 a proposta de reunir e disponibilizar, em um único lugar, os Recursos Educacionais Digitais dos principais @@ -603,9 +595,6 @@ export default function AboutPage(props) { entre professoras(es)!<br/><br/>Faça parte deste espaço de colaborativo você também! </p> - <br/> - <br/> - <br/> <img src={Agpl} alt="agpl" /> <p> Este programa é software livre, sob os termos da @@ -624,7 +613,7 @@ export default function AboutPage(props) { <div className="container-secao"> <div className="conteudo-secao"> <Grid container spacing={0}> - <Grid item xs={6}> + <Grid item xs style={{paddingRight:20}}> <h2>O que nos faz diferentes?</h2> <h3>Espaço construído por e para professores</h3> <p> @@ -645,9 +634,15 @@ export default function AboutPage(props) { os Recursos Educacionais Digitais dos principais portais abertos. </p> </Grid> - <Grid item xs={6}> - <img src={Notebook} alt="Imagem Notebook"/> - </Grid> + { + pageWidth >= 751? + <Grid item xs={6} style={{position:"relative"}}> + <img src={Notebook} alt="Imagem Notebook" style={styleIMGSec3}/> + </Grid> + : + <div/> + } + </Grid> @@ -656,6 +651,8 @@ export default function AboutPage(props) { </div> </Secao3> + + <Secao4> <div className="container"> <div className="container-secao" id="portaisparceiros"> @@ -664,89 +661,9 @@ export default function AboutPage(props) { <h2>Portais Parceiros</h2> <p>Aqui na Plataforma você encontra os Recursos Digitais dos principais portais do MEC e de vários outros parceiros.</p> </div> - <div className="portais"> - <ul className="itens"> - <li> - <a href="http://portaldoprofessor.mec.gov.br/index.html" rel="noreferrer" target="_blank"> - <img src={LogoPortalDoProfessor} alt="LogoPortalDoProfessor" /> - </a> - </li> - <li> - <a href="http://objetoseducacionais2.mec.gov.br/" rel="noreferrer" target="_blank"> - <img src={LogoBioe} alt="LogoBioe" /> - </a> - </li> - <li> - <a href="http://www.dominiopublico.gov.br/pesquisa/PesquisaObraForm.jsp" rel="noreferrer" target="_blank"> - <img src={LogoDominioPublico} alt="LogoDominioPublico" /> - </a> - </li> - <li> - <a href="https://tvescola.org.br/" rel="noreferrer" target="_blank"> - <img src={LogoTvEscola} alt="LogoTvEscola" /> - </a> - </li> - </ul> - <ul className="itens"> - <li> - <a href="http://www.fundacaolemann.org.br/" rel="noreferrer" target="_blank"> - <img style={{align: "middle"}} src={FundacaoLemann} alt="FundacaoLemann" /> - </a> - </li> - <li> - <a href="http://new.safernet.org.br/" rel="noreferrer" target="_blank"> - <img src={Safer} alt="Safer" /> - </a> - </li> - <li> - <a href="http://institutocrescer.org.br/" rel="noreferrer" target="_blank"> - <img src={InstitutoCrescer} alt="InstitutoCrescer" /> - </a> - </li> - <li> - <a href="http://escoladigital.org.br/" rel="noreferrer" target="_blank"> - <img src={RedeEscola} alt="RedeEscola" /> - </a> - </li> - <li> - <a href="http://educadigital.org.br" rel="noreferrer" target="_blank"> - <img src={Educagital} alt="Educagital" /> - </a> - </li> - <li> - <a href="http://www.aefbrasil.org.br" rel="noreferrer" target="_blank"> - <img style={{height:"130px",filter: "grayscale(1)"}} src={EnefAef} alt="EnefAef" /> - </a> - </li> - </ul> - <ul className="itens"> - <li> - <a href="https://impa.br/" rel="noreferrer" target="_blank"> - <img src={Impa} alt="Impa" /> - </a> - </li> - <li> - <a href="http://futura.org.br/" rel="noreferrer" target="_blank"> - <img src={Futura} alt="Futura" /> - </a> - </li> - <li> - <a href="http://impulsiona.org.br/" rel="noreferrer" target="_blank"> - <img src={Impulsiona} alt="Impulsiona" /> - </a> - </li> - <li> - <a href="http://www.institutopeninsula.org.br/" rel="noreferrer" target="_blank"> - <img src={InstPeninsula} alt="InstPeninsula" /> - </a> - </li> - <li> - <a href="http://fundacaotelefonica.org.br/" rel="noreferrer" target="_blank"> - <img src={Telefonica} alt="Telefonica" /> - </a> - </li> - </ul> - </div> + + <AboutCarouselPartner/> + <div> <h3>Você busca Recursos Educacionais Digitais em outros sites?</h3> <p> @@ -807,7 +724,7 @@ export default function AboutPage(props) { </div> <div> <Grid container spacing={3}> - <Grid item xs={3}> + <Grid item xs> <div className="card"> <img src={Professores} alt="" /> <h3>Professores</h3> @@ -818,7 +735,7 @@ export default function AboutPage(props) { </p> </div> </Grid> - <Grid item xs={3}> + <Grid item xs> <div className="card"> <img src={Alunos} alt="" /> <h3>Alunos</h3> @@ -829,7 +746,7 @@ export default function AboutPage(props) { </p> </div> </Grid> - <Grid item xs={3}> + <Grid item xs> <div className="card"> <img src={Gestores} alt="" /> <h3>Gestores</h3> @@ -839,7 +756,7 @@ export default function AboutPage(props) { </p> </div> </Grid> - <Grid item xs={3}> + <Grid item xs> <div className="card"> <img src={Comunidade} alt="" /> <h3>Comunidade Escolar</h3> diff --git a/src/Pages/CollectionPage.js b/src/Pages/CollectionPage.js index 123f6c6a4be006f4807aa5625e940cbc0d9ed5e0..7aec85f4c15248b0f38a886f918c5befc6df02d6 100644 --- a/src/Pages/CollectionPage.js +++ b/src/Pages/CollectionPage.js @@ -16,20 +16,20 @@ 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, { useRef, useState, useEffect, useContext } from 'react'; -import axios from 'axios'; import { Grid } from '@material-ui/core'; import CollectionAuthor from '../Components/CollectionAuthor.js'; import VerticalRuler from '../Components/VerticalRuler.js'; import CollectionDescription from '../Components/CollectionDescription.js'; import ResourceList from '../Components/ResourceList.js'; import CollectionCommentSection from '../Components/CollectionCommentSection.js'; -import { apiUrl, apiDomain } from '../env'; +import { apiDomain } from '../env'; import styled from 'styled-components'; import DowloadButton from '../Components/CollectionDowloadButton.js'; import Breadcrumbs from "@material-ui/core/Breadcrumbs"; import { Link } from 'react-router-dom'; import FollowCollectionButton from '../Components/FollowCollectionButton'; import { Store } from '../Store.js' +import {getRequest} from '../Components/HelperFunctions/getAxiosConfig.js' export default function CollectionPage(props) { const { state } = useContext(Store); @@ -42,16 +42,15 @@ export default function CollectionPage(props) { const comment_ref = useRef(null); useEffect(() => { - axios.get(apiUrl + '/collections/' + collection_id) - .then(res => { - setCollection(Object.assign({}, res.data)); - }); + const url = `/collections/${collection_id}` + + getRequest(url, (data) => {setCollection(Object.assign({}, data))}, (error) => {console.log(error)}) }, []); const handleScrollToComments = () => { window.scrollTo(0, comment_ref.current.offsetTop); } - + console.log("COLLECTION >> ", collection) return ( <> <BreadCrumbsDiv> @@ -112,7 +111,6 @@ export default function CollectionPage(props) { return { type: i.collectionable.object_type, author: i.collectionable.author, - published: i.collectionable.published_at, title: i.collectionable.name, rating: i.collectionable.review_average, likeCount: i.collectionable.likes_count, @@ -121,6 +119,9 @@ export default function CollectionPage(props) { thumbnail: i.collectionable.thumbnail, tags: i.collectionable.tags.map(t => t), id: i.collectionable.id, + downloadableLink: i.collectionable.default_attachment_location, + publisher: i.collectionable.publisher.name, + published: i.collectionable.state } }) : [] @@ -141,11 +142,11 @@ export default function CollectionPage(props) { // style={mainContainerStyle}> // <Grid item xs={10} md={3}> - // <CollectionAuthor + // <CollectionAuthor // author_id={collection.owner ? collection.owner.id : 0} // name={collection.owner ? collection.owner.name : ""} // imgsrc={collection.owner ? apiDomain+collection.owner.avatar : ''}/> - // </Grid> + // </Grid> // <VerticalRuler width={1} height={300} color="rgb(238, 238, 238)"/> @@ -154,12 +155,12 @@ export default function CollectionPage(props) { // scrollToComments={handleScrollToComments} // title={collection.name ? collection.name : ""} // collection_id={collection.id ? collection.id : 0}/> - // </Grid> + // </Grid> // <Grid container item xs={12} direction="row" justify="center" alignItems="center" style={{backgroundColor: '#f4f4f4'}}> // <Grid item xs={10}> // <ResourceList resources={ - // collection.collection_items ? + // collection.collection_items ? // collection.collection_items.map(i => { // return { // type: i.collectionable.object_type, @@ -190,7 +191,6 @@ export default function CollectionPage(props) { const StyledBreadCrumbs = styled(Breadcrumbs)` display: flex; justify-content: flex-start; - max-width: 1170px; span { color: #a5a5a5; } @@ -204,5 +204,3 @@ const BreadCrumbsDiv = styled.div` padding: 10px; display: flex; `; - - diff --git a/src/Pages/EditLearningObjectPage.js b/src/Pages/EditLearningObjectPage.js index 7f4e39ba6bd45cd6b6a48efb5d993c7a69251076..5e04a247c29d2b1fe130a18e5b15af4fab026d69 100644 --- a/src/Pages/EditLearningObjectPage.js +++ b/src/Pages/EditLearningObjectPage.js @@ -25,7 +25,6 @@ import UploadFileWrapper from '../Components/UploadPageComponents/UploadFileWrap import Alert from '../Components/Alert.js'; import Snackbar from '@material-ui/core/Snackbar'; import {GreyButton, OrangeButton, InfoBox} from '../Components/UploadPageComponents/StyledComponents.js' -import {getAxiosConfig} from '../Components/HelperFunctions/getAxiosConfig.js' import {Background} from '../Components/UploadPageComponents/StyledComponents' import LoadingSpinner from '../Components/LoadingSpinner' import NewTitle from '../Components/UploadPageComponents/Forms/NewTitle.js' @@ -41,7 +40,7 @@ import {LoadingDiv} from '../Components/UploadPageComponents/PartTwo.js' import EditThumbnail from '../Components/UploadPageComponents/PartTwoComponents/EditThumbnail.js' import DisplayThumbnail from '../Components/UploadPageComponents/PartTwoComponents/DisplayThumbnail.js' import DragAndDropThumbnail from '../Components/UploadPageComponents/PartTwoComponents/DragAndDropThumbnail' - +import {getRequest, deleteRequest, putRequest, postRequest} from '../Components/HelperFunctions/getAxiosConfig.js' export default function EditLearningObjectPage (props) { const recursoId = props.match.params.recursoId @@ -52,23 +51,19 @@ export default function EditLearningObjectPage (props) { const [eduStages, setEduStages] = useState([]) const [subjects, setSubjects] = useState([]) + function handleSuccessfulGet (data) { + setLearningObject(data) + if(data.thumbnail) { + setThumbnail(data.thumbnail) + setThumbnailStage('done') + } + setUpdatedInfo({...updatedInfo, 'id' : data.id}) + toggleLoading(false) + } + useEffect( () => { - const config = getAxiosConfig() - axios.get( (`${apiUrl}/learning_objects/` + recursoId), config - ).then( (response) => { - console.log(response.data) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - setLearningObject(response.data) - if(response.data.thumbnail) { - setThumbnail(response.data.thumbnail) - setThumbnailStage('done') - } - setUpdatedInfo({...updatedInfo, 'id' : response.data.id}) - toggleLoading(false) - }, (error) => {console.log(error)} - ) + const url = `/learning_objects/${recursoId}` + getRequest(url, handleSuccessfulGet, (error) => {console.log(error)}) axios.get(`${apiUrl}/object_types/`).then( (response) => { @@ -99,7 +94,7 @@ export default function EditLearningObjectPage (props) { }, (error) => {console.log(error)} ) - }, [state.currentUser.id]) + }, []) const [loading, toggleLoading] = useState(true) @@ -111,58 +106,37 @@ export default function EditLearningObjectPage (props) { const [snackbarOpen, toggleSnackbar] = useState(false) + function handleSuccessfulDelete (data) { + toggleSnackbar(true) + props.history.push("/") + } const handleDelete = () => { - let config = getAxiosConfig() - axios.delete((`${apiUrl}/learning_objects/` + learningObject.id), config).then( - (response) => { - toggleSnackbar(true) - console.log(response.data) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - props.history.push("/") - }, - (error) => { - console.log(error) - } - ) + const url = `/learning_objects/${learningObject.id}` + + deleteRequest(url, handleSuccessfulDelete, (error) => {console.log(error)}) } const handleUpdateInfo = () => { - let config = getAxiosConfig() - console.log(updatedInfo) + const url = `/learning_objects/${learningObject.id}` let payload = { "learning_object" : updatedInfo } - console.log(payload) - axios.put((`${apiUrl}/learning_objects/` + learningObject.id), payload, config).then( - (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response.data); props.history.goBack() - }, - (error) => {console.log(error)} - ) + + putRequest(url, payload, (data) => {props.history.goBack()}, (error) => {console.log(error)}) } const handlePost = () => { - let config = getAxiosConfig() - console.log(updatedInfo) + const url = `/learning_objects/${learningObject.id}/publish` + let payload = { "learning_object" : updatedInfo } - console.log(payload) - axios.post((`${apiUrl}/learning_objects/` + learningObject.id + '/publish'), payload, config).then( - (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response.data); - props.history.push('/recurso/' + learningObject.id) - }, + + postRequest(url, payload, + (data) => {props.history.push( `/recurso/${learningObject.id}`)}, (error) => {console.log(error)} ) + } const [thumbnailStage, setThumbnailStage] = useState('default') @@ -182,63 +156,31 @@ export default function EditLearningObjectPage (props) { } + function handleFinalizeThumb (data) { + if(data.thumbnail) { + setThumbnail(data.thumbnail) + setThumbnailStage('done') + } + } + const finalizeThumb = () => { setThumbnailStage('uploading') - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - } - } - config.headers["access-Token"] = sessionStorage.getItem('@portalmec/accessToken'); - config.headers.client = sessionStorage.getItem('@portalmec/clientToken') - config.headers.uid = sessionStorage.getItem('@portalmec/uid') + + const url = `/learning_objects/${learningObject.id}` let fdThumb = new FormData() fdThumb.set('learning_object[thumbnail]', thumbnail) - axios.put((`${apiUrl}/learning_objects/` + learningObject.id), fdThumb, config).then( - (response) => { - setThumbnailStage('done') - console.log(response.data) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - if(response.data.thumbnail) { - setThumbnail(response.data.thumbnail) - setThumbnailStage('done') - } - }, - () => { - setThumbnailStage('default') - } - ) + + putRequest(url, fdThumb, handleFinalizeThumb, (error) => {setThumbnailStage('default')}) } const handleDeleteThumbnail = () => { - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - } - } - config.headers["access-Token"] = sessionStorage.getItem('@portalmec/accessToken'); - config.headers.client = sessionStorage.getItem('@portalmec/clientToken') - config.headers.uid = sessionStorage.getItem('@portalmec/uid') + const url = `/learning_objects/${learningObject.id}` let fdThumb = new FormData() fdThumb.set('learning_object[thumbnail]', null) - axios.put((`${apiUrl}/learning_objects/` + learningObject.id), fdThumb, config).then( - (response) => { - setThumbnailStage('default') - console.log(response.data) - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - }, - (error) => { - console.log(error) - } - ) + + putRequest(url, fdThumb, (data) => {setThumbnailStage('default')}, (error) => {console.log(error)}) } const chooseRenderStageThumbnail = () => { diff --git a/src/Pages/EditProfilePage.js b/src/Pages/EditProfilePage.js index b91d0c4d6186cf0d394d1e887e3f9f630d8a6195..381a2872bd9441e8442b2944dbe1d9daabe70d07 100644 --- a/src/Pages/EditProfilePage.js +++ b/src/Pages/EditProfilePage.js @@ -10,13 +10,11 @@ import Snackbar from '@material-ui/core/Snackbar'; import {Alert} from '../Components/LoginModal.js' import Grid from '@material-ui/core/Grid' import CustomizedBreadcrumbs from '../Components/TabPanels/Breadcrumbs.js' -import axios from 'axios' -import {getAxiosConfig} from '../Components/HelperFunctions/getAxiosConfig' -import {apiUrl} from '../env.js' +import {putRequest} from '../Components/HelperFunctions/getAxiosConfig' import {Store} from '../Store.js' export default function EditProfilePage (props) { - const {state} = useContext(Store) + const {state, dispatch} = useContext(Store) const id = state.currentUser.id // eslint-disable-next-line @@ -38,62 +36,42 @@ export default function EditProfilePage (props) { } const updateUserInfo = (newUserInfo) => { - console.log(newUserInfo) - let config = getAxiosConfig() - - axios.put( (`${apiUrl}/users/` + id), newUserInfo, config - ).then ( - (res) => { - console.log(res) - if ( res.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', res.headers['access-token']) - } - - props.history.push('/perfil') - - }, - (err) => { - console.log(err) - } + const url = `/users/${id}` + + putRequest(url, newUserInfo, + (data) => {props.history.push('/perfil')}, + (error) => {console.log(error)} ) } + function handleSuccessUpdateEmail (data) { + let auth_headers = JSON.parse(sessionStorage.getItem('@portalmec/auth_headers')) + + auth_headers['uid'] = data.uid + + sessionStorage.setItem('@portalmec/auth_headers', JSON.stringify(auth_headers)) + + const target = state.currentUser + const source = {uid : data.uid} + dispatch({ + type : 'USER_UPDATED_EMAIL', + currUser : Object.assign(target, source) + }) + } + const updateUserEmail = (newUserInfo) => { - let config = getAxiosConfig() - - axios.put( (`${apiUrl}/users/` + id), newUserInfo, config - ).then ( - (res) => { - console.log(res) - if ( res.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', res.headers['access-token']) - } - - sessionStorage.setItem('@portalmec/uid', res.headers['uid']) - }, - (err) => { - console.log(err) - } + const url = `/users/${id}` + + putRequest(url, newUserInfo, handleSuccessUpdateEmail, (error) => {console.log(error)} ) } const updateUserPassword = (newUserInfo) => { - let config = getAxiosConfig() - - axios.put( (`${apiUrl}/users/` + id), newUserInfo, config - ).then ( - (res) => { - console.log(res) - if ( res.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', res.headers['access-token']) - } - - handleSnackbar(true) - - }, - (err) => { - console.log(err) - } + const url = `/users/${id}` + + putRequest(url, newUserInfo, + (data) => {handleSnackbar(true)}, + (error) => {console.log(error)} ) } diff --git a/src/Pages/HelpCenter.js b/src/Pages/HelpCenter.js index a082dce11815138a40eb343c1b81b1958bde2b84..f70481b0db11f0001894d7909721f1f293758eca 100644 --- a/src/Pages/HelpCenter.js +++ b/src/Pages/HelpCenter.js @@ -34,13 +34,20 @@ import CardGerenciando from '../Components/HelpCenter/Cards/CardGerenciando'; function HelpCenter(props) { + let windowWidth = window.innerWidth + return( <div style={{backgroundColor: "#f4f4f4"}}> <link href="https://fonts.googleapis.com/css?family=Pompiere|Roboto:300,400&display=swap" rel="stylesheet"/> <Secao1> <div className= "container"> - <img src={Banner3} alt="banner3"/> + { + windowWidth > 420? + <img src={Banner3} alt="banner3"/> + : + <div/> + } <div className= "conteudo"> <div className= "title"> <h2>OLÁ! COMO PODEMOS AJUDAR?</h2> @@ -57,17 +64,17 @@ function HelpCenter(props) { <h2>Tópicos de Ajuda</h2> </div> <div> - <Grid container spacing={2}> - <Grid item xs={3}> + <Grid container justify="center" style={{margin:-8}}> + <Grid item xs={12} md={5} style={{padding:8}}> <CardPublicando/> </Grid> - <Grid item xs={3}> + <Grid item xs={12} md={5} style={{padding:8}}> <CardEncontrando/> </Grid> - <Grid item xs={3}> + <Grid item xs={12} md={5} style={{padding:8}}> <CardParticipando/> </Grid> - <Grid item xs={3}> + <Grid item xs={12} md={5} style={{padding:8}}> <CardGerenciando/> </Grid> </Grid> @@ -77,64 +84,66 @@ function HelpCenter(props) { </div> </Secao2> - + <div style={{width:"100%"}}> <Secao3> - <Grid style={{height:"100%"}} container spacing={2}> - <Grid style={{backgroundColor: "#333",paddingInline:"0" }} item xs={6}> - <iframe title="Vídeo página ajuda" src="https://player.vimeo.com/video/231609051" width="100%" height="100%" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe> - </Grid> - <Grid item xs={6}> - <p className="titulo-sobre-ajuda">Plataforma MEC de Recursos Educacionais Digitais</p> - <p className="conteudo-sobre-ajuda"> - Construa conosco a plataforma e amplie sua rede de conhecimento<br/> - interagindo com pessoas envolvidas com experiências que ocorrem<br/> - em todo o Brasil! - </p> - <hr/> - <Grid container spacing={1}> - <Grid item xs={6}> - <p className="links"> - <br/> - <Link to={{ - pathname : 'plataforma-mec', - state : {value : '0'} - }}>O que é a Plataforma MEC</Link> - <br/> - <Link to={{ - pathname : 'plataforma-mec', - state : {value : '1'} - }}>Como foi construida a Plataforma<br/>MEC?</Link> - <br/> - <Link to={{ - pathname : 'plataforma-mec', - state : {value : '3'} - }}>Quais são os Portais Parceiros?</Link> - </p> - </Grid> - <Grid item xs={6}> - <p className="links"> - <br/> - <Link to={{ - pathname : 'plataforma-mec', - state : {value : '2'} - }}>Entendendo as 3 áreas</Link> - <br/> - <Link to={{ - pathname : 'plataforma-mec', - state : {value : '4'} - }}>Tipos de recursos</Link> - <br/> - <Link to={{ - pathname : 'plataforma-mec', - state : {value : '5'} - }}>Softwares específicos</Link> + <Grid style={{height:"100%"}} container justify="center"> + <Grid style={{backgroundColor: "#333",paddingInline:"0" }} item xs={12} md={6}> + <iframe title="Vídeo página ajuda" src="https://player.vimeo.com/video/231609051" width="100%" height="100%" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe> + </Grid> + <Grid item xs={12} md={6}> + <div> + <p className="titulo-sobre-ajuda">Plataforma MEC de Recursos Educacionais Digitais</p> + <p className="conteudo-sobre-ajuda"> + Construa conosco a plataforma e amplie sua rede de conhecimento + interagindo com pessoas envolvidas com experiências que ocorrem + em todo o Brasil! </p> + </div> + <Grid container> + <Grid item xs={12} md={6}> + <p className="links"> + <br/> + <Link to={{ + pathname : 'plataforma-mec', + state : {value : '0'} + }}>O que é a Plataforma MEC</Link> + <br/> + <Link to={{ + pathname : 'plataforma-mec', + state : {value : '1'} + }}>Como foi construida a Plataforma<br/>MEC?</Link> + <br/> + <Link to={{ + pathname : 'plataforma-mec', + state : {value : '3'} + }}>Quais são os Portais Parceiros?</Link> + </p> + </Grid> + <Grid item xs={12} md={6}> + <p className="links"> + <br/> + <Link to={{ + pathname : 'plataforma-mec', + state : {value : '2'} + }}>Entendendo as 3 áreas</Link> + <br/> + <Link to={{ + pathname : 'plataforma-mec', + state : {value : '4'} + }}>Tipos de recursos</Link> + <br/> + <Link to={{ + pathname : 'plataforma-mec', + state : {value : '5'} + }}>Softwares específicos</Link> + </p> + </Grid> </Grid> - </Grid> + </Grid> </Grid> - </Grid> - </Secao3> + </Secao3> + </div> <Secao4> <div className="container"> @@ -142,7 +151,7 @@ function HelpCenter(props) { <h2>Não encontrou o que você precisa?</h2> <span>Entre em contato com a nossa Central de Ajuda</span> <br/> - <button><a href="contato">ENTRAR EM CONTATO</a></button> + <button style={{marginBottom:50, marginTop:20}}><a href="contato">ENTRAR EM CONTATO</a></button> </div> </div> @@ -156,27 +165,25 @@ export default HelpCenter; const Secao1 = styled.div` - height: 374px; background-color:#00bcd4; text-align: center; + width: 100%; .container { height: 100%; - width: 1170px; display: flex; -webkit-box-pack: center; justify-content: center; -webkit-box-align: center; align-items: center; - padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; img { position: relative; - left: 82px; top: 41.6%; - width: 230px; + max-width: 230px; + width: 90%; float: left; min-height: 1px; padding-right: 15px; @@ -208,14 +215,13 @@ const Secao1 = styled.div` ` const Secao2 = styled.div` - height: 536px; background-color:#f4f4f4; text-align: center; margin-bottom: 20px; - + padding-bottom: 50px + width: 100%; .container { height: 100%; - width: 1170px; margin-right: auto; margin-left: auto; @@ -243,7 +249,7 @@ const Secao2 = styled.div` .card { height: 280px; - padding: 40px 15px; + padding: 40px 0px; text-align: center; font-size: 14px; background-color:#fff; @@ -258,13 +264,6 @@ const Secao2 = styled.div` line-height: 1.1; } - hr { - margin-top: 20px; - margin-bottom: 20px; - border: 0; - border-top: 1px solid #eee; - color: #a5a5a5; - } a { font-size: 15px; @@ -321,14 +320,12 @@ const Secao2 = styled.div` ` const Secao3 = styled.div` - height: 375px; padding: 0; text-align: center; background-color: #fff; - width: 1170px; margin-inline: auto; color: rgba(0,0,0,0.87); - + width: 100%; .links { font-size: 15px; font-weight: lighter; @@ -356,26 +353,16 @@ const Secao3 = styled.div` margin: 0 0 10px; } - hr { - width: 350px; - border: 0; - border-top: 1px solid #ccc; - margin-top: 20px; - margin-bottom: 20px; - - } ` const Secao4 = styled.div` - height: 290px; - + width: 100%; .container { height: 100%; color: #a5a5a5; - width: 1170px; margin-inline: auto; display: flex; flex-direction: column; diff --git a/src/Pages/PageProfessor.js b/src/Pages/PageProfessor.js index 6c2f45380a19d8ced2e175add35b0387931b0f32..6ee8588e27a0ba57100336e6da714c2c938f1acd 100644 --- a/src/Pages/PageProfessor.js +++ b/src/Pages/PageProfessor.js @@ -6,8 +6,7 @@ import PartTwo from '../Components/PageProfessorComponents/PartTwo.js' import PartThree from '../Components/PageProfessorComponents/PartThree.js' import SuccessfulRequest from '../Components/PageProfessorComponents/SuccessfulRequest.js' import ModalConfirmarProfessor from '../Components/PageProfessorComponents/ModalConfirmarProfessor.js' -import axios from 'axios' -import {apiUrl} from '../env'; +import {postRequest} from '../Components/HelperFunctions/getAxiosConfig' export default function PageProfessor (props) { const {state} = useContext(Store) @@ -49,7 +48,6 @@ export default function PageProfessor (props) { } const handleBuscarParteUm = (ufAbbreviation, ufName, nomeMunicipio, inep) => { - console.log('handleBuscarParteUm: ', ufAbbreviation, ufName, nomeMunicipio, inep) setRegisterInformation({...registerInformation, school_uf : { abbreviation: (ufAbbreviation ? ufAbbreviation : ''), @@ -90,27 +88,24 @@ export default function PageProfessor (props) { props.history.push('/perfil/atualizacoes') } + function handleSuccessfulSubmit (data) { + toggleModal() + toggleStepper(false, false, false, true) + } + const handleFinalSubmit = () => { - //adicionar headers de accessToken - axios.post( `${apiUrl}/users/teacher_request`, { + const url = `/users/teacher_request` + + const payload = { city : registerInformation.school_city.name, cpf : registerInformation.teacher_cpf, inep_id : registerInformation.inep_code, phone : registerInformation.school_phone, school : registerInformation.school_name, uf : registerInformation.school_uf.name - }, - { headers : { - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid') - }} - ) - .then( (response) => { - toggleModal() - toggleStepper(false, false, false, true) - }, (error) => console.log('deu erro') - ) + } + + postRequest(url, payload, handleSuccessfulSubmit, (error) =>{console.log(error)}) } return ( @@ -118,7 +113,6 @@ export default function PageProfessor (props) { { state.userAgreedToPublicationTerms? ( - [ <> <ModalConfirmarProfessor open={modalOpen} handleClose={handleModal} info={registerInformation} confirmar = {() => {handleFinalSubmit()}} @@ -154,7 +148,6 @@ export default function PageProfessor (props) { </div> </div> </> - ] ) : ( diff --git a/src/Pages/PasswordRecoveryPage.js b/src/Pages/PasswordRecoveryPage.js index a2691a50b901e88c2ab24aa323d07894ddf85bc3..010a164ba112a342e7e01e14fc2c5ba2bc38a1ff 100644 --- a/src/Pages/PasswordRecoveryPage.js +++ b/src/Pages/PasswordRecoveryPage.js @@ -2,14 +2,12 @@ import React, {useState} from 'react' import {BackgroundDiv} from '../Components/TabPanels/StyledComponents.js' import Paper from '@material-ui/core/Paper'; import styled from 'styled-components' -import ValidateUserInput from '../Components/FormValidationFunction.js' +import ValidateUserInput from '../Components/HelperFunctions/FormValidationFunction.js' import Default from '../Components/PasswordRecoveryComponents/Default.js' import Success from '../Components/PasswordRecoveryComponents/Success.js' import CaseError from '../Components/PasswordRecoveryComponents/Error.js' import CustomizedBreadcrumbs from '../Components/TabPanels/Breadcrumbs.js' -import {apiUrl} from '../env'; -import axios from 'axios' - +import {postRequest} from '../Components/HelperFunctions/getAxiosConfig' export default function PasswordRecoveryPage (props) { @@ -40,18 +38,21 @@ export default function PasswordRecoveryPage (props) { setCase(value) }; + function handleSuccessfulSubmit (data) { + handleChangeSwitch((data.success ? "success" : "error")) + } const onSubmit = (e) => { e.stopPropagation() + + const url = `/auth/password` + const payload = { "email" : formEmail.value, "redirect_url" : "https://plataformaintegrada.mec.gov.br/recuperar-senha#/alterar-senha" } - axios.post((`${apiUrl}/auth/password`), payload).then( - (response) => { - console.log(response) - handleChangeSwitch(response.data.success ? "success" : "error") - }, - (error) => {console.log(error)}) + + postRequest(url, payload, handleSuccessfulSubmit, (error) => {console.log(error)}) + } diff --git a/src/Pages/ProfilePage.js b/src/Pages/ProfilePage.js deleted file mode 100644 index 6959ad9357650785a7088ddbb25ac0a0ac3bffe1..0000000000000000000000000000000000000000 --- a/src/Pages/ProfilePage.js +++ /dev/null @@ -1,30 +0,0 @@ -/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre -Departamento de Informatica - Universidade Federal do Parana - -This file is part of Plataforma Integrada MEC. - -Plataforma Integrada MEC is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -Plataforma Integrada MEC is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -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, {Component} from 'react'; - - -class ProfilePage extends Component { - render() { - return ( - <h1> Página visulizar prefil de usuário</h1> - ); - } - } - -export default ProfilePage; diff --git a/src/Pages/PublicUserPage.js b/src/Pages/PublicUserPage.js index 6ff59cb44ae98e984a0401c41bafde8d921a3900..2000c8619371ba81c0b8ea395ede083935a4a1de 100644 --- a/src/Pages/PublicUserPage.js +++ b/src/Pages/PublicUserPage.js @@ -18,8 +18,7 @@ along with Plataforma Integrada MEC. If not, see <http://www.gnu.org/licenses/> import React, {useEffect, useState} from 'react' import styled from 'styled-components' -import axios from 'axios' -import {apiUrl, apiDomain} from '../env'; +import {apiDomain} from '../env'; import CustomizedBreadcrumbs from '../Components/TabPanels/Breadcrumbs.js' import Grid from '@material-ui/core/Grid'; import FollowButton from '../Components/ContactButtons/FollowButton.js' @@ -34,6 +33,7 @@ import TabRede from '../Components/TabPanels/PublicUserPageTabs/TabRede.js' import CheckDecagram from '../img/check-decagram-blue.svg' import ReportButton from '../Components/ReportButton.js' import {HeaderContainer, UserProfileContainer, CoverContainer, UserProfileInfoDiv, StyledTabs, CheckTeacherDiv, RodapeDiv, NavBarContentContainer, BackgroundDiv} from '../Components/TabPanels/StyledComponents.js' +import {fetchAllRequest} from '../Components/HelperFunctions/getAxiosConfig' const RenderFollowContainer = (boolUserFollowed, id, followCount) => { return ( @@ -121,38 +121,19 @@ export default function PublicUserPage (props) { const handleCollections = (data) => {setCollections(data)} /*---------------------------------------------------------*/ + function handleSuccess (responseArr) { + fillUserInfo(responseArr[0]) + + handleLearningObjects(responseArr[1]) + + handleCollections(responseArr[2]) + } /*Component Will Mount*/ useEffect( () => { - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid'), - } - } - axios.all([ - axios.get( (`${apiUrl}/users/` + id ), config ), - axios.get( (`${apiUrl}/users/` + id + '/learning_objects'), {'Accept': 'application/json','Content-Type':'application/json'}), - axios.get( (`${apiUrl}/users/` + id + '/collections'), {'Accept': 'application/json','Content-Type':'application/json'}) - ]) - .then( (responseArr) => { - - console.log(responseArr) - fillUserInfo(responseArr[0].data) - - console.log(responseArr[1]) - handleLearningObjects(responseArr[1].data) - - console.log(responseArr[2]) - handleCollections(responseArr[2].data) - }, - (error) => { - console.log('error while running ComponentDidMout') - } - ) + const urls = [`/users/${id}`, `/users/${id}/learning_objects`, `/users/${id}/collections`] + + fetchAllRequest(urls, handleSuccess, (error) => {console.log(error)}) }, []) /*---------------------------------------------------------*/ @@ -170,7 +151,7 @@ export default function PublicUserPage (props) { <HeaderContainer> <> {RenderFollowContainer(userData.followed, id, userData.follows_count)} - {RenderProfileAvatar(userData.avatar ? userData.avatar : noAvatar)} + {RenderProfileAvatar(userData.avatar ? userData.avatar : undefined)} <CoverContainer> {userData.cover && <img src={apiDomain + userData.cover} alt = '' style= {{width:"100%", height:"100%", objectFit : "cover" }}/>} </CoverContainer> @@ -208,7 +189,7 @@ export default function PublicUserPage (props) { {tabValue === 0 && <TabInicio id={id} user={userData} learningObjs={learningObjArr} collections={collectionsArr}/>} {tabValue === 1 && - <TabRecursos count={userData.learning_objects_count} learningObjs={learningObjArr}/>} + <TabRecursos count={userData.learning_objects_count} learningObjs={learningObjArr} id={id}/>} {tabValue === 2 && <TabColecoes count={userData.collections_count} collections={collectionsArr} />} diff --git a/src/Pages/ResourcePage.js b/src/Pages/ResourcePage.js index 546cffcdb415f4ce53b0becdad0dc9e1eff83c1a..194807e62cc60998b5b1f470a2bf7decc803fef4 100644 --- a/src/Pages/ResourcePage.js +++ b/src/Pages/ResourcePage.js @@ -19,8 +19,7 @@ along with Plataforma Integrada MEC. If not, see <http://www.gnu.org/licenses/> import React, {useEffect, useState, useContext} from 'react' import {Store} from '../Store.js' import styled from 'styled-components' -import axios from 'axios' -import {apiUrl, apiDomain} from '../env'; +import {apiDomain} from '../env'; import Grid from '@material-ui/core/Grid'; import TextoObjeto from '../Components/ResourcePageComponents/TextoObjeto.js' import Footer from '../Components/ResourcePageComponents/Footer.js' @@ -36,7 +35,7 @@ import AppBar from '@material-ui/core/AppBar'; import ButtonAvaliarRecurso from '../Components/ButtonAvaliarRecurso' import ModalAvaliarRecurso from '../Components/ModalAvaliarRecurso' import ModalConfirmarCuradoria from '../Components/ModalConfirmarCuradoria' -import {getAxiosConfig} from '../Components/HelperFunctions/getAxiosConfig' +import {getRequest} from '../Components/HelperFunctions/getAxiosConfig' function urlVerify (url) { return (url ? url.indexOf("youtu") !== -1 || url.indexOf("vimeo") !== -1 : false) @@ -48,29 +47,16 @@ export default function LearningObjectPage (props){ const [carregando, toggle] = useState(true) const [recurso, setRecurso] = useState({}) + function handleSuccessfulGet (data) { + setRecurso(data) + toggle(false) + } useEffect( () => { - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - } - } - if (state.currentUser.id !== "") { - config.headers["Access-Token"] = sessionStorage.getItem('@portalmec/accessToken'); - config.headers.Client = sessionStorage.getItem('@portalmec/clientToken') - config.headers.Uid = sessionStorage.getItem('@portalmec/uid') - } + const url = `/learning_objects/${id}` - axios.get( (`${apiUrl}/learning_objects/` + id), config - ).then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - setRecurso(response.data) - toggle(false) - }, (error) => {console.log(error);}) - }, [state.currentUser]) + getRequest(url, handleSuccessfulGet, (error) => {console.log(error)}) + + }, []) const [snackbarOpen, toggleSnackbar] = useState(false) @@ -118,15 +104,8 @@ export default function LearningObjectPage (props){ const finalizeCuratorshipFlow = () => { handleModalConfirmarCuradoria(false) - let config = getAxiosConfig() - axios.get( (`${apiUrl}/learning_objects/` + id), config - ).then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - console.log(response) - setRecurso(response.data) - }, (error) => {console.log(error);}) + const url = `/learning_objects/${id}` + getRequest(url, (data) => {setRecurso(data)}, (error) => {console.log(error)}) } return ( diff --git a/src/Pages/Search.js b/src/Pages/Search.js index d7c3fcd27250a8331a69e395dc5e78328b15cc11..8648fbaf61b2a2f986dce3186432ca33454a381d 100644 --- a/src/Pages/Search.js +++ b/src/Pages/Search.js @@ -39,6 +39,9 @@ import ResourceCardFunction from "../Components/ResourceCardFunction"; import CollectionCardFunction from "../Components/CollectionCardFunction"; import ContactCard from "../Components/ContactCard"; import CircularProgress from '@material-ui/core/CircularProgress'; +import { saveHeaders } from '../Components/HelperFunctions/saveTokens'; +import {getRequest} from '../Components/HelperFunctions/getAxiosConfig' + let order = "review_average"; let currFilter = ""; @@ -53,7 +56,7 @@ export default function Search(props) { const [isloading, setIsLoading] = useState(false); const [loadingMoreData, setLoadingMoreData] = useState(false); const [isFiltering, setIsFiltering] = useState(false); - const [resultsPerPage, setResultsPerPage] = useState(6); + const [resultsPerPage, setResultsPerPage] = useState(12); const [totalResults, setTotalResults] = useState(0); const [options] = React.useState([ { label: "Recursos", value: "LearningObject" }, @@ -74,33 +77,34 @@ export default function Search(props) { ); const [optionResult, setOptionResult] = useState(option); + function handleSuccessfulGet (data) { + if (option === "LearningObject") setResultsResource(data); + else if (option === "Collection") setResultsCollection(data); + else if (option === "User") setResultsUser(data); + setOptionResult(option); + dispatch({ + type: "SAVE_SEARCH", + newSearch: { + query: state.search.query, + class: option, + }, + }); + setTotalResults(data.length); + setIsLoading(false); + setIsFiltering(false); + setLoadingMoreData(false); + } + const collectStuff = (tipoBusca, filtro) => { - currFilter = filtro; + if (!loadingMoreData) // this line prevents resetting filter when loading more data + currFilter = filtro; if (filtro) setIsFiltering(true); - axios - .get( - `${apiUrl}/search?page=${page}&results_per_page=${resultsPerPage}&order=${order}&query=${state.search.query}${currFilter ? currFilter : ""}&search_class=${tipoBusca}` - ) - .then((res) => { - if (tipoBusca === "LearningObject") setResultsResource(res.data); - else if (tipoBusca === "Collection") setResultsCollection(res.data); - else if (tipoBusca === "User") setResultsUser(res.data); - setOptionResult(tipoBusca); - dispatch({ - type: "SAVE_SEARCH", - newSearch: { - query: state.search.query, - class: tipoBusca, - }, - }); - console.log(res); - setTotalResults(res.headers["x-total-count"]); - setIsLoading(false); - setIsFiltering(false); - setLoadingMoreData(false); - }); + const url = `/search?page=${page}&results_per_page=${resultsPerPage}&order=${order}&query=${state.search.query}${currFilter ? currFilter : ""}&search_class=${tipoBusca}` + + getRequest(url, handleSuccessfulGet, (error) => {console.log(error)}) + }; useEffect(() => { @@ -112,7 +116,6 @@ export default function Search(props) { const urlParams = new URLSearchParams(window.location.search); const query = urlParams.get("query"); const searchClass = urlParams.get("search_class"); - console.log(searchClass); if (state.search.query !== query || state.search.class !== searchClass) { dispatch({ type: "SAVE_SEARCH", @@ -136,230 +139,100 @@ export default function Search(props) { return ( <div style={{ backgroundColor: "#f4f4f4" }}> - {/* <React.Fragment> - <h1> - Search for {state.search.query !== "*" ? state.search.query : "all"}{" "} - in {state.search.class} - </h1> - {state.search.class === "LearningObject" && ( - <ul> - {results.map((res) => ( - <li key={res.id}> {res.name} </li> - ))} - </ul> - )} - {state.search.class === "Collection" && ( - <ul> - {results.map((res) => ( - <li key={res.id}> {res.name} </li> - ))} - </ul> - )} - {state.search.class === "User" && ( - <ul> - {results.map((res) => ( - <li key={res.id}> {res.name} </li> - ))} - </ul> - )} - </React.Fragment> */} - <Principal> - <BreadCrumbsDiv> + <BreadCrumbsDiv style={{margin:"15px 2%", }}> <StyledBreadCrumbs> <Link to="/">Página Inicial</Link> <span>Busca</span> </StyledBreadCrumbs> </BreadCrumbsDiv> - <HeaderFilters elevation={4} square> - <Grid container spacing={0} style={{ height: "100%" }}> - <Grid - item - xs={4} - style={{ - display: "flex", - flexDirection: "column", - justifyContent: "center", - paddingLeft: 20, - }} - > - <div style={{ display: "flex", flexDirection: "row" }}> - <span style={{ alignSelf: "center", marginRight: 10 }}> - MOSTRAR: - </span> - <Dropdown - options={options} - value={optionResult} - onChange={(e) => { - setIsLoading(true); - setOption(e.value); - collectStuff(e.value, ""); - }} - placeholder="Select an type" - /> - </div> - </Grid> - <Grid - item - xs={4} - style={{ - display: "flex", - flexDirection: "column", - justifyContent: "center", - }} - > - <div> - Resultados encontrados: {totalResults} - </div> - </Grid> - { - optionResult === "User" ? null : - <Grid - item - xs={4} - style={{ - display: "flex", - flexDirection: "column", - justifyContent: "center", - paddingRight: 20, - }} - > - <div - style={{ - display: "flex", - flexDirection: "row", - justifyContent: "end", - }} - > - <span - style={{ - textAlign: "right", - alignSelf: "center", - marginRight: 10, - }} - > - ORDENAR POR: - </span> - <Dropdown - options={ordenar} - value={currOrder} - onChange={(e) => { - order = e.value; - setCurrOrder(e.label) - collectStuff(optionResult, currFilter); - }} - placeholder="Select an order " - /> + + <div style={{margin:"15px 2%", }}> + <HeaderFilters elevation={4} square> + <Grid container spacing={0} style={{ height: "100%" }}> + <Grid item xs style={{display:"flex", flexDirection:"column", justifyContent:"center", paddingLeft:20}}> + <div style={{ marginRight:5, marginTop:15 }}> + <div className="textInfo"> + <span style={{ fontWeight:"bold" }}> + MOSTRAR + </span> </div> - </Grid> - } - </Grid> - </HeaderFilters> - - { - isloading ? <LoadingSpinner text="Carregando..." /> : - optionResult === "Collection" ? ( - <GridBuscaCollection container spacing={2}> - <Grid item md={12} xs={12}> - <Grid container spacing={2}> - {resultsCollection.map((card) => ( - <Grid item md={4} xs={6} key={card.id}> - <CollectionCardFunction - name={card.name} - rating={card.score} - id={card.id} - author={card.owner.name} - description={card.description} - thumbnails={card.items_thumbnails} - avatar={card.owner.avatar} - /> - </Grid> - ))} - </Grid> - <div - style={{ - display: "flex", - flexDirection: "row", - justifyContent: "center", + <Dropdown options={options} value={optionResult} onChange={(e) => { + setIsLoading(true); + setOption(e.value); + collectStuff(e.value, ""); }} - > - <button - style={{ - height: 36, - backgroundColor: "#ff7f00", - marginBottom: 50, - marginTop: 50, - fontSize: 14, - color: "white", - borderRadius: 4, - border: "none", - }} - onClick={() => { - setLoadingMoreData(true); - setResultsPerPage(resultsPerPage + 12) - // collectStuff("Collection", ""); - }} - > - { - loadingMoreData ? <CircularProgress size={24} color="inherit" /> : "Carregar mais 12" - } - </button> - </div> - </Grid> - </GridBuscaCollection> - ) : - - optionResult === "LearningObject" ? ( - <GridBuscaResource container spacing={2}> - <Grid item md={3} xs={12}> - <Paper elevation={4} square> - <SearchExpansionPanel onChange={collectStuff} onFiltering={isFiltering} /> - </Paper> + placeholder="Selecione um tipo" + /> + </div> + </Grid> + + { + optionResult === "User" ? null : + <Grid item xs style={{display: "flex", flexDirection: "column", justifyContent: "center", paddingRight: 20,}}> + <div style={{marginLeft:5, marginTop:15}}> + <div className="textInfo"> + <span style={{ fontWeight:"bold" }}> + ORDENAR POR + </span> + </div> + <Dropdown options={ordenar} value={currOrder} onChange={(e) => { + order = e.value; + setCurrOrder(e.label) + collectStuff(optionResult, currFilter); + }} + placeholder="Selecione uma opção" + /> + </div> </Grid> - <Grid item md={9} xs={12}> + } + <Grid item xs={12}> + <div style={{display: "flex", flexDirection: "column", justifyContent: "center" }}> + <div style={{textAlign: "center", paddingTop: 10, fontWeight:"bolder"}}> + {/* Exibindo {totalResults === 0 ? 0 : resultsPerPage} resultados de {totalResults} encontrados */} + Exibindo {totalResults === 0 ? 0 : resultsPerPage} resultados + </div> + </div> + </Grid> + </Grid> + </HeaderFilters> + + { + isloading ? <LoadingSpinner text="Carregando..." /> : + optionResult === "Collection" ? ( + <GridBuscaCollection container spacing={2}> + <Grid item xs> <Grid container spacing={2}> - {resultsResource.map((card) => ( - <Grid item md={4} xs={6} key={card.id}> - <ResourceCardFunction - avatar={card.publisher.avatar} + {resultsCollection.map((card) => ( + <Grid item xs key={card.id}> + <CollectionCardFunction + name={card.name} + tags={card.tags} + rating={card.review_average} id={card.id} - thumbnail={card.thumbnail} - type={card.object_type ? card.object_type : "Outros"} - title={card.name} - published={card.state === "published" ? true : false} + author={card.owner.name} + description={card.description} + thumbnails={card.items_thumbnails} + avatar={card.owner.avatar} likeCount={card.likes_count} + followed={card.followed} liked={card.liked} - rating={card.review_average} - author={card.author} - tags={card.educational_stages} - href={"/recurso/" + card.id} - downloadableLink={card.default_attachment_location} + collections={card.collection_items} + authorID={card.owner.id} /> + </Grid> ))} </Grid> - <div - style={{ - display: "flex", - flexDirection: "row", - justifyContent: "center", - }} - > + <div style={{ display: "flex", flexDirection: "row", justifyContent: "center", }}> <button - style={{ - height: 36, - backgroundColor: "#ff7f00", - marginBottom: 50, - marginTop: 50, - fontSize: 14, - color: "white", - borderRadius: 4, - border: "none", + style={{ height: 36, backgroundColor: "#ff7f00", marginBottom: 50, marginTop: 50, fontSize: 14, + color: "white", borderRadius: 4,border: "none", }} onClick={() => { setLoadingMoreData(true); setResultsPerPage(resultsPerPage + 12) - // collectStuff("LearningObject", ""); + // collectStuff("Collection", ""); }} > { @@ -368,24 +241,38 @@ export default function Search(props) { </button> </div> </Grid> - </GridBuscaResource> + </GridBuscaCollection> ) : - optionResult === "User" && ( - <GridBuscaUser container spacing={2}> - <Grid item md={12} xs={12}> + + optionResult === "LearningObject" ? ( + <GridBuscaResource container spacing={2}> + <Grid item xs={12} md={2}> + <Grid container > + <Grid item xs={12}> + <Paper elevation={4} square> + <SearchExpansionPanel onChange={collectStuff} onFiltering={isFiltering} /> + </Paper> + </Grid> + </Grid> + </Grid> + <Grid item xs> <Grid container spacing={2}> - {resultsUser.map((card) => ( - <Grid item md={4} xs={6} key={card.id}> - <ContactCard - name={card.name} - avatar={card.avatar ? apiDomain + card.avatar : null} - cover={card.cover ? apiDomain + card.cover : null} - numCollections={card.collections_count} - numLearningObjects={card.learning_objects_count} - follow_count={card.follows_count} - followed={card.followed || null} - followerID={card.id} - href={'/usuario-publico/' + card.id} + {resultsResource.map((card) => ( + <Grid item xs={12} sm={6} md={4} lg={3} key={card.id}> + <ResourceCardFunction + avatar={card.publisher.avatar} + id={card.id} + thumbnail={card.thumbnail} + type={card.object_type ? card.object_type : "Outros"} + title={card.name} + published={card.state === "published" ? true : false} + likeCount={card.likes_count} + liked={card.liked} + rating={card.review_average} + author={card.author} + tags={card.educational_stages} + href={"/recurso/" + card.id} + downloadableLink={card.default_attachment_location} /> </Grid> ))} @@ -411,18 +298,71 @@ export default function Search(props) { onClick={() => { setLoadingMoreData(true); setResultsPerPage(resultsPerPage + 12) - // collectStuff("User", ""); + // collectStuff("LearningObject", ""); }} > { - loadingMoreData ? <CircularProgress color="inherit" size={24} /> : "Carregar mais 12" + loadingMoreData ? <CircularProgress size={24} color="inherit" /> : "Carregar mais 12" } </button> </div> </Grid> - </GridBuscaUser> - ) - } + </GridBuscaResource> + ) : + optionResult === "User" && ( + <GridBuscaUser container spacing={2}> + <Grid item xs > + <Grid container spacing={2}> + {resultsUser.map((card) => ( + <Grid item xs key={card.id}> + <ContactCard + name={card.name} + avatar={card.avatar ? apiDomain + card.avatar : null} + cover={card.cover ? apiDomain + card.cover : null} + numCollections={card.collections_count} + numLearningObjects={card.learning_objects_count} + follow_count={card.follows_count} + followed={card.followed || null} + followerID={card.id} + href={'/usuario-publico/' + card.id} + /> + </Grid> + ))} + </Grid> + <div + style={{ + display: "flex", + flexDirection: "row", + justifyContent: "center", + }} + > + <button + style={{ + height: 36, + backgroundColor: "#ff7f00", + marginBottom: 50, + marginTop: 50, + fontSize: 14, + color: "white", + borderRadius: 4, + border: "none", + }} + onClick={() => { + setLoadingMoreData(true); + setResultsPerPage(resultsPerPage + 12) + // collectStuff("User", ""); + }} + > + { + loadingMoreData ? <CircularProgress color="inherit" size={24} /> : "Carregar mais 12" + } + </button> + </div> + </Grid> + </GridBuscaUser> + ) + } + </div> </Principal> </div> ); @@ -463,11 +403,14 @@ const GridBuscaUser = styled(Grid)` `; const HeaderFilters = styled(Paper)` - height: 60px; + height: 150px; text-align: center; background-color: #fff; margin-bottom: 30px; color: #666; + .textInfo{ + text-align: start; + } `; const StyledBreadCrumbs = styled(Breadcrumbs)` @@ -489,6 +432,5 @@ const BreadCrumbsDiv = styled.div` `; const Principal = styled.div` - width: 1170px; margin-inline: auto; `; diff --git a/src/Pages/TabsHelp/TabManageAc.js b/src/Pages/TabsHelp/TabManageAc.js index ab485dd16d8ee5c976d9fff0cd335e209d5b7673..9aa293b3fac8e07bc551a59e97f6161618f4d4f9 100644 --- a/src/Pages/TabsHelp/TabManageAc.js +++ b/src/Pages/TabsHelp/TabManageAc.js @@ -65,41 +65,32 @@ export default function TabManageAc(props) { <span>{tabs[5]}</span> </StyledBreadCrumbs> </BreadCrumbsDiv> - <Grid container spacing={4}> - <Grid item xs={3}> - <Menu> - <h4>{tabs[5]}</h4> - <TabsStyled - orientation="vertical" - variant="scrollable" - value={tabValue} - onChange={handleChangeTab} - TabIndicatorProps={{ style: { display: "none" } }} - > + <Grid container justify="center"> + <Grid item xs={12} md={10} > + <Principal> + <Menu> + <div className="fixo"> + <img src={GerenciandoConta} alt="Gerenciando a conta" /> + <span>{tabs[5]}</span> + </div> + <TabsStyled orientation = "vertical" + variant = "scrollable" + value = {tabValue} + onChange = {handleChangeTab} + TabIndicatorProps = {{style:{display: "none"}}} + > <TabStyled label={tabs[0]}></TabStyled> <TabStyled label={tabs[1]}></TabStyled> <TabStyled label={tabs[2]}></TabStyled> <TabStyled label={tabs[3]}></TabStyled> <TabStyled label={tabs[4]}></TabStyled> - </TabsStyled> - <br /> - <div className="voltarInicio"> - <a href="ajuda">VOLTAR AO ÍNICIO</a> - </div> - <hr /> - <div className="procurava"> - Não encontrou o que procurava? Entre em - <a href="contato"> contato</a> - </div> - </Menu> - </Grid> + </TabsStyled> + <br/> + <div className="voltarInicio"> + <a href="ajuda">VOLTAR AO ÍNICIO</a> + </div> + </Menu> - <Grid item xs={9}> - <Principal> - <div className="fixo"> - <img src={GerenciandoConta} alt="Gerenciando a conta" /> - <span>{tabs[5]}</span> - </div> {tabValue === 0 && <Why title={tabs[0]} />} {tabValue === 1 && <HowToDo title={tabs[1]} />} {tabValue === 2 && <HowToChange title={tabs[2]} />} @@ -108,69 +99,77 @@ export default function TabManageAc(props) { <div className="resultadosProcura"> <span>Não era bem o que você procurava?</span> <div className="subtitulo"> - <span> - Você pode navegar pelos tópicos de ajuda ou entrar em{" "} - <a href="contato">Contato</a>. - </span> + <span>Você pode navegar pelos tópicos de ajuda ou entrar em <a href="contato">Contato</a>.</span> </div> </div> - <Grid style={{ marginBottom: "50px" }} container spacing={2}> - <Grid item xs={4}> + + </Principal> + </Grid> + </Grid> + + + <Grid style={{ marginBottom: "50px" }} container justify={"center"}> + <Grid item xs={12} md={3} style={{margin:5}}> <CardPublicando /> </Grid> - <Grid item xs={4}> + <Grid item xs={12} md={3} style={{margin:5}}> <CardEncontrando /> </Grid> - <Grid item xs={4}> + <Grid item xs={12} md={3} style={{margin:5}}> <CardParticipando /> </Grid> </Grid> - </Principal> - </Grid> - </Grid> </Secao> </div> ); } const StyledBreadCrumbs = styled(Breadcrumbs)` - display: flex; - justify-content: flex-start; - max-width: 1170px; + display : flex; + justify-content : flex-start; span { - color: #a5a5a5; + color : #a5a5a5; } a { color: #00bcd4; text-decoration: none; } -`; + +` const BreadCrumbsDiv = styled.div` - padding: 10px; - display: flex; -`; + + padding : 10px; + display : flex; +` + const Principal = styled.div` .fixo { + height: 40px; text-align: center; background-color: #fff; - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); padding: 30px; margin-bottom: 30px; color: #666; + img { height: 50px; width: 50px; margin-right: 40px; vertical-align: middle; + } span { font-size: 20px; + vertical-align: ; } + + + } .resultadosProcura { text-align: center; @@ -184,46 +183,62 @@ const Principal = styled.div` margin-top: 10px; span { - font-size: 15px; + font-size: 15px } a { font-size: 15px; padding: 0; - color: #00bcd4; + color:#00bcd4; text-decoration: none; } + } } -`; + +` const TabsStyled = styled(Tabs)` + .Mui-selected { background-color: #e7e4e4; } - .MuiTab-root { + .MuiTab-root{ text-transform: none !important; + max-width:100% } -`; + text-align: center; + width:100% + +` const TabStyled = styled(Tab)` + padding: 4px 15px !important; font-weight: 500; font-size: 14px !important; border-radius: 4px !important; + text-align: center; + + + + &:hover { background-color: #e7e4e4; } -`; +` + const Menu = styled.div` width: auto; background-color: #fff; color: #666; padding-block: 10px; - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); + box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); + margin-bottom:30px + h4 { padding-inline: 15px; @@ -240,7 +255,7 @@ const Menu = styled.div` a { font-size: 15px; padding: 0; - color: #00bcd4; + color:#00bcd4; text-decoration: none; } } @@ -260,13 +275,15 @@ const Menu = styled.div` a { font-size: 15px; padding: 0; - color: #00bcd4; + color:#00bcd4; text-decoration: none; } + } -`; + +` const Secao = styled.div` - width: 1138px; margin-inline: auto; -`; + +` diff --git a/src/Pages/TabsHelp/TabNetPart.js b/src/Pages/TabsHelp/TabNetPart.js index c63a0816447bb4e42fead5e2a08c5b0c49025ff8..107a998b5eda35618bd647ec5a266c41bc86e871 100644 --- a/src/Pages/TabsHelp/TabNetPart.js +++ b/src/Pages/TabsHelp/TabNetPart.js @@ -73,37 +73,29 @@ export default function TabNetPart (props) { </StyledBreadCrumbs> </BreadCrumbsDiv> - <Grid container spacing={4}> - <Grid item xs={3}> - <Menu> - <h4>{tabs[2]}</h4> - <TabsStyled orientation = "vertical" - variant = "scrollable" - value = {tabValue} - onChange = {handleChangeTab} - TabIndicatorProps = {{style:{display: "none"}}} - > - <TabStyled label={tabs[0]}></TabStyled> - <TabStyled label={tabs[1]}></TabStyled> - </TabsStyled> - <br/> - <div className="voltarInicio"> - <a href="ajuda">VOLTAR AO ÍNICIO</a> - </div> - <hr/> - <div className="procurava"> - Não encontrou o que procurava? Entre em - <a href="contato"> contato</a> - </div> - </Menu> - </Grid> - - <Grid item xs={9}> + <Grid container justify="center"> + <Grid item xs={12} md={10} > <Principal> - <div className="fixo"> + <Menu> + <div className="fixo"> <img src={ParticipandoRede} alt="Participando da Rede"/> - <span>{tabs[2]}</span> - </div> + <span>{tabs[2]}</span> + </div> + <TabsStyled orientation = "vertical" + variant = "scrollable" + value = {tabValue} + onChange = {handleChangeTab} + TabIndicatorProps = {{style:{display: "none"}}} + > + <TabStyled label={tabs[0]}></TabStyled> + <TabStyled label={tabs[1]}></TabStyled> + </TabsStyled> + <br/> + <div className="voltarInicio"> + <a href="ajuda">VOLTAR AO ÍNICIO</a> + </div> + </Menu> + {tabValue === 0 && <How title={tabs[0]}/>} {tabValue === 1 && <What title={tabs[1]}/>} <div className="resultadosProcura"> @@ -112,24 +104,25 @@ export default function TabNetPart (props) { <span>Você pode navegar pelos tópicos de ajuda ou entrar em <a href="contato">Contato</a>.</span> </div> </div> - <Grid style={{marginBottom:"50px"}} container spacing={2}> - <Grid item xs={4}> + + </Principal> + </Grid> + </Grid> + + + <Grid style={{paddingBottom:"50px"}} container justify={"center"}> + <Grid item xs={12} md={3} style={{margin:5}}> <CardPublicando/> </Grid> - <Grid item xs={4}> + <Grid item xs={12} md={3} style={{margin:5}}> <CardEncontrando/> </Grid> - <Grid item xs={4}> + <Grid item xs={12} md={3} style={{margin:5}}> <CardGerenciando/> </Grid> </Grid> - </Principal> - </Grid> - </Grid> - - </Secao> </div> ); @@ -137,7 +130,6 @@ export default function TabNetPart (props) { const StyledBreadCrumbs = styled(Breadcrumbs)` display : flex; justify-content : flex-start; - max-width : 1170px; span { color : #a5a5a5; } @@ -161,7 +153,6 @@ const Principal = styled.div` height: 40px; text-align: center; background-color: #fff; - box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); padding: 30px; margin-bottom: 30px; color: #666; @@ -218,7 +209,10 @@ const TabsStyled = styled(Tabs)` .MuiTab-root{ text-transform: none !important; + max-width:100% } + text-align: center; + width:100% ` @@ -228,6 +222,7 @@ const TabStyled = styled(Tab)` font-weight: 500; font-size: 14px !important; border-radius: 4px !important; + text-align: center; @@ -245,6 +240,8 @@ const Menu = styled.div` color: #666; padding-block: 10px; box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); + margin-bottom:30px + h4 { padding-inline: 15px; @@ -290,7 +287,6 @@ const Menu = styled.div` ` const Secao = styled.div` - width: 1138px; margin-inline: auto; ` diff --git a/src/Pages/TabsHelp/TabResourseFind.js b/src/Pages/TabsHelp/TabResourseFind.js index 0398c28b69f62e73bdac18f43a561068cea761d1..8691d2822ea4f4f7100eb8a413f104a78db94788 100644 --- a/src/Pages/TabsHelp/TabResourseFind.js +++ b/src/Pages/TabsHelp/TabResourseFind.js @@ -73,38 +73,30 @@ export default function TabResourseFind (props) { </StyledBreadCrumbs> </BreadCrumbsDiv> - <Grid container spacing={4}> - <Grid item xs={3}> - <Menu> - <h4>{tabs[3]}</h4> - <TabsStyled orientation = "vertical" - variant = "scrollable" - value = {tabValue} - onChange = {handleChangeTab} - TabIndicatorProps = {{style:{display: "none"}}} - > - <TabStyled label={tabs[0]}></TabStyled> - <TabStyled label={tabs[1]}></TabStyled> - <TabStyled label={tabs[2]}></TabStyled> - </TabsStyled> - <br/> - <div className="voltarInicio"> - <a href="ajuda">VOLTAR AO ÍNICIO</a> - </div> - <hr/> - <div className="procurava"> - Não encontrou o que procurava? Entre em - <a href="contato"> contato</a> - </div> - </Menu> - </Grid> - - <Grid item xs={9}> + <Grid container justify="center"> + <Grid item xs={12} md={10} > <Principal> - <div className="fixo"> + <Menu> + <div className="fixo"> <img src={EncontrandoRecurso} alt="Encontrando Recursos"/> - <span>{tabs[3]}</span> - </div> + <span>{tabs[3]}</span> + </div> + <TabsStyled orientation = "vertical" + variant = "scrollable" + value = {tabValue} + onChange = {handleChangeTab} + TabIndicatorProps = {{style:{display: "none"}}} + > + <TabStyled label={tabs[0]}></TabStyled> + <TabStyled label={tabs[1]}></TabStyled> + <TabStyled label={tabs[2]}></TabStyled> + </TabsStyled> + <br/> + <div className="voltarInicio"> + <a href="ajuda">VOLTAR AO ÍNICIO</a> + </div> + </Menu> + {tabValue === 0 && <HowToDo title={tabs[0]}/>} {tabValue === 1 && <HowToFilter title={tabs[1]}/>} {tabValue === 2 && <HowToRank title={tabs[2]}/>} @@ -114,22 +106,23 @@ export default function TabResourseFind (props) { <span>Você pode navegar pelos tópicos de ajuda ou entrar em <a href="contato">Contato</a>.</span> </div> </div> - <Grid style={{marginBottom:"50px"}} container spacing={2}> - <Grid item xs={4}> - <CardPublicando/> - </Grid> - <Grid item xs={4}> - <CardParticipando/> - </Grid> - <Grid item xs={4}> - <CardGerenciando/> - </Grid> - </Grid> + </Principal> </Grid> </Grid> - + <Grid style={{paddingBottom:"50px"}} container justify={"center"}> + <Grid item xs={12} md={3} style={{margin:5}}> + <CardPublicando/> + </Grid> + <Grid item xs={12} md={3} style={{margin:5}}> + <CardParticipando/> + </Grid> + <Grid item xs={12} md={3} style={{margin:5}}> + <CardGerenciando/> + </Grid> + </Grid> + </Secao> </div> @@ -139,7 +132,6 @@ export default function TabResourseFind (props) { const StyledBreadCrumbs = styled(Breadcrumbs)` display : flex; justify-content : flex-start; - max-width : 1170px; span { color : #a5a5a5; } @@ -156,13 +148,13 @@ const BreadCrumbsDiv = styled.div` display : flex; ` + const Principal = styled.div` .fixo { height: 40px; text-align: center; background-color: #fff; - box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); padding: 30px; margin-bottom: 30px; color: #666; @@ -219,7 +211,10 @@ const TabsStyled = styled(Tabs)` .MuiTab-root{ text-transform: none !important; + max-width:100% } + text-align: center; + width:100% ` @@ -229,6 +224,7 @@ const TabStyled = styled(Tab)` font-weight: 500; font-size: 14px !important; border-radius: 4px !important; + text-align: center; @@ -246,6 +242,8 @@ const Menu = styled.div` color: #666; padding-block: 10px; box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); + margin-bottom:30px + h4 { padding-inline: 15px; @@ -291,7 +289,6 @@ const Menu = styled.div` ` const Secao = styled.div` - width: 1138px; margin-inline: auto; ` diff --git a/src/Pages/TabsHelp/TabResoursePub.js b/src/Pages/TabsHelp/TabResoursePub.js index 00214bc494e26f617c2a50c9767a88e43e96e72f..75dead021e85c99fc38053789a634f487d94e9dd 100644 --- a/src/Pages/TabsHelp/TabResoursePub.js +++ b/src/Pages/TabsHelp/TabResoursePub.js @@ -60,48 +60,37 @@ export default function TabResoursePub (props) { </Link> <Link to="ajuda" > Ajuda - </Link> - + </Link> <span> {tabs[3]} </span> - - </StyledBreadCrumbs> </BreadCrumbsDiv> - <Grid container spacing={4}> - <Grid item xs={3}> - <Menu> - <h4>{tabs[3]}</h4> - <TabsStyled orientation = "vertical" - variant = "scrollable" - value = {tabValue} - onChange = {handleChangeTab} - TabIndicatorProps = {{style:{display: "none"}}} - > - <TabStyled label={tabs[0]}></TabStyled> - <TabStyled label={tabs[1]}></TabStyled> - <TabStyled label={tabs[2]}></TabStyled> - </TabsStyled> - <br/> - <div className="voltarInicio"> - <a href="ajuda">VOLTAR AO ÍNICIO</a> - </div> - <hr/> - <div className="procurava"> - Não encontrou o que procurava? Entre em - <a href="contato"> contato</a> - </div> - </Menu> - </Grid> - - <Grid item xs={9}> + <Grid container justify="center"> + <Grid item xs={12} md={10} > <Principal> - <div className="fixo"> - <img src={PublicandoRecursos} alt="Publicando Recursos"/> - <span>{tabs[3]}</span> - </div> + <Menu> + <div className="fixo"> + <img src={PublicandoRecursos} alt="Publicando Recursos"/> + <span>{tabs[3]}</span> + </div> + <TabsStyled orientation = "vertical" + variant = "scrollable" + value = {tabValue} + onChange = {handleChangeTab} + TabIndicatorProps = {{style:{display: "none"}}} + > + <TabStyled label={tabs[0]}></TabStyled> + <TabStyled label={tabs[1]}></TabStyled> + <TabStyled label={tabs[2]}></TabStyled> + </TabsStyled> + <br/> + <div className="voltarInicio"> + <a href="ajuda">VOLTAR AO ÍNICIO</a> + </div> + </Menu> + {tabValue === 0 && <Why title={tabs[0]}/>} {tabValue === 1 && <How title={tabs[1]}/>} {tabValue === 2 && <Which title={tabs[2]}/>} @@ -111,22 +100,22 @@ export default function TabResoursePub (props) { <span>Você pode navegar pelos tópicos de ajuda ou entrar em <a href="contato">Contato</a>.</span> </div> </div> - <Grid style={{marginBottom:"50px"}} container spacing={2}> - <Grid item xs={4}> - <CardEncontrando/> - </Grid> - <Grid item xs={4}> - <CardParticipando/> - </Grid> - <Grid item xs={4}> - <CardGerenciando/> - </Grid> - - </Grid> </Principal> </Grid> - </Grid> + </Grid> + <Grid style={{paddingBottom:"50px"}} container justify={"center"}> + <Grid item xs={12} md={3} style={{margin:5}}> + <CardEncontrando/> + </Grid> + <Grid item xs={12} md={3} style={{margin:5}}> + <CardParticipando/> + </Grid> + <Grid item xs={12} md={3} style={{margin:5}}> + <CardGerenciando/> + </Grid> + + </Grid> </Secao> @@ -136,7 +125,6 @@ export default function TabResoursePub (props) { const StyledBreadCrumbs = styled(Breadcrumbs)` display : flex; justify-content : flex-start; - max-width : 1170px; span { color : #a5a5a5; } @@ -160,7 +148,6 @@ const Principal = styled.div` height: 40px; text-align: center; background-color: #fff; - box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); padding: 30px; margin-bottom: 30px; color: #666; @@ -217,7 +204,10 @@ const TabsStyled = styled(Tabs)` .MuiTab-root{ text-transform: none !important; + max-width:100% } + text-align: center; + width:100% ` @@ -227,6 +217,7 @@ const TabStyled = styled(Tab)` font-weight: 500; font-size: 14px !important; border-radius: 4px !important; + text-align: center; @@ -244,6 +235,8 @@ const Menu = styled.div` color: #666; padding-block: 10px; box-shadow: 0 1px 3px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.24); + margin-bottom:30px + h4 { padding-inline: 15px; @@ -289,7 +282,6 @@ const Menu = styled.div` ` const Secao = styled.div` - width: 1138px; margin-inline: auto; ` diff --git a/src/Pages/UploadPage.js b/src/Pages/UploadPage.js index 8883bceff94c2b8907525e7169ae2b4c9f4d5d37..848b3b5b76edf5f975011b676dcfc021bbcd701e 100644 --- a/src/Pages/UploadPage.js +++ b/src/Pages/UploadPage.js @@ -17,14 +17,12 @@ 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, useEffect, useContext} from 'react' -import axios from 'axios' -import {apiUrl} from '../env'; import Grid from '@material-ui/core/Grid'; import UploadFileWrapper from '../Components/UploadPageComponents/UploadFileWrapper.js' import {Store} from '../Store.js' import {InfoBox} from '../Components/UploadPageComponents/StyledComponents.js' import Stepper from '../Components/UploadPageComponents/Stepper.js' -import {getAxiosConfig} from '../Components/HelperFunctions/getAxiosConfig.js' +import {postRequest} from '../Components/HelperFunctions/getAxiosConfig.js' import PartOne from '../Components/UploadPageComponents/PartOne.js' import PartTwo from '../Components/UploadPageComponents/PartTwo.js' import PartThree from '../Components/UploadPageComponents/PartThree.js' @@ -42,19 +40,19 @@ export default function UploadPage (props) { const [loading, toggleLoading] = useState(true) const [draft, setDraft] = useState({}) + function handleSuccessfulGet (data) { + setDraft(data) + toggleLoading(false) + } useEffect( () => { if (state.currentUser.id !== "") { - const config = getAxiosConfig() + + const url = `/learning_objects/` + let payload = {} - axios.post( (`${apiUrl}/learning_objects/`), payload, config - ).then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - setDraft(response.data) - toggleLoading(false) - console.log(response) - }, (error) => {console.log(error)}) + + postRequest(url, payload, handleSuccessfulGet, (error) => {console.log(error)}) + } }, []) @@ -66,38 +64,33 @@ export default function UploadPage (props) { const handlePost = () => { if (state.currentUser.id !== "") { - const config = getAxiosConfig() + const url = `/learning_objects/${draft.id}/publish` + let payload = {} - axios.post( (`${apiUrl}/learning_objects/` + draft.id + '/publish'), payload, config - ).then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - handleModal(true) - console.log(response) - }, (error) => {console.log(error)}) + postRequest(url, payload, + (data) => {handleModal(true)}, + (error) => {console.log(error)} + ) + } } const handleSubmit = () => { if (state.currentUser.id !== "") { - const config = getAxiosConfig() + const url = `/submissions/` + let payload = { "submission" : { "learning_object_id" : draft.id } } - axios.post( (`${apiUrl}/submissions/`), payload, config - ).then( (response) => { - if ( response.headers['access-token'] ) { - sessionStorage.setItem('@portalmec/accessToken', response.headers['access-token']) - } - handleModal(true) - console.log(response) + postRequest(url, payload, + (data) => {handleModal(true)}, + (error) => {console.log(error)} + ) - }, (error) => {console.log(error)}) } } diff --git a/src/Pages/UserPage.js b/src/Pages/UserPage.js index 92d821b53164aecb062223c61fb372ebcc3351e4..c4b0755096ba9eae554a9525245915dccc2536d8 100644 --- a/src/Pages/UserPage.js +++ b/src/Pages/UserPage.js @@ -28,8 +28,6 @@ import TabPanelFavoritos from '../Components/TabPanels/UserPageTabs/PanelFavorit import TabPanelColecoes from '../Components/TabPanels/UserPageTabs/PanelColecoes.js' import TabPanelRede from '../Components/TabPanels/UserPageTabs/PanelRede.js' import TabPanelCuradoria from '../Components/TabPanels/UserPageTabs/PanelCuradoria.js' -import axios from 'axios' -import {apiUrl} from '../env'; import Grid from '@material-ui/core/Grid'; import {HeaderContainer, UserProfileContainer, CheckTeacherDiv, StyledTabs, RodapeDiv, NavBarContentContainer, BackgroundDiv} from '../Components/TabPanels/StyledComponents.js' @@ -38,23 +36,7 @@ import ProfileAvatar from '../Components/UserPageComponents/Avatar.js' import UserInfo from '../Components/UserPageComponents/UserInfo.js' import EditProfileButton from '../Components/UserPageComponents/EditProfileButton.js' import SubmitterStatus from '../Components/UserPageComponents/SubmitterStatus.js' -import {getAxiosConfig} from '../Components/HelperFunctions/getAxiosConfig.js' - -const GetHeaderConfig = () => { - - let config = { - headers : { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'Access-Token': sessionStorage.getItem('@portalmec/accessToken'), - 'Client': sessionStorage.getItem('@portalmec/clientToken'), - 'Uid': sessionStorage.getItem('@portalmec/uid'), - } - } - // {/*'Host': 'api.portalmec.c3sl.ufpr.br', - // 'Cookie': ''*/} - return config -} +import {getRequest} from '../Components/HelperFunctions/getAxiosConfig.js' export default function UserPage (props){ const {state, dispatch} = useContext(Store) @@ -70,31 +52,25 @@ export default function UserPage (props){ setTabValue(newValue) } + function handleSuccessfulGet (data) { + dispatch ( { + type: 'GET_USER', + user: data + } + ) + + if((data.role_ids.includes(4))) { + setTabs([ + 'Atividades', 'Meus Recursos', 'Favoritos', 'Coleções', 'Rede', 'Curadoria' + ]) + } + } + useEffect( () => { - let config = getAxiosConfig() if (id !== '') { - axios.get( (`${apiUrl}/users/` + id), config) - .then( (response) => { - console.log(response) - dispatch ( { - type: 'GET_USER', - user: response.data - } - ) - - if((response.data.role_ids.includes(4))) { - setTabs([ - 'Atividades', 'Meus Recursos', 'Favoritos', 'Coleções', 'Rede', 'Curadoria' - ]) - } - }).catch( (error) => { - if (error.statusText === 401) { - console.log('erro 401') - //validate Token - - //retry request - } - }) + const url = `/users/${id}` + + getRequest(url, handleSuccessfulGet, (error) => {console.log(error)}) } }, []) @@ -115,7 +91,7 @@ export default function UserPage (props){ <ModalAlterarAvatar open={modalOpen} handleClose={() => {toggleModal(false)}} - userAvatar={state.currentUser.avatar_file_name} + userAvatar={state.currentUser.avatar} /> <BackgroundDiv> @@ -164,17 +140,17 @@ export default function UserPage (props){ <Grid item xs={12}> {tabValue === 0 && - <TabPanelAtividades id={id} config={GetHeaderConfig()}/>} + <TabPanelAtividades id={id}/>} {tabValue === 1 && - <TabPanelMeusRecursos id={id} config={GetHeaderConfig()}/>} + <TabPanelMeusRecursos id={id}/>} {tabValue === 2 && - <TabPanelFavoritos id={id} config={GetHeaderConfig()}/>} + <TabPanelFavoritos id={id}/>} {tabValue === 3 && - <TabPanelColecoes id={id} config={GetHeaderConfig()}/>} + <TabPanelColecoes id={id}/>} {tabValue === 4 && - <TabPanelRede id={id} config={GetHeaderConfig()}/>} + <TabPanelRede id={id}/>} {tabValue === 5 && - <TabPanelCuradoria id={id} config={GetHeaderConfig()}/>} + <TabPanelCuradoria id={id}/>} </Grid> </Grid> </BackgroundDiv> diff --git a/src/Pages/UserTerms.js b/src/Pages/UserTerms.js index fed310add1e7d2306df10a04d8da3a3621d8da32..d7722bef70cdf003c64d9f8ae743c4f2337c99b1 100644 --- a/src/Pages/UserTerms.js +++ b/src/Pages/UserTerms.js @@ -199,7 +199,7 @@ class UserTerms extends Component { </BannerStyle> <ImagemSeçao2> - <Grid container spacing={3}> + <Grid container > <Grid item xs={12} md={1}></Grid> <Grid item xs={12} md={10}> <div> @@ -216,7 +216,7 @@ class UserTerms extends Component { </ImagemSeçao2> <Secao3 > - <Grid container spacing ={3}> + <Grid container > <h3>Para melhor compreensão, podemos dividir os recursos em dois tipos:</h3> <Grid item xs={12} md={1} ></Grid> <Grid item xs={12} md={5} > @@ -243,7 +243,7 @@ class UserTerms extends Component { - <Grid container spacing={3}> + <Grid container > <Grid item xs={12} md={1}></Grid> <Grid item xs={12} md={10}> <Secao4> @@ -267,7 +267,7 @@ class UserTerms extends Component { </Grid> - <Grid container spacing={3}> + <Grid container > <Grid item xs={12} md={1}></Grid> <Grid item xs={12} md={10}> <div style={{ marginBottom:"50px",paddingTop: "20px"}}> diff --git a/src/Store.js b/src/Store.js index d53af64db8a76e34c23dd854893b0a03dd23dec6..6beb65ee59e17e1bcb427dfccf31fbb433f40922 100644 --- a/src/Store.js +++ b/src/Store.js @@ -39,8 +39,8 @@ const initialState = { id : '', name : '', email : '', - avatar_file_name : '', - cover_file_name : '', + avatar : '', + cover : '', uid : '', follows_count : 0, collections_count : 0, @@ -83,7 +83,19 @@ function reducer(state, action) { return { ...state, userIsLoggedIn:action.userLoggedOut, - currentUser:action.login, + currentUser:{ + askTeacherQuestion : false, + id : '', + name : '', + email : '', + avatar_file_name : '', + cover_file_name : '', + uid : '', + follows_count : 0, + collections_count : 0, + submitter_request : 'default', + roles : [] + }, userAgreedToPublicationTerms: false, userAgreedToPublicationPermissions: false } @@ -136,6 +148,11 @@ function reducer(state, action) { ...state, currentUser:action.user } + case 'USER_UPDATED_EMAIL': + return { + ...state, + currentUser : action.currUser + } default: return state }