diff --git a/package-lock.json b/package-lock.json index 08f60021cefc50d7342430c248044ca112cc818e..53fbe6a2f757f97cd9fb3d49af611e6ab3658bb7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10730,6 +10730,35 @@ "resolved": "https://registry.npmjs.org/material-design-icons/-/material-design-icons-3.0.1.tgz", "integrity": "sha1-mnHEh0chjrylHlGmbaaCA4zct78=" }, + "material-ui-popup-state": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/material-ui-popup-state/-/material-ui-popup-state-1.8.0.tgz", + "integrity": "sha512-czXksi+b1I1Dgemp82UNUBjIy9DV60ttw6a9fyk60UX/Axqmf4hzcp/ulhd3JcMS5HgmmO1Vw/DNkV10ngj16A==", + "requires": { + "@babel/runtime": "^7.12.5", + "@material-ui/types": "^4.1.1", + "classnames": "^2.2.6", + "prop-types": "^15.7.2" + }, + "dependencies": { + "@babel/runtime": { + "version": "7.13.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.13.10.tgz", + "integrity": "sha512-4QPkjJq6Ns3V/RgpEahRk+AGfL0eO6RHHtTWoNNr5mO49G6B5+X6d6THgWEAvTrznU5xYpbAlVKRYcsCgh/Akw==", + "requires": { + "regenerator-runtime": "^0.13.4" + } + }, + "@material-ui/types": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@material-ui/types/-/types-4.1.1.tgz", + "integrity": "sha512-AN+GZNXytX9yxGi0JOfxHrRTbhFybjUJ05rnsBVjcB+16e466Z0Xe5IxawuOayVZgTBNDxmPKo5j4V6OnMtaSQ==", + "requires": { + "@types/react": "*" + } + } + } + }, "math-random": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/math-random/-/math-random-1.0.4.tgz", diff --git a/package.json b/package.json index c3718bad8cf32ea8b44e8178687fae91fc15d68c..810336403bf2e5ce2b913a3c1bfedd0540fbe88b 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "image-to-base64": "^2.1.1", "install": "^0.13.0", "material-design-icons": "^3.0.1", + "material-ui-popup-state": "^1.8.0", "moment": "^2.29.1", "npm": "^7.6.2", "react": "^16.14.0", diff --git a/src/Components/AreasSubPagesFunction.js b/src/Components/AreasSubPagesFunction.js index 347cacabaec592292a16548cbf3553ddb411d7af..dda8cf98d425f8b15121dd020f070b39291edfb3 100644 --- a/src/Components/AreasSubPagesFunction.js +++ b/src/Components/AreasSubPagesFunction.js @@ -35,450 +35,478 @@ import { getRequest } from './HelperFunctions/getAxiosConfig.js' import Grid from '@material-ui/core/Grid'; import { Link } from 'react-router-dom' import { CircularProgress } from "@material-ui/core"; +import ColecaoVazia from '../img/Pagina_vazia_colecao.png' +import RecursoVazio from '../img/Pagina_vazia_Sem_publicar.png' function objectsPerPage() { - var pageWidth = window.innerWidth - if (pageWidth >= 1200) { - return 3 + var pageWidth = window.innerWidth + if (pageWidth >= 1200) { + return 3 + } + else { + if (pageWidth > 766) { + return 2 } else { - if (pageWidth > 766) { - return 2 - } - else { - return 1 - } + return 1 } + } } function ReqResources(props) { - const [rows, setRows] = useState([]) - const [isLoading, setIsLoading] = useState(false) - - function onSuccessfulGet(data) { - var aux = [] - var resources_per_page = objectsPerPage() - for (let i = 0; i < 12 / resources_per_page; i++) { - aux.push(data.slice(i * resources_per_page, resources_per_page * (i + 1))) - } - setRows(aux) - setIsLoading(false) + const [rows, setRows] = useState([]) + const [isLoading, setIsLoading] = useState(false) + + function onSuccessfulGet(data) { + var aux = [] + var resources_per_page = objectsPerPage() + for (let i = 0; i < 12 / resources_per_page; i++) { + aux.push(data.slice(i * resources_per_page, resources_per_page * (i + 1))) } + setRows(aux) + setIsLoading(false) + } + + useEffect(() => { + setIsLoading(true) + const url = `/search?page=0&results_per_page=12&order=${props.order}&query=*&search_class=LearningObject` + + getRequest(url, (data) => onSuccessfulGet(data), (error) => { console.log(error) }) + }, [props.order]) + + return ( + isLoading ? + <Grid container justify="center" alignItems="center" style={{ margin: "2em" }} > + <Grid item> + <CircularProgress size={24} color="#ff7f00" /> + </Grid> + </Grid> + : + <Carousel showThumbs={false} infiniteLoop={true} showStatus={false}> + { + rows.length >= 1 ? + 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> + )) + : + <Grid container justify="center" alignItems="center"> + <Grid item> + <img src={RecursoVazio} alt="Não há recursos" /> + </Grid> + </Grid> + } + </Carousel> - useEffect(() => { - setIsLoading(true) - const url = `/search?page=0&results_per_page=12&order=${props.order}&query=*&search_class=LearningObject` - - getRequest(url, (data) => onSuccessfulGet(data), (error) => { console.log(error) }) - }, [props.order]) - - return ( - <Carousel showThumbs={false} infiniteLoop={true} showStatus={false}> - { - isLoading ? <CircularProgress size={24} color="#ff7f00" style={{ margin: "2em" }} /> - : - 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> - ))} - </Carousel> - ) + ) } function ReqCollections(props) { - const [rows, setRows] = useState([]) - const [isLoading, setIsLoading] = useState(false) - - function onSuccessfulGet(data) { - var aux = [] - var collections_per_page = objectsPerPage() - for (let i = 0; i < 12 / collections_per_page; i++) { - aux.push(data.slice(i * collections_per_page, collections_per_page * (i + 1))) - } - setIsLoading(false) - setRows(aux) + const [rows, setRows] = useState([]) + const [isLoading, setIsLoading] = useState(false) + + function onSuccessfulGet(data) { + var aux = [] + var collections_per_page = objectsPerPage() + for (let i = 0; i < 12 / collections_per_page; i++) { + aux.push(data.slice(i * collections_per_page, collections_per_page * (i + 1))) } - - useEffect(() => { - setIsLoading(true) - const url = `/search?page=0&results_per_page=12&order=${props.order}&query=*&search_class=Collection` - - getRequest(url, (data) => onSuccessfulGet(data), (error) => { console.log(error) }) - }, [props.order]) - - return ( + setIsLoading(false) + setRows(aux) + } + + useEffect(() => { + setIsLoading(true) + const url = `/search?page=0&results_per_page=12&order=${props.order}&query=*&search_class=Collection` + + getRequest(url, (data) => onSuccessfulGet(data), (error) => { console.log(error) }) + }, [props.order]) + + return ( + isLoading ? + <Grid container justify="center" alignItems="center" style={{ marginTop: "2em" }}> + <Grid item> + <CircularProgress size={24} color="#673ab7" /> + </Grid> + </Grid> + : + rows.length >= 1 ? <Carousel showThumbs={false} infiniteLoop={true} showStatus={false}> - { - isLoading ? <CircularProgress size={24} color="#673ab7" style={{ marginTop: "2em" }} /> - : - 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 ? card.owner.name : ""} - description={card.description} - thumbnails={card.items_thumbnails} - avatar={card.owner ? card.owner.avatar : ""} - likeCount={card.likes_count} - followed={card.followed} - liked={card.liked} - collections={card.collection_items} - authorID={card.owner ? card.owner.id : ""} - /> - </div> - ))} - </Row> - ))} + { + 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 ? card.owner.name : ""} + description={card.description} + thumbnails={card.items_thumbnails} + avatar={card.owner ? card.owner.avatar : ""} + likeCount={card.likes_count} + followed={card.followed} + liked={card.liked} + collections={card.collection_items} + authorID={card.owner ? card.owner.id : ""} + /> + </div> + ))} + </Row> + ))} </Carousel> - ) + : + <Grid container justify="center" alignItems="center"> + <Grid item> + <img src={ColecaoVazia} alt="Não há coleções" /> + </Grid> + </Grid> + ) } function TabRecurso() { - const text = "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!" - const [currOrder, setCurrOrder] = useState("Mais Recentes"); - const [currValue, setCurrValue] = useState("publicationdesc"); - const [ordenar] = useState([ - { label: "Mais Estrelas", value: "review_average" }, - { label: "Mais Relevante", value: "score" }, - { label: "Mais Baixados", value: "downloads" }, - { label: "Mais Favoritados", value: "likes" }, - { label: "Mais Recentes", value: "publicationdesc" }, - { label: "Ordem Alfabética", value: "title" }, - ]); - - return ( - <React.Fragment> - <div style={{ backgroundColor: "#ff7f00", position: "relative" }}> - <StyledTab container> - <Grid item md={3} xs={12}> - <img - src={recursos} - alt="aba recursos" - style={{ float: "left", marginRight: 20, marginBottom: 20, marginLeft: window.innerWidth >= 825 ? "25%" : "0px" }} - /> - </Grid> - { - window.innerWidth <= 501 && - <h4> - Recursos Educacionais Digitais + const text = "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!" + const [currOrder, setCurrOrder] = useState("Mais Recentes"); + const [currValue, setCurrValue] = useState("score"); + const [ordenar] = useState([ + { label: "Mais Estrelas", value: "review_average" }, + { label: "Mais Relevante", value: "score" }, + { label: "Mais Baixados", value: "downloads" }, + { label: "Mais Favoritados", value: "likes" }, + { label: "Mais Recentes", value: "publicationdesc" }, + { label: "Ordem Alfabética", value: "title" }, + ]); + + return ( + <React.Fragment> + <div style={{ backgroundColor: "#ff7f00", position: "relative" }}> + <StyledTab container> + <Grid item md={3} xs={12}> + <img + src={recursos} + alt="aba recursos" + style={{ float: "left", marginRight: 20, marginBottom: 20, marginLeft: window.innerWidth >= 825 ? "25%" : "0px" }} + /> + </Grid> + { + window.innerWidth <= 501 && + <h4> + Recursos Educacionais Digitais </h4> - } - <Grid item md={6} xs={12}> - <p> - {text} - </p> - </Grid> - { - window.innerWidth <= 501 && - <div style={{ display: "flex", justifyContent: "center" }}> - <Link to={`/busca?query=&search_class=LearningObject`} className="button-ver">VER RECURSOS</Link> - </div> - } - </StyledTab> + } + <Grid item md={6} xs={12}> + <p> + {text} + </p> + </Grid> + { + window.innerWidth <= 501 && + <div style={{ display: "flex", justifyContent: "center" }}> + <Link to={`/busca?query=&search_class=LearningObject`} className="button-ver">VER RECURSOS</Link> </div> - { - window.innerWidth > 501 && - <Container style={{ padding: "20px" }}> - <Grid - container - direction="row" - justify="space-between" - alignItems="center" - style={{ - paddingBottom: "5px", - borderBottom: "1px solid #ff7f00", - color: "#ff7f00", - }} - > - <Grid item> - <p - style={{ margin: 0, padding: 0 }} - > - { - `Recursos ${currOrder}` - } - </p> - </Grid> - - <Grid item> - <Grid container direction="row" alignItems="center" spacing={1}> - <Grid item> - <p style={{ margin: 0, padding: 0 }}> - Ordenar por: + } + </StyledTab> + </div> + { + window.innerWidth > 501 && + <Container style={{ padding: "20px" }}> + <Grid + container + direction="row" + justify="space-between" + alignItems="center" + style={{ + paddingBottom: "5px", + borderBottom: "1px solid #ff7f00", + color: "#ff7f00", + }} + > + <Grid item> + <p + style={{ margin: 0, padding: 0 }} + > + { + `Recursos ${currOrder}` + } + </p> + </Grid> + + <Grid item> + <Grid container direction="row" alignItems="center" spacing={1}> + <Grid item> + <p style={{ margin: 0, padding: 0 }}> + Ordenar por: </p> - </Grid> - <Grid item> - <Dropdown options={ordenar} value={currOrder} onChange={(e) => { - setCurrOrder(e.label) - setCurrValue(e.value) - }} - placeholder="Selecione uma opção" - /> - </Grid> - </Grid> - </Grid> - </Grid> - <Hidden sm xs> - <ReqResources order={currValue} /> - </Hidden> - <Visible sm xs> - <ReqResources order={currValue} /> - </Visible> - </Container> - } - </React.Fragment> - ) + </Grid> + <Grid item> + <Dropdown options={ordenar} value={currOrder} onChange={(e) => { + setCurrOrder(e.label) + setCurrValue(e.value) + }} + placeholder="Selecione uma opção" + /> + </Grid> + </Grid> + </Grid> + </Grid> + <Hidden sm xs> + <ReqResources order={currValue} /> + </Hidden> + <Visible sm xs> + <ReqResources order={currValue} /> + </Visible> + </Container> + } + </React.Fragment> + ) } function TabColecoes() { - const text = "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!" - const [currOrder, setCurrOrder] = useState("Mais Recentes"); - const [currValue, setCurrValue] = useState("publicationdesc"); - const [ordenar] = useState([ - { label: "Mais Estrelas", value: "review_average" }, - { label: "Mais Relevante", value: "score" }, - { label: "Mais Baixados", value: "downloads" }, - { label: "Mais Favoritados", value: "likes" }, - { label: "Mais Recentes", value: "publicationdesc" }, - { label: "Ordem Alfabética", value: "title" }, - ]); - - return ( - <React.Fragment> - <div style={{ backgroundColor: "#673ab7", position: "relative" }}> - <StyledTab container> - <Grid item md={3} xs={12}> - <img - src={colecoes} - alt="aba recursos" - style={{ float: "left", marginRight: 20, marginBottom: 20, marginLeft: window.innerWidth >= 825 ? "25%" : "0px" }} - /> - </Grid> - { - window.innerWidth <= 501 && - <h4> - Coleções dos Usuários + const text = "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!" + const [currOrder, setCurrOrder] = useState("Mais Recentes"); + const [currValue, setCurrValue] = useState("publicationdesc"); + const [ordenar] = useState([ + { label: "Mais Estrelas", value: "review_average" }, + { label: "Mais Relevante", value: "score" }, + { label: "Mais Baixados", value: "downloads" }, + { label: "Mais Favoritados", value: "likes" }, + { label: "Mais Recentes", value: "publicationdesc" }, + { label: "Ordem Alfabética", value: "title" }, + ]); + + return ( + <React.Fragment> + <div style={{ backgroundColor: "#673ab7", position: "relative" }}> + <StyledTab container> + <Grid item md={3} xs={12}> + <img + src={colecoes} + alt="aba recursos" + style={{ float: "left", marginRight: 20, marginBottom: 20, marginLeft: window.innerWidth >= 825 ? "25%" : "0px" }} + /> + </Grid> + { + window.innerWidth <= 501 && + <h4> + Coleções dos Usuários </h4> - } - <Grid item md={6} xs={12}> - <p> - {text} - </p> - </Grid> - { - window.innerWidth <= 501 && - <div style={{ display: "flex", justifyContent: "center" }}> - <Link to={`/busca?query=&search_class=Collection`} className="button-ver">VER COLEÇÕES</Link> - </div> - } - </StyledTab> + } + <Grid item md={6} xs={12}> + <p> + {text} + </p> + </Grid> + { + window.innerWidth <= 501 && + <div style={{ display: "flex", justifyContent: "center" }}> + <Link to={`/busca?query=&search_class=Collection`} className="button-ver">VER COLEÇÕES</Link> </div> - { - window.innerWidth > 501 && - <Container style={{ padding: "20px" }}> - <Grid - container - direction="row" - justify="space-between" - alignItems="center" - style={{ - paddingBottom: "5px", - borderBottom: "1px solid #673ab7", - color: "#673ab7", - }} - > - <Grid item> - <p - style={{ margin: 0, padding: 0 }} - > - { - `Coleções ${currOrder}` - } - </p> - </Grid> - - <Grid item> - <Grid container direction="row" alignItems="center" spacing={1}> - <Grid item> - <p style={{ margin: 0, padding: 0 }}> - Ordenar por: + } + </StyledTab> + </div> + { + window.innerWidth > 501 && + <Container style={{ padding: "20px" }}> + <Grid + container + direction="row" + justify="space-between" + alignItems="center" + style={{ + paddingBottom: "5px", + borderBottom: "1px solid #673ab7", + color: "#673ab7", + }} + > + <Grid item> + <p + style={{ margin: 0, padding: 0 }} + > + { + `Coleções ${currOrder}` + } + </p> + </Grid> + + <Grid item> + <Grid container direction="row" alignItems="center" spacing={1}> + <Grid item> + <p style={{ margin: 0, padding: 0 }}> + Ordenar por: </p> - </Grid> - <Grid item> - <Dropdown options={ordenar} value={currOrder} onChange={(e) => { - setCurrOrder(e.label) - setCurrValue(e.value) - }} - placeholder="Selecione uma opção" - /> - </Grid> - </Grid> - </Grid> - </Grid> - <ReqCollections order={currValue}/> - </Container> - } - </React.Fragment> - ) + </Grid> + <Grid item> + <Dropdown options={ordenar} value={currOrder} onChange={(e) => { + setCurrOrder(e.label) + setCurrValue(e.value) + }} + placeholder="Selecione uma opção" + /> + </Grid> + </Grid> + </Grid> + </Grid> + <ReqCollections order={currValue} /> + </Container> + } + </React.Fragment> + ) } function TabMateriais() { - const text = "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." + const text = "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." - const materials = colecoes_obj() + const materials = colecoes_obj() - const [currMaterial, setCurrMaterial] = useState({ + const [currMaterial, setCurrMaterial] = useState({ + open: false, + material: {} + }) + + const handleExpandMaterial = (id) => { + if (id !== currMaterial.material.id) + setCurrMaterial({ + open: true, + material: { ...materials[id] } + }) + else { + setCurrMaterial({ open: false, material: {} - }) - - const handleExpandMaterial = (id) => { - if (id !== currMaterial.material.id) - setCurrMaterial({ - open: true, - material: { ...materials[id] } - }) - else { - setCurrMaterial({ - open: false, - material: {} - }) - } + }) } - - return ( - <React.Fragment> - <div style={{ backgroundColor: "#e81f4f", position: "relative" }}> - <StyledTab container> - <Grid item md={3} xs={12}> - <img - src={materiais} - alt="aba recursos" - style={{ float: "left", marginRight: 20, marginBottom: 20, marginLeft: window.innerWidth >= 825 ? "25%" : "0px" }} - /> - </Grid> - { - window.innerWidth <= 501 && - <h4> - Materiais de formação + } + + return ( + <React.Fragment> + <div style={{ backgroundColor: "#e81f4f", position: "relative" }}> + <StyledTab container> + <Grid item md={3} xs={12}> + <img + src={materiais} + alt="aba recursos" + style={{ float: "left", marginRight: 20, marginBottom: 20, marginLeft: window.innerWidth >= 825 ? "25%" : "0px" }} + /> + </Grid> + { + window.innerWidth <= 501 && + <h4> + Materiais de formação </h4> - } - <Grid item md={6} xs={12}> - <p> - {text} - </p> - </Grid> - { - window.innerWidth <= 501 && - <div style={{ display: "flex", justifyContent: "center" }}> - <Link to={`/material-formacao`} className="button-ver">VER MATERIAIS</Link> - </div> - } - </StyledTab> + } + <Grid item md={6} xs={12}> + <p> + {text} + </p> + </Grid> + { + window.innerWidth <= 501 && + <div style={{ display: "flex", justifyContent: "center" }}> + <Link to={`/material-formacao`} className="button-ver">VER MATERIAIS</Link> </div> - { - window.innerWidth > 501 && - <Container style={{ padding: "20px" }}> - <p - style={{ - paddingBottom: "5px", - borderBottom: "1px solid #e81f4f", - color: "#e81f4f", - }} - > - Materiais mais recentes{" "} - </p> - <Carousel - style={{ padding: "20px" }} - showThumbs={false} - infiniteLoop={true} - showStatus={false} - > - <Row> - { - 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> - { - currMaterial.open ? - <ExpandedMaterial material={currMaterial.material} /> - : - null - } - </Container> - } - </React.Fragment > - ) + } + </StyledTab> + </div> + { + window.innerWidth > 501 && + <Container style={{ padding: "20px" }}> + <p + style={{ + paddingBottom: "5px", + borderBottom: "1px solid #e81f4f", + color: "#e81f4f", + }} + > + Materiais mais recentes{" "} + </p> + <Carousel + style={{ padding: "20px" }} + showThumbs={false} + infiniteLoop={true} + showStatus={false} + > + <Row> + { + 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> + { + currMaterial.open ? + <ExpandedMaterial material={currMaterial.material} /> + : + null + } + </Container> + } + </React.Fragment > + ) } export default function AreasSubPages(props) { - const areaRender = () => { - switch (props.banner) { - case "Recursos": - return <TabRecurso /> - case "Materiais": - return <TabMateriais /> - case "Colecoes": - return <TabColecoes /> - default: - return null - } + const areaRender = () => { + switch (props.banner) { + case "Recursos": + return <TabRecurso /> + case "Materiais": + return <TabMateriais /> + case "Colecoes": + return <TabColecoes /> + default: + return null } - - return ( - <React.Fragment> - { - window.innerWidth <= 501 ? ( - <React.Fragment> - <TabRecurso /> - <TabMateriais /> - <TabColecoes /> - </React.Fragment> - ) : ( - areaRender() - ) - } - </React.Fragment> - ) + } + + return ( + <React.Fragment> + { + window.innerWidth <= 501 ? ( + <React.Fragment> + <TabRecurso /> + <TabMateriais /> + <TabColecoes /> + </React.Fragment> + ) : ( + areaRender() + ) + } + </React.Fragment> + ) } const StyledTab = styled(Grid)` diff --git a/src/Components/ColCardPublicOptions.js b/src/Components/ColCardPublicOptions.js index 48a7bab2be1d264fb8681bb3e79637c68d08894f..6e374d7a159e18c51bc06a44038c0aa859c796d6 100644 --- a/src/Components/ColCardPublicOptions.js +++ b/src/Components/ColCardPublicOptions.js @@ -16,23 +16,23 @@ GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Plataforma Integrada MEC. If not, see <http://www.gnu.org/licenses/>.*/ -import React, {useState} from 'react'; +import React, { useState } from 'react'; import Button from '@material-ui/core/Button'; import Menu from '@material-ui/core/Menu'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import MenuItem from '@material-ui/core/MenuItem'; import OpenIcon from '@material-ui/icons/OpenInNew'; -import {Link} from 'react-router-dom' +import { Link } from 'react-router-dom' 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 ReportProblemIcon from '@material-ui/icons/ReportProblem'; import OpenInBrowserIcon from '@material-ui/icons/OpenInBrowser'; -import {deleteRequest} from '../Components/HelperFunctions/getAxiosConfig' +import { deleteRequest } from '../Components/HelperFunctions/getAxiosConfig' -export default function ColCardPublicOptions (props) { - const [anchorEl, setAnchorEl] = React.useState(null); +export default function ColCardPublicOptions(props) { + const [anchorEl, setAnchorEl] = React.useState(null); function handleClick(event) { setAnchorEl(event.currentTarget); @@ -43,11 +43,13 @@ export default function ColCardPublicOptions (props) { } const [reportModalOpen, toggleReportModal] = useState(false) - const handleReportModal = (value) => {toggleReportModal(value)} + const handleReportModal = (value) => { toggleReportModal(value) } const handleUnfollow = () => { - - deleteRequest(`/collections/${props.id}/follow`, (data) => {console.log(data)}, (error) => {console.log(error)}) + if (props.currentUserId) + deleteRequest(`/collections/${props.id}/follow`, (data) => { console.log(data) }, (error) => { console.log(error) }) + else + props.handleLogin() } return ( @@ -104,7 +106,10 @@ export default function ColCardPublicOptions (props) { <StyledMenuItem onClick={() => { - handleReportModal(true); + if (props.currentUserId) + handleReportModal(true); + else + props.handleLogin() }} > <ListItemIcon> diff --git a/src/Components/CollectionCardFunction.js b/src/Components/CollectionCardFunction.js index fe0844f15ae24d38025de34d359c9cd30ba07463..ced5cb77028a259d4aa39136ff48f18f696ec114 100644 --- a/src/Components/CollectionCardFunction.js +++ b/src/Components/CollectionCardFunction.js @@ -42,263 +42,271 @@ import Snackbar from '@material-ui/core/Snackbar'; import MuiAlert from '@material-ui/lab/Alert'; export default function CollectionCardFunction(props) { - const { state } = useContext(Store) - - // eslint-disable-next-line - const [userAvatar] = useState(props.avatar ? (`${apiDomain}` + props.avatar) : noAvatar) - const [userFollowingCol, toggleUserFollowingCol] = useState(props.followed ? props.followed : false) - const handleToggleUserFollowingCol = () => { toggleUserFollowingCol(!userFollowingCol) } - - const [name, setName] = useState(props.name) - const changeColName = (newName) => {setName(newName)} - - const [privacy, setPrivacy] = useState(props.privacy) - const changeColPrivacy = (newPrivacy) => {setPrivacy(newPrivacy)} - - 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 = () => { - putRequest(`/collections/${props.id}/like`, {}, handleSuccessLike, (error) => { console.log(error) }) - } - - const [followingHover, handleFollowingHover] = useState(false) - const toggleFollowingHover = (value) => { handleFollowingHover(value) } - - const [slideIn, setSlide] = useState(false) - const controlSlide = () => { setSlide(!slideIn) } - - function handleSuccessFollow(data) { - handleToggleUserFollowingCol() - } - const handleFollow = () => { - putRequest(`/collections/${props.id}/follow`, {}, handleSuccessFollow, (error) => { console.log(error) }) - } + const { state } = useContext(Store) + + // eslint-disable-next-line + const [userAvatar] = useState(props.avatar ? (`${apiDomain}` + props.avatar) : noAvatar) + const [userFollowingCol, toggleUserFollowingCol] = useState(props.followed ? props.followed : false) + const handleToggleUserFollowingCol = () => { toggleUserFollowingCol(!userFollowingCol) } + + const [name, setName] = useState(props.name) + const changeColName = (newName) => { setName(newName) } + + const [privacy, setPrivacy] = useState(props.privacy) + const changeColPrivacy = (newPrivacy) => { setPrivacy(newPrivacy) } + + 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 = () => { + if (state.currentUser.id) + putRequest(`/collections/${props.id}/like`, {}, handleSuccessLike, (error) => { console.log(error) }) + else + handleLogin() + } + + const [followingHover, handleFollowingHover] = useState(false) + const toggleFollowingHover = (value) => { handleFollowingHover(value) } + + const [slideIn, setSlide] = useState(false) + const controlSlide = () => { setSlide(!slideIn) } + + function handleSuccessFollow(data) { + handleToggleUserFollowingCol() + } + const handleFollow = () => { + if (state.currentUser.id) + putRequest(`/collections/${props.id}/follow`, {}, handleSuccessFollow, (error) => { console.log(error) }) + else + handleLogin() + } + + const RenderFollowButton = () => { + return ( + <FollowButton onClick={handleFollow}> + <AddIcon /><span>SEGUIR</span> + </FollowButton> + ) + } - const RenderFollowButton = () => { - return ( - <FollowButton onClick={handleFollow}> - <AddIcon /><span>SEGUIR</span> - </FollowButton> - ) + useEffect(() => { + if (!state.currentUser.id) { + toggleLiked(false); + toggleUserFollowingCol(false); } + }, [state.currentUser.id]) - useEffect(() => { - if (!state.currentUser.id) { - toggleLiked(false); - toggleUserFollowingCol(false); + 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> + ] + ) } - }, [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> - ] - ) - } - </FollowingButton> - ) - } + </FollowingButton> + ) + } - const SlideAnimationContent = () => { - return ( - <SlideContentDiv> - <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: + const SlideAnimationContent = () => { + return ( + <SlideContentDiv> + <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 /> - <p>{props.author}</p> - </EnviadoPor> - </HeaderContainer> - { - props.tags ? - <TagContainer container direction="row"> - { - props.tags.map((tag) => - <Grid item key={tag.id}> - <span >{tag.name}</span> - </Grid> - ) - } - </TagContainer> : - null - } - </SlideContentDiv> - ) - } + <p>{props.author}</p> + </EnviadoPor> + </HeaderContainer> + { + props.tags ? + <TagContainer container direction="row"> + { + props.tags.map((tag) => + <Grid item key={tag.id}> + <span >{tag.name}</span> + </Grid> + ) + } + </TagContainer> : + null + } + </SlideContentDiv> + ) + } - const handleSignUp = () => { - setSignUp(!signUpOpen) - } + const handleSignUp = () => { + setSignUp(!signUpOpen) + } - const handleLogin = () => { - setLogin(!loginOpen) - } + const handleLogin = () => { + setLogin(!loginOpen) + } - function Alert(props) { - return <MuiAlert elevation={6} variant="filled" {...props} />; - } + function Alert(props) { + return <MuiAlert elevation={6} variant="filled" {...props} />; + } - function toggleLoginSnackbar(reason) { - if (reason === 'clickaway') { - return; - } - handleSuccessfulLogin(false); + function toggleLoginSnackbar(reason) { + if (reason === 'clickaway') { + return; } - - 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"}>{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" }} /> - </Grid> - ) - } - </StyledGrid> - </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" }}> - { - privacy === 'private' && - <LockIcon style={{ color: "#666" }} /> - } - </Grid> - <Grid item xs={6} style={{ display: "flex", justifyContent: "flex-end" }}> - <ColCardOwnerOptions - id={props.id} - changeColName={changeColName} - changeColPrivacy={changeColPrivacy} - /> - </Grid> - </Grid> - </CardReaFooter> - ) - : - ( - <CardReaFooter> {/*renders following/unfollow and follow button*/} - { - userFollowingCol ? - ( - [ - RenderFollowingButton() - ] - ) - : - ( - [ - RenderFollowButton() - ] - ) - } - <ColCardPublicOptions - id={props.id} - /> - </CardReaFooter> - ) - } - - </CardDiv> - </StyledCard> - </> - ) + 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"}>{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" }} /> + </Grid> + ) + } + </StyledGrid> + </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" }}> + { + privacy === 'private' && + <LockIcon style={{ color: "#666" }} /> + } + </Grid> + <Grid item xs={6} style={{ display: "flex", justifyContent: "flex-end" }}> + <ColCardOwnerOptions + id={props.id} + changeColName={changeColName} + changeColPrivacy={changeColPrivacy} + /> + </Grid> + </Grid> + </CardReaFooter> + ) + : + ( + <CardReaFooter> {/*renders following/unfollow and follow button*/} + { + userFollowingCol ? + ( + [ + RenderFollowingButton() + ] + ) + : + ( + [ + RenderFollowButton() + ] + ) + } + <ColCardPublicOptions + id={props.id} + handleLogin={handleLogin} + currentUserId={state.currentUser.id} + /> + </CardReaFooter> + ) + } + + </CardDiv> + </StyledCard> + </> + ) } diff --git a/src/Components/ContactCardOptions.js b/src/Components/ContactCardOptions.js index 4a1340e49610f335749d4db4a3b2212a03afd1a3..2cf3555c6ac3cae3da3cb7590ae2d149653391e4 100644 --- a/src/Components/ContactCardOptions.js +++ b/src/Components/ContactCardOptions.js @@ -27,7 +27,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 {putRequest} from './HelperFunctions/getAxiosConfig' +import { putRequest } from './HelperFunctions/getAxiosConfig' import ReportModal from './ReportModal.js' import {Link} from 'react-router-dom' import LoginModal from './LoginModal.js' @@ -75,7 +75,7 @@ export default function SimpleMenu(props) { putRequest(`/users/${followerID}/follow`, {}, (data) => { console.log(data); props.toggleFollowed() - }, (error) => {console.log(error)}) + }, (error) => { console.log(error) }) handleClose(); } diff --git a/src/Components/Dropdown.js b/src/Components/Dropdown.js index 31d7047d63cfd5d837734ebbf0cd057bfbc4430f..a1a45fb6213f3c0f97be42dde448cf89b1ba83a6 100644 --- a/src/Components/Dropdown.js +++ b/src/Components/Dropdown.js @@ -1,59 +1,58 @@ -/*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, useRef, useEffect, useContext } from 'react' -import { HashLink as Link } from 'react-router-hash-link'; -import { Button, Grow, Paper, Popper, MenuItem, MenuList } from '@material-ui/core'; -import { withStyles } from '@material-ui/styles'; -import styled from 'styled-components' +// /*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, { useEffect } from 'react'; +import { makeStyles } from '@material-ui/core/styles'; +import Popper from '@material-ui/core/Popper'; +import Button from '@material-ui/core/Button'; +import Fade from '@material-ui/core/Fade'; +import Paper from '@material-ui/core/Paper'; +import { MenuItem, MenuList } from '@material-ui/core/' import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import { Store } from '../Store'; +import { HashLink as Link } from 'react-router-hash-link'; -const styles = theme => ({ - root: { - display: 'flex', - - }, - paper: { - marginRight: '2px', +const useStyles = makeStyles((theme) => ({ + typography: { + padding: theme.spacing(2), }, -}); - -const DropdownStyled = styled.div` - *{ - margin: 0 !important; - text-decoration: none; - } - Button{ - text-transform: capitalize; - } - -` - - -function Dropdown(props) { - const [open, setOpen] = useState(false); - - const innerDropdown = useRef(null) - - const { state , dispatch } = useContext(Store) +})); + +export default function PositionedPopper(props) { + const [anchorEl, setAnchorEl] = React.useState(null); + const [open, setOpen] = React.useState(false); + const [placement, setPlacement] = React.useState(); + const classes = useStyles(); + const { state, dispatch } = React.useContext(Store) + const innerDropdown = React.useRef(null) + + const handleClick = (newPlacement) => (event) => { + if (state.searchOpen) + dispatch({ + type: 'HANDLE_SEARCH_BAR', + opened: false + }) + setAnchorEl(event.currentTarget); + setOpen((prev) => placement !== newPlacement || !prev); + setPlacement(newPlacement); + }; - useEffect(()=>{ + useEffect(() => { const handleClickOutside = (event) => { innerDropdown.current && !innerDropdown.current.contains(event.target) && setOpen(false) } @@ -62,50 +61,34 @@ function Dropdown(props) { return () => document.removeEventListener('mousedown', handleClickOutside) - },[]) - - - const handleToggle = () => { - setOpen(true) - if(state.searchOpen) - dispatch({ - type: 'HANDLE_SEARCH_BAR', - opened: false - }) - } + }, []) return ( - <DropdownStyled ref={innerDropdown}> + <div className={classes.root}> + <Popper open={open} anchorEl={anchorEl} placement="bottom" transition ref={innerDropdown}> + {({ TransitionProps }) => ( + <Fade {...TransitionProps} timeout={350}> + <Paper> + <MenuList> + { + props.items.map((item) => + <Link style={{ textDecoration: "none", color: "black" }} key={`${item.name}_${new Date().toString()}`} to={item.href} ><MenuItem>{item.name}</MenuItem></Link> + ) + } + </MenuList> + </Paper> + </Fade> + )} + </Popper> <Button + style={{ textTransform: "none", fontSize: "14px"}} aria-controls="menu-list-grow" aria-haspopup="true" - onClick={handleToggle} + onClick={handleClick('bottom')} > {props.name} - <ExpandMoreIcon/> + <ExpandMoreIcon /> </Button> - { open && - <Popper open={open} keepMounted transition disablePortal placement={'bottom'}> - {({ TransitionProps, placement }) => ( - <Grow - {...TransitionProps} - style={{ transformOrigin: 'center top !important', anchorOrigin : "center bottom !important"}} - > - <Paper id="menu-list-grow"> - <MenuList> - { - props.items.map((item)=> - <Link key={`${item.name}_${new Date().toString()}` } to={item.href} ><MenuItem>{item.name}</MenuItem></Link> - ) - } - </MenuList> - </Paper> - </Grow> - )} - </Popper> - } - </DropdownStyled> + </div> ); -} - -export default withStyles(styles)(Dropdown) +} \ No newline at end of file diff --git a/src/Components/Header.js b/src/Components/Header.js index 7cb8a2db3f7652fef30467738dabfec68c6b8e7f..3b278a89aafd110ca6f354b989e89a85ee178311 100644 --- a/src/Components/Header.js +++ b/src/Components/Header.js @@ -27,127 +27,123 @@ import Snackbar from '@material-ui/core/Snackbar'; import MuiAlert from '@material-ui/lab/Alert'; import { useLocation, useHistory } from 'react-router-dom' import MenuBarMobile from './MenuBarMobile.js' -import {getRequest, validateGoogleLoginToken } from './HelperFunctions/getAxiosConfig' +import { getRequest, 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} />; } export default function Header(props) { - const { state, dispatch } = useContext(Store) - const [signUpOpen, setSignUp] = useState(false) - const [loginOpen, setLogin] = useState(false) - const [successfulLoginOpen, handleSuccessfulLogin] = useState(false) - const [modalColaborar, setModalColaborar] = useState(false) - - function handleSuccessValidateToken (data) { - dispatch ({ - type: "USER_LOGGED_IN", - userLoggedIn: !state.userIsLoggedIn, - login: data.data - } - ) + const { state, dispatch } = useContext(Store) + const [signUpOpen, setSignUp] = useState(false) + const [loginOpen, setLogin] = useState(false) + const [successfulLoginOpen, handleSuccessfulLogin] = useState(false) + const [modalColaborar, setModalColaborar] = useState(false) + + function handleSuccessValidateToken(data) { + dispatch({ + type: "USER_LOGGED_IN", + userLoggedIn: !state.userIsLoggedIn, + login: data.data + } + ) } - useEffect( () => { - if (sessionStorage.getItem('@portalmec/auth_headers')) { - const url = `/auth/validate_token/` - getRequest(url, handleSuccessValidateToken, (error) => {console.log(error)}) - } + useEffect(() => { + if (sessionStorage.getItem('@portalmec/auth_headers')) { + const url = `/auth/validate_token/` + getRequest(url, handleSuccessValidateToken, (error) => { console.log(error) }) + } }, []) let loc = useLocation() let history = useHistory() useEffect(() => { - const url = `/auth/validate_token/` - - 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(url, config, handleSuccessValidateToken, (error) => {console.log(error)}) - history.push("/") + const url = `/auth/validate_token/` + + 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(url, config, handleSuccessValidateToken, (error) => { console.log(error) }) + history.push("/") + } }, [loc]) - useEffect ( () => { - if (state.currentUser.askTeacherQuestion === true) { - dispatch({ - type: "TOGGLE_MODAL_COLABORAR_PLATAFORMA", - modalColaborarPlataformaOpen: true - }); - } + useEffect(() => { + if (state.currentUser.askTeacherQuestion === true) { + dispatch({ + type: "TOGGLE_MODAL_COLABORAR_PLATAFORMA", + modalColaborarPlataformaOpen: true + }); + } }, [state.currentUser.askTeacherQuestion]) const toggleSnackbar = (event, reason) => { - if (reason === 'clickaway') { - return; - } - - handleSuccessfulLogin(false); + if (reason === 'clickaway') { + return; } - const handleSignUp = () => { - setSignUp(!signUpOpen) - } + handleSuccessfulLogin(false); + } - const handleLogin = () => { - setLogin(!loginOpen) - } + const handleSignUp = () => { + setSignUp(!signUpOpen) + } - const handleClickSearch = (open) => { - dispatch({ - type: "HANDLE_SEARCH_BAR", - opened: !state.searchOpen - }) - } + const handleLogin = () => { + setLogin(!loginOpen) + } + + const handleClickSearch = (open) => { + dispatch({ + type: "HANDLE_SEARCH_BAR", + opened: !state.searchOpen + }) + } let windowWidth = window.innerWidth return ( <React.Fragment> - {/* - 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/MenuList.js b/src/Components/MenuList.js index 3614035457caeb857efe57232b3857c7a6ced80f..65ab3c6b76925816bb26b17ce48e8793192667a2 100644 --- a/src/Components/MenuList.js +++ b/src/Components/MenuList.js @@ -63,8 +63,7 @@ export default function MenuList(props) { <OverrideButton aria-controls="customized-menu" aria-haspopup="true" - onMouseEnter={handleClick} - + onMouseOver={handleClick} > <div style={{borderRadius: "50%", border: "2px solid #fff", background: "#fff", overflow: "hidden", maxWidth : "50px", maxHeight : "50px"}}> { @@ -105,8 +104,6 @@ export default function MenuList(props) { ) } <StyledButtonSair onClick={handleLogout}> <StyledMenuItem disableGutters={true}>Sair<StyledExitToAppIcon/></StyledMenuItem></StyledButtonSair> - - </Menu> </div> ); diff --git a/src/Components/ResourceCardOptions.js b/src/Components/ResourceCardOptions.js index 44bc52df18fd48f3deeeae344a8457ff06e6a8b6..81d9286c5d0671f8885250daf08f2a4e601b3c87 100644 --- a/src/Components/ResourceCardOptions.js +++ b/src/Components/ResourceCardOptions.js @@ -104,6 +104,16 @@ export default function ResourceCardOptions(props) { setLogin(!loginOpen) } + const handleReport = () => { + if (!state.currentUser.id) { + handleLogin() + } + else { + handleModalReportar(true); + } + handleClose(); + } + function Alert(props) { return <MuiAlert elevation={6} variant="filled" {...props} />; } @@ -187,7 +197,7 @@ export default function ResourceCardOptions(props) { <ListItemIcon><AddIcon /></ListItemIcon>Guardar </StyledMenuItem> - <StyledMenuItem onClick={() => { handleModalReportar(true); handleClose() }}> + <StyledMenuItem onClick={() => { handleReport() }}> <ListItemIcon><ReportIcon /></ListItemIcon>Reportar </StyledMenuItem> diff --git a/src/Components/SnackbarComponent.js b/src/Components/SnackbarComponent.js index 0a359a78ba406c70f94ce37fba45b979f4608f60..b0bd36a67d134d598e603d3d8c749763132579d7 100644 --- a/src/Components/SnackbarComponent.js +++ b/src/Components/SnackbarComponent.js @@ -20,12 +20,12 @@ import React from 'react' import Alert from '../Components/Alert.js'; import Snackbar from '@material-ui/core/Snackbar'; -export default function SnackbarComponent (props) { +export default function SnackbarComponent(props) { return ( <Snackbar open={props.snackbarOpen} autoHideDuration={3000} onClose={props.handleClose} - anchorOrigin = {{ vertical:'top', horizontal:'right' }} + anchorOrigin={{ vertical: 'top', horizontal: 'right' }} > - <Alert severity={props.severity} style={ props.color === null ? {backgroundColor:"#00acc1"} : {backgroundColor: props.color}}> + <Alert severity={props.severity} style={props.color ? { backgroundColor: props.color } : { backgroundColor: "#00acc1" }}> {props.text} </Alert> </Snackbar> diff --git a/src/Components/TabPanels/PublicUserPageTabs/LastLearnObj.js b/src/Components/TabPanels/PublicUserPageTabs/LastLearnObj.js index 705faa8d77e70cdeee8b6bbf4ea9e65ead1313fc..2a489ac6808bad38d577ef87125d56e60bcd4f7e 100644 --- a/src/Components/TabPanels/PublicUserPageTabs/LastLearnObj.js +++ b/src/Components/TabPanels/PublicUserPageTabs/LastLearnObj.js @@ -30,13 +30,6 @@ export default function LastLearnObjs(props) { <Grid item xs={9}> <h3>Últimos Recursos Publicados</h3> </Grid> - <Grid item xs={3} style={{ textAlign: "end" }}> - {props.count > 4 && - <span> - VER MAIS - </span> - } - </Grid> </HeaderGrid> { @@ -57,10 +50,10 @@ export default function LastLearnObjs(props) { : ( [ - <StyledGrid container spacing={1} style={{ paddingLeft: "0.5em" }}> + <StyledGrid container spacing={1} style={{ paddingLeft: "30px", paddingRight: "15px" }}> { props.learningObjs.slice(0, 4).map((card) => - <Grid item md={3} xs={12} key={card.id}> + <Grid item xs={12} sm={6} md={'auto'} lg={3} key={card.id}> <ResourceCardFunction avatar={card.publisher.avatar} id={card.id} diff --git a/src/Components/TabPanels/PublicUserPageTabs/TabColecoes.js b/src/Components/TabPanels/PublicUserPageTabs/TabColecoes.js index 2b81757d34ee93379d60a8165bac6f6f31216f2e..22fe8e4da3e4ba7e536b2227ca7319f39f600805 100644 --- a/src/Components/TabPanels/PublicUserPageTabs/TabColecoes.js +++ b/src/Components/TabPanels/PublicUserPageTabs/TabColecoes.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, {useState, useEffect} from 'react' -import {HeaderGrid, ContainerStyled, Carregados} from '../StyledComponents.js' +import React, { useState, useEffect } from 'react' +import { HeaderGrid, ContainerStyled, Carregados, StyledGrid } from '../StyledComponents.js' import Grid from '@material-ui/core/Grid'; import CollectionCardFunction from '../../CollectionCardFunction.js' import { ButtonMostrarMaisColecao } from '../PanelComponents/ButtonsArea.js' @@ -46,10 +46,10 @@ export default function TabRecursos(props) { </Grid> </HeaderGrid> - <Grid container spacing={1} style={{ paddingLeft: "0.5em" }}> + <StyledGrid container spacing={1} style={{ paddingLeft: "30px", paddingRight: "15px" }}> { colsSlice.map((card) => - <Grid item md={3} xs={12} key={card.id}> + <Grid item xs={12} sm={6} md={'auto'} lg={3} key={card.id}> <CollectionCardFunction name={card.name} tags={card.tags} @@ -68,7 +68,7 @@ export default function TabRecursos(props) { </Grid> ) } - </Grid> + </StyledGrid> <Carregados> <p style={{ margin: "0 0 10px", fontSize: "14px" }}> diff --git a/src/Components/TabPanels/PublicUserPageTabs/TabRecursos.js b/src/Components/TabPanels/PublicUserPageTabs/TabRecursos.js index bf677ebd921dd7f91ffe469a49c4800686843191..bbce193bcde870391dda55ee9a67c79aacb768b4 100644 --- a/src/Components/TabPanels/PublicUserPageTabs/TabRecursos.js +++ b/src/Components/TabPanels/PublicUserPageTabs/TabRecursos.js @@ -16,13 +16,14 @@ 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 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' - +import { ButtonMostrarMaisRecurso } from '../PanelComponents/ButtonsArea' +import { getRequest } from '../../HelperFunctions/getAxiosConfig' +import { StyledGrid } from '../StyledComponents' + export default function TabRecursos(props) { const [arr, setArr] = useState([]) const [objsSlice, setSlice] = useState([]) @@ -33,7 +34,7 @@ export default function TabRecursos(props) { setSlice(props.learningObjs.slice(0, 4)) }, []) - function handleSuccess (data) { + function handleSuccess(data) { setArr(data) setSlice(data) } @@ -43,7 +44,7 @@ export default function TabRecursos(props) { if (newLength > 12) { const url = `/users/${props.id}/learning_objects?limit=${newLength}$offset=4` - getRequest(url,handleSuccess,(error) => {console.log(error)}) + getRequest(url, handleSuccess, (error) => { console.log(error) }) } else { handleSlice(arr.slice(0, sliceLength + quantity)) @@ -60,10 +61,10 @@ export default function TabRecursos(props) { </Grid> </HeaderGrid> - <Grid container spacing={1} style={{ paddingLeft: "0.5em" }}> + <StyledGrid container spacing={1} style={{ paddingLeft: "30px", paddingRight: "15px" }}> { objsSlice.map((card) => - <Grid item md={3} xs={12} key={card.id}> + <Grid item xs={12} sm={6} md={'auto'} lg={3} key={card.id}> <ResourceCardFunction avatar={card.publisher.avatar} id={card.id} @@ -82,7 +83,7 @@ export default function TabRecursos(props) { </Grid> ) } - </Grid> + </StyledGrid> <Carregados> <p style={{ margin: "0 0 10px", fontSize: "14px" }}> diff --git a/src/Pages/PublicUserPage.js b/src/Pages/PublicUserPage.js index b54d2d9ad465ca720e3f7c0f43f5d2ad9df99f9e..0f2a14d5930535cd1309fa7f10fcb591c45f8af6 100644 --- a/src/Pages/PublicUserPage.js +++ b/src/Pages/PublicUserPage.js @@ -17,7 +17,7 @@ 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, { useEffect, useState, useContext } from 'react' -import {Store} from '../Store' +import { Store } from '../Store' import styled from 'styled-components' import { apiDomain } from '../env'; import CustomizedBreadcrumbs from '../Components/TabPanels/Breadcrumbs.js' @@ -39,219 +39,221 @@ import Typography from '@material-ui/core/Typography'; import CircularProgress from '@material-ui/core/CircularProgress'; function RenderFollowContainer(props) { - const {state} = useContext(Store) - const [followed, setFollowed] = useState(props.followed) - const toggleFollowed = () => {setFollowed(!followed)} - console.log(followed); - return ( - <FollowContainer> - <> - { - (props.id !== state.currentUser.id) && - followed ? - ( - <FollowingButton followedID={props.id} toggleFollowed={toggleFollowed}/> - ) - : - ( - <FollowButton followerID={props.id} toggleFollowed={toggleFollowed}/> - ) - } - <FollowersCountButton followCount={props.followCount} /> - </> - </FollowContainer> - ) + const { state } = useContext(Store) + const [followed, setFollowed] = useState(props.followed) + const toggleFollowed = () => { setFollowed(!followed) } + console.log(followed); + return ( + <FollowContainer> + <> + { + (props.id !== state.currentUser.id) && + followed ? + ( + <FollowingButton followedID={props.id} toggleFollowed={toggleFollowed} /> + ) + : + ( + <FollowButton followerID={props.id} toggleFollowed={toggleFollowed} /> + ) + } + <FollowersCountButton followCount={props.followCount} /> + </> + </FollowContainer> + ) } const RenderProfileAvatar = (userAvatar) => { - return ( - <ProfileAvatarDiv> - <img src={userAvatar ? apiDomain + userAvatar : noAvatar} alt="user avatar" style={{ height: "inherit", width: "inherit", border: "0", verticalAlign: "middle" }} /> - </ProfileAvatarDiv> - ) + return ( + <ProfileAvatarDiv> + <img src={userAvatar ? apiDomain + userAvatar : noAvatar} alt="user avatar" style={{ height: "inherit", width: "inherit", border: "0", verticalAlign: "middle" }} /> + </ProfileAvatarDiv> + ) } const RenderUserProfileInfo = (userName) => { - return ( - <UserProfileInfoDiv> - <p - style={{ fontSize: "28px", color: "#fff", marginBottom: "2px", fontWeight: "500", borderRadius: "5px", textShadow: "0 1px 2px rgba(0,0,0,.45)" }} - > - {userName} - </p> - </UserProfileInfoDiv> - ) + return ( + <UserProfileInfoDiv> + <p + style={{ fontSize: "28px", color: "#fff", marginBottom: "2px", fontWeight: "500", borderRadius: "5px", textShadow: "0 1px 2px rgba(0,0,0,.45)" }} + > + {userName} + </p> + </UserProfileInfoDiv> + ) } const RenderCheckTeacher = (submitter_request) => { - if (submitter_request === "accepted") { - return ( - <CheckTeacherDiv> - <p> - <span> - <img alt="" src={CheckDecagram} /> - </span> + if (submitter_request === "accepted") { + return ( + <CheckTeacherDiv> + <p> + <span> + <img alt="" src={CheckDecagram} /> + </span> Professor(a) </p> - </CheckTeacherDiv> - ) - } + </CheckTeacherDiv> + ) + } } export default function PublicUserPage(props) { - /*user info variables--------------------------------------*/ - const WIDTH = window.innerWidth; - const id = props.match.params.userId + /*currentUser info variables--------------------------------------*/ + const { state } = useContext(Store) + /*user info variables--------------------------------------*/ + const WIDTH = window.innerWidth; + const id = props.match.params.userId - const [loading, setLoading] = useState(false); + const [loading, setLoading] = useState(false); - const [userData, setUserData] = useState({}) - const fillUserInfo = (data) => { - setUserData(data) - } - /*---------------------------------------------------------*/ - const [following, setFollowing] = useState([]); - const fillFollowing = (data) => { - setFollowing(data); - } + const [userData, setUserData] = useState({}) + const fillUserInfo = (data) => { + setUserData(data) + } + /*---------------------------------------------------------*/ + const [following, setFollowing] = useState([]); + const fillFollowing = (data) => { + setFollowing(data); + } - /*content control variables--------------------------------*/ - // eslint-disable-next-line - const [tabs, setTabs] = useState([ - 'Início', 'Recursos', 'Coleções', 'Rede' - ]) - const [tabValue, setTabValue] = useState(0); - const handleChangeTab = (event, newValue) => { - setTabValue(newValue) - } - /*---------------------------------------------------------*/ + /*content control variables--------------------------------*/ + // eslint-disable-next-line + const [tabs, setTabs] = useState([ + 'Início', 'Recursos', 'Coleções', 'Rede' + ]) + const [tabValue, setTabValue] = useState(0); + const handleChangeTab = (event, newValue) => { + setTabValue(newValue) + } + /*---------------------------------------------------------*/ - /*content variables--------------------------------*/ - const [learningObjArr, setLearningObjects] = useState([]) - const handleLearningObjects = (data) => { setLearningObjects(data) } - const [collectionsArr, setCollections] = useState([]) - const handleCollections = (data) => { setCollections(data) } - /*---------------------------------------------------------*/ + /*content variables--------------------------------*/ + const [learningObjArr, setLearningObjects] = useState([]) + const handleLearningObjects = (data) => { setLearningObjects(data) } + const [collectionsArr, setCollections] = useState([]) + const handleCollections = (data) => { setCollections(data) } + /*---------------------------------------------------------*/ - function handleSuccess(responseArr) { - fillUserInfo(responseArr[0]) + function handleSuccess(responseArr) { + fillUserInfo(responseArr[0]) - handleLearningObjects(responseArr[1]) + handleLearningObjects(responseArr[1]) - handleCollections(responseArr[2]) + handleCollections(responseArr[2]) - fillFollowing(responseArr[3]); - setLoading(false); - } + fillFollowing(responseArr[3]); + setLoading(false); + } - /*Component Will Mount*/ - useEffect(() => { - const urls = [`/users/${id}`, `/users/${id}/learning_objects`, `/users/${id}/collections`, `/users/${id}/following/User` ] - setLoading(true); - fetchAllRequest(urls, handleSuccess, (error) => { console.log(error) }) - }, []) - /*---------------------------------------------------------*/ + /*Component Will Mount*/ + useEffect(() => { + const urls = [`/users/${id}`, `/users/${id}/learning_objects`, `/users/${id}/collections`, `/users/${id}/following/User`] + setLoading(true); + fetchAllRequest(urls, handleSuccess, (error) => { console.log(error) }) + }, [state.currentUser.id]) + /*---------------------------------------------------------*/ - return ( - <React.Fragment> - <link href="https://fonts.googleapis.com/css?family=Roboto:100,400,500&display=swap" rel="stylesheet" /> - <BackgroundDiv> - <CustomizedBreadcrumbs - values={["Usuário Público", tabs[tabValue]]} - /> - <Grid container spacing={2}> - <Grid item xs={12}> - <div style={{ padding: "10px 0 8px 0" }}> - <UserProfileContainer> - <HeaderContainer> - <> - {!loading && <RenderFollowContainer followed={userData.followed} id={id} followCount={userData.follows_count} />} - {RenderProfileAvatar(userData.avatar ? userData.avatar : undefined)} - <CoverContainer> - {userData.cover && <img src={apiDomain + userData.cover} alt='' style={{ width: "100%", height: "100%", objectFit: "cover" }} />} - </CoverContainer> - { - WIDTH <= 501 ? null : RenderUserProfileInfo(userData.name) - } - </> - </HeaderContainer> - { - WIDTH <= 501 ? - <Grid style={{ marginTop: '4em' }} container justify="center" alignItems="center" direction="column"> - <Grid item> - <Typography variant="h4" gutterBottom style={{textAlign : "center"}}> - { - userData.name - } - </Typography> - </Grid> - <Grid style={{marginTop: '0.5em', marginBottom: '0.5em', borderTop : "0.5px solid #DCDCDC", borderBottom : "0.5px solid #DCDCDC" }} container spacing={4} justify="center" alignItems="center" direction="row"> - <Grid item> - <Typography variant="h6" > - { - loading ? - <CircularProgress size={20}/> : - `${userData.follows_count} seguidores` - } - </Typography> - </Grid> - <Grid item> - <Typography variant="h6" > - { - loading ? - <CircularProgress size={20}/> : - following ? - `${following.length} seguindo` : - "0 seguindo" - } - </Typography> - </Grid> - </Grid> - </Grid> - : - RenderCheckTeacher(userData.submitter_request)} - <RodapeDiv> - <NavBarContentContainer> - <StyledTabs - value={tabValue} - onChange={handleChangeTab} - indicatorColor="primary" - textColor="primary" - variant="fullwidth" - scrollButtons="desktop" - TabIndicatorProps={{ style: { background: "#00bcd4" } }} - > - { - tabs.map((tab) => - <Tab label={tab} key={tab} - disabled={(tab === "Recursos" && learningObjArr.length === 0) || (tab === "Coleções" && collectionsArr.length === 0)} - /> - ) - } - </StyledTabs> - </NavBarContentContainer> - <ReportButton className="report-button" complainableId={userData.id} complainableType={"User"} /> - </RodapeDiv> - </UserProfileContainer> - </div> + return ( + <React.Fragment> + <link href="https://fonts.googleapis.com/css?family=Roboto:100,400,500&display=swap" rel="stylesheet" /> + <BackgroundDiv> + <CustomizedBreadcrumbs + values={["Usuário Público", tabs[tabValue]]} + /> + <Grid container spacing={2}> + <Grid item xs={12}> + <div style={{ padding: "10px 0 8px 0" }}> + <UserProfileContainer> + <HeaderContainer> + <> + {!loading && <RenderFollowContainer followed={userData.followed} id={id} followCount={userData.follows_count} />} + {RenderProfileAvatar(userData.avatar ? userData.avatar : undefined)} + <CoverContainer> + {userData.cover && <img src={apiDomain + userData.cover} alt='' style={{ width: "100%", height: "100%", objectFit: "cover" }} />} + </CoverContainer> + { + WIDTH <= 501 ? null : RenderUserProfileInfo(userData.name) + } + </> + </HeaderContainer> + { + WIDTH <= 501 ? + <Grid style={{ marginTop: '4em' }} container justify="center" alignItems="center" direction="column"> + <Grid item> + <Typography variant="h4" gutterBottom style={{ textAlign: "center" }}> + { + userData.name + } + </Typography> + </Grid> + <Grid style={{ marginTop: '0.5em', marginBottom: '0.5em', borderTop: "0.5px solid #DCDCDC", borderBottom: "0.5px solid #DCDCDC" }} container spacing={4} justify="center" alignItems="center" direction="row"> + <Grid item> + <Typography variant="h6" > + { + loading ? + <CircularProgress size={20} /> : + `${userData.follows_count} seguidores` + } + </Typography> + </Grid> + <Grid item> + <Typography variant="h6" > + { + loading ? + <CircularProgress size={20} /> : + following ? + `${following.length} seguindo` : + "0 seguindo" + } + </Typography> + </Grid> + </Grid> </Grid> + : + RenderCheckTeacher(userData.submitter_request)} + <RodapeDiv> + <NavBarContentContainer> + <StyledTabs + value={tabValue} + onChange={handleChangeTab} + indicatorColor="primary" + textColor="primary" + variant="fullwidth" + scrollButtons="desktop" + TabIndicatorProps={{ style: { background: "#00bcd4" } }} + > + { + tabs.map((tab) => + <Tab label={tab} key={tab} + disabled={(tab === "Recursos" && learningObjArr.length === 0) || (tab === "Coleções" && collectionsArr.length === 0)} + /> + ) + } + </StyledTabs> + </NavBarContentContainer> + <ReportButton className="report-button" complainableId={userData.id} complainableType={"User"} /> + </RodapeDiv> + </UserProfileContainer> + </div> + </Grid> - <Grid item xs={12}> - {tabValue === 0 && - <TabInicio id={id} user={userData} learningObjs={learningObjArr} collections={collectionsArr} />} - {tabValue === 1 && - <TabRecursos count={userData.learning_objects_count} learningObjs={learningObjArr} id={id} />} - {tabValue === 2 && - <TabColecoes count={userData.collections_count} collections={collectionsArr} - />} - {tabValue === 3 && - <TabRede id={id} username={userData.name} />} + <Grid item xs={12}> + {tabValue === 0 && + <TabInicio id={id} user={userData} learningObjs={learningObjArr} collections={collectionsArr} />} + {tabValue === 1 && + <TabRecursos count={userData.learning_objects_count} learningObjs={learningObjArr} id={id} />} + {tabValue === 2 && + <TabColecoes count={userData.collections_count} collections={collectionsArr} + />} + {tabValue === 3 && + <TabRede id={id} username={userData.name} />} - </Grid> - </Grid> - </BackgroundDiv> - </React.Fragment> - ) + </Grid> + </Grid> + </BackgroundDiv> + </React.Fragment> + ) } @@ -286,4 +288,4 @@ const FollowContainer = styled.div` right : 0; position : absolute; z-index : 1; -` +` \ No newline at end of file diff --git a/src/Pages/Search.js b/src/Pages/Search.js index 16b2111af2e2c9b79a580ec39d72ae9e59be8498..59c24ee39f9e043c024923372cf32ac141889bf3 100644 --- a/src/Pages/Search.js +++ b/src/Pages/Search.js @@ -81,7 +81,6 @@ export default function Search(props) { if (currOption === "LearningObject") setResultsResource(data); else if (currOption === "Collection") setResultsCollection(data); else if (currOption === "User") setResultsUser(data); - setOptionResult(option); dispatch({ type: "SAVE_SEARCH", newSearch: { @@ -93,7 +92,6 @@ export default function Search(props) { setTotalResults(headers.get('X-Total-Count')); } setShowingResults(data.length) - setOptionResult(currOption); setIsLoading(false); setIsFiltering(false); setLoadingMoreData(false); @@ -127,7 +125,9 @@ export default function Search(props) { }, }); } - + currOption = searchClass + setOption(searchClass) + setOptionResult(searchClass) collectStuff(searchClass) return () => @@ -135,7 +135,7 @@ export default function Search(props) { type: "HANDLE_SEARCH_BAR", opened: false, }); - }, [window.history.state.key]) + }, [window.history.state.key, state.currentUser.id]) useEffect(() => { setIsLoading(true); @@ -337,9 +337,9 @@ export default function Search(props) { </Grid> </Grid> <Grid item xs={12} md={10}> - <Grid container direction="row" justify="center" alignItems="center" style={{height: "100%", width:"100%" }}> + <Grid container direction="row" justify="center" alignItems="center" style={{ height: "100%", width: "100%" }}> <Grid> - <img src={RecursoVazio} alt="coleção vazia"/> + <img src={RecursoVazio} alt="coleção vazia" /> </Grid> </Grid> </Grid> diff --git a/src/Pages/UserPage.js b/src/Pages/UserPage.js index 6882eb50f7ef17bb2f96af0732efd52f33371e4a..da97c43e1f7d0a75be524b76168c8e666125a584 100644 --- a/src/Pages/UserPage.js +++ b/src/Pages/UserPage.js @@ -30,13 +30,13 @@ import TabPanelRede from "../Components/TabPanels/UserPageTabs/PanelRede.js"; import TabPanelCuradoria from "../Components/TabPanels/UserPageTabs/PanelCuradoria.js"; import Grid from "@material-ui/core/Grid"; import { - HeaderContainer, - UserProfileContainer, - CheckTeacherDiv, - StyledTabs, - RodapeDiv, - NavBarContentContainer, - BackgroundDiv, + HeaderContainer, + UserProfileContainer, + CheckTeacherDiv, + StyledTabs, + RodapeDiv, + NavBarContentContainer, + BackgroundDiv, } from "../Components/TabPanels/StyledComponents.js"; import CircularProgress from "@material-ui/core/CircularProgress"; import Cover from "../Components/UserPageComponents/Cover.js"; @@ -48,201 +48,205 @@ import { getRequest } from "../Components/HelperFunctions/getAxiosConfig.js"; import Typography from "@material-ui/core/Typography"; export default function UserPage(props) { - const { state, dispatch } = useContext(Store); - const id = state.currentUser.id; + const { state, dispatch } = useContext(Store); + const id = state.currentUser.id; - const [follows, setFollows] = useState(0); - const [following, setFollowing] = useState(0); - const [loading, setLoading] = useState(false); + const [follows, setFollows] = useState(0); + const [following, setFollowing] = useState(0); + const [loading, setLoading] = useState(false); - const [tabValue, setTabValue] = useState(Number(props.location.state) || 0); - const [tabs, setTabs] = useState([ + const [tabValue, setTabValue] = useState(Number(props.location.state) || 0); + const [tabs, setTabs] = useState([ + "Atividades", + "Meus Recursos", + "Favoritos", + "Coleções", + "Rede", + ]); + const handleChangeTab = (event, newValue) => { + setTabValue(newValue); + }; + + function handleSuccessfulGet(data) { + console.log(data); + dispatch({ + type: "GET_USER", + user: data, + }); + + setFollows(data.follows_count); + + if (data.role_ids.includes(4)) { + setTabs([ "Atividades", "Meus Recursos", "Favoritos", "Coleções", "Rede", - ]); - const handleChangeTab = (event, newValue) => { - setTabValue(newValue); - }; - - function handleSuccessfulGet(data) { - console.log(data); - dispatch({ - type: "GET_USER", - user: data, - }); - - setFollows(data.follows_count); - - if (data.role_ids.includes(4)) { - setTabs([ - "Atividades", - "Meus Recursos", - "Favoritos", - "Coleções", - "Rede", - "Curadoria", - ]); - } + "Curadoria", + ]); } + } + + function handleSuccesGetFollowing(data) { + setFollowing(data.length); + setLoading(false); + } - function handleSuccesGetFollowing(data) { - setFollowing(data.length); - setLoading(false); + useEffect(() => { + if (id !== "") { + const url = `/users/${id}`; + const url2 = `/users/${id}/following/User`; + setLoading(true); + getRequest(url, handleSuccessfulGet, (error) => { + console.log(error); + }); + getRequest(url2, handleSuccesGetFollowing, (error) => { + console.log(error); + }); } + }, []); + + useEffect(() => { + setTabValue(Number(props.location.state)) + }, [window.history.state.key]) + + const redirect = () => { + props.history.push("/"); + }; + + const [modalOpen, toggleModal] = useState(false); + const WIDTH = window.innerWidth; + + return ( + <div> + <link + href="https://fonts.googleapis.com/css?family=Roboto:100,400,500&display=swap" + rel="stylesheet" + /> + { + state.userIsLoggedIn ? ( + [ + <React.Fragment> + <ModalAlterarAvatar + open={modalOpen} + handleClose={() => { + toggleModal(false); + }} + userAvatar={state.currentUser.avatar} + /> - useEffect(() => { - if (id !== "") { - const url = `/users/${id}`; - const url2 = `/users/${id}/following/User`; - setLoading(true); - getRequest(url, handleSuccessfulGet, (error) => { - console.log(error); - }); - getRequest(url2, handleSuccesGetFollowing, (error) => { - console.log(error); - }); - } - }, []); - - const redirect = () => { - props.history.push("/"); - }; - - const [modalOpen, toggleModal] = useState(false); - const WIDTH = window.innerWidth; - - return ( - <div> - <link - href="https://fonts.googleapis.com/css?family=Roboto:100,400,500&display=swap" - rel="stylesheet" - /> - { - state.userIsLoggedIn ? ( - [ - <React.Fragment> - <ModalAlterarAvatar - open={modalOpen} - handleClose={() => { - toggleModal(false); - }} - userAvatar={state.currentUser.avatar} - /> - - <BackgroundDiv> - <CustomizedBreadcrumbs values={["Minha área", tabs[tabValue]]} /> - <Grid container spacing={2}> - <Grid item xs={12}> - <div style={{ padding: "10px 0 8px 0" }}> - <UserProfileContainer> - <HeaderContainer> - <Cover id={id} /> - <ProfileAvatar id={id} /> - {WIDTH <= 501 ? null : <UserInfo />} - <EditProfileButton /> - </HeaderContainer> - {WIDTH <= 501 ? ( - <Grid - style={{ marginTop: "4em" }} - container - justify="center" - alignItems="center" - direction="column" - > - <Grid item> - <Typography - variant="h4" - gutterBottom - style={{ textAlign: "center" }} - > - {state.currentUser.name} - </Typography> - </Grid> - <Grid - style={{ - marginTop: "0.5em", - marginBottom: "0.5em", - borderTop: "0.5px solid #eee", - borderBottom: "0.5px solid #eee", - }} - container - spacing={4} - justify="center" - alignItems="center" - direction="row" - > - <Grid item> - <Typography variant="h6" onClick={(e)=>{handleChangeTab(e, 4)}}> - {loading ? ( - <CircularProgress size={20} /> - ) : ( - `${follows} seguidores` - )} - </Typography> - </Grid> - <Grid item> - <Typography variant="h6" onClick={(e)=>{handleChangeTab(e, 4)}}> - {loading ? ( - <CircularProgress size={20} /> - ) : ( - `${following} seguindo` - )} - </Typography> - </Grid> - </Grid> - </Grid> - ) : ( - <CheckTeacherDiv> - <SubmitterStatus /> - </CheckTeacherDiv> - )} - <RodapeDiv> - <NavBarContentContainer> - <StyledTabs - value={tabValue} - onChange={handleChangeTab} - indicatorColor="primary" - textColor="primary" - variant="scrollable" - scrollButtons="auto" - TabIndicatorProps={{ - style: { background: "#00bcd4" }, - }} - > - {tabs.map((tab) => ( - <StyledTab label={tab} key={tab} /> - ))} - </StyledTabs> - </NavBarContentContainer> - </RodapeDiv> - </UserProfileContainer> - </div> - </Grid> - <Grid item xs={12}> - {tabValue === 0 && <TabPanelAtividades id={id} />} - {tabValue === 1 && <TabPanelMeusRecursos id={id} />} - {tabValue === 2 && <TabPanelFavoritos id={id} />} - {tabValue === 3 && <TabPanelColecoes id={id} />} - {tabValue === 4 && <TabPanelRede id={id} />} - {tabValue === 5 && <TabPanelCuradoria id={id} />} - </Grid> - </Grid> - </BackgroundDiv> - </React.Fragment> - ] - ) - : - ( - <> - { redirect() } - </> - ) - } - </div> - ) + <BackgroundDiv> + <CustomizedBreadcrumbs values={["Minha área", tabs[tabValue]]} /> + <Grid container spacing={2}> + <Grid item xs={12}> + <div style={{ padding: "10px 0 8px 0" }}> + <UserProfileContainer> + <HeaderContainer> + <Cover id={id} /> + <ProfileAvatar id={id} /> + {WIDTH <= 501 ? null : <UserInfo />} + <EditProfileButton /> + </HeaderContainer> + {WIDTH <= 501 ? ( + <Grid + style={{ marginTop: "4em" }} + container + justify="center" + alignItems="center" + direction="column" + > + <Grid item> + <Typography + variant="h4" + gutterBottom + style={{ textAlign: "center" }} + > + {state.currentUser.name} + </Typography> + </Grid> + <Grid + style={{ + marginTop: "0.5em", + marginBottom: "0.5em", + borderTop: "0.5px solid #eee", + borderBottom: "0.5px solid #eee", + }} + container + spacing={4} + justify="center" + alignItems="center" + direction="row" + > + <Grid item> + <Typography variant="h6" onClick={(e) => { handleChangeTab(e, 4) }}> + {loading ? ( + <CircularProgress size={20} /> + ) : ( + `${follows} seguidores` + )} + </Typography> + </Grid> + <Grid item> + <Typography variant="h6" onClick={(e) => { handleChangeTab(e, 4) }}> + {loading ? ( + <CircularProgress size={20} /> + ) : ( + `${following} seguindo` + )} + </Typography> + </Grid> + </Grid> + </Grid> + ) : ( + <CheckTeacherDiv> + <SubmitterStatus /> + </CheckTeacherDiv> + )} + <RodapeDiv> + <NavBarContentContainer> + <StyledTabs + value={tabValue} + onChange={handleChangeTab} + indicatorColor="primary" + textColor="primary" + variant="scrollable" + scrollButtons="auto" + TabIndicatorProps={{ + style: { background: "#00bcd4" }, + }} + > + {tabs.map((tab) => ( + <StyledTab label={tab} key={tab} /> + ))} + </StyledTabs> + </NavBarContentContainer> + </RodapeDiv> + </UserProfileContainer> + </div> + </Grid> + <Grid item xs={12}> + {tabValue === 0 && <TabPanelAtividades id={id} />} + {tabValue === 1 && <TabPanelMeusRecursos id={id} />} + {tabValue === 2 && <TabPanelFavoritos id={id} />} + {tabValue === 3 && <TabPanelColecoes id={id} />} + {tabValue === 4 && <TabPanelRede id={id} />} + {tabValue === 5 && <TabPanelCuradoria id={id} />} + </Grid> + </Grid> + </BackgroundDiv> + </React.Fragment> + ] + ) + : + ( + <> + {redirect()} + </> + ) + } + </div> + ) } const StyledTab = styled(Tab)`