frontend: Loader + Refactoring

This commit is contained in:
Divlo 2020-03-21 16:43:37 +01:00
parent a0fb5ee13a
commit 895d0c7f6b
8 changed files with 144 additions and 64 deletions

View File

@ -11,6 +11,12 @@
cursor: pointer;
transition: all .3s;
}
.FunctionCard__container {
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
}
.FunctionCard:hover {
transform: translateY(-7px);
}

View File

@ -1,20 +1,36 @@
import Link from 'next/link';
import { useState, Fragment } from 'react';
import Loader from '../Loader/Loader';
import './FunctionCard.css';
const FunctionCard = (props) => (
<Link href={`/functions/${props.slug}`}>
<div className="FunctionCard col-sm-24 col-md-10 col-xl-7">
<div className="FunctionCard__top">
<img className="FunctionCard__image" alt={props.title} src={props.image} />
<h2 className="FunctionCard__title">{props.title}</h2>
<p className="FunctionCard__description">{props.description}</p>
</div>
<div className="FunctionCard__info">
<p className="FunctionCard__category" style={{ backgroundColor: props.category.color }}>{props.category.name}</p>
<p className="FunctionCard__publication-date">{props.publicationDate}</p>
</div>
</div>
</Link>
);
const FunctionCard = (props) => {
const [isLoading, setIsLoading] = useState(true);
const handleLoad = () => {
setIsLoading(false);
}
return (
<Link href={`/functions/${props.slug}`}>
<Fragment>
<div className={"FunctionCard col-sm-24 col-md-10 col-xl-7"}>
{isLoading && <Loader width="100px" height="100px" />}
<div className={`FunctionCard__container ${isLoading ? "d-none" : ""}`}>
<div className="FunctionCard__top">
<img onLoad={handleLoad} className="FunctionCard__image" alt={props.title} src={props.image} />
<h2 className="FunctionCard__title">{props.title}</h2>
<p className="FunctionCard__description">{props.description}</p>
</div>
<div className="FunctionCard__info">
<p className="FunctionCard__category" style={{ backgroundColor: props.category.color }}>{props.category.name}</p>
<p className="FunctionCard__publication-date">{props.publicationDate}</p>
</div>
</div>
</div>
</Fragment>
</Link>
);
}
export default FunctionCard;

View File

@ -0,0 +1,13 @@
.Loader {
transform-origin: 50% 50%; animation: .9s linear 0s infinite normal forwards running Loader__spin;
}
@keyframes Loader__spin {
0% {
animation-timing-function: cubic-bezier(0.5856,0.0703,0.4143,0.9297);
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}

View File

@ -0,0 +1,11 @@
import './Loader.css';
const Loader = ({ width, height }) => (
<svg width={width} height={height} viewBox="0 0 100 100">
<g transform="translate(50 50) rotate(0) scale(1 1) translate(-50 -50)">
<image className="Loader" x="0" y="0" width="100" height="100" href="/images/FunctionProject_icon.png"></image>
</g>
</svg>
);
export default Loader;

31
frontend/hooks/useAPI.js Normal file
View File

@ -0,0 +1,31 @@
import { useEffect, useState } from 'react';
import api from '../config/api';
/**
* @param {String} url
* @param {*} defaultData
* @param {String} method
* @param {Object} options
*/
function useAPI(url, defaultData = [], method = "get", options = {}) {
const [isLoading, setIsLoading] = useState(true);
const [data, setData] = useState(defaultData);
const [hasError, setHasError] = useState(false);
useEffect(() => {
api[method](url, options)
.then((result) => {
setData(result.data);
setIsLoading(false);
})
.catch((error) => {
setHasError(true);
console.error(error);
});
}, []);
return [isLoading, data, hasError];
}
export default useAPI;

View File

@ -1,60 +1,50 @@
import { Fragment, useState, useEffect } from 'react';
import HeadTag from '../components/HeadTag';
import FunctionCard from '../components/FunctionCard/FunctionCard';
import Loader from '../components/Loader/Loader';
import '../public/css/pages/functions.css';
import { API_URL } from '../config/config';
import api from '../config/api';
import useAPI from '../hooks/useAPI';
const Functions = () => {
// State de recherche et de catégories
const [categories, setCategories] = useState([]);
const [, categories] = useAPI('/categories');
const [inputSearch, setInputSearch] = useState({ search: "", selectedCategory: "0" });
// State pour afficher les fonctions
const [functions, setFunctions] = useState([]);
const [functionsData, setFunctionsData] = useState({ hasMore: true, rows: [] });
const [isLoadingFunctions, setLoadingFunctions] = useState(true);
const [pageFunctions, setPageFunctions] = useState(1);
const [hasMoreFunctions, sethasMoreFunctions] = useState(false);
// Récupère les catégories
useEffect(() => {
api.get('/categories')
.then((result) => {
setCategories(result.data);
})
.catch((error) => console.error(error));
}, []);
const getFunctionsData = () => {
setLoadingFunctions(true);
return new Promise(async (next) => {
const result = await api.get(`/functions?page=${pageFunctions}&limit=10&categoryId=${inputSearch.selectedCategory}&search=${inputSearch.search}`);
setLoadingFunctions(false);
next(result.data);
});
}
// Récupère les fonctions si la page change
useEffect(() => {
api.get(`/functions?page=${pageFunctions}&limit=10&categoryId=${inputSearch.selectedCategory}&search=${inputSearch.search}`)
.then((result) => {
setLoadingFunctions(false);
sethasMoreFunctions(result.data.hasMore);
setFunctions([...functions, ...result.data.rows]);
})
.catch((error) => console.error(error));
getFunctionsData().then((data) => setFunctionsData({
hasMore: data.hasMore,
rows: [...functionsData.rows, ...data.rows]
}));
}, [pageFunctions]);
// Récupère les fonctions si la catégorie/recherche change
useEffect(() => {
api.get(`/functions?page=${pageFunctions}&limit=10&categoryId=${inputSearch.selectedCategory}&search=${inputSearch.search}`)
.then((result) => {
setLoadingFunctions(false);
sethasMoreFunctions(result.data.hasMore);
setFunctions(result.data.rows);
})
.catch((error) => console.error(error));
getFunctionsData().then((data) => setFunctionsData(data));
}, [inputSearch.selectedCategory, inputSearch.search]);
const loadMore = () => {
setLoadingFunctions(true);
setPageFunctions(pageFunctions + 1);
}
const handleChange = (event) => {
setLoadingFunctions(true);
const inputSearchNew = { ...inputSearch };
inputSearchNew[event.target.name] = event.target.value;
setInputSearch(inputSearchNew);
@ -72,7 +62,7 @@ const Functions = () => {
<div className="row justify-content-center">
<h1 className="Functions__title">Fonctions</h1>
</div>
<div className="Functions__search-container row justify-content-center">
<select name="selectedCategory" value={inputSearch.selectedCategory} onChange={handleChange} className="Functions__select form-control">
<option value="0">Toutes catégories</option>
@ -84,18 +74,19 @@ const Functions = () => {
</div>
<div className="row justify-content-center">
{functions.map((f) => (
{functionsData.rows.map((f) => (
<FunctionCard key={f.id} slug={f.slug} image={API_URL + f.image} title={f.title} description={f.description} category={f.categorie} publicationDate={new Date(f.createdAt).toLocaleDateString('fr-FR')} />
))}
</div>
{
!isLoadingFunctions && hasMoreFunctions
?
<button className="btn btn-dark" onClick={loadMore}>Charger plus de fonctions ?</button>
: !hasMoreFunctions ?
null
{
isLoadingFunctions ?
<Loader width="100px" height="100px" />
: functionsData.hasMore ?
<div className="row justify-content-center">
<button className="btn btn-dark" style={{marginBottom: "50px"}} onClick={loadMore}>Charger plus de fonctions ?</button>
</div>
:
<p>Chargement...</p>
null
}
</div>
</Fragment>

View File

@ -1,16 +1,25 @@
import { Fragment } from 'react';
import { Fragment, useEffect } from 'react';
import HeadTag from '../components/HeadTag';
const Home = () => (
<Fragment>
<HeadTag
title="FunctionProject"
description="FunctionProject est un projet créé par Divlo qui a pour but de rassembler plein de mini-programme permettant de faire plusieurs choses comme savoir la météo, générer un nombre aléatoire, etc."
image="/images/FunctionProject_icon_small.png"
/>
<div>Home</div>
{console.log('%c ⚙️ FunctionProject', 'color: #ffd800; font-weight: bold; background-color: #181818;padding: 10px;border-radius: 10px;font-size: 20px')}
</Fragment>
);
const Home = () => {
useEffect(() => {
console.log(
'%c ⚙️ FunctionProject',
'color: #ffd800; font-weight: bold; background-color: #181818;padding: 10px;border-radius: 10px;font-size: 20px'
);
}, []);
return (
<Fragment>
<HeadTag
title="FunctionProject"
description="FunctionProject est un projet créé par Divlo qui a pour but de rassembler plein de mini-programme permettant de faire plusieurs choses comme savoir la météo, générer un nombre aléatoire, etc."
image="/images/FunctionProject_icon_small.png"
/>
<div>Home</div>
</Fragment>
);
}
export default Home;

View File

@ -60,6 +60,9 @@ a, .important {
color: var(--important);
text-decoration: none;
}
.d-none {
display: none !important;
}
.form-control {
display: block;
height: calc(1.5em + .75rem + 2px);