🎨 Configure standardJS
This commit is contained in:
1
website/.env.example
Normal file
1
website/.env.example
Normal file
@ -0,0 +1 @@
|
||||
NEXT_PUBLIC_API_URL = "http://localhost:8080"
|
2
website/.gitignore
vendored
2
website/.gitignore
vendored
@ -17,7 +17,7 @@
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env*
|
||||
.env
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
|
@ -1,12 +1,12 @@
|
||||
import SyntaxHighlighter from "react-syntax-highlighter";
|
||||
import { atomOneDark as styles} from "react-syntax-highlighter/dist/cjs/styles/hljs";
|
||||
import SyntaxHighlighter from 'react-syntax-highlighter'
|
||||
import { atomOneDark as styles } from 'react-syntax-highlighter/dist/cjs/styles/hljs'
|
||||
|
||||
const CodeBlock = ({ language, value }) => {
|
||||
return (
|
||||
<SyntaxHighlighter language={language} style={styles}>
|
||||
{value}
|
||||
</SyntaxHighlighter>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<SyntaxHighlighter language={language} style={styles}>
|
||||
{value}
|
||||
</SyntaxHighlighter>
|
||||
)
|
||||
}
|
||||
|
||||
export default CodeBlock;
|
||||
export default CodeBlock
|
||||
|
@ -1,16 +1,16 @@
|
||||
import Link from 'next/link';
|
||||
import './Footer.css';
|
||||
import Link from 'next/link'
|
||||
import './Footer.css'
|
||||
|
||||
export default function Footer() {
|
||||
return (
|
||||
<footer className="footer">
|
||||
<p className="footer-text text-center">
|
||||
<Link href={"/about"}>
|
||||
<a>FunctionProject</a>
|
||||
</Link>
|
||||
- Version 2.0 <br/>
|
||||
<a href="https://divlo.fr/" target="_blank" rel="noopener noreferrer">Divlo</a> | Tous droits réservés
|
||||
</p>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
export default function Footer () {
|
||||
return (
|
||||
<footer className='footer'>
|
||||
<p className='footer-text text-center'>
|
||||
<Link href='/about'>
|
||||
<a>FunctionProject</a>
|
||||
</Link>
|
||||
- Version 2.0 <br />
|
||||
<a href='https://divlo.fr/' target='_blank' rel='noopener noreferrer'>Divlo</a> | Tous droits réservés
|
||||
</p>
|
||||
</footer>
|
||||
)
|
||||
}
|
||||
|
@ -1,129 +1,126 @@
|
||||
import { Fragment, useState, useEffect } from 'react';
|
||||
import htmlParser from 'html-react-parser';
|
||||
import Loader from '../../components/Loader';
|
||||
import useAPI from '../../hooks/useAPI';
|
||||
import api from '../../utils/api';
|
||||
import '../../public/css/pages/admin.css';
|
||||
import { useState, useEffect } from 'react'
|
||||
import htmlParser from 'html-react-parser'
|
||||
import Loader from '../../components/Loader'
|
||||
import useAPI from '../../hooks/useAPI'
|
||||
import api from '../../utils/api'
|
||||
import '../../public/css/pages/admin.css'
|
||||
|
||||
const AddEditFunction = (props) => {
|
||||
const [, categories] = useAPI('/categories')
|
||||
const [inputState, setInputState] = useState(props.defaultInputState)
|
||||
const [message, setMessage] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const [, categories] = useAPI('/categories');
|
||||
const [inputState, setInputState] = useState(props.defaultInputState);
|
||||
const [message, setMessage] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (categories.length > 0 && !props.isEditing) {
|
||||
handleChange({
|
||||
target: {
|
||||
name: "categorieId",
|
||||
value: categories[0].id
|
||||
}
|
||||
});
|
||||
useEffect(() => {
|
||||
if (categories.length > 0 && !props.isEditing) {
|
||||
handleChange({
|
||||
target: {
|
||||
name: 'categorieId',
|
||||
value: categories[0].id
|
||||
}
|
||||
}, [categories]);
|
||||
})
|
||||
}
|
||||
}, [categories])
|
||||
|
||||
const apiCallFunction = (formData) => {
|
||||
if (props.isEditing) return api.put(`/admin/functions/${inputState.id}`, formData, { headers: { 'Authorization': props.user.token } });
|
||||
return api.post('/admin/functions', formData, { headers: { 'Authorization': props.user.token } });
|
||||
const apiCallFunction = (formData) => {
|
||||
if (props.isEditing) return api.put(`/admin/functions/${inputState.id}`, formData, { headers: { Authorization: props.user.token } })
|
||||
return api.post('/admin/functions', formData, { headers: { Authorization: props.user.token } })
|
||||
}
|
||||
|
||||
const handleChange = (event, isTypeCheck = false) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = (event.target.files != null) ? event.target.files[0] : (isTypeCheck) ? event.target.checked : event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
event.preventDefault()
|
||||
setIsLoading(true)
|
||||
const formData = new window.FormData()
|
||||
formData.append('type', inputState.type)
|
||||
formData.append('categorieId', inputState.categorieId)
|
||||
formData.append('title', inputState.title)
|
||||
formData.append('slug', inputState.slug)
|
||||
formData.append('description', inputState.description)
|
||||
formData.append('image', inputState.image)
|
||||
|
||||
if (props.isEditing) {
|
||||
formData.append('isOnline', inputState.isOnline)
|
||||
}
|
||||
|
||||
const handleChange = (event, isTypeCheck = false) => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = (event.target.files != undefined) ? event.target.files[0] : (isTypeCheck) ? event.target.checked : event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
}
|
||||
apiCallFunction(formData)
|
||||
.then(() => {
|
||||
setIsLoading(false)
|
||||
window.location.reload(true)
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`)
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
event.preventDefault();
|
||||
setIsLoading(true);
|
||||
const formData = new FormData();
|
||||
formData.append('type', inputState.type);
|
||||
formData.append('categorieId', inputState.categorieId);
|
||||
formData.append('title', inputState.title);
|
||||
formData.append('slug', inputState.slug);
|
||||
formData.append('description', inputState.description);
|
||||
formData.append('image', inputState.image);
|
||||
return (
|
||||
<>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='title'>Titre :</label>
|
||||
<input value={inputState.title} onChange={handleChange} type='text' name='title' id='title' className='form-control' placeholder='(e.g : Nombre aléatoire)' />
|
||||
</div>
|
||||
|
||||
if (props.isEditing) {
|
||||
formData.append('isOnline', inputState.isOnline);
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='slug'>Slug :</label>
|
||||
<input value={inputState.slug} onChange={handleChange} type='text' name='slug' id='slug' className='form-control' placeholder='(e.g : randomNumber)' />
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='description'>Description :</label>
|
||||
<textarea style={{ height: 'auto' }} value={inputState.description} onChange={handleChange} name='description' id='description' className='form-control' rows='5' />
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='type'>Type :</label>
|
||||
<select onChange={handleChange} name='type' id='type' className='form-control' {...(props.isEditing) && { value: inputState.type }}>
|
||||
<option value='form'>Formulaire</option>
|
||||
<option value='article'>Article</option>
|
||||
<option value='page'>Page</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='categorieId'>Catégorie :</label>
|
||||
<select onChange={handleChange} name='categorieId' id='categorieId' className='form-control' {...(props.isEditing) && { value: inputState.categorieId }}>
|
||||
{categories.map((category) => (
|
||||
<option key={category.id} value={category.id} className='Admin__Modal-select-option' style={{ backgroundColor: category.color }}>{category.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='image'>Image <em>(150x150 recommandé)</em> :</label>
|
||||
<br />
|
||||
<input onChange={handleChange} accept='image/jpeg,image/jpg,image/png' type='file' name='image' id='image' />
|
||||
</div>
|
||||
|
||||
{(props.isEditing) &&
|
||||
<div className='form-group custom-control custom-switch'>
|
||||
<input onChange={(event) => handleChange(event, true)} type='checkbox' name='isOnline' checked={inputState.isOnline} className='custom-control-input' id='isOnline' />
|
||||
<label className='custom-control-label' htmlFor='isOnline'>isOnline</label>
|
||||
</div>}
|
||||
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className='form-result text-center'>
|
||||
{
|
||||
(isLoading)
|
||||
? <Loader />
|
||||
: htmlParser(message)
|
||||
}
|
||||
|
||||
apiCallFunction(formData)
|
||||
.then(() => {
|
||||
setIsLoading(false);
|
||||
window.location.reload(true);
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
|
||||
setIsLoading(false);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="title">Titre :</label>
|
||||
<input value={inputState.title} onChange={handleChange} type="text" name="title" id="title" className="form-control" placeholder="(e.g : Nombre aléatoire)" />
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="slug">Slug :</label>
|
||||
<input value={inputState.slug} onChange={handleChange} type="text" name="slug" id="slug" className="form-control" placeholder="(e.g : randomNumber)" />
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="description">Description :</label>
|
||||
<textarea style={{ height: 'auto' }} value={inputState.description} onChange={handleChange} name="description" id="description" className="form-control" rows="5"></textarea>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="type">Type :</label>
|
||||
<select onChange={handleChange} name="type" id="type" className="form-control" { ...(props.isEditing) && { value: inputState.type } }>
|
||||
<option value="form">Formulaire</option>
|
||||
<option value="article">Article</option>
|
||||
<option value="page">Page</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="categorieId">Catégorie :</label>
|
||||
<select onChange={handleChange} name="categorieId" id="categorieId" className="form-control" { ...(props.isEditing) && { value: inputState.categorieId } }>
|
||||
{categories.map((category) => (
|
||||
<option key={category.id} value={category.id} className="Admin__Modal-select-option" style={{ backgroundColor: category.color }}>{category.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="image">Image <em>(150x150 recommandé)</em> :</label>
|
||||
<br/>
|
||||
<input onChange={handleChange} accept="image/jpeg,image/jpg,image/png" type="file" name="image" id="image" />
|
||||
</div>
|
||||
|
||||
{(props.isEditing) &&
|
||||
<div className="form-group custom-control custom-switch">
|
||||
<input onChange={(event) => handleChange(event, true)} type="checkbox" name="isOnline" checked={inputState.isOnline} className="custom-control-input" id="isOnline" />
|
||||
<label className="custom-control-label" htmlFor="isOnline">isOnline</label>
|
||||
</div>
|
||||
}
|
||||
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="form-result text-center">
|
||||
{
|
||||
(isLoading) ?
|
||||
<Loader />
|
||||
:
|
||||
htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default AddEditFunction;
|
||||
export default AddEditFunction
|
||||
|
@ -1,46 +1,45 @@
|
||||
import { useState } from 'react';
|
||||
import dynamic from 'next/dynamic';
|
||||
import { complex } from '../../utils/sunEditorConfig';
|
||||
import api from '../../utils/api';
|
||||
import FunctionArticle from '../FunctionPage/FunctionArticle';
|
||||
import 'notyf/notyf.min.css';
|
||||
import '../../public/css/suneditor.min.css';
|
||||
import { useState } from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { complex } from '../../utils/sunEditorConfig'
|
||||
import api from '../../utils/api'
|
||||
import FunctionArticle from '../FunctionPage/FunctionArticle'
|
||||
import 'notyf/notyf.min.css'
|
||||
import '../../public/css/suneditor.min.css'
|
||||
|
||||
const SunEditor = dynamic(
|
||||
() => import('suneditor-react'),
|
||||
{ ssr: false }
|
||||
);
|
||||
() => import('suneditor-react'),
|
||||
{ ssr: false }
|
||||
)
|
||||
|
||||
const EditArticleFunction = (props) => {
|
||||
const [htmlContent, setHtmlContent] = useState('')
|
||||
|
||||
const [htmlContent, setHtmlContent] = useState("");
|
||||
const handleEditorChange = (content) => {
|
||||
setHtmlContent(content)
|
||||
}
|
||||
|
||||
const handleEditorChange = (content) => {
|
||||
setHtmlContent(content);
|
||||
const handleSave = async (content) => {
|
||||
let Notyf
|
||||
if (typeof window !== 'undefined') {
|
||||
Notyf = require('notyf')
|
||||
}
|
||||
|
||||
const handleSave = async (content) => {
|
||||
let Notyf;
|
||||
if (typeof window != 'undefined') {
|
||||
Notyf = require('notyf');
|
||||
}
|
||||
const notyf = new Notyf.Notyf({
|
||||
duration: 5000
|
||||
});
|
||||
try {
|
||||
await api.put(`/admin/functions/article/${props.functionInfo.id}`, { article: content }, { headers: { 'Authorization': props.user.token } });
|
||||
notyf.success('Sauvegardé!');
|
||||
} catch {
|
||||
notyf.error('Erreur!');
|
||||
}
|
||||
const notyf = new Notyf.Notyf({
|
||||
duration: 5000
|
||||
})
|
||||
try {
|
||||
await api.put(`/admin/functions/article/${props.functionInfo.id}`, { article: content }, { headers: { Authorization: props.user.token } })
|
||||
notyf.success('Sauvegardé!')
|
||||
} catch {
|
||||
notyf.error('Erreur!')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
<SunEditor setContents={props.functionInfo.article} lang="fr" onChange={handleEditorChange} setOptions={{ buttonList: complex, callBackSave: handleSave }} />
|
||||
<FunctionArticle article={htmlContent} />
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className='container-fluid'>
|
||||
<SunEditor setContents={props.functionInfo.article} lang='fr' onChange={handleEditorChange} setOptions={{ buttonList: complex, callBackSave: handleSave }} />
|
||||
<FunctionArticle article={htmlContent} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default EditArticleFunction;
|
||||
export default EditArticleFunction
|
||||
|
@ -1,158 +1,154 @@
|
||||
import { useState, Fragment } from 'react';
|
||||
import api from '../../utils/api';
|
||||
import 'notyf/notyf.min.css';
|
||||
import { useState } from 'react'
|
||||
import api from '../../utils/api'
|
||||
import 'notyf/notyf.min.css'
|
||||
|
||||
const EditFormFunction = (props) => {
|
||||
const [inputsArray, setInputsArray] = useState(props.functionInfo.utilizationForm || [])
|
||||
|
||||
const [inputsArray, setInputsArray] = useState(props.functionInfo.utilizationForm || []);
|
||||
const addInput = () => {
|
||||
const newInputsArray = [...inputsArray]
|
||||
newInputsArray.push({ name: '', label: '', placeholder: '', type: 'text' })
|
||||
setInputsArray(newInputsArray)
|
||||
}
|
||||
|
||||
const addInput = () => {
|
||||
const newInputsArray = [...inputsArray];
|
||||
newInputsArray.push({ name: "", label: "", placeholder: "", type: "text" });
|
||||
setInputsArray(newInputsArray);
|
||||
const addOption = (event) => {
|
||||
const newInputsArray = [...inputsArray]
|
||||
const index = event.target.id.split('-')[1]
|
||||
const inputObject = newInputsArray[index]
|
||||
inputObject.options.push({ name: '', value: '' })
|
||||
setInputsArray(newInputsArray)
|
||||
}
|
||||
|
||||
const handleChangeOption = (inputIndex, optionIndex, event) => {
|
||||
const newInputsArray = [...inputsArray]
|
||||
const inputObject = newInputsArray[inputIndex]
|
||||
const optionObject = inputObject.options[optionIndex]
|
||||
optionObject[event.target.name] = event.target.value
|
||||
setInputsArray(newInputsArray)
|
||||
}
|
||||
|
||||
const handleChangeInput = (event) => {
|
||||
const newInputsArray = [...inputsArray]
|
||||
const index = event.target.id.split('-')[1]
|
||||
const inputObject = newInputsArray[index]
|
||||
inputObject[event.target.name] = event.target.value
|
||||
if (event.target.value === 'select') {
|
||||
inputObject.options = []
|
||||
}
|
||||
setInputsArray(newInputsArray)
|
||||
}
|
||||
|
||||
const addOption = (event) => {
|
||||
const newInputsArray = [...inputsArray];
|
||||
const index = event.target.id.split('-')[1];
|
||||
const inputObject = newInputsArray[index];
|
||||
inputObject.options.push({ name: "", value: "" });
|
||||
setInputsArray(newInputsArray);
|
||||
const handleSubmit = async (event) => {
|
||||
event.preventDefault()
|
||||
let Notyf
|
||||
if (typeof window !== 'undefined') {
|
||||
Notyf = require('notyf')
|
||||
}
|
||||
|
||||
const handleChangeOption = (inputIndex, optionIndex, event) => {
|
||||
const newInputsArray = [...inputsArray];
|
||||
const inputObject = newInputsArray[inputIndex];
|
||||
const optionObject = inputObject.options[optionIndex];
|
||||
optionObject[event.target.name] = event.target.value;
|
||||
setInputsArray(newInputsArray);
|
||||
const notyf = new Notyf.Notyf({
|
||||
duration: 5000
|
||||
})
|
||||
try {
|
||||
await api.put(`/admin/functions/form/${props.functionInfo.id}`, { form: inputsArray }, { headers: { Authorization: props.user.token } })
|
||||
notyf.success('Sauvegardé!')
|
||||
} catch (error) {
|
||||
notyf.error('Erreur!')
|
||||
}
|
||||
}
|
||||
|
||||
const handleChangeInput = (event) => {
|
||||
const newInputsArray = [...inputsArray];
|
||||
const index = event.target.id.split('-')[1];
|
||||
const inputObject = newInputsArray[index];
|
||||
inputObject[event.target.name] = event.target.value;
|
||||
if (event.target.value === "select") {
|
||||
inputObject.options = [];
|
||||
}
|
||||
setInputsArray(newInputsArray);
|
||||
}
|
||||
const handleRemoveInput = (event) => {
|
||||
const newInputsArray = [...inputsArray]
|
||||
const index = event.target.id.split('-')[1]
|
||||
newInputsArray.splice(index, 1)
|
||||
setInputsArray(newInputsArray)
|
||||
}
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
let Notyf;
|
||||
if (typeof window != 'undefined') {
|
||||
Notyf = require('notyf');
|
||||
}
|
||||
const notyf = new Notyf.Notyf({
|
||||
duration: 5000
|
||||
});
|
||||
try {
|
||||
await api.put(`/admin/functions/form/${props.functionInfo.id}`, { form: inputsArray }, { headers: { 'Authorization': props.user.token } });
|
||||
notyf.success('Sauvegardé!');
|
||||
} catch (error) {
|
||||
notyf.error('Erreur!');
|
||||
}
|
||||
}
|
||||
const handleRemoveOption = (inputIndex, optionIndex) => {
|
||||
const newInputsArray = [...inputsArray]
|
||||
const inputObject = newInputsArray[inputIndex]
|
||||
const optionsArray = inputObject.options
|
||||
optionsArray.splice(optionIndex, 1)
|
||||
setInputsArray(newInputsArray)
|
||||
}
|
||||
|
||||
const handleRemoveInput = (event) => {
|
||||
const newInputsArray = [...inputsArray];
|
||||
const index = event.target.id.split('-')[1];
|
||||
newInputsArray.splice(index, 1);
|
||||
setInputsArray(newInputsArray);
|
||||
}
|
||||
return (
|
||||
<div className='container-fluid'>
|
||||
|
||||
const handleRemoveOption = (inputIndex, optionIndex) => {
|
||||
const newInputsArray = [...inputsArray];
|
||||
const inputObject = newInputsArray[inputIndex];
|
||||
const optionsArray = inputObject.options;
|
||||
optionsArray.splice(optionIndex, 1);
|
||||
setInputsArray(newInputsArray);
|
||||
}
|
||||
<form onSubmit={handleSubmit}>
|
||||
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
{(inputsArray.length > 0) &&
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Sauvegarder</button>
|
||||
</div>}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
{inputsArray.map((input, index) => {
|
||||
return (
|
||||
<div key={index} className='form-group Admin__Input-group'>
|
||||
|
||||
{(inputsArray.length > 0) &&
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Sauvegarder</button>
|
||||
</div>
|
||||
}
|
||||
<div className='text-center'>
|
||||
<button type='button' onClick={handleRemoveInput} id={`remove-${index}`} className='btn btn-dark'>Supprimer l'input</button>
|
||||
</div>
|
||||
|
||||
{inputsArray.map((input, index) => {
|
||||
<label className='form-label' htmlFor={`name-${index}`}>Nom de l'input :</label>
|
||||
<input value={input.name} onChange={handleChangeInput} type='text' name='name' id={`name-${index}`} className='form-control' placeholder='(e.g : cityName)' />
|
||||
<br />
|
||||
|
||||
<label className='form-label' htmlFor={`label-${index}`}>Label :</label>
|
||||
<input value={input.label} onChange={handleChangeInput} type='text' name='label' id={`label-${index}`} className='form-control' placeholder="(e.g : Entrez le nom d'une ville :)" />
|
||||
<br />
|
||||
|
||||
{(input.type !== 'select') &&
|
||||
<>
|
||||
<label className='form-label' htmlFor={`placeholder-${index}`}>Placeholder :</label>
|
||||
<input value={input.placeholder} onChange={handleChangeInput} type='text' name='placeholder' id={`placeholder-${index}`} className='form-control' placeholder='(e.g : Paris, FR)' />
|
||||
<br />
|
||||
</>}
|
||||
|
||||
<label className='form-label' htmlFor={`type-${index}`}>Type :</label>
|
||||
<select value={input.type} onChange={handleChangeInput} name='type' id={`type-${index}`} className='form-control'>
|
||||
<option value='text'>text</option>
|
||||
<option value='integer'>Number integer</option>
|
||||
<option value='float'>Number float</option>
|
||||
<option value='calendar'>calendar</option>
|
||||
<option value='select'>select</option>
|
||||
</select>
|
||||
|
||||
{(input.type === 'select') &&
|
||||
<div style={{ marginTop: '50px' }}>
|
||||
|
||||
<label className='form-label'>Options :</label>
|
||||
|
||||
{input.options.map((option, optionIndex) => {
|
||||
return (
|
||||
<div key={index} className="form-group Admin__Input-group">
|
||||
|
||||
<div className="text-center">
|
||||
<button type="button" onClick={handleRemoveInput} id={`remove-${index}`} className="btn btn-dark">Supprimer l'input</button>
|
||||
</div>
|
||||
|
||||
<label className="form-label" htmlFor={`name-${index}`}>Nom de l'input :</label>
|
||||
<input value={input.name} onChange={handleChangeInput} type="text" name="name" id={`name-${index}`} className="form-control" placeholder="(e.g : cityName)" />
|
||||
<br/>
|
||||
|
||||
<label className="form-label" htmlFor={`label-${index}`}>Label :</label>
|
||||
<input value={input.label} onChange={handleChangeInput} type="text" name="label" id={`label-${index}`} className="form-control" placeholder="(e.g : Entrez le nom d'une ville :)" />
|
||||
<br/>
|
||||
|
||||
{(input.type !== "select") &&
|
||||
<Fragment>
|
||||
<label className="form-label" htmlFor={`placeholder-${index}`}>Placeholder :</label>
|
||||
<input value={input.placeholder} onChange={handleChangeInput} type="text" name="placeholder" id={`placeholder-${index}`} className="form-control" placeholder="(e.g : Paris, FR)" />
|
||||
<br/>
|
||||
</Fragment>
|
||||
}
|
||||
|
||||
<label className="form-label" htmlFor={`type-${index}`}>Type :</label>
|
||||
<select value={input.type} onChange={handleChangeInput} name="type" id={`type-${index}`} className="form-control">
|
||||
<option value="text">text</option>
|
||||
<option value="integer">Number integer</option>
|
||||
<option value="float">Number float</option>
|
||||
<option value="calendar">calendar</option>
|
||||
<option value="select">select</option>
|
||||
</select>
|
||||
|
||||
{(input.type === "select") &&
|
||||
<div style={{ marginTop: '50px' }}>
|
||||
|
||||
<label className="form-label">Options :</label>
|
||||
|
||||
{input.options.map((option, optionIndex) => {
|
||||
return (
|
||||
<div key={optionIndex} style={{ margin: "0 0 30px 0" }} className="form-group Admin__Input-group">
|
||||
<div className="text-center">
|
||||
<button type="button" onClick={() => handleRemoveOption(index, optionIndex)} className="btn btn-dark">Supprimer l'option</button>
|
||||
</div>
|
||||
|
||||
<label className="form-label" htmlFor={`optionName-${optionIndex}-${index}`}>Nom de l'option</label>
|
||||
<input onChange={(event) => handleChangeOption(index, optionIndex, event)} value={option.name} id={`optionName-${optionIndex}-${index}`} name="name" type="text"className="form-control" placeholder="Nom de l'option" />
|
||||
|
||||
<br />
|
||||
<label className="form-label" htmlFor={`optionValue-${optionIndex}-${index}`}>Valeur de l'option</label>
|
||||
<input onChange={(event) => handleChangeOption(index, optionIndex, event)} value={option.value} id={`optionValue-${optionIndex}-${index}`} name="value" type="text"className="form-control" placeholder="Valeur de l'option" />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="form-group text-center">
|
||||
<button id={`optionAdd-${index}`} onClick={addOption} type="button" className="btn btn-dark">Ajouter une option</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<div key={optionIndex} style={{ margin: '0 0 30px 0' }} className='form-group Admin__Input-group'>
|
||||
<div className='text-center'>
|
||||
<button type='button' onClick={() => handleRemoveOption(index, optionIndex)} className='btn btn-dark'>Supprimer l'option</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
</form>
|
||||
<label className='form-label' htmlFor={`optionName-${optionIndex}-${index}`}>Nom de l'option</label>
|
||||
<input onChange={(event) => handleChangeOption(index, optionIndex, event)} value={option.name} id={`optionName-${optionIndex}-${index}`} name='name' type='text' className='form-control' placeholder="Nom de l'option" />
|
||||
|
||||
<div style={{ marginBottom: '30px' }} className="form-group text-center">
|
||||
<button type="button" onClick={addInput} className="btn btn-dark">Ajouter un input</button>
|
||||
<br />
|
||||
<label className='form-label' htmlFor={`optionValue-${optionIndex}-${index}`}>Valeur de l'option</label>
|
||||
<input onChange={(event) => handleChangeOption(index, optionIndex, event)} value={option.value} id={`optionValue-${optionIndex}-${index}`} name='value' type='text' className='form-control' placeholder="Valeur de l'option" />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
<div className='form-group text-center'>
|
||||
<button id={`optionAdd-${index}`} onClick={addOption} type='button' className='btn btn-dark'>Ajouter une option</button>
|
||||
</div>
|
||||
</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
})}
|
||||
|
||||
</form>
|
||||
|
||||
<div style={{ marginBottom: '30px' }} className='form-group text-center'>
|
||||
<button type='button' onClick={addInput} className='btn btn-dark'>Ajouter un input</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default EditFormFunction;
|
||||
export default EditFormFunction
|
||||
|
@ -1,58 +1,56 @@
|
||||
import Link from 'next/link';
|
||||
import { useState, forwardRef } from 'react';
|
||||
import date from 'date-and-time';
|
||||
import Loader from '../Loader';
|
||||
import { API_URL } from '../../utils/config/config';
|
||||
import './FunctionCard.css';
|
||||
import Link from 'next/link'
|
||||
import { useState, forwardRef } from 'react'
|
||||
import date from 'date-and-time'
|
||||
import Loader from '../Loader'
|
||||
import { API_URL } from '../../utils/config/config'
|
||||
import './FunctionCard.css'
|
||||
|
||||
const FunctionCard = forwardRef((props, ref) => {
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const handleLoad = () => {
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
const handleLoad = () => {
|
||||
setIsLoading(false);
|
||||
}
|
||||
const handleError = (event) => {
|
||||
event.target.src = API_URL + '/images/functions/default.png'
|
||||
}
|
||||
|
||||
const handleError = (event) => {
|
||||
event.target.src = API_URL + "/images/functions/default.png";
|
||||
}
|
||||
const isFormOrArticle = (props.type === 'form' || props.type === 'article')
|
||||
|
||||
const isFormOrArticle = (props.type === 'form' || props.type === 'article');
|
||||
return (
|
||||
<Link
|
||||
{
|
||||
...(props.isAdmin)
|
||||
? {
|
||||
href: '/admin/[slug]',
|
||||
as: `/admin/${props.slug}`
|
||||
}
|
||||
: {
|
||||
href: (isFormOrArticle) ? '/functions/[slug]' : `/functions/${props.slug}`,
|
||||
as: `/functions/${props.slug}`
|
||||
}
|
||||
}
|
||||
>
|
||||
{/* FunctionCard a une hauteur pendant chargement */}
|
||||
<div ref={ref} style={isLoading ? { height: '360px', justifyContent: 'center' } : null} className='FunctionCard col-sm-24 col-md-10 col-xl-7'>
|
||||
|
||||
return (
|
||||
<Link
|
||||
{
|
||||
...(props.isAdmin) ?
|
||||
{
|
||||
href: "/admin/[slug]",
|
||||
as: `/admin/${props.slug}`
|
||||
}
|
||||
:
|
||||
{
|
||||
href: (isFormOrArticle) ? "/functions/[slug]" : `/functions/${props.slug}`,
|
||||
as: `/functions/${props.slug}`
|
||||
}
|
||||
}
|
||||
>
|
||||
{/* FunctionCard a une hauteur pendant chargement */}
|
||||
<div ref={ref} style={isLoading ? { height: "360px", justifyContent: "center" } : null} className={"FunctionCard col-sm-24 col-md-10 col-xl-7"}>
|
||||
{isLoading && <Loader width='125px' height='125px' />}
|
||||
|
||||
{isLoading && <Loader width="125px" height="125px" />}
|
||||
<div className={`FunctionCard__container ${isLoading ? 'd-none' : ''}`}>
|
||||
<div className='FunctionCard__top'>
|
||||
<img onLoad={handleLoad} onError={handleError} className='FunctionCard__image' alt={props.title} src={API_URL + props.image} />
|
||||
<h2 className='FunctionCard__title'>{props.title}</h2>
|
||||
<p className='FunctionCard__description text-center'>{props.description}</p>
|
||||
</div>
|
||||
<div className='FunctionCard__info'>
|
||||
<p className='FunctionCard__category' style={{ backgroundColor: props.categorie.color }}>{props.categorie.name}</p>
|
||||
<p className='FunctionCard__publication-date'>{date.format(new Date(props.createdAt), 'DD/MM/YYYY', true)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
)
|
||||
})
|
||||
|
||||
<div className={`FunctionCard__container ${isLoading ? "d-none" : ""}`}>
|
||||
<div className="FunctionCard__top">
|
||||
<img onLoad={handleLoad} onError={handleError} className="FunctionCard__image" alt={props.title} src={API_URL + props.image} />
|
||||
<h2 className="FunctionCard__title">{props.title}</h2>
|
||||
<p className="FunctionCard__description text-center">{props.description}</p>
|
||||
</div>
|
||||
<div className="FunctionCard__info">
|
||||
<p className="FunctionCard__category" style={{ backgroundColor: props.categorie.color }}>{props.categorie.name}</p>
|
||||
<p className="FunctionCard__publication-date">{date.format(new Date(props.createdAt), 'DD/MM/YYYY', true)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
});
|
||||
|
||||
export default FunctionCard;
|
||||
export default FunctionCard
|
||||
|
@ -1,108 +1,109 @@
|
||||
import Link from 'next/link';
|
||||
import { useEffect, useState, forwardRef, useContext, Fragment } from 'react';
|
||||
import date from 'date-and-time';
|
||||
import htmlParser from 'html-react-parser';
|
||||
import { UserContext } from '../../../contexts/UserContext';
|
||||
import { API_URL } from '../../../utils/config/config';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import CodeBlock from "../../CodeBlock";
|
||||
import api from '../../../utils/api';
|
||||
import './CommentCard.css';
|
||||
import Link from 'next/link'
|
||||
import { useEffect, useState, forwardRef, useContext } from 'react'
|
||||
import date from 'date-and-time'
|
||||
import htmlParser from 'html-react-parser'
|
||||
import { UserContext } from '../../../contexts/UserContext'
|
||||
import { API_URL } from '../../../utils/config/config'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import CodeBlock from '../../CodeBlock'
|
||||
import api from '../../../utils/api'
|
||||
import './CommentCard.css'
|
||||
|
||||
const CommentCard = forwardRef((props, ref) => {
|
||||
const { isAuth, user } = useContext(UserContext)
|
||||
const [isEditing, setEditing] = useState(false)
|
||||
const [editInput, setEditInput] = useState('')
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
const { isAuth, user } = useContext(UserContext);
|
||||
const [isEditing, setEditing] = useState(false);
|
||||
const [editInput, setEditInput] = useState("");
|
||||
const [message, setMessage] = useState("");
|
||||
useEffect(() => {
|
||||
setEditInput(props.message)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
setEditInput(props.message);
|
||||
}, []);
|
||||
|
||||
const deleteCommentById = async () => {
|
||||
props.manageComment.setLoadingComments(true);
|
||||
if (isAuth && user.token != undefined) {
|
||||
try {
|
||||
await api.delete(`/comments/${props.id}`, { headers: { 'Authorization': user.token } });
|
||||
const newCommentsData = { ...props.manageComment.commentsData };
|
||||
const commentIndex = newCommentsData.rows.findIndex((value) => value.id === props.id);
|
||||
newCommentsData.rows.splice(commentIndex, 1);
|
||||
props.manageComment.setCommentsData({ hasMore: props.manageComment.commentsData.hasMore, rows: newCommentsData.rows });
|
||||
} catch {}
|
||||
}
|
||||
props.manageComment.setLoadingComments(false);
|
||||
const deleteCommentById = async () => {
|
||||
props.manageComment.setLoadingComments(true)
|
||||
if (isAuth && user.token != null) {
|
||||
try {
|
||||
await api.delete(`/comments/${props.id}`, { headers: { Authorization: user.token } })
|
||||
const newCommentsData = { ...props.manageComment.commentsData }
|
||||
const commentIndex = newCommentsData.rows.findIndex((value) => value.id === props.id)
|
||||
newCommentsData.rows.splice(commentIndex, 1)
|
||||
props.manageComment.setCommentsData({ hasMore: props.manageComment.commentsData.hasMore, rows: newCommentsData.rows })
|
||||
} catch {}
|
||||
}
|
||||
props.manageComment.setLoadingComments(false)
|
||||
}
|
||||
|
||||
const handleChange = (event) => {
|
||||
setEditInput(event.target.value);
|
||||
}
|
||||
const handleChange = (event) => {
|
||||
setEditInput(event.target.value)
|
||||
}
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
event.preventDefault();
|
||||
api.put(`/comments/${props.id}`, { message: editInput }, { headers: { 'Authorization': user.token } })
|
||||
.then((_response) => {
|
||||
setEditing(false);
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
|
||||
});
|
||||
}
|
||||
const handleSubmit = (event) => {
|
||||
event.preventDefault()
|
||||
api.put(`/comments/${props.id}`, { message: editInput }, { headers: { Authorization: user.token } })
|
||||
.then((_response) => {
|
||||
setEditing(false)
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`)
|
||||
})
|
||||
}
|
||||
|
||||
const editComment = () => {
|
||||
setEditing(true);
|
||||
setMessage("");
|
||||
}
|
||||
const editComment = () => {
|
||||
setEditing(true)
|
||||
setMessage('')
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={ref} className="CommentCard col-24">
|
||||
<div className="CommentCard__container">
|
||||
<div className="row">
|
||||
<Link href={"/users/[name]"} as={`/users/${props.user.name}`}>
|
||||
<img className="CommentCard__user-logo" src={API_URL + props.user.logo} alt={props.user.name} />
|
||||
</Link>
|
||||
<span className="CommentCard__message-info">
|
||||
<Link href={"/users/[name]"} as={`/users/${props.user.name}`}>
|
||||
<a>{props.user.name}</a>
|
||||
</Link>
|
||||
- {date.format(new Date(props.createdAt), 'DD/MM/YYYY à HH:mm', true)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="col-24">
|
||||
{
|
||||
(!isEditing) ?
|
||||
<Fragment>
|
||||
<div className="CommentCard__message">
|
||||
<ReactMarkdown source={editInput} renderers={{ code: CodeBlock }} />
|
||||
</div>
|
||||
{(isAuth && user.name === props.user.name) &&
|
||||
<p style={{ fontSize: '15px', margin: '15px 0 0 0', fontStyle: 'italic' }}>
|
||||
<a onClick={deleteCommentById} href="#">supprimer</a>
|
||||
-
|
||||
<a style={{ cursor: 'pointer' }} onClick={editComment}>modifier</a>
|
||||
</p>
|
||||
}
|
||||
</Fragment>
|
||||
:
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group FunctionComments__post-group">
|
||||
<label className="form-label" htmlFor="commentEdit">Modifier le commentaire :</label>
|
||||
<textarea style={{ height: 'auto' }} value={editInput} onChange={handleChange} name="commentEdit" id="commentEdit" className="form-control" rows="5" placeholder="Idée d'amélioration, avis, remarque, partage d'expérience personnel, ... (Markdown autorisé)"></textarea>
|
||||
</div>
|
||||
<div className="form-group" style={{ marginTop: '0.7em' }}>
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
{htmlParser(message)}
|
||||
</div>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
return (
|
||||
<div ref={ref} className='CommentCard col-24'>
|
||||
<div className='CommentCard__container'>
|
||||
<div className='row'>
|
||||
<Link href='/users/[name]' as={`/users/${props.user.name}`}>
|
||||
<img className='CommentCard__user-logo' src={API_URL + props.user.logo} alt={props.user.name} />
|
||||
</Link>
|
||||
<span className='CommentCard__message-info'>
|
||||
<Link href='/users/[name]' as={`/users/${props.user.name}`}>
|
||||
<a>{props.user.name}</a>
|
||||
</Link>
|
||||
- {date.format(new Date(props.createdAt), 'DD/MM/YYYY à HH:mm', true)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
<div className='row'>
|
||||
<div className='col-24'>
|
||||
{
|
||||
(!isEditing)
|
||||
? (
|
||||
<>
|
||||
<div className='CommentCard__message'>
|
||||
<ReactMarkdown source={editInput} renderers={{ code: CodeBlock }} />
|
||||
</div>
|
||||
{(isAuth && user.name === props.user.name) &&
|
||||
<p style={{ fontSize: '15px', margin: '15px 0 0 0', fontStyle: 'italic' }}>
|
||||
<a onClick={deleteCommentById} href='#'>supprimer</a>
|
||||
-
|
||||
<a style={{ cursor: 'pointer' }} onClick={editComment}>modifier</a>
|
||||
</p>}
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group FunctionComments__post-group'>
|
||||
<label className='form-label' htmlFor='commentEdit'>Modifier le commentaire :</label>
|
||||
<textarea style={{ height: 'auto' }} value={editInput} onChange={handleChange} name='commentEdit' id='commentEdit' className='form-control' rows='5' placeholder="Idée d'amélioration, avis, remarque, partage d'expérience personnel, ... (Markdown autorisé)" />
|
||||
</div>
|
||||
<div className='form-group' style={{ marginTop: '0.7em' }}>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
<div className='text-center'>
|
||||
{htmlParser(message)}
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default CommentCard;
|
||||
export default CommentCard
|
||||
|
@ -1,11 +1,11 @@
|
||||
import htmlParser from 'html-react-parser';
|
||||
import htmlParser from 'html-react-parser'
|
||||
|
||||
const FunctionArticle = ({ article }) => {
|
||||
return (
|
||||
<div style={{ marginBottom: '50px' }} className="container-fluid">
|
||||
{(article != undefined) ? htmlParser(article) : <p className="text-center">L'article n'est pas encore disponible.</p>}
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div style={{ marginBottom: '50px' }} className='container-fluid'>
|
||||
{(article != null) ? htmlParser(article) : <p className='text-center'>L'article n'est pas encore disponible.</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default FunctionArticle;
|
||||
export default FunctionArticle
|
||||
|
@ -1,115 +1,114 @@
|
||||
import { Fragment, useState, useEffect, useContext, useRef, useCallback } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { UserContext } from '../../../contexts/UserContext';
|
||||
import CommentCard from '../CommentCard/CommentCard';
|
||||
import Loader from '../../Loader';
|
||||
import api from '../../../utils/api';
|
||||
import './FunctionComments.css';
|
||||
import { useState, useEffect, useContext, useRef, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { UserContext } from '../../../contexts/UserContext'
|
||||
import CommentCard from '../CommentCard/CommentCard'
|
||||
import Loader from '../../Loader'
|
||||
import api from '../../../utils/api'
|
||||
import './FunctionComments.css'
|
||||
|
||||
const FunctionComments = ({ functionId }) => {
|
||||
// State pour poster un commentaire
|
||||
const { isAuth, user } = useContext(UserContext)
|
||||
const [inputState, setInputState] = useState({})
|
||||
|
||||
// State pour poster un commentaire
|
||||
const { isAuth, user } = useContext(UserContext);
|
||||
const [inputState, setInputState] = useState({});
|
||||
// State pour afficher les commentaires
|
||||
const [commentsData, setCommentsData] = useState({ hasMore: true, rows: [] })
|
||||
const [isLoadingComments, setLoadingComments] = useState(true)
|
||||
const [pageComments, setPageComments] = useState(1)
|
||||
|
||||
// State pour afficher les commentaires
|
||||
const [commentsData, setCommentsData] = useState({ hasMore: true, rows: [] });
|
||||
const [isLoadingComments, setLoadingComments] = useState(true);
|
||||
const [pageComments, setPageComments] = useState(1);
|
||||
// Récupère les commentaires si la page change
|
||||
useEffect(() => {
|
||||
getCommentsData().then((data) => setCommentsData({
|
||||
hasMore: data.hasMore,
|
||||
rows: [...commentsData.rows, ...data.rows]
|
||||
}))
|
||||
}, [pageComments])
|
||||
|
||||
// Récupère les commentaires si la page change
|
||||
useEffect(() => {
|
||||
getCommentsData().then((data) => setCommentsData({
|
||||
hasMore: data.hasMore,
|
||||
rows: [...commentsData.rows, ...data.rows]
|
||||
}));
|
||||
}, [pageComments]);
|
||||
// Permet la pagination au scroll
|
||||
const observer = useRef()
|
||||
const lastCommentCardRef = useCallback((node) => {
|
||||
if (isLoadingComments) return
|
||||
if (observer.current) observer.current.disconnect()
|
||||
observer.current = new window.IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && commentsData.hasMore) {
|
||||
setPageComments(pageComments + 1)
|
||||
}
|
||||
}, { threshold: 1 })
|
||||
if (node) observer.current.observe(node)
|
||||
}, [isLoadingComments, commentsData.hasMore])
|
||||
|
||||
// Permet la pagination au scroll
|
||||
const observer = useRef();
|
||||
const lastCommentCardRef = useCallback((node) => {
|
||||
if (isLoadingComments) return;
|
||||
if (observer.current) observer.current.disconnect();
|
||||
observer.current = new IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && commentsData.hasMore) {
|
||||
setPageComments(pageComments + 1);
|
||||
const getCommentsData = async () => {
|
||||
setLoadingComments(true)
|
||||
const { data } = await api.get(`/comments/${functionId}/?page=${pageComments}&limit=10`)
|
||||
setLoadingComments(false)
|
||||
return data
|
||||
}
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
setLoadingComments(true)
|
||||
event.preventDefault()
|
||||
const token = user.token
|
||||
if (isAuth && token != null && inputState.commentPost != null) {
|
||||
try {
|
||||
const response = await api.post(`/comments/${functionId}`, { message: inputState.commentPost }, { headers: { Authorization: token } })
|
||||
const comment = { ...response.data, user: { name: user.name, logo: user.logo } }
|
||||
setCommentsData({ hasMore: commentsData.hasMore, rows: [comment, ...commentsData.rows] })
|
||||
setInputState({ commentPost: '' })
|
||||
} catch { }
|
||||
}
|
||||
setLoadingComments(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='FunctionComments__post container-fluid'>
|
||||
<div className='row FunctionComments__row'>
|
||||
<div className='col-24'>
|
||||
{
|
||||
(isAuth)
|
||||
? (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group FunctionComments__post-group'>
|
||||
<label className='form-label' htmlFor='commentPost'>Ajouter un commentaire :</label>
|
||||
<textarea className='FunctionComments__textarea form-control' value={inputState.commentPost} onChange={handleChange} name='commentPost' id='commentPost' placeholder="Idée d'amélioration, avis, remarque, partage d'expérience personnel, ... (Markdown autorisé)" />
|
||||
</div>
|
||||
<div className='form-group' style={{ marginTop: '0.7em' }}>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
: (
|
||||
<p className='text-center'>
|
||||
Vous devez être <Link href='/users/login'><a>connecté</a></Link> pour poster un commentaire.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
}, { threshold: 1 });
|
||||
if (node) observer.current.observe(node);
|
||||
}, [isLoadingComments, commentsData.hasMore]);
|
||||
|
||||
const getCommentsData = () => {
|
||||
setLoadingComments(true);
|
||||
return new Promise(async (next) => {
|
||||
const result = await api.get(`/comments/${functionId}/?page=${pageComments}&limit=10`);
|
||||
setLoadingComments(false);
|
||||
next(result.data);
|
||||
});
|
||||
}
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
}
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
setLoadingComments(true);
|
||||
event.preventDefault();
|
||||
const token = user.token;
|
||||
if (isAuth && token != undefined && inputState.commentPost != undefined) {
|
||||
try {
|
||||
const response = await api.post(`/comments/${functionId}`, { message: inputState.commentPost }, { headers: { 'Authorization': token } });
|
||||
const comment = { ...response.data, user: { name: user.name, logo: user.logo } };
|
||||
setCommentsData({ hasMore: commentsData.hasMore, rows: [comment, ...commentsData.rows] });
|
||||
setInputState({ commentPost: "" });
|
||||
} catch { }
|
||||
}
|
||||
setLoadingComments(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<div className="FunctionComments__post container-fluid">
|
||||
<div className="row FunctionComments__row">
|
||||
<div className="col-24">
|
||||
{
|
||||
(isAuth) ?
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group FunctionComments__post-group">
|
||||
<label className="form-label" htmlFor="commentPost">Ajouter un commentaire :</label>
|
||||
<textarea className="FunctionComments__textarea form-control" value={inputState.commentPost} onChange={handleChange} name="commentPost" id="commentPost" placeholder="Idée d'amélioration, avis, remarque, partage d'expérience personnel, ... (Markdown autorisé)"></textarea>
|
||||
</div>
|
||||
<div className="form-group" style={{ marginTop: '0.7em' }}>
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
:
|
||||
<p className="text-center">
|
||||
Vous devez être <Link href={'/users/login'}><a>connecté</a></Link> pour poster un commentaire.
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="container-fluid">
|
||||
{isLoadingComments &&
|
||||
<div className="row justify-content-center">
|
||||
<Loader />
|
||||
</div>
|
||||
}
|
||||
<div className="row justify-content-center">
|
||||
{commentsData.rows.map((comment, index) => {
|
||||
// Si c'est le dernier élément
|
||||
if (commentsData.rows.length === index + 1) {
|
||||
return <CommentCard key={comment.id} ref={lastCommentCardRef} { ...comment } manageComment={{ setCommentsData, commentsData, setLoadingComments }} />;
|
||||
}
|
||||
return <CommentCard key={comment.id} { ...comment } manageComment={{ setCommentsData, commentsData, setLoadingComments }} />;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='container-fluid'>
|
||||
{isLoadingComments &&
|
||||
<div className='row justify-content-center'>
|
||||
<Loader />
|
||||
</div>}
|
||||
<div className='row justify-content-center'>
|
||||
{commentsData.rows.map((comment, index) => {
|
||||
// Si c'est le dernier élément
|
||||
if (commentsData.rows.length === index + 1) {
|
||||
return <CommentCard key={comment.id} ref={lastCommentCardRef} {...comment} manageComment={{ setCommentsData, commentsData, setLoadingComments }} />
|
||||
}
|
||||
return <CommentCard key={comment.id} {...comment} manageComment={{ setCommentsData, commentsData, setLoadingComments }} />
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default FunctionComments;
|
||||
export default FunctionComments
|
||||
|
@ -1,71 +1,69 @@
|
||||
import { useState, useEffect, useContext } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faStar } from '@fortawesome/free-solid-svg-icons';
|
||||
import { faStar as farStar } from '@fortawesome/free-regular-svg-icons';
|
||||
import date from 'date-and-time';
|
||||
import { UserContext } from '../../contexts/UserContext';
|
||||
import api from '../../utils/api';
|
||||
import { API_URL } from '../../utils/config/config';
|
||||
import '../FunctionCard/FunctionCard.css';
|
||||
import { useState, useEffect, useContext } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||
import { faStar } from '@fortawesome/free-solid-svg-icons'
|
||||
import { faStar as farStar } from '@fortawesome/free-regular-svg-icons'
|
||||
import date from 'date-and-time'
|
||||
import { UserContext } from '../../contexts/UserContext'
|
||||
import api from '../../utils/api'
|
||||
import { API_URL } from '../../utils/config/config'
|
||||
import '../FunctionCard/FunctionCard.css'
|
||||
|
||||
const FunctionComponentTop = (props) => {
|
||||
const { isAuth, user } = useContext(UserContext)
|
||||
const [isFavorite, setIsFavorite] = useState(false)
|
||||
|
||||
const { isAuth, user } = useContext(UserContext);
|
||||
const [isFavorite, setIsFavorite] = useState(false);
|
||||
useEffect(() => {
|
||||
if (isAuth && user.token != null) {
|
||||
fetchFavorite()
|
||||
}
|
||||
}, [isAuth])
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuth && user.token != undefined) {
|
||||
fetchFavorite();
|
||||
const fetchFavorite = async () => {
|
||||
try {
|
||||
const favoriteResponse = await api.get(`/favorites/${props.id}`, { headers: { Authorization: user.token } })
|
||||
setIsFavorite(favoriteResponse.data.isFavorite)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const toggleFavorite = async () => {
|
||||
if (isAuth && user.token != null) {
|
||||
try {
|
||||
if (isFavorite) {
|
||||
const response = await api.delete(`/favorites/${props.id}`, { headers: { Authorization: user.token } })
|
||||
if (response.status === 200) return setIsFavorite(false)
|
||||
}
|
||||
}, [isAuth]);
|
||||
|
||||
const fetchFavorite = async () => {
|
||||
try {
|
||||
const favoriteResponse = await api.get(`/favorites/${props.id}`, { headers: { 'Authorization': user.token } });
|
||||
setIsFavorite(favoriteResponse.data.isFavorite);
|
||||
} catch {}
|
||||
const response = await api.post(`/favorites/${props.id}`, {}, { headers: { Authorization: user.token } })
|
||||
if (response.status === 201) return setIsFavorite(true)
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
const toggleFavorite = async () => {
|
||||
if (isAuth && user.token != undefined) {
|
||||
try {
|
||||
if (isFavorite) {
|
||||
const response = await api.delete(`/favorites/${props.id}`, { headers: { 'Authorization': user.token } });
|
||||
if (response.status === 200) return setIsFavorite(false);
|
||||
}
|
||||
const response = await api.post(`/favorites/${props.id}`, {}, { headers: { 'Authorization': user.token } });
|
||||
if (response.status === 201) return setIsFavorite(true);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
const handleError = (event) => {
|
||||
event.target.src = API_URL + '/images/functions/default.png'
|
||||
}
|
||||
|
||||
const handleError = (event) => {
|
||||
event.target.src = API_URL + "/images/functions/default.png";
|
||||
}
|
||||
return (
|
||||
<div className='container-fluid'>
|
||||
<div className='row justify-content-center text-center'>
|
||||
<div className='FunctionComponent__top col-24'>
|
||||
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
<div className="row justify-content-center text-center">
|
||||
<div className="FunctionComponent__top col-24">
|
||||
{(isAuth) &&
|
||||
<FontAwesomeIcon onClick={toggleFavorite} {...(isFavorite) ? { icon: faStar } : { icon: farStar }} title={(isFavorite) ? 'Retirer la fonction des favoris' : 'Ajouter la fonction aux favoris'} className='FunctionComponent__star-favorite' />}
|
||||
|
||||
{(isAuth) &&
|
||||
<FontAwesomeIcon onClick={toggleFavorite} { ...(isFavorite) ? { icon: faStar } : { icon: farStar } } title={(isFavorite) ? "Retirer la fonction des favoris" : "Ajouter la fonction aux favoris"} className="FunctionComponent__star-favorite" />
|
||||
}
|
||||
|
||||
<img onError={handleError} className="FunctionComponent__image" src={API_URL + props.image} alt={props.title} />
|
||||
<h1 className="FunctionComponent__title title-important">{props.title}</h1>
|
||||
<p className="FunctionComponent__description">{props.description}</p>
|
||||
<div className="FunctionCard__info">
|
||||
<Link href={`/functions?categoryId=${props.categorieId}`}>
|
||||
<a className="FunctionCard__category" style={{ backgroundColor: props.categorie.color, color: 'inherit' }}>{props.categorie.name}</a>
|
||||
</Link>
|
||||
<p className="FunctionCard__publication-date">{date.format(new Date(props.createdAt), 'DD/MM/YYYY', true)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<img onError={handleError} className='FunctionComponent__image' src={API_URL + props.image} alt={props.title} />
|
||||
<h1 className='FunctionComponent__title title-important'>{props.title}</h1>
|
||||
<p className='FunctionComponent__description'>{props.description}</p>
|
||||
<div className='FunctionCard__info'>
|
||||
<Link href={`/functions?categoryId=${props.categorieId}`}>
|
||||
<a className='FunctionCard__category' style={{ backgroundColor: props.categorie.color, color: 'inherit' }}>{props.categorie.name}</a>
|
||||
</Link>
|
||||
<p className='FunctionCard__publication-date'>{date.format(new Date(props.createdAt), 'DD/MM/YYYY', true)}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default FunctionComponentTop;
|
||||
export default FunctionComponentTop
|
||||
|
@ -1,161 +1,160 @@
|
||||
import { Fragment, useState, useEffect } from 'react';
|
||||
import Loader from '../Loader';
|
||||
import htmlParser from 'html-react-parser';
|
||||
import dynamic from 'next/dynamic';
|
||||
import api from '../../utils/api';
|
||||
import fr from 'date-fns/locale/fr';
|
||||
import { registerLocale } from "react-datepicker";
|
||||
import date from 'date-and-time';
|
||||
import "react-datepicker/dist/react-datepicker.css";
|
||||
import { useState, useEffect } from 'react'
|
||||
import Loader from '../Loader'
|
||||
import htmlParser from 'html-react-parser'
|
||||
import dynamic from 'next/dynamic'
|
||||
import api from '../../utils/api'
|
||||
import fr from 'date-fns/locale/fr'
|
||||
import { registerLocale } from 'react-datepicker'
|
||||
import date from 'date-and-time'
|
||||
import 'react-datepicker/dist/react-datepicker.css'
|
||||
|
||||
registerLocale('fr', fr);
|
||||
registerLocale('fr', fr)
|
||||
|
||||
const FunctionForm = (props) => {
|
||||
const [inputState, setInputState] = useState({})
|
||||
const [message, setMessage] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const [inputState, setInputState] = useState({});
|
||||
const [message, setMessage] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
// inputState par défaut
|
||||
useEffect(() => {
|
||||
const inputStateNew = { ...inputState }
|
||||
props.inputsArray.forEach((input) => {
|
||||
if (input.type === 'select' && input.options.length > 0) {
|
||||
inputStateNew[input.name] = input.options[0].value
|
||||
}
|
||||
})
|
||||
setInputState(inputStateNew)
|
||||
}, [])
|
||||
|
||||
// inputState par défaut
|
||||
useEffect(() => {
|
||||
const inputStateNew = { ...inputState };
|
||||
props.inputsArray.forEach((input) => {
|
||||
if (input.type === "select" && input.options.length > 0) {
|
||||
inputStateNew[input.name] = input.options[0].value;
|
||||
}
|
||||
});
|
||||
setInputState(inputStateNew);
|
||||
}, []);
|
||||
const handleSubmit = (event) => {
|
||||
setIsLoading(true)
|
||||
event.preventDefault()
|
||||
api.post(`/functions/${props.slug}`, inputState)
|
||||
.then((response) => {
|
||||
setMessage(response.data.resultHTML)
|
||||
setIsLoading(false)
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(error.response.data.message)
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
setIsLoading(true);
|
||||
event.preventDefault();
|
||||
api.post(`/functions/${props.slug}`, inputState)
|
||||
.then((response) => {
|
||||
setMessage(response.data.resultHTML);
|
||||
setIsLoading(false);
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(error.response.data.message);
|
||||
setIsLoading(false);
|
||||
});
|
||||
}
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
}
|
||||
|
||||
if (props.inputsArray.length <= 0) {
|
||||
return (
|
||||
<div className="FunctionComponent__slide text-center">
|
||||
<p>La fonction n'est pas encore disponible.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (props.inputsArray.length <= 0) {
|
||||
return (
|
||||
<Fragment>
|
||||
<form onSubmit={handleSubmit}>
|
||||
{props.inputsArray.map((input, index) => {
|
||||
switch (input.type) {
|
||||
case "text":
|
||||
return (
|
||||
<div key={index} className="form-group">
|
||||
<label className="form-label" htmlFor={input.name}>{input.label}</label>
|
||||
<input onChange={handleChange} type="text" name={input.name} id={input.name} placeholder={input.placeholder} className="form-control" />
|
||||
</div>
|
||||
);
|
||||
case "integer":
|
||||
case "float":
|
||||
return (
|
||||
<div key={index} className="form-group">
|
||||
<label className="form-label" htmlFor={input.name}>{input.label}</label>
|
||||
<input onChange={handleChange} type="number" step={(input.type === "integer") ? "1" : "0.01"} name={input.name} id={input.name} placeholder={input.placeholder} className="form-control" />
|
||||
</div>
|
||||
);
|
||||
case "calendar":
|
||||
// Permet au datepicker de prendre la hauteur
|
||||
if (typeof window != 'undefined') {
|
||||
const newScript = document.createElement("script");
|
||||
newScript.src = "/js/extraHeightCSS.js";
|
||||
document.body.appendChild(newScript);
|
||||
}
|
||||
const DatePicker = dynamic(
|
||||
() => import('react-datepicker'),
|
||||
{ ssr: false }
|
||||
);
|
||||
return (
|
||||
<div key={index} className="form-group">
|
||||
<label className="form-label" htmlFor={input.name}>{input.label}</label>
|
||||
<br/>
|
||||
<DatePicker
|
||||
selected={(() => {
|
||||
try {
|
||||
if (inputState[input.name] != undefined) {
|
||||
const dateArray = inputState[input.name].split('/');
|
||||
const year = dateArray[2];
|
||||
const month = dateArray[1];
|
||||
const day = dateArray[0];
|
||||
return new Date(year, parseInt(month) - 1, parseInt(day) + 1);
|
||||
}
|
||||
throw "Not a valid date";
|
||||
} catch {
|
||||
return new Date();
|
||||
}
|
||||
})()}
|
||||
locale="fr"
|
||||
dateFormat="dd/MM/yyyy"
|
||||
fixedHeight
|
||||
placeholderText={input.placeholder}
|
||||
onChange={(dateObject) => {
|
||||
try {
|
||||
const formattedDate = date.format(dateObject, 'DD/MM/YYYY', true);
|
||||
handleChange({
|
||||
target: {
|
||||
name: input.name,
|
||||
value: formattedDate
|
||||
}
|
||||
});
|
||||
} catch {}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
case "select":
|
||||
return (
|
||||
<div key={index} className="form-group">
|
||||
<label className="form-label" htmlFor={input.name}>{input.label}</label>
|
||||
<select onChange={handleChange} name={input.name} id={input.name} value={inputState[input.name] || input.options[0]} className="form-control">
|
||||
{input.options.map((option, optionIndex) => {
|
||||
return (
|
||||
<option key={optionIndex} value={option.value}>{option.name}</option>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<p>Erreur, l'input n'est pas valide...</p>
|
||||
);
|
||||
}
|
||||
})}
|
||||
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
<div className='FunctionComponent__slide text-center'>
|
||||
<p>La fonction n'est pas encore disponible.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<form onSubmit={handleSubmit}>
|
||||
{props.inputsArray.map((input, index) => {
|
||||
switch (input.type) {
|
||||
case 'text':
|
||||
return (
|
||||
<div key={index} className='form-group'>
|
||||
<label className='form-label' htmlFor={input.name}>{input.label}</label>
|
||||
<input onChange={handleChange} type='text' name={input.name} id={input.name} placeholder={input.placeholder} className='form-control' />
|
||||
</div>
|
||||
</form>
|
||||
<div className="form-result text-center">
|
||||
{
|
||||
(isLoading) ?
|
||||
<Loader />
|
||||
:
|
||||
htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
)
|
||||
case 'integer':
|
||||
case 'float':
|
||||
return (
|
||||
<div key={index} className='form-group'>
|
||||
<label className='form-label' htmlFor={input.name}>{input.label}</label>
|
||||
<input onChange={handleChange} type='number' step={(input.type === 'integer') ? '1' : '0.01'} name={input.name} id={input.name} placeholder={input.placeholder} className='form-control' />
|
||||
</div>
|
||||
)
|
||||
case 'calendar':
|
||||
// Permet au datepicker de prendre la hauteur
|
||||
if (typeof window !== 'undefined') {
|
||||
const newScript = document.createElement('script')
|
||||
newScript.src = '/js/extraHeightCSS.js'
|
||||
document.body.appendChild(newScript)
|
||||
}
|
||||
// eslint-disable-next-line
|
||||
const DatePicker = dynamic(
|
||||
() => import('react-datepicker'),
|
||||
{ ssr: false }
|
||||
)
|
||||
return (
|
||||
<div key={index} className='form-group'>
|
||||
<label className='form-label' htmlFor={input.name}>{input.label}</label>
|
||||
<br />
|
||||
<DatePicker
|
||||
selected={(() => {
|
||||
try {
|
||||
if (inputState[input.name] != null) {
|
||||
const dateArray = inputState[input.name].split('/')
|
||||
const year = dateArray[2]
|
||||
const month = dateArray[1]
|
||||
const day = dateArray[0]
|
||||
return new Date(year, parseInt(month) - 1, parseInt(day) + 1)
|
||||
}
|
||||
throw new Error('Not a valid date')
|
||||
} catch {
|
||||
return new Date()
|
||||
}
|
||||
})()}
|
||||
locale='fr'
|
||||
dateFormat='dd/MM/yyyy'
|
||||
fixedHeight
|
||||
placeholderText={input.placeholder}
|
||||
onChange={(dateObject) => {
|
||||
try {
|
||||
const formattedDate = date.format(dateObject, 'DD/MM/YYYY', true)
|
||||
handleChange({
|
||||
target: {
|
||||
name: input.name,
|
||||
value: formattedDate
|
||||
}
|
||||
})
|
||||
} catch {}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
case 'select':
|
||||
return (
|
||||
<div key={index} className='form-group'>
|
||||
<label className='form-label' htmlFor={input.name}>{input.label}</label>
|
||||
<select onChange={handleChange} name={input.name} id={input.name} value={inputState[input.name] || input.options[0]} className='form-control'>
|
||||
{input.options.map((option, optionIndex) => {
|
||||
return (
|
||||
<option key={optionIndex} value={option.value}>{option.name}</option>
|
||||
)
|
||||
})}
|
||||
</select>
|
||||
</div>
|
||||
)
|
||||
default:
|
||||
return (
|
||||
<p>Erreur, l'input n'est pas valide...</p>
|
||||
)
|
||||
}
|
||||
})}
|
||||
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className='form-result text-center'>
|
||||
{
|
||||
(isLoading)
|
||||
? <Loader />
|
||||
: htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default FunctionForm;
|
||||
export default FunctionForm
|
||||
|
@ -1,24 +1,23 @@
|
||||
import { Fragment, useState } from 'react';
|
||||
import { API_URL } from '../../utils/config/config';
|
||||
import HeadTag from '../HeadTag';
|
||||
import FunctionTabsTop from './FunctionTabsTop';
|
||||
import FunctionComponentTop from './FunctionComponentTop';
|
||||
import { useState } from 'react'
|
||||
import { API_URL } from '../../utils/config/config'
|
||||
import HeadTag from '../HeadTag'
|
||||
import FunctionTabsTop from './FunctionTabsTop'
|
||||
import FunctionComponentTop from './FunctionComponentTop'
|
||||
|
||||
const FunctionPage = (props) => {
|
||||
const [slideIndex, setSlideIndex] = useState(0)
|
||||
|
||||
const [slideIndex, setSlideIndex] = useState(0);
|
||||
return (
|
||||
<>
|
||||
<HeadTag title={props.title} description={props.description} image={API_URL + props.image} />
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag title={props.title} description={props.description} image={API_URL + props.image} />
|
||||
|
||||
<div className="container-fluid">
|
||||
<FunctionTabsTop slideIndex={slideIndex} setSlideIndex={setSlideIndex} tabNames={props.tabNames} />
|
||||
<FunctionComponentTop { ...props } />
|
||||
<props.FunctionTabManager { ...props } slideIndex={slideIndex} setSlideIndex={setSlideIndex} />
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
<div className='container-fluid'>
|
||||
<FunctionTabsTop slideIndex={slideIndex} setSlideIndex={setSlideIndex} tabNames={props.tabNames} />
|
||||
<FunctionComponentTop {...props} />
|
||||
<props.FunctionTabManager {...props} slideIndex={slideIndex} setSlideIndex={setSlideIndex} />
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default FunctionPage;
|
||||
export default FunctionPage
|
||||
|
@ -1,14 +1,14 @@
|
||||
import SwipeableViews from 'react-swipeable-views';
|
||||
import './FunctionTabs.css';
|
||||
import SwipeableViews from 'react-swipeable-views'
|
||||
import './FunctionTabs.css'
|
||||
|
||||
const FunctionTabs = (props) => {
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
<SwipeableViews onChangeIndex={(index) => props.setSlideIndex(index)} index={props.slideIndex}>
|
||||
{props.children}
|
||||
</SwipeableViews>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className='container-fluid'>
|
||||
<SwipeableViews onChangeIndex={(index) => props.setSlideIndex(index)} index={props.slideIndex}>
|
||||
{props.children}
|
||||
</SwipeableViews>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default FunctionTabs;
|
||||
export default FunctionTabs
|
||||
|
@ -1,24 +1,24 @@
|
||||
const FunctionTabsTop = (props) => {
|
||||
return (
|
||||
<div className="container">
|
||||
<div className="row justify-content-center">
|
||||
<ul className="FunctionTabs__nav">
|
||||
{props.tabNames.map((tabName, index) => {
|
||||
return (
|
||||
<li key={index} className="FunctionTabs__nav-item">
|
||||
<a
|
||||
className={`FunctionTabs__nav-link ${(props.slideIndex === index) ? "FunctionTabs__nav-link-active" : ""}`}
|
||||
onClick={() => props.setSlideIndex(index)}
|
||||
>
|
||||
{tabName}
|
||||
</a>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className='container'>
|
||||
<div className='row justify-content-center'>
|
||||
<ul className='FunctionTabs__nav'>
|
||||
{props.tabNames.map((tabName, index) => {
|
||||
return (
|
||||
<li key={index} className='FunctionTabs__nav-item'>
|
||||
<a
|
||||
className={`FunctionTabs__nav-link ${(props.slideIndex === index) ? 'FunctionTabs__nav-link-active' : ''}`}
|
||||
onClick={() => props.setSlideIndex(index)}
|
||||
>
|
||||
{tabName}
|
||||
</a>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default FunctionTabsTop;
|
||||
export default FunctionTabsTop
|
||||
|
@ -1,104 +1,103 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { useRouter } from 'next/router';
|
||||
import FunctionCard from '../FunctionCard/FunctionCard';
|
||||
import Loader from '../Loader';
|
||||
import api from '../../utils/api';
|
||||
import useAPI from '../../hooks/useAPI';
|
||||
import './FunctionsList.css';
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { useRouter } from 'next/router'
|
||||
import FunctionCard from '../FunctionCard/FunctionCard'
|
||||
import Loader from '../Loader'
|
||||
import api from '../../utils/api'
|
||||
import useAPI from '../../hooks/useAPI'
|
||||
import './FunctionsList.css'
|
||||
|
||||
let pageFunctions = 1;
|
||||
let pageFunctions = 1
|
||||
const FunctionsList = (props) => {
|
||||
const { categoryId } = useRouter().query
|
||||
|
||||
const { categoryId } = useRouter().query;
|
||||
// State de recherche et de catégories
|
||||
const [, categories] = useAPI('/categories')
|
||||
const [inputSearch, setInputSearch] = useState({ search: '', selectedCategory: categoryId || '0' })
|
||||
|
||||
// State de recherche et de catégories
|
||||
const [, categories] = useAPI('/categories');
|
||||
const [inputSearch, setInputSearch] = useState({ search: "", selectedCategory: categoryId || "0" });
|
||||
// State pour afficher les fonctions
|
||||
const [functionsData, setFunctionsData] = useState({ hasMore: true, rows: [] })
|
||||
const [isLoadingFunctions, setLoadingFunctions] = useState(true)
|
||||
|
||||
// State pour afficher les fonctions
|
||||
const [functionsData, setFunctionsData] = useState({ hasMore: true, rows: [] });
|
||||
const [isLoadingFunctions, setLoadingFunctions] = useState(true);
|
||||
|
||||
// Récupère la catégorie avec la query categoryId
|
||||
useEffect(() => {
|
||||
if (categoryId) {
|
||||
handleChange({ target: { name: "selectedCategory", value: categoryId } });
|
||||
}
|
||||
}, [categoryId]);
|
||||
|
||||
// Récupère les fonctions si la catégorie/recherche change
|
||||
useEffect(() => {
|
||||
pageFunctions = 1;
|
||||
getFunctionsData().then((data) => setFunctionsData(data));
|
||||
}, [inputSearch]);
|
||||
|
||||
// Permet la pagination au scroll
|
||||
const observer = useRef();
|
||||
const lastFunctionCardRef = useCallback((node) => {
|
||||
if (isLoadingFunctions) return;
|
||||
if (observer.current) observer.current.disconnect();
|
||||
observer.current = new IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && functionsData.hasMore) {
|
||||
pageFunctions += 1;
|
||||
getFunctionsData().then((data) => {
|
||||
setFunctionsData((oldData) => {
|
||||
return {
|
||||
hasMore: data.hasMore,
|
||||
rows: [...oldData.rows, ...data.rows]
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}, { threshold: 1 });
|
||||
if (node) observer.current.observe(node);
|
||||
}, [isLoadingFunctions, functionsData.hasMore]);
|
||||
|
||||
const getFunctionsData = async () => {
|
||||
setLoadingFunctions(true);
|
||||
const URL = `${(props.isAdmin) ? "/admin/functions" : "/functions"}?page=${pageFunctions}&limit=10&categoryId=${inputSearch.selectedCategory}&search=${inputSearch.search}`;
|
||||
const { data } = await api.get(URL, {
|
||||
headers: {
|
||||
...(props.isAdmin && props.token != undefined) && { 'Authorization': props.token }
|
||||
}
|
||||
});
|
||||
setLoadingFunctions(false);
|
||||
return data;
|
||||
// Récupère la catégorie avec la query categoryId
|
||||
useEffect(() => {
|
||||
if (categoryId) {
|
||||
handleChange({ target: { name: 'selectedCategory', value: categoryId } })
|
||||
}
|
||||
}, [categoryId])
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputSearchNew = { ...inputSearch };
|
||||
inputSearchNew[event.target.name] = event.target.value;
|
||||
setInputSearch(inputSearchNew);
|
||||
}
|
||||
// Récupère les fonctions si la catégorie/recherche change
|
||||
useEffect(() => {
|
||||
pageFunctions = 1
|
||||
getFunctionsData().then((data) => setFunctionsData(data))
|
||||
}, [inputSearch])
|
||||
|
||||
return (
|
||||
<div className="container text-center">
|
||||
<div className="row justify-content-center">
|
||||
{props.children}
|
||||
</div>
|
||||
// Permet la pagination au scroll
|
||||
const observer = useRef()
|
||||
const lastFunctionCardRef = useCallback((node) => {
|
||||
if (isLoadingFunctions) return
|
||||
if (observer.current) observer.current.disconnect()
|
||||
observer.current = new window.IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && functionsData.hasMore) {
|
||||
pageFunctions += 1
|
||||
getFunctionsData().then((data) => {
|
||||
setFunctionsData((oldData) => {
|
||||
return {
|
||||
hasMore: data.hasMore,
|
||||
rows: [...oldData.rows, ...data.rows]
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}, { threshold: 1 })
|
||||
if (node) observer.current.observe(node)
|
||||
}, [isLoadingFunctions, functionsData.hasMore])
|
||||
|
||||
<div className="Functions__search-container row justify-content-center">
|
||||
<select name="selectedCategory" value={inputSearch.selectedCategory} onChange={handleChange} className="Functions__select Functions__form-control">
|
||||
<option value="0">Toutes catégories</option>
|
||||
{categories.map((category) => (
|
||||
<option key={category.id} value={category.id} className="Functions__select-option" style={{ backgroundColor: category.color }}>{category.name}</option>
|
||||
))}
|
||||
</select>
|
||||
<input value={inputSearch.search} onChange={handleChange} type="search" className="Functions__form-control Functions__search-input" name="search" id="search" placeholder="🔎 Rechercher..." />
|
||||
</div>
|
||||
const getFunctionsData = async () => {
|
||||
setLoadingFunctions(true)
|
||||
const URL = `${(props.isAdmin) ? '/admin/functions' : '/functions'}?page=${pageFunctions}&limit=10&categoryId=${inputSearch.selectedCategory}&search=${inputSearch.search}`
|
||||
const { data } = await api.get(URL, {
|
||||
headers: {
|
||||
...(props.isAdmin && props.token != null) && { Authorization: props.token }
|
||||
}
|
||||
})
|
||||
setLoadingFunctions(false)
|
||||
return data
|
||||
}
|
||||
|
||||
<div className="row justify-content-center">
|
||||
{functionsData.rows.map((currentFunction, index) => {
|
||||
// Si c'est le dernier élément
|
||||
if (functionsData.rows.length === index + 1) {
|
||||
return <FunctionCard isAdmin={props.isAdmin} key={currentFunction.id} ref={lastFunctionCardRef} { ...currentFunction } />;
|
||||
}
|
||||
return <FunctionCard isAdmin={props.isAdmin} key={currentFunction.id} { ...currentFunction } />;
|
||||
})}
|
||||
</div>
|
||||
{isLoadingFunctions && <Loader />}
|
||||
</div>
|
||||
);
|
||||
const handleChange = (event) => {
|
||||
const inputSearchNew = { ...inputSearch }
|
||||
inputSearchNew[event.target.name] = event.target.value
|
||||
setInputSearch(inputSearchNew)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='container text-center'>
|
||||
<div className='row justify-content-center'>
|
||||
{props.children}
|
||||
</div>
|
||||
|
||||
<div className='Functions__search-container row justify-content-center'>
|
||||
<select name='selectedCategory' value={inputSearch.selectedCategory} onChange={handleChange} className='Functions__select Functions__form-control'>
|
||||
<option value='0'>Toutes catégories</option>
|
||||
{categories.map((category) => (
|
||||
<option key={category.id} value={category.id} className='Functions__select-option' style={{ backgroundColor: category.color }}>{category.name}</option>
|
||||
))}
|
||||
</select>
|
||||
<input value={inputSearch.search} onChange={handleChange} type='search' className='Functions__form-control Functions__search-input' name='search' id='search' placeholder='🔎 Rechercher...' />
|
||||
</div>
|
||||
|
||||
<div className='row justify-content-center'>
|
||||
{functionsData.rows.map((currentFunction, index) => {
|
||||
// Si c'est le dernier élément
|
||||
if (functionsData.rows.length === index + 1) {
|
||||
return <FunctionCard isAdmin={props.isAdmin} key={currentFunction.id} ref={lastFunctionCardRef} {...currentFunction} />
|
||||
}
|
||||
return <FunctionCard isAdmin={props.isAdmin} key={currentFunction.id} {...currentFunction} />
|
||||
})}
|
||||
</div>
|
||||
{isLoadingFunctions && <Loader />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default FunctionsList;
|
||||
export default FunctionsList
|
||||
|
@ -1,43 +1,43 @@
|
||||
import Head from 'next/head';
|
||||
import Head from 'next/head'
|
||||
|
||||
const HeadTag = ({ title, image, description }) => (
|
||||
<Head>
|
||||
<title>{title || ""}</title>
|
||||
<link rel="icon" type="image/png" href={image} />
|
||||
<Head>
|
||||
<title>{title || ''}</title>
|
||||
<link rel='icon' type='image/png' href={image} />
|
||||
|
||||
{/* Meta Tag */}
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="description" content={description} />
|
||||
<link rel="canonical" href="function.divlo.fr"/>
|
||||
<meta name="Language" content="fr" />
|
||||
<meta name="theme-color" content="#ffd800" />
|
||||
{/* Meta Tag */}
|
||||
<meta name='viewport' content='width=device-width, initial-scale=1' />
|
||||
<meta name='description' content={description} />
|
||||
<link rel='canonical' href='function.divlo.fr' />
|
||||
<meta name='Language' content='fr' />
|
||||
<meta name='theme-color' content='#ffd800' />
|
||||
|
||||
{/* Open Graph Metadata */}
|
||||
<meta property="og:title" content={title} />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://function.divlo.fr/" />
|
||||
<meta property="og:image" content={image} />
|
||||
<meta property="og:description" content={description} />
|
||||
<meta property="og:locale" content="fr_FR" />
|
||||
<meta property="og:site_name" content="FunctionProject" />
|
||||
{/* Open Graph Metadata */}
|
||||
<meta property='og:title' content={title} />
|
||||
<meta property='og:type' content='website' />
|
||||
<meta property='og:url' content='https://function.divlo.fr/' />
|
||||
<meta property='og:image' content={image} />
|
||||
<meta property='og:description' content={description} />
|
||||
<meta property='og:locale' content='fr_FR' />
|
||||
<meta property='og:site_name' content='FunctionProject' />
|
||||
|
||||
{/* Twitter card Metadata */}
|
||||
<meta name="twitter:card" content="summary" />
|
||||
<meta name="twitter:description" content={description} />
|
||||
<meta name="twitter:title" content={title} />
|
||||
<meta name="twitter:site" content="@Divlo_FR" />
|
||||
<meta name="twitter:image:src" content={image} />
|
||||
<meta name="twitter:creator" content="@Divlo_FR" />
|
||||
{/* Twitter card Metadata */}
|
||||
<meta name='twitter:card' content='summary' />
|
||||
<meta name='twitter:description' content={description} />
|
||||
<meta name='twitter:title' content={title} />
|
||||
<meta name='twitter:site' content='@Divlo_FR' />
|
||||
<meta name='twitter:image:src' content={image} />
|
||||
<meta name='twitter:creator' content='@Divlo_FR' />
|
||||
|
||||
{/* Preloader script */}
|
||||
<script src="/js/preloader.js"></script>
|
||||
</Head>
|
||||
);
|
||||
{/* Preloader script */}
|
||||
<script src='/js/preloader.js' />
|
||||
</Head>
|
||||
)
|
||||
|
||||
HeadTag.defaultProps = {
|
||||
title: "FunctionProject",
|
||||
description: "Apprenez la programmation grâce à l'apprentissage par projet alias fonction.",
|
||||
image: "/images/FunctionProject_icon_small.png"
|
||||
title: 'FunctionProject',
|
||||
description: "Apprenez la programmation grâce à l'apprentissage par projet alias fonction.",
|
||||
image: '/images/FunctionProject_icon_small.png'
|
||||
}
|
||||
|
||||
export default HeadTag;
|
||||
export default HeadTag
|
||||
|
@ -1,71 +1,73 @@
|
||||
import { Fragment, useState, useContext } from 'react';
|
||||
import { UserContext } from '../../contexts/UserContext';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/router';
|
||||
import NavigationLink from './NavigationLink';
|
||||
import './Header.css';
|
||||
import { useState, useContext } from 'react'
|
||||
import { UserContext } from '../../contexts/UserContext'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/router'
|
||||
import NavigationLink from './NavigationLink'
|
||||
import './Header.css'
|
||||
|
||||
export default function Header() {
|
||||
export default function Header () {
|
||||
const { isAuth, logoutUser, user } = useContext(UserContext)
|
||||
const [isActive, setIsActive] = useState(false)
|
||||
const { pathname } = useRouter()
|
||||
|
||||
const { isAuth, logoutUser, user } = useContext(UserContext);
|
||||
const [isActive, setIsActive] = useState(false);
|
||||
const { pathname } = useRouter();
|
||||
const toggleNavbar = () => {
|
||||
setIsActive(!isActive)
|
||||
}
|
||||
|
||||
const toggleNavbar = () => {
|
||||
setIsActive(!isActive);
|
||||
}
|
||||
return (
|
||||
<header className='Header'>
|
||||
<div className='container'>
|
||||
|
||||
return (
|
||||
<header className="Header">
|
||||
<div className="container">
|
||||
{/* Brand */}
|
||||
<Link href='/'>
|
||||
<a className='Header__brand-link'>
|
||||
<img id='brand-link__logo' src='/images/FunctionProject_brand-logo.png' alt='FunctionProject' />
|
||||
<img id='brand-link__logo-small-screen' src='/images/FunctionProject_icon_small.png' alt='FunctionProject' />
|
||||
</a>
|
||||
</Link>
|
||||
|
||||
{/* Brand */}
|
||||
<Link href={"/"}>
|
||||
<a className="Header__brand-link">
|
||||
<img id="brand-link__logo" src="/images/FunctionProject_brand-logo.png" alt="FunctionProject" />
|
||||
<img id="brand-link__logo-small-screen" src="/images/FunctionProject_icon_small.png" alt="FunctionProject" />
|
||||
</a>
|
||||
</Link>
|
||||
{/* Hamburger icon on Mobile */}
|
||||
<div onClick={toggleNavbar} className={`Header__hamburger ${(isActive) ? 'Header__hamburger-active' : ''}`}>
|
||||
<span />
|
||||
</div>
|
||||
|
||||
{/* Hamburger icon on Mobile */}
|
||||
<div onClick={toggleNavbar} className={`Header__hamburger ${(isActive) ? "Header__hamburger-active" : ""}`}>
|
||||
<span></span>
|
||||
</div>
|
||||
{/* Navigation */}
|
||||
<nav className='Header__navbar'>
|
||||
<ul className={`navbar__list ${(isActive) ? 'navbar__list-active' : ''}`}>
|
||||
<NavigationLink name='Accueil' path='/' />
|
||||
<NavigationLink name='Fonctions' path='/functions' />
|
||||
<NavigationLink name='Utilisateurs' path='/users' />
|
||||
{
|
||||
(!isAuth)
|
||||
? (
|
||||
<>
|
||||
<NavigationLink name="S'inscrire" path='/users/register' />
|
||||
<NavigationLink name='Connexion' path='/users/login' />
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<li className='navbar-item'>
|
||||
<Link href='/users/[name]' as={`/users/${user.name}`}>
|
||||
<a className={`navbar-link ${pathname === '/users/[name]' ? 'navbar-link-active' : null}`}>Mon Profil</a>
|
||||
</Link>
|
||||
</li>
|
||||
<li className='navbar-item'>
|
||||
<Link href='/'>
|
||||
<a onClick={logoutUser} className='navbar-link'>Se déconnecter</a>
|
||||
</Link>
|
||||
</li>
|
||||
</>
|
||||
)
|
||||
}
|
||||
{
|
||||
(isAuth && user.isAdmin) &&
|
||||
<NavigationLink name='Admin' path='/admin' />
|
||||
}
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="Header__navbar">
|
||||
<ul className={`navbar__list ${(isActive) ? "navbar__list-active" : ""}`}>
|
||||
<NavigationLink name="Accueil" path="/" />
|
||||
<NavigationLink name="Fonctions" path="/functions" />
|
||||
<NavigationLink name="Utilisateurs" path="/users" />
|
||||
{
|
||||
(!isAuth) ?
|
||||
<Fragment>
|
||||
<NavigationLink name="S'inscrire" path="/users/register" />
|
||||
<NavigationLink name="Connexion" path="/users/login" />
|
||||
</Fragment>
|
||||
:
|
||||
<Fragment>
|
||||
<li className="navbar-item">
|
||||
<Link href={"/users/[name]"} as={`/users/${user.name}`}>
|
||||
<a className={`navbar-link ${pathname === "/users/[name]" ? "navbar-link-active" : null}`}>Mon Profil</a>
|
||||
</Link>
|
||||
</li>
|
||||
<li className="navbar-item">
|
||||
<Link href={"/"}>
|
||||
<a onClick={logoutUser} className="navbar-link">Se déconnecter</a>
|
||||
</Link>
|
||||
</li>
|
||||
</Fragment>
|
||||
}
|
||||
{
|
||||
(isAuth && user.isAdmin) &&
|
||||
<NavigationLink name="Admin" path="/admin" />
|
||||
}
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
@ -1,18 +1,17 @@
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/router';
|
||||
import './Header.css';
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/router'
|
||||
import './Header.css'
|
||||
|
||||
export default function NavigationLink(props) {
|
||||
export default function NavigationLink (props) {
|
||||
const { pathname } = useRouter()
|
||||
|
||||
const { pathname } = useRouter();
|
||||
|
||||
return (
|
||||
<li className="navbar-item">
|
||||
<Link href={props.path}>
|
||||
<a className={`navbar-link ${pathname === props.path ? "navbar-link-active" : null}`}>
|
||||
{props.name}
|
||||
</a>
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<li className='navbar-item'>
|
||||
<Link href={props.path}>
|
||||
<a className={`navbar-link ${pathname === props.path ? 'navbar-link-active' : null}`}>
|
||||
{props.name}
|
||||
</a>
|
||||
</Link>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
@ -1,15 +1,15 @@
|
||||
const Loader = ({ width, height, speed }) => (
|
||||
<svg width={width} height={height} viewBox="0 0 100 100">
|
||||
<g transform="translate(50 50) rotate(0) scale(1 1) translate(-50 -50)">
|
||||
<image style={{transformOrigin: "50% 50%", animation: `${speed} linear 0s infinite normal forwards running Loader__spin`}} x="0" y="0" width="100" height="100" href="/images/FunctionProject_icon.png"></image>
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
<svg width={width} height={height} viewBox='0 0 100 100'>
|
||||
<g transform='translate(50 50) rotate(0) scale(1 1) translate(-50 -50)'>
|
||||
<image style={{ transformOrigin: '50% 50%', animation: `${speed} linear 0s infinite normal forwards running Loader__spin` }} x='0' y='0' width='100' height='100' href='/images/FunctionProject_icon.png' />
|
||||
</g>
|
||||
</svg>
|
||||
)
|
||||
|
||||
Loader.defaultProps = {
|
||||
width: "100px",
|
||||
height: "100px",
|
||||
speed: ".9s"
|
||||
width: '100px',
|
||||
height: '100px',
|
||||
speed: '.9s'
|
||||
}
|
||||
|
||||
export default Loader;
|
||||
export default Loader
|
||||
|
@ -1,9 +1,9 @@
|
||||
const Modal = (props) => (
|
||||
<div className="Modal container-fluid">
|
||||
<div className="Modal__content">
|
||||
{props.children}
|
||||
</div>
|
||||
<div className='Modal container-fluid'>
|
||||
<div className='Modal__content'>
|
||||
{props.children}
|
||||
</div>
|
||||
);
|
||||
</div>
|
||||
)
|
||||
|
||||
export default Modal;
|
||||
export default Modal
|
||||
|
@ -1,68 +1,63 @@
|
||||
import { createContext, useState, useEffect } from 'react';
|
||||
import Cookies from "universal-cookie";
|
||||
import api from '../utils/api';
|
||||
import { createContext, useState, useEffect } from 'react'
|
||||
import Cookies from 'universal-cookie'
|
||||
import api from '../utils/api'
|
||||
|
||||
const cookies = new Cookies();
|
||||
const cookies = new Cookies()
|
||||
|
||||
export const UserContext = createContext();
|
||||
export const UserContext = createContext()
|
||||
|
||||
function UserContextProvider(props) {
|
||||
function UserContextProvider (props) {
|
||||
const [user, setUser] = useState(null)
|
||||
const [isAuth, setIsAuth] = useState(false)
|
||||
const [loginLoading, setLoginLoading] = useState(false)
|
||||
const [messageLogin, setMessageLogin] = useState('')
|
||||
|
||||
const [user, setUser] = useState(null);
|
||||
const [isAuth, setIsAuth] = useState(false);
|
||||
const [loginLoading, setLoginLoading] = useState(false);
|
||||
const [messageLogin, setMessageLogin] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const newUser = cookies.get('user');
|
||||
if (newUser != undefined) {
|
||||
setIsAuth(true);
|
||||
setUser(newUser);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuth) {
|
||||
setMessageLogin('<p class="form-error"><b>Erreur:</b> Vous devez être déconnecter avant de vous connecter.</p>');
|
||||
} else {
|
||||
setMessageLogin("");
|
||||
}
|
||||
}, [isAuth]);
|
||||
|
||||
const logoutUser = () => {
|
||||
cookies.remove('user', { path: '/' });
|
||||
setUser(null);
|
||||
setIsAuth(false);
|
||||
}
|
||||
|
||||
const loginUser = ({ email, password }) => {
|
||||
setLoginLoading(true);
|
||||
return new Promise(async (next) => {
|
||||
try {
|
||||
const response = await api.post('/users/login', { email, password });
|
||||
const newUser = response.data;
|
||||
cookies.remove('user', { path: '/' });
|
||||
cookies.set('user', newUser, { path: '/', maxAge: newUser.expiresIn });
|
||||
setUser(newUser);
|
||||
setIsAuth(true);
|
||||
setMessageLogin('<p class="form-success"><b>Succès:</b> Connexion réussi!</p>');
|
||||
setLoginLoading(false);
|
||||
return next();
|
||||
} catch (error) {
|
||||
setMessageLogin(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
|
||||
setLoginLoading(false);
|
||||
setIsAuth(false);
|
||||
setUser(null);
|
||||
return next();
|
||||
}
|
||||
});
|
||||
useEffect(() => {
|
||||
const newUser = cookies.get('user')
|
||||
if (newUser != null) {
|
||||
setIsAuth(true)
|
||||
setUser(newUser)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={{ user, loginUser, logoutUser, loginLoading, messageLogin, isAuth, setMessageLogin }}>
|
||||
{props.children}
|
||||
</UserContext.Provider>
|
||||
);
|
||||
useEffect(() => {
|
||||
if (isAuth) {
|
||||
setMessageLogin('<p class="form-error"><b>Erreur:</b> Vous devez être déconnecter avant de vous connecter.</p>')
|
||||
} else {
|
||||
setMessageLogin('')
|
||||
}
|
||||
}, [isAuth])
|
||||
|
||||
const logoutUser = () => {
|
||||
cookies.remove('user', { path: '/' })
|
||||
setUser(null)
|
||||
setIsAuth(false)
|
||||
}
|
||||
|
||||
const loginUser = async ({ email, password }) => {
|
||||
setLoginLoading(true)
|
||||
try {
|
||||
const response = await api.post('/users/login', { email, password })
|
||||
const newUser = response.data
|
||||
cookies.remove('user', { path: '/' })
|
||||
cookies.set('user', newUser, { path: '/', maxAge: newUser.expiresIn })
|
||||
setUser(newUser)
|
||||
setIsAuth(true)
|
||||
setMessageLogin('<p class="form-success"><b>Succès:</b> Connexion réussi!</p>')
|
||||
setLoginLoading(false)
|
||||
} catch (error) {
|
||||
setMessageLogin(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`)
|
||||
setLoginLoading(false)
|
||||
setIsAuth(false)
|
||||
setUser(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={{ user, loginUser, logoutUser, loginLoading, messageLogin, isAuth, setMessageLogin }}>
|
||||
{props.children}
|
||||
</UserContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export default UserContextProvider;
|
||||
export default UserContextProvider
|
||||
|
@ -1,19 +1,17 @@
|
||||
import { useContext } from 'react';
|
||||
import { UserContext } from '../contexts/UserContext';
|
||||
import redirect from '../utils/redirect';
|
||||
import { useContext } from 'react'
|
||||
import { UserContext } from '../contexts/UserContext'
|
||||
import redirect from '../utils/redirect'
|
||||
|
||||
const withoutAuth = (WrappedComponent) => {
|
||||
|
||||
const Component = (props) => {
|
||||
|
||||
const { isAuth, user } = useContext(UserContext);
|
||||
|
||||
if (isAuth) return redirect({}, `/users/${user.name}`);
|
||||
const Component = (props) => {
|
||||
const { isAuth, user } = useContext(UserContext)
|
||||
|
||||
return <WrappedComponent { ...props } />;
|
||||
}
|
||||
if (isAuth) return redirect({}, `/users/${user.name}`)
|
||||
|
||||
return Component;
|
||||
}
|
||||
return <WrappedComponent {...props} />
|
||||
}
|
||||
|
||||
export default withoutAuth;
|
||||
return Component
|
||||
}
|
||||
|
||||
export default withoutAuth
|
||||
|
@ -1,31 +1,30 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import api from '../utils/api';
|
||||
import { useEffect, useState } from 'react'
|
||||
import api from '../utils/api'
|
||||
|
||||
/**
|
||||
* @param {String} url
|
||||
* @param {*} defaultData
|
||||
* @param {String} method
|
||||
* @param {Object} options
|
||||
* @param {String} url
|
||||
* @param {*} defaultData
|
||||
* @param {String} method
|
||||
* @param {Object} options
|
||||
*/
|
||||
function useAPI(url, defaultData = [], method = "get", options = {}) {
|
||||
function useAPI (url, defaultData = [], method = 'get', options = {}) {
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [data, setData] = useState(defaultData)
|
||||
const [hasError, setHasError] = useState(false)
|
||||
|
||||
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)
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
api[method](url, options)
|
||||
.then((result) => {
|
||||
setData(result.data);
|
||||
setIsLoading(false);
|
||||
})
|
||||
.catch((error) => {
|
||||
setHasError(true);
|
||||
console.error(error);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return [isLoading, data, hasError];
|
||||
return [isLoading, data, hasError]
|
||||
}
|
||||
|
||||
export default useAPI;
|
||||
export default useAPI
|
||||
|
@ -1,3 +1,3 @@
|
||||
const withCSS = require('@zeit/next-css');
|
||||
const withFonts = require('next-fonts');
|
||||
module.exports = withFonts(withCSS());
|
||||
const withCSS = require('@zeit/next-css')
|
||||
const withFonts = require('next-fonts')
|
||||
module.exports = withFonts(withCSS())
|
||||
|
9005
website/package-lock.json
generated
9005
website/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -4,10 +4,11 @@
|
||||
"description": "Website frontend for FunctionProject",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"dev": "cross-env NODE_ENV=dev node server",
|
||||
"dev": "cross-env NODE_ENV=development node server",
|
||||
"build": "next build",
|
||||
"export": "next export",
|
||||
"start": "cross-env NODE_ENV=production node server"
|
||||
"start": "cross-env NODE_ENV=production node server",
|
||||
"format": "standard \"./**/*.{js,jsx}\" --fix | snazzy || exit 0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-svg-core": "^1.2.28",
|
||||
@ -22,7 +23,7 @@
|
||||
"express": "^4.17.1",
|
||||
"express-http-to-https": "^1.1.4",
|
||||
"html-react-parser": "^0.10.2",
|
||||
"next": "9.3.2",
|
||||
"next": "^9.5.1",
|
||||
"next-fonts": "^1.0.3",
|
||||
"notyf": "^3.6.0",
|
||||
"nprogress": "^0.2.0",
|
||||
@ -39,6 +40,8 @@
|
||||
"universal-cookie": "^4.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"cross-env": "^7.0.2"
|
||||
"cross-env": "^7.0.2",
|
||||
"snazzy": "^8.0.0",
|
||||
"standard": "^14.3.4"
|
||||
}
|
||||
}
|
||||
|
@ -1,22 +1,21 @@
|
||||
import { Fragment } from 'react';
|
||||
import Link from 'next/link';
|
||||
import HeadTag from '../components/HeadTag';
|
||||
import '../public/css/pages/404.css';
|
||||
import Link from 'next/link'
|
||||
import HeadTag from '../components/HeadTag'
|
||||
import '../public/css/pages/404.css'
|
||||
|
||||
const Error404 = () => (
|
||||
<Fragment>
|
||||
<HeadTag
|
||||
title="Erreur 404"
|
||||
description="Cette page n'existe pas!"
|
||||
image="/images/error404.png"
|
||||
/>
|
||||
<div className="Error404__container">
|
||||
<h1>Erreur <span className="important">404</span></h1>
|
||||
<p className="text-center">
|
||||
Cette page n'existe pas! <Link href={"/"}><a>Revenir à la page d'accueil ?</a></Link>
|
||||
</p>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
<>
|
||||
<HeadTag
|
||||
title='Erreur 404'
|
||||
description="Cette page n'existe pas!"
|
||||
image='/images/error404.png'
|
||||
/>
|
||||
<div className='Error404__container'>
|
||||
<h1>Erreur <span className='important'>404</span></h1>
|
||||
<p className='text-center'>
|
||||
Cette page n'existe pas! <Link href='/'><a>Revenir à la page d'accueil ?</a></Link>
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
|
||||
export default Error404;
|
||||
export default Error404
|
||||
|
@ -1,33 +1,33 @@
|
||||
/* Libraries Imports */
|
||||
import Router from 'next/router'
|
||||
import NProgress from 'nprogress';
|
||||
import NProgress from 'nprogress'
|
||||
|
||||
/* Components Imports */
|
||||
import Header from '../components/Header/Header';
|
||||
import Footer from '../components/Footer/Footer';
|
||||
import Header from '../components/Header/Header'
|
||||
import Footer from '../components/Footer/Footer'
|
||||
|
||||
/* Contexts Imports */
|
||||
import UserContextProvider from '../contexts/UserContext';
|
||||
import UserContextProvider from '../contexts/UserContext'
|
||||
|
||||
/* CSS Imports */
|
||||
import '../public/fonts/Montserrat/Montserrat.css';
|
||||
import '../public/css/normalize.css';
|
||||
import '../public/css/grid.css';
|
||||
import '../public/css/general.css';
|
||||
import '../public/css/nprogress.css';
|
||||
import '../public/fonts/Montserrat/Montserrat.css'
|
||||
import '../public/css/normalize.css'
|
||||
import '../public/css/grid.css'
|
||||
import '../public/css/general.css'
|
||||
import '../public/css/nprogress.css'
|
||||
|
||||
Router.events.on('routeChangeStart', () => NProgress.start())
|
||||
Router.events.on('routeChangeComplete', () => NProgress.done())
|
||||
Router.events.on('routeChangeError', () => NProgress.done())
|
||||
|
||||
Router.events.on('routeChangeStart', () => NProgress.start());
|
||||
Router.events.on('routeChangeComplete', () => NProgress.done());
|
||||
Router.events.on('routeChangeError', () => NProgress.done());
|
||||
|
||||
const App = ({ Component, pageProps }) => (
|
||||
<UserContextProvider>
|
||||
<Header />
|
||||
<div className="content container-fluid">
|
||||
<Component {...pageProps} />
|
||||
</div>
|
||||
<Footer />
|
||||
</UserContextProvider>
|
||||
);
|
||||
<UserContextProvider>
|
||||
<Header />
|
||||
<div className='content container-fluid'>
|
||||
<Component {...pageProps} />
|
||||
</div>
|
||||
<Footer />
|
||||
</UserContextProvider>
|
||||
)
|
||||
|
||||
export default App;
|
||||
export default App
|
||||
|
@ -1,28 +1,28 @@
|
||||
import Document, { Html, Head, Main, NextScript } from "next/document";
|
||||
import Loader from '../components/Loader';
|
||||
import Document, { Html, Head, Main, NextScript } from 'next/document'
|
||||
import Loader from '../components/Loader'
|
||||
|
||||
class MyDocument extends Document {
|
||||
static async getInitialProps(ctx) {
|
||||
const initialProps = await Document.getInitialProps(ctx);
|
||||
return { ...initialProps };
|
||||
}
|
||||
static async getInitialProps (ctx) {
|
||||
const initialProps = await Document.getInitialProps(ctx)
|
||||
return { ...initialProps }
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Html lang="fr">
|
||||
<Head />
|
||||
<body>
|
||||
<div id="preloader">
|
||||
<Loader />
|
||||
</div>
|
||||
<div className="isLoading">
|
||||
<Main />
|
||||
</div>
|
||||
<NextScript />
|
||||
</body>
|
||||
</Html>
|
||||
);
|
||||
}
|
||||
render () {
|
||||
return (
|
||||
<Html lang='fr'>
|
||||
<Head />
|
||||
<body>
|
||||
<div id='preloader'>
|
||||
<Loader />
|
||||
</div>
|
||||
<div className='isLoading'>
|
||||
<Main />
|
||||
</div>
|
||||
<NextScript />
|
||||
</body>
|
||||
</Html>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default MyDocument;
|
||||
export default MyDocument
|
||||
|
@ -1,49 +1,48 @@
|
||||
import { Fragment } from 'react';
|
||||
import axios from 'axios'
|
||||
import ReactMarkdown from 'react-markdown/with-html';
|
||||
import HeadTag from '../components/HeadTag';
|
||||
import ReactMarkdown from 'react-markdown/with-html'
|
||||
import HeadTag from '../components/HeadTag'
|
||||
|
||||
const About = (props) => {
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag
|
||||
title="À-propos - FunctionProject"
|
||||
description="À-propos de FunctionProject."
|
||||
return (
|
||||
<>
|
||||
<HeadTag
|
||||
title='À-propos - FunctionProject'
|
||||
description='À-propos de FunctionProject.'
|
||||
/>
|
||||
|
||||
<div className='container'>
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24 text-center'>
|
||||
<h1 style={{ marginBottom: 0, paddingTop: '20px' }}>À-propos</h1>
|
||||
<p style={{ marginTop: '5px', borderBottom: '1px solid var(--important)', paddingBottom: '30px' }}>(README.md du <a target='_blank' rel='noopener noreferrer' href='https://github.com/Divlo/FunctionProject'>GitHub</a>)</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: '30px' }} className='row'>
|
||||
<div className='col-24'>
|
||||
<ReactMarkdown
|
||||
source={props.data}
|
||||
escapeHtml={false}
|
||||
linkTarget='_blank'
|
||||
transformLinkUri={(uri) => {
|
||||
if (uri.startsWith('./')) {
|
||||
return `https://github.com/Divlo/FunctionProject/blob/master/${uri.slice(2)}`
|
||||
}
|
||||
return uri
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="container">
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24 text-center">
|
||||
<h1 style={{ marginBottom: 0, paddingTop: "20px" }}>À-propos</h1>
|
||||
<p style={{ marginTop: '5px', borderBottom: '1px solid var(--important)', paddingBottom: '30px' }}>(README.md du <a target="_blank" rel="noopener noreferrer" href="https://github.com/Divlo/FunctionProject">GitHub</a>)</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: '30px' }} className="row">
|
||||
<div className="col-24">
|
||||
<ReactMarkdown
|
||||
source={props.data}
|
||||
escapeHtml={false}
|
||||
linkTarget="_blank"
|
||||
transformLinkUri={(uri) => {
|
||||
if (uri.startsWith('./')) {
|
||||
return `https://github.com/Divlo/FunctionProject/blob/master/${uri.slice(2)}`;
|
||||
}
|
||||
return uri;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export async function getServerSideProps(_context) {
|
||||
const { data } = await axios.get('https://raw.githubusercontent.com/Divlo/FunctionProject/master/README.md');
|
||||
return {
|
||||
props: { data }
|
||||
};
|
||||
export async function getServerSideProps (_context) {
|
||||
const { data } = await axios.get('https://raw.githubusercontent.com/Divlo/FunctionProject/master/README.md')
|
||||
return {
|
||||
props: { data }
|
||||
}
|
||||
}
|
||||
|
||||
export default About;
|
||||
export default About
|
||||
|
@ -1,88 +1,87 @@
|
||||
import { Fragment, useState } from 'react';
|
||||
import Cookies from "universal-cookie";
|
||||
import SwipeableViews from 'react-swipeable-views';
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import AddEditFunction from '../../components/FunctionAdmin/AddEditFunction';
|
||||
import EditArticleFunction from '../../components/FunctionAdmin/EditArticleFunction';
|
||||
import EditFormFunction from '../../components/FunctionAdmin/EditFormFunction';
|
||||
import redirect from '../../utils/redirect';
|
||||
import api from '../../utils/api';
|
||||
import { API_URL } from '../../utils/config/config';
|
||||
import '../../components/FunctionPage/FunctionTabs.css';
|
||||
import '../../public/css/pages/admin.css';
|
||||
import { useState } from 'react'
|
||||
import Cookies from 'universal-cookie'
|
||||
import SwipeableViews from 'react-swipeable-views'
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import AddEditFunction from '../../components/FunctionAdmin/AddEditFunction'
|
||||
import EditArticleFunction from '../../components/FunctionAdmin/EditArticleFunction'
|
||||
import EditFormFunction from '../../components/FunctionAdmin/EditFormFunction'
|
||||
import redirect from '../../utils/redirect'
|
||||
import api from '../../utils/api'
|
||||
import { API_URL } from '../../utils/config/config'
|
||||
import '../../components/FunctionPage/FunctionTabs.css'
|
||||
import '../../public/css/pages/admin.css'
|
||||
|
||||
const AdminFunctionComponent = (props) => {
|
||||
const [slideIndex, setSlideIndex] = useState(0)
|
||||
|
||||
const [slideIndex, setSlideIndex] = useState(0);
|
||||
const handleDeleteFunction = async () => {
|
||||
await api.delete(`/admin/functions/${props.functionInfo.id}`, { headers: { Authorization: props.user.token } })
|
||||
redirect({}, '/admin')
|
||||
}
|
||||
|
||||
const handleDeleteFunction = async () => {
|
||||
await api.delete(`/admin/functions/${props.functionInfo.id}`, { headers: { 'Authorization': props.user.token } });
|
||||
redirect({}, '/admin');
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<HeadTag title={props.functionInfo.title} description={props.functionInfo.description} image={API_URL + props.functionInfo.image} />
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag title={props.functionInfo.title} description={props.functionInfo.description} image={API_URL + props.functionInfo.image} />
|
||||
<div className='container-fluid'>
|
||||
<div className='container'>
|
||||
<div className='row justify-content-center'>
|
||||
<ul className='FunctionTabs__nav'>
|
||||
<li className='FunctionTabs__nav-item'>
|
||||
<a onClick={() => setSlideIndex(0)} className={`FunctionTabs__nav-link ${(slideIndex === 0) && 'FunctionTabs__nav-link-active'}`}>✒️ Modifier</a>
|
||||
</li>
|
||||
<li className='FunctionTabs__nav-item'>
|
||||
<a onClick={() => setSlideIndex(1)} className={`FunctionTabs__nav-link ${(slideIndex === 1) && 'FunctionTabs__nav-link-active'}`}>📝 Article</a>
|
||||
</li>
|
||||
<li className='FunctionTabs__nav-item'>
|
||||
<a onClick={() => setSlideIndex(2)} className={`FunctionTabs__nav-link ${(slideIndex === 2) && 'FunctionTabs__nav-link-active'}`}>⚙️ Utilisation</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="container-fluid">
|
||||
<div className="container">
|
||||
<div className="row justify-content-center">
|
||||
<ul className="FunctionTabs__nav">
|
||||
<li className="FunctionTabs__nav-item">
|
||||
<a onClick={() => setSlideIndex(0)} className={`FunctionTabs__nav-link ${(slideIndex === 0) && "FunctionTabs__nav-link-active"}`}>✒️ Modifier</a>
|
||||
</li>
|
||||
<li className="FunctionTabs__nav-item">
|
||||
<a onClick={() => setSlideIndex(1)} className={`FunctionTabs__nav-link ${(slideIndex === 1) && "FunctionTabs__nav-link-active"}`}>📝 Article</a>
|
||||
</li>
|
||||
<li className="FunctionTabs__nav-item">
|
||||
<a onClick={() => setSlideIndex(2)} className={`FunctionTabs__nav-link ${(slideIndex === 2) && "FunctionTabs__nav-link-active"}`}>⚙️ Utilisation</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="container-fluid">
|
||||
<SwipeableViews onChangeIndex={(index) => setSlideIndex(index)} index={slideIndex}>
|
||||
<div className="Admin__Function-slide">
|
||||
<AddEditFunction
|
||||
defaultInputState={{ ...props.functionInfo }}
|
||||
user={props.user}
|
||||
isEditing
|
||||
/>
|
||||
<div style={{ marginBottom: '30px' }} className="text-center">
|
||||
<button onClick={handleDeleteFunction} className="btn btn-dark">Supprimer la fonction</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="Admin__Function-slide">
|
||||
<EditArticleFunction { ...props } />
|
||||
</div>
|
||||
<div className="Admin__Function-slide">
|
||||
<EditFormFunction { ...props } />
|
||||
</div>
|
||||
</SwipeableViews>
|
||||
</div>
|
||||
<div className='container-fluid'>
|
||||
<SwipeableViews onChangeIndex={(index) => setSlideIndex(index)} index={slideIndex}>
|
||||
<div className='Admin__Function-slide'>
|
||||
<AddEditFunction
|
||||
defaultInputState={{ ...props.functionInfo }}
|
||||
user={props.user}
|
||||
isEditing
|
||||
/>
|
||||
<div style={{ marginBottom: '30px' }} className='text-center'>
|
||||
<button onClick={handleDeleteFunction} className='btn btn-dark'>Supprimer la fonction</button>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
<div className='Admin__Function-slide'>
|
||||
<EditArticleFunction {...props} />
|
||||
</div>
|
||||
<div className='Admin__Function-slide'>
|
||||
<EditFormFunction {...props} />
|
||||
</div>
|
||||
</SwipeableViews>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
const cookies = new Cookies(context.req.headers.cookie);
|
||||
const user = { ...cookies.get('user') };
|
||||
const { slug } = context.params;
|
||||
if (!user.isAdmin) {
|
||||
return redirect(context, '/404');
|
||||
}
|
||||
return api.get(`/admin/functions/${slug}`, { headers: { 'Authorization': user.token } })
|
||||
.then((response) => {
|
||||
return {
|
||||
props: {
|
||||
user,
|
||||
functionInfo: response.data
|
||||
}
|
||||
};
|
||||
})
|
||||
.catch(() => redirect(context, '/404'));
|
||||
export async function getServerSideProps (context) {
|
||||
const cookies = new Cookies(context.req.headers.cookie)
|
||||
const user = { ...cookies.get('user') }
|
||||
const { slug } = context.params
|
||||
if (!user.isAdmin) {
|
||||
return redirect(context, '/404')
|
||||
}
|
||||
return api.get(`/admin/functions/${slug}`, { headers: { Authorization: user.token } })
|
||||
.then((response) => {
|
||||
return {
|
||||
props: {
|
||||
user,
|
||||
functionInfo: response.data
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => redirect(context, '/404'))
|
||||
}
|
||||
|
||||
export default AdminFunctionComponent;
|
||||
export default AdminFunctionComponent
|
||||
|
@ -1,76 +1,76 @@
|
||||
import Link from 'next/link';
|
||||
import { Fragment, useState } from 'react';
|
||||
import Cookies from "universal-cookie";
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faTimes } from '@fortawesome/free-solid-svg-icons';
|
||||
import Modal from '../../components/Modal';
|
||||
import FunctionsList from '../../components/FunctionsList/FunctionsList';
|
||||
import AddEditFunction from '../../components/FunctionAdmin/AddEditFunction';
|
||||
import redirect from '../../utils/redirect';
|
||||
import '../../public/css/pages/admin.css';
|
||||
import Link from 'next/link'
|
||||
import { useState } from 'react'
|
||||
import Cookies from 'universal-cookie'
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||
import { faTimes } from '@fortawesome/free-solid-svg-icons'
|
||||
import Modal from '../../components/Modal'
|
||||
import FunctionsList from '../../components/FunctionsList/FunctionsList'
|
||||
import AddEditFunction from '../../components/FunctionAdmin/AddEditFunction'
|
||||
import redirect from '../../utils/redirect'
|
||||
import '../../public/css/pages/admin.css'
|
||||
|
||||
const Admin = (props) => {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const toggleModal = () => setIsOpen(!isOpen)
|
||||
|
||||
const toggleModal = () => setIsOpen(!isOpen);
|
||||
return (
|
||||
<>
|
||||
<HeadTag title='Admin - FunctionProject' description="Page d'administration de FunctionProject." />
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag title="Admin - FunctionProject" description="Page d'administration de FunctionProject." />
|
||||
{/* Création d'une fonction */}
|
||||
{(isOpen)
|
||||
? (
|
||||
<Modal toggleModal={toggleModal}>
|
||||
<div className='Admin__Modal__container container-fluid'>
|
||||
<div className='Admin__Modal__row row'>
|
||||
<div className='col-24'>
|
||||
<div className='Admin__Modal-top-container row'>
|
||||
<div className='col-24'>
|
||||
<span onClick={toggleModal} style={{ cursor: 'pointer', position: 'absolute', left: 0 }}>
|
||||
<FontAwesomeIcon icon={faTimes} style={{ width: '1.5rem', color: 'red' }} />
|
||||
</span>
|
||||
<h2 className='text-center'>Crée une nouvelle fonction</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Création d'une fonction */}
|
||||
{(isOpen) ?
|
||||
<Modal toggleModal={toggleModal}>
|
||||
<div className="Admin__Modal__container container-fluid">
|
||||
<div className="Admin__Modal__row row">
|
||||
<div className="col-24">
|
||||
<div className="Admin__Modal-top-container row">
|
||||
<div className="col-24">
|
||||
<span onClick={toggleModal} style={{ cursor: 'pointer', position: 'absolute', left: 0 }}>
|
||||
<FontAwesomeIcon icon={faTimes} style={{ width: '1.5rem', color: 'red' }} />
|
||||
</span>
|
||||
<h2 className="text-center">Crée une nouvelle fonction</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='col-24'>
|
||||
<AddEditFunction defaultInputState={{ type: 'form' }} {...props} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
|
||||
<div className="col-24">
|
||||
<AddEditFunction defaultInputState={{ type: 'form' }} { ...props } />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
:
|
||||
|
||||
<FunctionsList isAdmin token={props.user.token}>
|
||||
<div className="col-24">
|
||||
<h1 className="Functions__title">Administration</h1>
|
||||
<button onClick={toggleModal} style={{ margin: '0 0 40px 0' }} className="btn btn-dark">Crée une nouvelle fonction</button>
|
||||
<Link href={"/admin/manageCategories"}>
|
||||
<button style={{ margin: '0 0 0 20px' }} className="btn btn-dark">Gérer les catégories</button>
|
||||
</Link>
|
||||
<Link href={"/admin/manageQuotes"}>
|
||||
<button style={{ margin: '0 0 0 20px' }} className="btn btn-dark">Gérer les citations</button>
|
||||
</Link>
|
||||
</div>
|
||||
</FunctionsList>
|
||||
}
|
||||
</Fragment>
|
||||
);
|
||||
: (
|
||||
<FunctionsList isAdmin token={props.user.token}>
|
||||
<div className='col-24'>
|
||||
<h1 className='Functions__title'>Administration</h1>
|
||||
<button onClick={toggleModal} style={{ margin: '0 0 40px 0' }} className='btn btn-dark'>Crée une nouvelle fonction</button>
|
||||
<Link href='/admin/manageCategories'>
|
||||
<button style={{ margin: '0 0 0 20px' }} className='btn btn-dark'>Gérer les catégories</button>
|
||||
</Link>
|
||||
<Link href='/admin/manageQuotes'>
|
||||
<button style={{ margin: '0 0 0 20px' }} className='btn btn-dark'>Gérer les citations</button>
|
||||
</Link>
|
||||
</div>
|
||||
</FunctionsList>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
const cookies = new Cookies(context.req.headers.cookie);
|
||||
const user = { ...cookies.get('user') };
|
||||
if (!user.isAdmin) {
|
||||
return redirect(context, '/404');
|
||||
}
|
||||
return {
|
||||
props: { user }
|
||||
};
|
||||
export async function getServerSideProps (context) {
|
||||
const cookies = new Cookies(context.req.headers.cookie)
|
||||
const user = { ...cookies.get('user') }
|
||||
if (!user.isAdmin) {
|
||||
return redirect(context, '/404')
|
||||
}
|
||||
return {
|
||||
props: { user }
|
||||
}
|
||||
}
|
||||
|
||||
export default Admin;
|
||||
export default Admin
|
||||
|
@ -1,187 +1,187 @@
|
||||
import { Fragment, useState } from 'react';
|
||||
import Cookies from "universal-cookie";
|
||||
import date from 'date-and-time';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faPen, faTrash, faTimes } from '@fortawesome/free-solid-svg-icons';
|
||||
import { PhotoshopPicker } from 'react-color';
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import Modal from '../../components/Modal';
|
||||
import redirect from '../../utils/redirect';
|
||||
import htmlParser from 'html-react-parser';
|
||||
import Loader from '../../components/Loader';
|
||||
import useAPI from '../../hooks/useAPI';
|
||||
import api from '../../utils/api';
|
||||
import '../../public/css/pages/admin.css';
|
||||
import { useState } from 'react'
|
||||
import Cookies from 'universal-cookie'
|
||||
import date from 'date-and-time'
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||
import { faPen, faTrash, faTimes } from '@fortawesome/free-solid-svg-icons'
|
||||
import { PhotoshopPicker } from 'react-color'
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import Modal from '../../components/Modal'
|
||||
import redirect from '../../utils/redirect'
|
||||
import htmlParser from 'html-react-parser'
|
||||
import Loader from '../../components/Loader'
|
||||
import useAPI from '../../hooks/useAPI'
|
||||
import api from '../../utils/api'
|
||||
import '../../public/css/pages/admin.css'
|
||||
|
||||
const defaultCategoryState = { name: "", color: "#ffffff" };
|
||||
const defaultCategoryState = { name: '', color: '#ffffff' }
|
||||
|
||||
const AddEditCategory = (props) => {
|
||||
const [inputState, setInputState] = useState(props.defaultInputState)
|
||||
const [message, setMessage] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const [inputState, setInputState] = useState(props.defaultInputState);
|
||||
const [message, setMessage] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const handleChange = (event, isTypeCheck = false) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = (event.target.files != null) ? event.target.files[0] : (isTypeCheck) ? event.target.checked : event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
const handleChange = (event, isTypeCheck = false) => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = (event.target.files != undefined) ? event.target.files[0] : (isTypeCheck) ? event.target.checked : event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
}
|
||||
const apiCallCategory = () => {
|
||||
if (props.isEditing) return api.put(`/admin/categories/${inputState.id}`, { name: inputState.name, color: inputState.color }, { headers: { Authorization: props.user.token } })
|
||||
return api.post('/admin/categories', inputState, { headers: { Authorization: props.user.token } })
|
||||
}
|
||||
|
||||
const apiCallCategory = () => {
|
||||
if (props.isEditing) return api.put(`/admin/categories/${inputState.id}`, { name: inputState.name, color: inputState.color }, { headers: { 'Authorization': props.user.token } });
|
||||
return api.post('/admin/categories', inputState, { headers: { 'Authorization': props.user.token } });
|
||||
}
|
||||
const handleSubmit = (event) => {
|
||||
event.preventDefault()
|
||||
setIsLoading(true)
|
||||
apiCallCategory()
|
||||
.then(() => {
|
||||
setIsLoading(false)
|
||||
window.location.reload(true)
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`)
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
event.preventDefault();
|
||||
setIsLoading(true);
|
||||
apiCallCategory()
|
||||
.then(() => {
|
||||
setIsLoading(false);
|
||||
window.location.reload(true);
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
|
||||
setIsLoading(false);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="Admin__Modal__container container-fluid">
|
||||
<div className="Admin__Modal__row row">
|
||||
<div className="col-24">
|
||||
<div className="Admin__Modal-top-container row">
|
||||
<div className="col-24">
|
||||
<span onClick={props.toggleModal} style={{ cursor: 'pointer', position: 'absolute', left: 0 }}>
|
||||
<FontAwesomeIcon icon={faTimes} style={{ width: '1.5rem', color: 'red' }} />
|
||||
</span>
|
||||
<h2 className="text-center">{(props.isEditing) ? "Modifier la catégorie" : "Crée une nouvelle catégorie"}</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-24">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="name">Nom :</label>
|
||||
<input value={inputState.name} onChange={handleChange} type="text" name="name" id="name" className="form-control" placeholder="(e.g : ✨ Utilitaires)" />
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="title">Couleur :</label>
|
||||
<PhotoshopPicker color={inputState.color} onChange={(color) => handleChange({ target: { name: "color", value: color.hex } })} />
|
||||
</div>
|
||||
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="form-result text-center">
|
||||
{
|
||||
(isLoading) ?
|
||||
<Loader />
|
||||
:
|
||||
htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
return (
|
||||
<div className='Admin__Modal__container container-fluid'>
|
||||
<div className='Admin__Modal__row row'>
|
||||
<div className='col-24'>
|
||||
<div className='Admin__Modal-top-container row'>
|
||||
<div className='col-24'>
|
||||
<span onClick={props.handleToggleModal} style={{ cursor: 'pointer', position: 'absolute', left: 0 }}>
|
||||
<FontAwesomeIcon icon={faTimes} style={{ width: '1.5rem', color: 'red' }} />
|
||||
</span>
|
||||
<h2 className='text-center'>{(props.isEditing) ? 'Modifier la catégorie' : 'Crée une nouvelle catégorie'}</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
<div className='col-24'>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='name'>Nom :</label>
|
||||
<input value={inputState.name} onChange={handleChange} type='text' name='name' id='name' className='form-control' placeholder='(e.g : ✨ Utilitaires)' />
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='title'>Couleur :</label>
|
||||
<PhotoshopPicker color={inputState.color} onChange={(color) => handleChange({ target: { name: 'color', value: color.hex } })} />
|
||||
</div>
|
||||
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className='form-result text-center'>
|
||||
{
|
||||
(isLoading)
|
||||
? <Loader />
|
||||
: htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const manageCategories = (props) => {
|
||||
const [, categories] = useAPI('/categories')
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [isEditing, setIsEditing] = useState(false)
|
||||
const [defaultInputState, setDefaultInputState] = useState(defaultCategoryState)
|
||||
|
||||
const [, categories] = useAPI('/categories');
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [defaultInputState, setDefaultInputState] = useState(defaultCategoryState);
|
||||
const toggleModal = () => setIsOpen(!isOpen)
|
||||
|
||||
const toggleModal = () => setIsOpen(!isOpen);
|
||||
const handleRemoveCategory = async (categoryId) => {
|
||||
try {
|
||||
await api.delete(`/admin/categories/${categoryId}`, { headers: { Authorization: props.user.token } })
|
||||
window.location.reload(true)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const handleRemoveCategory = async (categoryId) => {
|
||||
try {
|
||||
await api.delete(`/admin/categories/${categoryId}`, { headers: { 'Authorization': props.user.token } });
|
||||
window.location.reload(true);
|
||||
} catch {}
|
||||
}
|
||||
const handleEditCategory = (categoryInfo) => {
|
||||
setDefaultInputState(categoryInfo)
|
||||
setIsEditing(true)
|
||||
toggleModal()
|
||||
}
|
||||
|
||||
const handleEditCategory = (categoryInfo) => {
|
||||
setDefaultInputState(categoryInfo);
|
||||
setIsEditing(true);
|
||||
toggleModal();
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<HeadTag title='Admin - FunctionProject' description="Page d'administration de FunctionProject. Gérer les catégories." />
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag title="Admin - FunctionProject" description="Page d'administration de FunctionProject. Gérer les catégories." />
|
||||
|
||||
{
|
||||
(isOpen) ?
|
||||
<Modal>
|
||||
<AddEditCategory toggleModal={toggleModal} defaultInputState={defaultInputState} { ...props } isEditing={isEditing} />
|
||||
</Modal>
|
||||
:
|
||||
<div className="container-fluid text-center">
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24">
|
||||
<h1>Gérer les catégories</h1>
|
||||
<button onClick={() => { setDefaultInputState(defaultCategoryState); toggleModal(); setIsEditing(false); }} style={{ margin: '0 0 40px 0' }} className="btn btn-dark">Ajouter une catégorie</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row justify-content-center">
|
||||
<div className="container-fluid">
|
||||
<div className="col-24 table-column">
|
||||
<table className="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="table-row" scope="col">id</th>
|
||||
<th className="table-row" scope="col">name</th>
|
||||
<th className="table-row" scope="col">color</th>
|
||||
<th className="table-row" scope="col">createdAt</th>
|
||||
<th className="table-row" scope="col">updatedAt</th>
|
||||
<th className="table-row" scope="col">Modifier</th>
|
||||
<th className="table-row" scope="col">Supprimer</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{categories.map((category) => {
|
||||
return (
|
||||
<tr key={category.id} style={{ backgroundColor: category.color }}>
|
||||
<td className="table-row">{category.id}</td>
|
||||
<td className="table-row">{category.name}</td>
|
||||
<td className="table-row">{category.color}</td>
|
||||
<td className="table-row">{date.format(new Date(category.createdAt), 'DD/MM/YYYY à HH:mm', true)}</td>
|
||||
<td className="table-row">{date.format(new Date(category.updatedAt), 'DD/MM/YYYY à HH:mm', true)}</td>
|
||||
<td style={{ cursor: 'pointer' }} onClick={() => handleEditCategory({ name: category.name, color: category.color, id: category.id })}>
|
||||
<FontAwesomeIcon icon={faPen} style={{ width: '1.5rem' }} />
|
||||
</td>
|
||||
<td style={{ cursor: 'pointer' }} onClick={() => handleRemoveCategory(category.id)}>
|
||||
<FontAwesomeIcon icon={faTrash} style={{ width: '1.5rem' }} />
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</Fragment>
|
||||
);
|
||||
{
|
||||
(isOpen)
|
||||
? (
|
||||
<Modal>
|
||||
<AddEditCategory handleToggleModal={toggleModal} defaultInputState={defaultInputState} {...props} isEditing={isEditing} />
|
||||
</Modal>
|
||||
)
|
||||
: (
|
||||
<div className='container-fluid text-center'>
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24'>
|
||||
<h1>Gérer les catégories</h1>
|
||||
<button onClick={() => { setDefaultInputState(defaultCategoryState); toggleModal(); setIsEditing(false) }} style={{ margin: '0 0 40px 0' }} className='btn btn-dark'>Ajouter une catégorie</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className='row justify-content-center'>
|
||||
<div className='container-fluid'>
|
||||
<div className='col-24 table-column'>
|
||||
<table className='table'>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className='table-row' scope='col'>id</th>
|
||||
<th className='table-row' scope='col'>name</th>
|
||||
<th className='table-row' scope='col'>color</th>
|
||||
<th className='table-row' scope='col'>createdAt</th>
|
||||
<th className='table-row' scope='col'>updatedAt</th>
|
||||
<th className='table-row' scope='col'>Modifier</th>
|
||||
<th className='table-row' scope='col'>Supprimer</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{categories.map((category) => {
|
||||
return (
|
||||
<tr key={category.id} style={{ backgroundColor: category.color }}>
|
||||
<td className='table-row'>{category.id}</td>
|
||||
<td className='table-row'>{category.name}</td>
|
||||
<td className='table-row'>{category.color}</td>
|
||||
<td className='table-row'>{date.format(new Date(category.createdAt), 'DD/MM/YYYY à HH:mm', true)}</td>
|
||||
<td className='table-row'>{date.format(new Date(category.updatedAt), 'DD/MM/YYYY à HH:mm', true)}</td>
|
||||
<td style={{ cursor: 'pointer' }} onClick={() => handleEditCategory({ name: category.name, color: category.color, id: category.id })}>
|
||||
<FontAwesomeIcon icon={faPen} style={{ width: '1.5rem' }} />
|
||||
</td>
|
||||
<td style={{ cursor: 'pointer' }} onClick={() => handleRemoveCategory(category.id)}>
|
||||
<FontAwesomeIcon icon={faTrash} style={{ width: '1.5rem' }} />
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
const cookies = new Cookies(context.req.headers.cookie);
|
||||
const user = { ...cookies.get('user') };
|
||||
if (!user.isAdmin) {
|
||||
return redirect(context, '/404');
|
||||
}
|
||||
return {
|
||||
props: { user }
|
||||
};
|
||||
export async function getServerSideProps (context) {
|
||||
const cookies = new Cookies(context.req.headers.cookie)
|
||||
const user = { ...cookies.get('user') }
|
||||
if (!user.isAdmin) {
|
||||
return redirect(context, '/404')
|
||||
}
|
||||
return {
|
||||
props: { user }
|
||||
}
|
||||
}
|
||||
|
||||
export default manageCategories;
|
||||
export default manageCategories
|
||||
|
@ -1,122 +1,121 @@
|
||||
import { Fragment, useState, useEffect, useRef, useCallback } from 'react';
|
||||
import Cookies from "universal-cookie";
|
||||
import Link from 'next/link';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faCheck, faTrash } from '@fortawesome/free-solid-svg-icons';
|
||||
import redirect from '../../utils/redirect';
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import api from '../../utils/api';
|
||||
import '../../public/css/pages/admin.css';
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import Cookies from 'universal-cookie'
|
||||
import Link from 'next/link'
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||
import { faCheck, faTrash } from '@fortawesome/free-solid-svg-icons'
|
||||
import redirect from '../../utils/redirect'
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import api from '../../utils/api'
|
||||
import '../../public/css/pages/admin.css'
|
||||
|
||||
const manageQuotes = (props) => {
|
||||
const [quotesData, setQuotesData] = useState({ hasMore: true, rows: [], totalItems: 0 })
|
||||
const [isLoadingQuotes, setLoadingQuotes] = useState(true)
|
||||
const [pageQuotes, setPageQuotes] = useState(1)
|
||||
|
||||
const [quotesData, setQuotesData] = useState({ hasMore: true, rows: [], totalItems: 0 });
|
||||
const [isLoadingQuotes, setLoadingQuotes] = useState(true);
|
||||
const [pageQuotes, setPageQuotes] = useState(1);
|
||||
// Récupère les citations si la page change
|
||||
useEffect(() => {
|
||||
getQuotesData()
|
||||
}, [pageQuotes])
|
||||
|
||||
// Récupère les citations si la page change
|
||||
useEffect(() => {
|
||||
getQuotesData();
|
||||
}, [pageQuotes]);
|
||||
const getQuotesData = async () => {
|
||||
setLoadingQuotes(true)
|
||||
const { data } = await api.get(`/admin/quotes?limit=20page=${pageQuotes}`, { headers: { Authorization: props.user.token } })
|
||||
setQuotesData({
|
||||
hasMore: data.hasMore,
|
||||
rows: [...quotesData.rows, ...data.rows],
|
||||
totalItems: data.totalItems
|
||||
})
|
||||
setLoadingQuotes(false)
|
||||
}
|
||||
|
||||
const getQuotesData = async () => {
|
||||
setLoadingQuotes(true);
|
||||
const { data } = await api.get(`/admin/quotes?limit=20page=${pageQuotes}`, { headers: { 'Authorization': props.user.token } });
|
||||
setQuotesData({
|
||||
hasMore: data.hasMore,
|
||||
rows: [...quotesData.rows, ...data.rows],
|
||||
totalItems: data.totalItems
|
||||
});
|
||||
setLoadingQuotes(false);
|
||||
}
|
||||
// Permet la pagination au scroll
|
||||
const observer = useRef()
|
||||
const lastQuoteRef = useCallback((node) => {
|
||||
if (isLoadingQuotes) return
|
||||
if (observer.current) observer.current.disconnect()
|
||||
observer.current = new window.IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && quotesData.hasMore) {
|
||||
setPageQuotes(pageQuotes + 1)
|
||||
}
|
||||
}, { threshold: 1 })
|
||||
if (node) observer.current.observe(node)
|
||||
}, [isLoadingQuotes, quotesData.hasMore])
|
||||
|
||||
// Permet la pagination au scroll
|
||||
const observer = useRef();
|
||||
const lastQuoteRef = useCallback((node) => {
|
||||
if (isLoadingQuotes) return;
|
||||
if (observer.current) observer.current.disconnect();
|
||||
observer.current = new IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && quotesData.hasMore) {
|
||||
setPageQuotes(pageQuotes + 1);
|
||||
}
|
||||
}, { threshold: 1 });
|
||||
if (node) observer.current.observe(node);
|
||||
}, [isLoadingQuotes, quotesData.hasMore]);
|
||||
const handleValidationQuote = async (id, isValid) => {
|
||||
try {
|
||||
await api.put(`/admin/quotes/${id}`, { isValid }, { headers: { Authorization: props.user.token } })
|
||||
window.location.reload(true)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const handleValidationQuote = async (id, isValid) => {
|
||||
try {
|
||||
await api.put(`/admin/quotes/${id}`, { isValid }, { headers: { 'Authorization': props.user.token } });
|
||||
window.location.reload(true);
|
||||
} catch {}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<HeadTag title='Admin - FunctionProject' description="Page d'administration de FunctionProject. Gérer les citations." />
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag title="Admin - FunctionProject" description="Page d'administration de FunctionProject. Gérer les citations." />
|
||||
<div className='container-fluid'>
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24 text-center'>
|
||||
<h2>Liste des citations (non validées) : </h2>
|
||||
<p style={{ marginTop: '5px' }}>Total de {quotesData.totalItems} citations.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="container-fluid">
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24 text-center">
|
||||
<h2>Liste des citations (non validées) : </h2>
|
||||
<p style={{ marginTop: '5px' }}>Total de {quotesData.totalItems} citations.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="row" style={{ marginBottom: '30px' }}>
|
||||
<div className="col-24 table-column">
|
||||
<table className="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="table-row" scope="col">Citation/Proverbe</th>
|
||||
<th className="table-row" scope="col">Auteur</th>
|
||||
<th className="table-row" scope="col">Proposée par</th>
|
||||
<th className="table-row" scope="col">Valider</th>
|
||||
<th className="table-row" scope="col">Supprimer</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{quotesData.rows.map((currentQuote, index) => {
|
||||
const quoteJSX = (
|
||||
<Fragment>
|
||||
<td className="table-row text-center">{currentQuote.quote}</td>
|
||||
<td className="table-row text-center">{currentQuote.author}</td>
|
||||
<td className="table-row text-center">
|
||||
<Link href={"/users/[name]"} as={`/users/${currentQuote.user.name}`}>
|
||||
<a>{currentQuote.user.name}</a>
|
||||
</Link>
|
||||
</td>
|
||||
<td onClick={() => handleValidationQuote(currentQuote.id, true)} className="table-row text-center" style={{ cursor: 'pointer' }}>
|
||||
<FontAwesomeIcon icon={faCheck} style={{ width: '1.5rem' }} />
|
||||
</td>
|
||||
<td onClick={() => handleValidationQuote(currentQuote.id, false)} className="table-row text-center" style={{ cursor: 'pointer' }}>
|
||||
<FontAwesomeIcon icon={faTrash} style={{ width: '1.5rem' }} />
|
||||
</td>
|
||||
</Fragment>
|
||||
);
|
||||
// Si c'est le dernier élément
|
||||
if (quotesData.rows.length === index + 1) {
|
||||
return <tr key={index} ref={lastQuoteRef}>{quoteJSX}</tr>
|
||||
}
|
||||
return <tr key={index}>{quoteJSX}</tr>
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
<div className='row' style={{ marginBottom: '30px' }}>
|
||||
<div className='col-24 table-column'>
|
||||
<table className='table'>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className='table-row' scope='col'>Citation/Proverbe</th>
|
||||
<th className='table-row' scope='col'>Auteur</th>
|
||||
<th className='table-row' scope='col'>Proposée par</th>
|
||||
<th className='table-row' scope='col'>Valider</th>
|
||||
<th className='table-row' scope='col'>Supprimer</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{quotesData.rows.map((currentQuote, index) => {
|
||||
const quoteJSX = (
|
||||
<>
|
||||
<td className='table-row text-center'>{currentQuote.quote}</td>
|
||||
<td className='table-row text-center'>{currentQuote.author}</td>
|
||||
<td className='table-row text-center'>
|
||||
<Link href='/users/[name]' as={`/users/${currentQuote.user.name}`}>
|
||||
<a>{currentQuote.user.name}</a>
|
||||
</Link>
|
||||
</td>
|
||||
<td onClick={() => handleValidationQuote(currentQuote.id, true)} className='table-row text-center' style={{ cursor: 'pointer' }}>
|
||||
<FontAwesomeIcon icon={faCheck} style={{ width: '1.5rem' }} />
|
||||
</td>
|
||||
<td onClick={() => handleValidationQuote(currentQuote.id, false)} className='table-row text-center' style={{ cursor: 'pointer' }}>
|
||||
<FontAwesomeIcon icon={faTrash} style={{ width: '1.5rem' }} />
|
||||
</td>
|
||||
</>
|
||||
)
|
||||
// Si c'est le dernier élément
|
||||
if (quotesData.rows.length === index + 1) {
|
||||
return <tr key={index} ref={lastQuoteRef}>{quoteJSX}</tr>
|
||||
}
|
||||
return <tr key={index}>{quoteJSX}</tr>
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
const cookies = new Cookies(context.req.headers.cookie);
|
||||
const user = { ...cookies.get('user') };
|
||||
if (!user.isAdmin) {
|
||||
return redirect(context, '/404');
|
||||
}
|
||||
return {
|
||||
props: { user }
|
||||
};
|
||||
export async function getServerSideProps (context) {
|
||||
const cookies = new Cookies(context.req.headers.cookie)
|
||||
const user = { ...cookies.get('user') }
|
||||
if (!user.isAdmin) {
|
||||
return redirect(context, '/404')
|
||||
}
|
||||
return {
|
||||
props: { user }
|
||||
}
|
||||
}
|
||||
|
||||
export default manageQuotes;
|
||||
export default manageQuotes
|
||||
|
@ -1,54 +1,54 @@
|
||||
import FunctionTabs from '../../components/FunctionPage/FunctionTabs';
|
||||
import FunctionForm from '../../components/FunctionPage/FunctionForm';
|
||||
import FunctionArticle from '../../components/FunctionPage/FunctionArticle';
|
||||
import FunctionComments from '../../components/FunctionPage/FunctionComments/FunctionComments';
|
||||
import FunctionPage from '../../components/FunctionPage/FunctionPage';
|
||||
import redirect from '../../utils/redirect';
|
||||
import api from '../../utils/api';
|
||||
import '../../public/css/pages/FunctionComponent.css';
|
||||
import FunctionTabs from '../../components/FunctionPage/FunctionTabs'
|
||||
import FunctionForm from '../../components/FunctionPage/FunctionForm'
|
||||
import FunctionArticle from '../../components/FunctionPage/FunctionArticle'
|
||||
import FunctionComments from '../../components/FunctionPage/FunctionComments/FunctionComments'
|
||||
import FunctionPage from '../../components/FunctionPage/FunctionPage'
|
||||
import redirect from '../../utils/redirect'
|
||||
import api from '../../utils/api'
|
||||
import '../../public/css/pages/FunctionComponent.css'
|
||||
|
||||
const FunctionTabManager = (props) => {
|
||||
if (props.type === "form") {
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionForm inputsArray={ [...props.utilizationForm || []] } slug={props.slug} />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.type === 'form') {
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
);
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionForm inputsArray={[...props.utilizationForm || []]} slug={props.slug} />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
)
|
||||
}
|
||||
|
||||
const FunctionComponent = (props) => (
|
||||
<FunctionPage
|
||||
FunctionTabManager={FunctionTabManager}
|
||||
{ ...props }
|
||||
tabNames={(props.type === "form") ? ["⚙️ Utilisation", "📝 Article", "📬 Commentaires"] : ["📝 Article", "📬 Commentaires"]}
|
||||
/>
|
||||
);
|
||||
<FunctionPage
|
||||
FunctionTabManager={FunctionTabManager}
|
||||
{...props}
|
||||
tabNames={(props.type === 'form') ? ['⚙️ Utilisation', '📝 Article', '📬 Commentaires'] : ['📝 Article', '📬 Commentaires']}
|
||||
/>
|
||||
)
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
const { slug } = context.params;
|
||||
return api.get(`/functions/${slug}`)
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'));
|
||||
export async function getServerSideProps (context) {
|
||||
const { slug } = context.params
|
||||
return api.get(`/functions/${slug}`)
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'))
|
||||
}
|
||||
|
||||
export default FunctionComponent;
|
||||
export default FunctionComponent
|
||||
|
@ -1,124 +1,123 @@
|
||||
import { useState } from 'react';
|
||||
import Codepen from "react-codepen-embed";
|
||||
import redirect from '../../utils/redirect';
|
||||
import FunctionPage from '../../components/FunctionPage/FunctionPage';
|
||||
import FunctionTabs from '../../components/FunctionPage/FunctionTabs';
|
||||
import FunctionArticle from '../../components/FunctionPage/FunctionArticle';
|
||||
import FunctionComments from '../../components/FunctionPage/FunctionComments/FunctionComments';
|
||||
import Loader from '../../components/Loader';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faPlay, faPause, faSync } from '@fortawesome/free-solid-svg-icons';
|
||||
import api from '../../utils/api';
|
||||
import '../../public/css/pages/FunctionComponent.css';
|
||||
import '../../public/css/pages/functions/chronometerTimer.css';
|
||||
import { useState } from 'react'
|
||||
import Codepen from 'react-codepen-embed'
|
||||
import redirect from '../../utils/redirect'
|
||||
import FunctionPage from '../../components/FunctionPage/FunctionPage'
|
||||
import FunctionTabs from '../../components/FunctionPage/FunctionTabs'
|
||||
import FunctionArticle from '../../components/FunctionPage/FunctionArticle'
|
||||
import FunctionComments from '../../components/FunctionPage/FunctionComments/FunctionComments'
|
||||
import Loader from '../../components/Loader'
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||
import { faPlay, faPause, faSync } from '@fortawesome/free-solid-svg-icons'
|
||||
import api from '../../utils/api'
|
||||
import '../../public/css/pages/FunctionComponent.css'
|
||||
import '../../public/css/pages/functions/chronometerTimer.css'
|
||||
|
||||
let interval;
|
||||
function convertSeconds(seconds) {
|
||||
return {
|
||||
minutes: Math.floor(seconds / 60),
|
||||
seconds: seconds % 60
|
||||
};
|
||||
let interval
|
||||
function convertSeconds (seconds) {
|
||||
return {
|
||||
minutes: Math.floor(seconds / 60),
|
||||
seconds: seconds % 60
|
||||
}
|
||||
}
|
||||
|
||||
const Chronometer = () => {
|
||||
const [timeLength, setTimeLength] = useState(0) // seconds
|
||||
const [isPlaying, setIsPlaying] = useState(false)
|
||||
|
||||
const [timeLength, setTimeLength] = useState(0); // seconds
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
|
||||
const handlePlayPause = () => {
|
||||
if (isPlaying) {
|
||||
clearInterval(interval);
|
||||
} else {
|
||||
if (interval) clearInterval(interval);
|
||||
interval = setInterval(() => {
|
||||
setTimeLength((time) => time + 1);
|
||||
}, 1000);
|
||||
}
|
||||
setIsPlaying(!isPlaying);
|
||||
const handlePlayPause = () => {
|
||||
if (isPlaying) {
|
||||
clearInterval(interval)
|
||||
} else {
|
||||
if (interval) clearInterval(interval)
|
||||
interval = setInterval(() => {
|
||||
setTimeLength((time) => time + 1)
|
||||
}, 1000)
|
||||
}
|
||||
setIsPlaying(!isPlaying)
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
if (interval) clearInterval(interval);
|
||||
setIsPlaying(false);
|
||||
setTimeLength(0);
|
||||
}
|
||||
const handleReset = () => {
|
||||
if (interval) clearInterval(interval)
|
||||
setIsPlaying(false)
|
||||
setTimeLength(0)
|
||||
}
|
||||
|
||||
const getFormattedValue = () => {
|
||||
const minutesAndSeconds = convertSeconds(timeLength);
|
||||
const minutes = (minutesAndSeconds.minutes < 100) ? (('0'+minutesAndSeconds.minutes).slice(-2)) : minutesAndSeconds.minutes;
|
||||
const seconds = ('0'+minutesAndSeconds.seconds).slice(-2);
|
||||
return `${minutes}:${seconds}`;
|
||||
}
|
||||
const getFormattedValue = () => {
|
||||
const minutesAndSeconds = convertSeconds(timeLength)
|
||||
const minutes = (minutesAndSeconds.minutes < 100) ? (('0' + minutesAndSeconds.minutes).slice(-2)) : minutesAndSeconds.minutes
|
||||
const seconds = ('0' + minutesAndSeconds.seconds).slice(-2)
|
||||
return `${minutes}:${seconds}`
|
||||
}
|
||||
|
||||
return(
|
||||
<div className="container-fluid">
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-sm-24 col-md-12">
|
||||
<div className="Chronometer__container">
|
||||
<div className="Chronometer__item">
|
||||
<div className="Chronomter__row">
|
||||
<div className="Chronometer__time-left">
|
||||
{getFormattedValue()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="Chronometer__item Chronometer__buttons">
|
||||
<div className="Chronomter__row Chronometer__row-button">
|
||||
<button onClick={handlePlayPause} className="Chronometer-btn">
|
||||
<FontAwesomeIcon { ...(isPlaying) ? { icon: faPause } : { icon: faPlay } } />
|
||||
</button>
|
||||
<button onClick={handleReset} className="Chronometer-btn" title="Remettre à zéro ?">
|
||||
<FontAwesomeIcon icon={faSync} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
return (
|
||||
<div className='container-fluid'>
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-sm-24 col-md-12'>
|
||||
<div className='Chronometer__container'>
|
||||
<div className='Chronometer__item'>
|
||||
<div className='Chronomter__row'>
|
||||
<div className='Chronometer__time-left'>
|
||||
{getFormattedValue()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='Chronometer__item Chronometer__buttons'>
|
||||
<div className='Chronomter__row Chronometer__row-button'>
|
||||
<button onClick={handlePlayPause} className='Chronometer-btn'>
|
||||
<FontAwesomeIcon {...(isPlaying) ? { icon: faPause } : { icon: faPlay }} />
|
||||
</button>
|
||||
<button onClick={handleReset} className='Chronometer-btn' title='Remettre à zéro ?'>
|
||||
<FontAwesomeIcon icon={faSync} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const Pomodoro = () => {
|
||||
return (
|
||||
<div style={{ marginBottom: '50px' }} className="container-fluid">
|
||||
<Codepen hash="vYEbPoB" user="Divlo" height={800} defaultTab="result" preview={false} loader={() => <Loader />} />
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div style={{ marginBottom: '50px' }} className='container-fluid'>
|
||||
<Codepen hash='vYEbPoB' user='Divlo' height={800} defaultTab='result' preview={false} loader={() => <Loader />} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const FunctionTabManager = (props) => {
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div className="FunctionComponent__slide">
|
||||
<Chronometer />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<Pomodoro />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
);
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<Chronometer />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<Pomodoro />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
)
|
||||
}
|
||||
|
||||
const chronometerTimer = (props) => (
|
||||
<FunctionPage
|
||||
FunctionTabManager={FunctionTabManager}
|
||||
{ ...props }
|
||||
tabNames={["⏰ Chronomètre", "⌛ Pomodoro", "📝 Article", "📬 Commentaires"]}
|
||||
/>
|
||||
);
|
||||
<FunctionPage
|
||||
FunctionTabManager={FunctionTabManager}
|
||||
{...props}
|
||||
tabNames={['⏰ Chronomètre', '⌛ Pomodoro', '📝 Article', '📬 Commentaires']}
|
||||
/>
|
||||
)
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
return api.get(`/functions/chronometerTimer`)
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'));
|
||||
export async function getServerSideProps (context) {
|
||||
return api.get('/functions/chronometerTimer')
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'))
|
||||
}
|
||||
|
||||
export default chronometerTimer;
|
||||
export default chronometerTimer
|
||||
|
@ -1,22 +1,20 @@
|
||||
import { Fragment } from 'react';
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import FunctionsList from '../../components/FunctionsList/FunctionsList';
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import FunctionsList from '../../components/FunctionsList/FunctionsList'
|
||||
|
||||
const Functions = () => {
|
||||
return (
|
||||
<>
|
||||
<HeadTag
|
||||
title='Fonctions'
|
||||
description='Liste des fonctions.'
|
||||
image='/images/FunctionProject_icon_small.png'
|
||||
/>
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag
|
||||
title="Fonctions"
|
||||
description="Liste des fonctions."
|
||||
image="/images/FunctionProject_icon_small.png"
|
||||
/>
|
||||
|
||||
<FunctionsList>
|
||||
<h1 className="Functions__title">Fonctions</h1>
|
||||
</FunctionsList>
|
||||
</Fragment>
|
||||
);
|
||||
<FunctionsList>
|
||||
<h1 className='Functions__title'>Fonctions</h1>
|
||||
</FunctionsList>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Functions;
|
||||
export default Functions
|
||||
|
@ -1,271 +1,267 @@
|
||||
import { Fragment, useState, useEffect, useContext, useRef, useCallback } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { UserContext } from '../../contexts/UserContext';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faTwitter } from '@fortawesome/free-brands-svg-icons';
|
||||
import redirect from '../../utils/redirect';
|
||||
import htmlParser from 'html-react-parser';
|
||||
import Loader from '../../components/Loader';
|
||||
import FunctionPage from '../../components/FunctionPage/FunctionPage';
|
||||
import FunctionTabs from '../../components/FunctionPage/FunctionTabs';
|
||||
import FunctionArticle from '../../components/FunctionPage/FunctionArticle';
|
||||
import FunctionComments from '../../components/FunctionPage/FunctionComments/FunctionComments';
|
||||
import api from '../../utils/api';
|
||||
import copyToClipboard from '../../utils/copyToClipboard';
|
||||
import 'notyf/notyf.min.css';
|
||||
import '../../public/css/pages/FunctionComponent.css';
|
||||
import { useState, useEffect, useContext, useRef, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { UserContext } from '../../contexts/UserContext'
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||
import { faTwitter } from '@fortawesome/free-brands-svg-icons'
|
||||
import redirect from '../../utils/redirect'
|
||||
import htmlParser from 'html-react-parser'
|
||||
import Loader from '../../components/Loader'
|
||||
import FunctionPage from '../../components/FunctionPage/FunctionPage'
|
||||
import FunctionTabs from '../../components/FunctionPage/FunctionTabs'
|
||||
import FunctionArticle from '../../components/FunctionPage/FunctionArticle'
|
||||
import FunctionComments from '../../components/FunctionPage/FunctionComments/FunctionComments'
|
||||
import api from '../../utils/api'
|
||||
import copyToClipboard from '../../utils/copyToClipboard'
|
||||
import 'notyf/notyf.min.css'
|
||||
import '../../public/css/pages/FunctionComponent.css'
|
||||
|
||||
const GenerateQuote = () => {
|
||||
const [quote, setQuote] = useState({ quote: '', author: '' })
|
||||
|
||||
const [quote, setQuote] = useState({ quote: "", author: "" });
|
||||
useEffect(() => {
|
||||
getRandomQuote()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
getRandomQuote();
|
||||
}, []);
|
||||
const getRandomQuote = async () => {
|
||||
const { data } = await api.post('/functions/randomQuote')
|
||||
setQuote(data)
|
||||
}
|
||||
|
||||
const getRandomQuote = async () => {
|
||||
const { data } = await api.post("/functions/randomQuote");
|
||||
setQuote(data);
|
||||
const handleCopyQuote = () => {
|
||||
let Notyf
|
||||
if (typeof window !== 'undefined') {
|
||||
Notyf = require('notyf')
|
||||
}
|
||||
const notyf = new Notyf.Notyf({
|
||||
duration: 5000
|
||||
})
|
||||
copyToClipboard(`"${quote?.quote}" - ${quote?.author}`)
|
||||
notyf.success('Citation copiée dans le presse-papier!')
|
||||
}
|
||||
|
||||
const handleCopyQuote = () => {
|
||||
let Notyf;
|
||||
if (typeof window != 'undefined') {
|
||||
Notyf = require('notyf');
|
||||
}
|
||||
const notyf = new Notyf.Notyf({
|
||||
duration: 5000
|
||||
});
|
||||
copyToClipboard(`"${quote?.quote}" - ${quote?.author}`);
|
||||
notyf.success('Citation copiée dans le presse-papier!');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24 text-center">
|
||||
<button onClick={getRandomQuote} className="btn btn-dark">Générer une nouvelle citation</button>
|
||||
<button style={{ marginLeft: '15px' }} onClick={handleCopyQuote} className="btn btn-dark">Copier la citation</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginTop: '20px' }} className="row justify-content-center">
|
||||
<div className="col-24 text-center">
|
||||
<p>" {quote?.quote} "</p>
|
||||
<p>- {quote?.author}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginBottom: '20px' }} className="row justify-content-center">
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
href={`https://twitter.com/intent/tweet?text="${quote?.quote}" - ${quote?.author}&via=Divlo_FR&hashtags=citation,FunctionProject&url=https://function.divlo.fr/functions/randomQuote`}
|
||||
className="btn btn-lg btn-primary"
|
||||
>
|
||||
<FontAwesomeIcon icon={faTwitter} style={{ width: '1em' }} /> Twitter
|
||||
</a>
|
||||
</div>
|
||||
return (
|
||||
<div className='container-fluid'>
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24 text-center'>
|
||||
<button onClick={getRandomQuote} className='btn btn-dark'>Générer une nouvelle citation</button>
|
||||
<button style={{ marginLeft: '15px' }} onClick={handleCopyQuote} className='btn btn-dark'>Copier la citation</button>
|
||||
</div>
|
||||
);
|
||||
</div>
|
||||
<div style={{ marginTop: '20px' }} className='row justify-content-center'>
|
||||
<div className='col-24 text-center'>
|
||||
<p>" {quote?.quote} "</p>
|
||||
<p>- {quote?.author}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginBottom: '20px' }} className='row justify-content-center'>
|
||||
<a
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
href={`https://twitter.com/intent/tweet?text="${quote?.quote}" - ${quote?.author}&via=Divlo_FR&hashtags=citation,FunctionProject&url=https://function.divlo.fr/functions/randomQuote`}
|
||||
className='btn btn-lg btn-primary'
|
||||
>
|
||||
<FontAwesomeIcon icon={faTwitter} style={{ width: '1em' }} /> Twitter
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
let pageQuotes = 1;
|
||||
let pageQuotes = 1
|
||||
const QuoteList = () => {
|
||||
const [quotesData, setQuotesData] = useState({ hasMore: true, rows: [], totalItems: 0 })
|
||||
const [isLoadingQuotes, setLoadingQuotes] = useState(true)
|
||||
|
||||
const [quotesData, setQuotesData] = useState({ hasMore: true, rows: [], totalItems: 0 });
|
||||
const [isLoadingQuotes, setLoadingQuotes] = useState(true);
|
||||
// Récupère les citations initiales
|
||||
useEffect(() => {
|
||||
getQuotesData().then((data) => setQuotesData(data))
|
||||
}, [])
|
||||
|
||||
// Récupère les citations initiales
|
||||
useEffect(() => {
|
||||
getQuotesData().then((data) => setQuotesData(data));
|
||||
}, []);
|
||||
const getQuotesData = async () => {
|
||||
setLoadingQuotes(true)
|
||||
const { data } = await api.get(`/quotes?page=${pageQuotes}&limit=20`)
|
||||
setLoadingQuotes(false)
|
||||
return data
|
||||
}
|
||||
|
||||
const getQuotesData = async () => {
|
||||
setLoadingQuotes(true);
|
||||
const { data } = await api.get(`/quotes?page=${pageQuotes}&limit=20`);
|
||||
setLoadingQuotes(false);
|
||||
return data;
|
||||
}
|
||||
|
||||
// Permet la pagination au scroll
|
||||
const observer = useRef();
|
||||
const lastQuoteRef = useCallback((node) => {
|
||||
if (isLoadingQuotes) return;
|
||||
if (observer.current) observer.current.disconnect();
|
||||
observer.current = new IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && quotesData.hasMore) {
|
||||
pageQuotes += 1;
|
||||
getQuotesData().then((data) => {
|
||||
setQuotesData((oldData) => {
|
||||
return {
|
||||
hasMore: data.hasMore,
|
||||
rows: [...oldData.rows, ...data.rows],
|
||||
totalItems: data.totalItems
|
||||
};
|
||||
});
|
||||
});
|
||||
// Permet la pagination au scroll
|
||||
const observer = useRef()
|
||||
const lastQuoteRef = useCallback((node) => {
|
||||
if (isLoadingQuotes) return
|
||||
if (observer.current) observer.current.disconnect()
|
||||
observer.current = new window.IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && quotesData.hasMore) {
|
||||
pageQuotes += 1
|
||||
getQuotesData().then((data) => {
|
||||
setQuotesData((oldData) => {
|
||||
return {
|
||||
hasMore: data.hasMore,
|
||||
rows: [...oldData.rows, ...data.rows],
|
||||
totalItems: data.totalItems
|
||||
}
|
||||
}, { threshold: 1 });
|
||||
if (node) observer.current.observe(node);
|
||||
}, [isLoadingQuotes, quotesData.hasMore]);
|
||||
})
|
||||
})
|
||||
}
|
||||
}, { threshold: 1 })
|
||||
if (node) observer.current.observe(node)
|
||||
}, [isLoadingQuotes, quotesData.hasMore])
|
||||
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24 text-center">
|
||||
<h2 style={{ margin: 0 }}>Liste des citations : </h2>
|
||||
<p style={{ marginTop: '5px' }}>Total de {quotesData.totalItems} citations.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="row" style={{ marginBottom: '30px' }}>
|
||||
<div className="col-24 table-column">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="table-row" scope="col">Citation/Proverbe</th>
|
||||
<th className="table-row" scope="col">Auteur</th>
|
||||
<th className="table-row" scope="col">Proposée par</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{quotesData.rows.map((currentQuote, index) => {
|
||||
const quoteJSX = (
|
||||
<Fragment>
|
||||
<td className="table-row text-center">{currentQuote.quote}</td>
|
||||
<td className="table-row text-center">{currentQuote.author}</td>
|
||||
<td className="table-row text-center">
|
||||
<Link href={"/users/[name]"} as={`/users/${currentQuote.user.name}`}>
|
||||
<a>{currentQuote.user.name}</a>
|
||||
</Link>
|
||||
</td>
|
||||
</Fragment>
|
||||
);
|
||||
// Si c'est le dernier élément
|
||||
if (quotesData.rows.length === index + 1) {
|
||||
return <tr key={index} ref={lastQuoteRef}>{quoteJSX}</tr>
|
||||
}
|
||||
return <tr key={index}>{quoteJSX}</tr>
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
return (
|
||||
<div className='container-fluid'>
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24 text-center'>
|
||||
<h2 style={{ margin: 0 }}>Liste des citations : </h2>
|
||||
<p style={{ marginTop: '5px' }}>Total de {quotesData.totalItems} citations.</p>
|
||||
</div>
|
||||
);
|
||||
</div>
|
||||
|
||||
<div className='row' style={{ marginBottom: '30px' }}>
|
||||
<div className='col-24 table-column'>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className='table-row' scope='col'>Citation/Proverbe</th>
|
||||
<th className='table-row' scope='col'>Auteur</th>
|
||||
<th className='table-row' scope='col'>Proposée par</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{quotesData.rows.map((currentQuote, index) => {
|
||||
const quoteJSX = (
|
||||
<>
|
||||
<td className='table-row text-center'>{currentQuote.quote}</td>
|
||||
<td className='table-row text-center'>{currentQuote.author}</td>
|
||||
<td className='table-row text-center'>
|
||||
<Link href='/users/[name]' as={`/users/${currentQuote.user.name}`}>
|
||||
<a>{currentQuote.user.name}</a>
|
||||
</Link>
|
||||
</td>
|
||||
</>
|
||||
)
|
||||
// Si c'est le dernier élément
|
||||
if (quotesData.rows.length === index + 1) {
|
||||
return <tr key={index} ref={lastQuoteRef}>{quoteJSX}</tr>
|
||||
}
|
||||
return <tr key={index}>{quoteJSX}</tr>
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const SuggestQuote = () => {
|
||||
const { isAuth, user } = useContext(UserContext)
|
||||
const [inputState, setInputState] = useState({ quote: '', author: '' })
|
||||
const [message, setMessage] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const { isAuth, user } = useContext(UserContext);
|
||||
const [inputState, setInputState] = useState({ quote: "", author: "" });
|
||||
const [message, setMessage] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
}
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
setIsLoading(true);
|
||||
event.preventDefault();
|
||||
const token = user.token;
|
||||
if (isAuth && token != undefined) {
|
||||
api.post('/quotes', inputState, { headers: { 'Authorization': token } })
|
||||
.then(({ data }) => {
|
||||
setInputState({ quote: "", author: "" });
|
||||
setMessage(`<p class="form-success"><b>Succès:</b> ${data.message}</p>`);
|
||||
setIsLoading(false);
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
|
||||
setIsLoading(false);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!isAuth) {
|
||||
return (
|
||||
<p className="text-center">
|
||||
Vous devez être <Link href={'/users/login'}><a>connecté</a></Link> pour proposer une citation.
|
||||
</p>
|
||||
);
|
||||
const handleSubmit = (event) => {
|
||||
setIsLoading(true)
|
||||
event.preventDefault()
|
||||
const token = user.token
|
||||
if (isAuth && token != null) {
|
||||
api.post('/quotes', inputState, { headers: { Authorization: token } })
|
||||
.then(({ data }) => {
|
||||
setInputState({ quote: '', author: '' })
|
||||
setMessage(`<p class="form-success"><b>Succès:</b> ${data.message}</p>`)
|
||||
setIsLoading(false)
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`)
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (!isAuth) {
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24 text-center">
|
||||
<h2 style={{ margin: 0 }}>Proposer une citation : </h2>
|
||||
<p style={{ marginTop: '5px' }}>Vous pouvez proposer des citations, et une fois validé elles seront rajoutés à la liste des citations.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginBottom: '40px' }} className="row">
|
||||
<div className="col-24">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label htmlFor="quote" className="form-label">Citation :</label>
|
||||
<textarea value={inputState.quote} onChange={handleChange} style={{ height: 'auto' }} id="quote" name="quote" type="text" className="form-control" rows="4" placeholder="La citation..." />
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="author" className="form-label">Auteur :</label>
|
||||
<input value={inputState.author} onChange={handleChange} name="author" id="author" type="text" className="form-control" placeholder="L'auteur de la citation..." />
|
||||
</div>
|
||||
<p className='text-center'>
|
||||
Vous devez être <Link href='/users/login'><a>connecté</a></Link> pour proposer une citation.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-result text-center">
|
||||
{
|
||||
(isLoading) ?
|
||||
<Loader />
|
||||
:
|
||||
htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
return (
|
||||
<div className='container-fluid'>
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24 text-center'>
|
||||
<h2 style={{ margin: 0 }}>Proposer une citation : </h2>
|
||||
<p style={{ marginTop: '5px' }}>Vous pouvez proposer des citations, et une fois validé elles seront rajoutés à la liste des citations.</p>
|
||||
</div>
|
||||
);
|
||||
</div>
|
||||
<div style={{ marginBottom: '40px' }} className='row'>
|
||||
<div className='col-24'>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group'>
|
||||
<label htmlFor='quote' className='form-label'>Citation :</label>
|
||||
<textarea value={inputState.quote} onChange={handleChange} style={{ height: 'auto' }} id='quote' name='quote' type='text' className='form-control' rows='4' placeholder='La citation...' />
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label htmlFor='author' className='form-label'>Auteur :</label>
|
||||
<input value={inputState.author} onChange={handleChange} name='author' id='author' type='text' className='form-control' placeholder="L'auteur de la citation..." />
|
||||
</div>
|
||||
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<div className='form-result text-center'>
|
||||
{
|
||||
(isLoading)
|
||||
? <Loader />
|
||||
: htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const FunctionTabManager = (props) => {
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div className="FunctionComponent__slide">
|
||||
<GenerateQuote />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<QuoteList />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<SuggestQuote />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
);
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<GenerateQuote />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<QuoteList />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<SuggestQuote />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
)
|
||||
}
|
||||
|
||||
const randomQuote = (props) => (
|
||||
<FunctionPage
|
||||
FunctionTabManager={FunctionTabManager}
|
||||
{ ...props }
|
||||
tabNames={["⚙️ Utilisation", "📜 Liste", "✒️ Proposer", "📝 Article", "📬 Commentaires"]}
|
||||
/>
|
||||
);
|
||||
<FunctionPage
|
||||
FunctionTabManager={FunctionTabManager}
|
||||
{...props}
|
||||
tabNames={['⚙️ Utilisation', '📜 Liste', '✒️ Proposer', '📝 Article', '📬 Commentaires']}
|
||||
/>
|
||||
)
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
return api.get(`/functions/randomQuote`)
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'));
|
||||
export async function getServerSideProps (context) {
|
||||
return api.get('/functions/randomQuote')
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'))
|
||||
}
|
||||
|
||||
export default randomQuote;
|
||||
export default randomQuote
|
||||
|
@ -1,152 +1,158 @@
|
||||
import { useState, Fragment } from 'react';
|
||||
import redirect from '../../utils/redirect';
|
||||
import FunctionPage from '../../components/FunctionPage/FunctionPage';
|
||||
import FunctionTabs from '../../components/FunctionPage/FunctionTabs';
|
||||
import FunctionArticle from '../../components/FunctionPage/FunctionArticle';
|
||||
import FunctionComments from '../../components/FunctionPage/FunctionComments/FunctionComments';
|
||||
import Loader from '../../components/Loader';
|
||||
import api from '../../utils/api';
|
||||
import '../../public/css/pages/FunctionComponent.css';
|
||||
import '../../public/css/pages/functions/rightPrice.css';
|
||||
import { useState } from 'react'
|
||||
import redirect from '../../utils/redirect'
|
||||
import FunctionPage from '../../components/FunctionPage/FunctionPage'
|
||||
import FunctionTabs from '../../components/FunctionPage/FunctionTabs'
|
||||
import FunctionArticle from '../../components/FunctionPage/FunctionArticle'
|
||||
import FunctionComments from '../../components/FunctionPage/FunctionComments/FunctionComments'
|
||||
import Loader from '../../components/Loader'
|
||||
import api from '../../utils/api'
|
||||
import '../../public/css/pages/FunctionComponent.css'
|
||||
import '../../public/css/pages/functions/rightPrice.css'
|
||||
|
||||
const PlayRightPrice = () => {
|
||||
const [isPlaying, setIsPlaying] = useState(false)
|
||||
const [productToGuess, setProductToGuess] = useState({})
|
||||
const [isLoadingProduct, setIsLoadingProduct] = useState(false)
|
||||
const [enteredPrice, setEnteredPrice] = useState('')
|
||||
const [attemptsArray, setAttemptsArray] = useState([])
|
||||
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
const [productToGuess, setProductToGuess] = useState({});
|
||||
const [isLoadingProduct, setIsLoadingProduct] = useState(false);
|
||||
const [enteredPrice, setEnteredPrice] = useState("");
|
||||
const [attemptsArray, setAttemptsArray] = useState([]);
|
||||
const handlePlaying = () => {
|
||||
setIsPlaying(true)
|
||||
setAttemptsArray([])
|
||||
fetchRandomAmazonProduct()
|
||||
}
|
||||
|
||||
const handlePlaying = () => {
|
||||
setIsPlaying(true);
|
||||
setAttemptsArray([]);
|
||||
fetchRandomAmazonProduct();
|
||||
const fetchRandomAmazonProduct = async () => {
|
||||
setIsLoadingProduct(true)
|
||||
const { data } = await api.post('/functions/rightPrice')
|
||||
setProductToGuess(data)
|
||||
setIsLoadingProduct(false)
|
||||
}
|
||||
|
||||
const handleChange = (event) => {
|
||||
setEnteredPrice(event.target.value)
|
||||
}
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
event.preventDefault()
|
||||
const objectTry = {}
|
||||
const guessedPrice = Number((enteredPrice).replace(',', '.').replace(' ', ''))
|
||||
if (!isNaN(guessedPrice)) {
|
||||
objectTry.guessedPrice = guessedPrice
|
||||
objectTry.numberTry = attemptsArray.length + 1
|
||||
if (guessedPrice > productToGuess.price) {
|
||||
objectTry.message = "C'est moins !"
|
||||
} else if (guessedPrice < productToGuess.price) {
|
||||
objectTry.message = "C'est plus !"
|
||||
} else {
|
||||
objectTry.message = 'Bravo, vous avez trouvé le juste prix !'
|
||||
}
|
||||
setAttemptsArray([objectTry, ...attemptsArray])
|
||||
}
|
||||
setEnteredPrice('')
|
||||
}
|
||||
|
||||
const fetchRandomAmazonProduct = async () => {
|
||||
setIsLoadingProduct(true);
|
||||
const { data } = await api.post('/functions/rightPrice');
|
||||
setProductToGuess(data);
|
||||
setIsLoadingProduct(false);
|
||||
}
|
||||
|
||||
const handleChange = (event) => {
|
||||
setEnteredPrice(event.target.value);
|
||||
}
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
const objectTry = {};
|
||||
const guessedPrice = Number((enteredPrice).replace(",", ".").replace(" ", ""));
|
||||
if (!isNaN(guessedPrice)) {
|
||||
objectTry.guessedPrice = guessedPrice;
|
||||
objectTry.numberTry = attemptsArray.length + 1;
|
||||
if (guessedPrice > productToGuess.price) {
|
||||
objectTry.message = "C'est moins !";
|
||||
} else if (guessedPrice < productToGuess.price) {
|
||||
objectTry.message = "C'est plus !";
|
||||
} else {
|
||||
objectTry.message = "Bravo, vous avez trouvé le juste prix !";
|
||||
}
|
||||
setAttemptsArray([objectTry, ...attemptsArray]);
|
||||
}
|
||||
setEnteredPrice("");
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
{
|
||||
(!isPlaying) ?
|
||||
<div className="row justify-content-center">
|
||||
<div className="form-group text-center">
|
||||
<button onClick={handlePlaying} type="submit" className="btn btn-dark">Jouer</button>
|
||||
</div>
|
||||
return (
|
||||
<div className='container-fluid'>
|
||||
{
|
||||
(!isPlaying)
|
||||
? (
|
||||
<div className='row justify-content-center'>
|
||||
<div className='form-group text-center'>
|
||||
<button onClick={handlePlaying} type='submit' className='btn btn-dark'>Jouer</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
: (isLoadingProduct)
|
||||
? (
|
||||
<div className='row justify-content-center'>
|
||||
<Loader />
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<>
|
||||
<div className='row justify-content-center'>
|
||||
<div style={{ marginBottom: '20px' }} className='col-24 text-center'>
|
||||
<h4>{productToGuess.name}</h4>
|
||||
<img src={productToGuess.image} alt={productToGuess.name} className='Product__image' />
|
||||
</div>
|
||||
</div>
|
||||
: (isLoadingProduct) ?
|
||||
<div className="row justify-content-center">
|
||||
<Loader />
|
||||
|
||||
<div className='row justify-content-center'>
|
||||
<div style={{ marginBottom: '25px' }} className='col-24'>
|
||||
{((attemptsArray.length > 0) && attemptsArray[0].message === 'Bravo, vous avez trouvé le juste prix !')
|
||||
? (
|
||||
<div className='form-group text-center'>
|
||||
<button onClick={handlePlaying} type='submit' className='btn btn-dark'>Rejouer ?</button>
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='text-center'>
|
||||
<input value={enteredPrice} onChange={handleChange} name='enteredPrice' id='enteredPrice' type='number' step='0.01' className='form-control' autoComplete='off' placeholder='Devinez le prix (prix à virgule possible!)' />
|
||||
</div>
|
||||
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Deviner</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
:
|
||||
<Fragment>
|
||||
<div className="row justify-content-center">
|
||||
<div style={{ marginBottom: '20px' }} className="col-24 text-center">
|
||||
<h4>{productToGuess.name}</h4>
|
||||
<img src={productToGuess.image} alt={productToGuess.name} className="Product__image" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="row justify-content-center">
|
||||
<div style={{ marginBottom: '25px' }} className="col-24">
|
||||
{((attemptsArray.length > 0) && attemptsArray[0].message === "Bravo, vous avez trouvé le juste prix !") ?
|
||||
<div className="form-group text-center">
|
||||
<button onClick={handlePlaying} type="submit" className="btn btn-dark">Rejouer ?</button>
|
||||
</div>
|
||||
:
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="text-center">
|
||||
<input value={enteredPrice} onChange={handleChange} name="enteredPrice" id="enteredPrice" type="number" step="0.01" className="form-control" autoComplete="off" placeholder="Devinez le prix (prix à virgule possible!)" />
|
||||
</div>
|
||||
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Deviner</button>
|
||||
</div>
|
||||
</form>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: '30px' }} className="row justify-content-center">
|
||||
{attemptsArray.map((attempt, index) => {
|
||||
const { message } = attempt;
|
||||
let priceResultClass;
|
||||
if (message === "C'est moins !") {
|
||||
priceResultClass = "Price__result-moins";
|
||||
} else if (message === "C'est plus !") {
|
||||
priceResultClass = "Price__result-plus";
|
||||
} else {
|
||||
priceResultClass = "Price__result-success";
|
||||
}
|
||||
return (
|
||||
<div key={index} className={`col-24 Price__result ${priceResultClass}`}>
|
||||
# {attempt.numberTry} ({attempt.guessedPrice}) {message}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Fragment>
|
||||
}
|
||||
</div>
|
||||
);
|
||||
<div style={{ marginBottom: '30px' }} className='row justify-content-center'>
|
||||
{attemptsArray.map((attempt, index) => {
|
||||
const { message } = attempt
|
||||
let priceResultClass
|
||||
if (message === "C'est moins !") {
|
||||
priceResultClass = 'Price__result-moins'
|
||||
} else if (message === "C'est plus !") {
|
||||
priceResultClass = 'Price__result-plus'
|
||||
} else {
|
||||
priceResultClass = 'Price__result-success'
|
||||
}
|
||||
return (
|
||||
<div key={index} className={`col-24 Price__result ${priceResultClass}`}>
|
||||
# {attempt.numberTry} ({attempt.guessedPrice}) {message}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const FunctionTabManager = (props) => {
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div style={{ marginTop: '10px' }}>
|
||||
<PlayRightPrice />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
);
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div style={{ marginTop: '10px' }}>
|
||||
<PlayRightPrice />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
)
|
||||
}
|
||||
|
||||
const rightPrice = (props) => (
|
||||
<FunctionPage
|
||||
FunctionTabManager={FunctionTabManager}
|
||||
{ ...props }
|
||||
tabNames={["🕹️ Jouer", "📝 Article", "📬 Commentaires"]}
|
||||
/>
|
||||
);
|
||||
<FunctionPage
|
||||
FunctionTabManager={FunctionTabManager}
|
||||
{...props}
|
||||
tabNames={['🕹️ Jouer', '📝 Article', '📬 Commentaires']}
|
||||
/>
|
||||
)
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
return api.get(`/functions/rightPrice`)
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'));
|
||||
export async function getServerSideProps (context) {
|
||||
return api.get('/functions/rightPrice')
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'))
|
||||
}
|
||||
|
||||
export default rightPrice;
|
||||
export default rightPrice
|
||||
|
@ -1,149 +1,147 @@
|
||||
import { useState, useEffect, useContext } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faTrash, faCheck, faTimes } from '@fortawesome/free-solid-svg-icons';
|
||||
import { UserContext } from '../../contexts/UserContext';
|
||||
import redirect from '../../utils/redirect';
|
||||
import FunctionPage from '../../components/FunctionPage/FunctionPage';
|
||||
import FunctionTabs from '../../components/FunctionPage/FunctionTabs';
|
||||
import FunctionArticle from '../../components/FunctionPage/FunctionArticle';
|
||||
import FunctionComments from '../../components/FunctionPage/FunctionComments/FunctionComments';
|
||||
import api from '../../utils/api';
|
||||
import '../../public/css/pages/FunctionComponent.css';
|
||||
import '../../public/css/pages/functions/toDoList.css';
|
||||
import { useState, useEffect, useContext } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||
import { faTrash, faCheck, faTimes } from '@fortawesome/free-solid-svg-icons'
|
||||
import { UserContext } from '../../contexts/UserContext'
|
||||
import redirect from '../../utils/redirect'
|
||||
import FunctionPage from '../../components/FunctionPage/FunctionPage'
|
||||
import FunctionTabs from '../../components/FunctionPage/FunctionTabs'
|
||||
import FunctionArticle from '../../components/FunctionPage/FunctionArticle'
|
||||
import FunctionComments from '../../components/FunctionPage/FunctionComments/FunctionComments'
|
||||
import api from '../../utils/api'
|
||||
import '../../public/css/pages/FunctionComponent.css'
|
||||
import '../../public/css/pages/functions/toDoList.css'
|
||||
|
||||
const ManageToDo = () => {
|
||||
const { isAuth, user } = useContext(UserContext)
|
||||
const [inputState, setInputState] = useState({ task: '' })
|
||||
const [tasks, setTasks] = useState([])
|
||||
|
||||
const { isAuth, user } = useContext(UserContext);
|
||||
const [inputState, setInputState] = useState({ task: "" });
|
||||
const [tasks, setTasks] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
const getTasks = async () => {
|
||||
const { data } = await api.get('/tasks', { headers: { 'Authorization': user.token } });
|
||||
setTasks(data);
|
||||
}
|
||||
if (isAuth && user.token != undefined) {
|
||||
getTasks();
|
||||
}
|
||||
}, [isAuth]);
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
useEffect(() => {
|
||||
const getTasks = async () => {
|
||||
const { data } = await api.get('/tasks', { headers: { Authorization: user.token } })
|
||||
setTasks(data)
|
||||
}
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
try {
|
||||
const { data } = await api.post('/tasks', inputState, { headers: { 'Authorization': user.token } });
|
||||
const newTasks = [...tasks];
|
||||
newTasks.push(data);
|
||||
setTasks(newTasks);
|
||||
setInputState({ task: "" });
|
||||
} catch {}
|
||||
if (isAuth && user.token != null) {
|
||||
getTasks()
|
||||
}
|
||||
}, [isAuth])
|
||||
|
||||
const handleRemoveTask = async (id, index) => {
|
||||
const newTasks = [...tasks];
|
||||
try {
|
||||
await api.delete(`/tasks/${id}`, { headers: { 'Authorization': user.token } });
|
||||
newTasks.splice(index, 1);
|
||||
setTasks(newTasks);
|
||||
} catch {}
|
||||
}
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
const handleEditTask = async (id, index, isCompleted) => {
|
||||
try {
|
||||
await api.put(`/tasks/${id}`, { isCompleted: !isCompleted }, { headers: { 'Authorization': user.token } });
|
||||
const newTasks = [...tasks];
|
||||
const taskObject = newTasks[index];
|
||||
taskObject.isCompleted = !isCompleted;
|
||||
setTasks(newTasks);
|
||||
} catch {}
|
||||
}
|
||||
const handleSubmit = async (event) => {
|
||||
event.preventDefault()
|
||||
try {
|
||||
const { data } = await api.post('/tasks', inputState, { headers: { Authorization: user.token } })
|
||||
const newTasks = [...tasks]
|
||||
newTasks.push(data)
|
||||
setTasks(newTasks)
|
||||
setInputState({ task: '' })
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (!isAuth) {
|
||||
return (
|
||||
<p className="text-center">
|
||||
Vous devez être <Link href={'/users/login'}><a>connecté</a></Link> pour gérer des "tâches à faire".
|
||||
</p>
|
||||
);
|
||||
}
|
||||
const handleRemoveTask = async (id, index) => {
|
||||
const newTasks = [...tasks]
|
||||
try {
|
||||
await api.delete(`/tasks/${id}`, { headers: { Authorization: user.token } })
|
||||
newTasks.splice(index, 1)
|
||||
setTasks(newTasks)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const handleEditTask = async (id, index, isCompleted) => {
|
||||
try {
|
||||
await api.put(`/tasks/${id}`, { isCompleted: !isCompleted }, { headers: { Authorization: user.token } })
|
||||
const newTasks = [...tasks]
|
||||
const taskObject = newTasks[index]
|
||||
taskObject.isCompleted = !isCompleted
|
||||
setTasks(newTasks)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (!isAuth) {
|
||||
return (
|
||||
<div className="container-fluid">
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="text-center">
|
||||
<label htmlFor="task" className="form-label">Ajouter une tâche à faire :</label>
|
||||
<input value={inputState.task} onChange={handleChange} name="task" id="task" type="text" className="form-control" placeholder="(e.g : Apprendre à coder)" />
|
||||
</div>
|
||||
<p className='text-center'>
|
||||
Vous devez être <Link href='/users/login'><a>connecté</a></Link> pour gérer des "tâches à faire".
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
return (
|
||||
<div className='container-fluid'>
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24'>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='text-center'>
|
||||
<label htmlFor='task' className='form-label'>Ajouter une tâche à faire :</label>
|
||||
<input value={inputState.task} onChange={handleChange} name='task' id='task' type='text' className='form-control' placeholder='(e.g : Apprendre à coder)' />
|
||||
</div>
|
||||
|
||||
{(tasks.length > 0) &&
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24 ManageToDo__container">
|
||||
<ul className="ManageToDo__list">
|
||||
{tasks.map((task, index) => {
|
||||
return (
|
||||
<li key={task.id} className={`ManageToDo__list-item ${(task.isCompleted) ? "isCompleted" : ""}`}>
|
||||
<span className="ManageToDo__list-item-span">{task.task}</span>
|
||||
<div>
|
||||
<button className="ManageToDo__task-btn" title="Supprimer de la liste" onClick={() => handleRemoveTask(task.id, index)}>
|
||||
<FontAwesomeIcon icon={faTrash} />
|
||||
</button>
|
||||
<button className="ManageToDo__task-btn" onClick={() => handleEditTask(task.id, index, task.isCompleted)}>
|
||||
<FontAwesomeIcon { ...(task.isCompleted) ? { icon: faTimes } : { icon: faCheck } } />
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
</div>
|
||||
|
||||
{(tasks.length > 0) &&
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24 ManageToDo__container'>
|
||||
<ul className='ManageToDo__list'>
|
||||
{tasks.map((task, index) => {
|
||||
return (
|
||||
<li key={task.id} className={`ManageToDo__list-item ${(task.isCompleted) ? 'isCompleted' : ''}`}>
|
||||
<span className='ManageToDo__list-item-span'>{task.task}</span>
|
||||
<div>
|
||||
<button className='ManageToDo__task-btn' title='Supprimer de la liste' onClick={() => handleRemoveTask(task.id, index)}>
|
||||
<FontAwesomeIcon icon={faTrash} />
|
||||
</button>
|
||||
<button className='ManageToDo__task-btn' onClick={() => handleEditTask(task.id, index, task.isCompleted)}>
|
||||
<FontAwesomeIcon {...(task.isCompleted) ? { icon: faTimes } : { icon: faCheck }} />
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const FunctionTabManager = (props) => {
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div className="FunctionComponent__slide">
|
||||
<ManageToDo />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className="FunctionComponent__slide">
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
);
|
||||
return (
|
||||
<FunctionTabs setSlideIndex={props.setSlideIndex} slideIndex={props.slideIndex}>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<ManageToDo />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionArticle article={props.article} />
|
||||
</div>
|
||||
<div className='FunctionComponent__slide'>
|
||||
<FunctionComments functionId={props.id} />
|
||||
</div>
|
||||
</FunctionTabs>
|
||||
)
|
||||
}
|
||||
|
||||
const toDoList = (props) => (
|
||||
<FunctionPage
|
||||
FunctionTabManager={FunctionTabManager}
|
||||
{ ...props }
|
||||
tabNames={["⚙️ Utilisation", "📝 Article", "📬 Commentaires"]}
|
||||
/>
|
||||
);
|
||||
<FunctionPage
|
||||
FunctionTabManager={FunctionTabManager}
|
||||
{...props}
|
||||
tabNames={['⚙️ Utilisation', '📝 Article', '📬 Commentaires']}
|
||||
/>
|
||||
)
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
return api.get(`/functions/toDoList`)
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'));
|
||||
export async function getServerSideProps (context) {
|
||||
return api.get('/functions/toDoList')
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'))
|
||||
}
|
||||
|
||||
export default toDoList;
|
||||
export default toDoList
|
||||
|
@ -1,70 +1,69 @@
|
||||
import { Fragment, useEffect } from 'react';
|
||||
import SwipeableViews from 'react-swipeable-views';
|
||||
import { autoPlay } from 'react-swipeable-views-utils';
|
||||
import Link from 'next/link';
|
||||
import HeadTag from '../components/HeadTag';
|
||||
import Loader from '../components/Loader';
|
||||
import '../public/css/pages/index.css';
|
||||
import { useEffect } from 'react'
|
||||
import SwipeableViews from 'react-swipeable-views'
|
||||
import { autoPlay } from 'react-swipeable-views-utils'
|
||||
import Link from 'next/link'
|
||||
import HeadTag from '../components/HeadTag'
|
||||
import Loader from '../components/Loader'
|
||||
import '../public/css/pages/index.css'
|
||||
|
||||
const AutoPlaySwipeableViews = autoPlay(SwipeableViews);
|
||||
const AutoPlaySwipeableViews = autoPlay(SwipeableViews)
|
||||
|
||||
const Home = () => {
|
||||
useEffect(() => {
|
||||
console.log(
|
||||
'%c ⚙️ FunctionProject',
|
||||
'color: #ffd800; font-weight: bold; background-color: #181818;padding: 10px;border-radius: 10px;font-size: 20px'
|
||||
)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
console.log(
|
||||
'%c ⚙️ FunctionProject',
|
||||
'color: #ffd800; font-weight: bold; background-color: #181818;padding: 10px;border-radius: 10px;font-size: 20px'
|
||||
);
|
||||
}, []);
|
||||
return (
|
||||
<>
|
||||
<HeadTag />
|
||||
<div className='Home__container container-fluid text-center'>
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag />
|
||||
<div className="Home__container container-fluid text-center">
|
||||
|
||||
<AutoPlaySwipeableViews enableMouseEvents interval={15000}>
|
||||
|
||||
{/* Slide 1 */}
|
||||
<div className="row align-items-center justify-content-center">
|
||||
<div className="col-24">
|
||||
<h1 className="title-important">FunctionProject</h1>
|
||||
<p className="Home__description">
|
||||
Apprenez la programmation grâce à l'apprentissage par projet alias fonction (en <span className="important">JavaScript</span>).
|
||||
<br/>
|
||||
<Link href={"/about"}>
|
||||
<a>En savoir plus ? (à-propos)</a>
|
||||
</Link>
|
||||
<br/>
|
||||
Découvrez la liste des fonctions disponibles :
|
||||
</p>
|
||||
</div>
|
||||
<div className="col-24 Home__logo-spin">
|
||||
<Link href={"/functions"}>
|
||||
<a><Loader width="100%" height="13em" speed="5s" /></a>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Slide 2 */}
|
||||
<div className="row align-items-center justify-content-center">
|
||||
<div className="col-24">
|
||||
<h1 className="title-important">Code Source</h1>
|
||||
<p className="Home__description">
|
||||
Le partage est essentiel afin de progresser. <br/>
|
||||
Par conséquent chaque fonction a un article expliquant comment elle fonctionne et <br/>
|
||||
le code source du projet est disponible sur mon profil GitHub :
|
||||
</p>
|
||||
</div>
|
||||
<div className="col-24">
|
||||
<a target="_blank" rel="noopener noreferrer" href="https://github.com/Divlo/FunctionProject"><img className="Home__image-width" src="/images/GitHub.png" alt="GitHub" /></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</AutoPlaySwipeableViews>
|
||||
<AutoPlaySwipeableViews enableMouseEvents interval={15000}>
|
||||
|
||||
{/* Slide 1 */}
|
||||
<div className='row align-items-center justify-content-center'>
|
||||
<div className='col-24'>
|
||||
<h1 className='title-important'>FunctionProject</h1>
|
||||
<p className='Home__description'>
|
||||
Apprenez la programmation grâce à l'apprentissage par projet alias fonction (en <span className='important'>JavaScript</span>).
|
||||
<br />
|
||||
<Link href='/about'>
|
||||
<a>En savoir plus ? (à-propos)</a>
|
||||
</Link>
|
||||
<br />
|
||||
Découvrez la liste des fonctions disponibles :
|
||||
</p>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
<div className='col-24 Home__logo-spin'>
|
||||
<Link href='/functions'>
|
||||
<a><Loader width='100%' height='13em' speed='5s' /></a>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Slide 2 */}
|
||||
<div className='row align-items-center justify-content-center'>
|
||||
<div className='col-24'>
|
||||
<h1 className='title-important'>Code Source</h1>
|
||||
<p className='Home__description'>
|
||||
Le partage est essentiel afin de progresser. <br />
|
||||
Par conséquent chaque fonction a un article expliquant comment elle fonctionne et <br />
|
||||
le code source du projet est disponible sur mon profil GitHub :
|
||||
</p>
|
||||
</div>
|
||||
<div className='col-24'>
|
||||
<a target='_blank' rel='noopener noreferrer' href='https://github.com/Divlo/FunctionProject'><img className='Home__image-width' src='/images/GitHub.png' alt='GitHub' /></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</AutoPlaySwipeableViews>
|
||||
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Home;
|
||||
export default Home
|
||||
|
@ -1,245 +1,238 @@
|
||||
import Link from 'next/link';
|
||||
import { Fragment, useContext, useState, useEffect } from 'react';
|
||||
import { UserContext } from '../../contexts/UserContext';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faPen, faTimes } from '@fortawesome/free-solid-svg-icons';
|
||||
import date from 'date-and-time';
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import FunctionCard from '../../components/FunctionCard/FunctionCard';
|
||||
import Modal from '../../components/Modal';
|
||||
import redirect from '../../utils/redirect';
|
||||
import htmlParser from 'html-react-parser';
|
||||
import Loader from '../../components/Loader';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import CodeBlock from "../../components/CodeBlock";
|
||||
import api from '../../utils/api';
|
||||
import { API_URL } from '../../utils/config/config';
|
||||
import '../../public/css/pages/profile.css';
|
||||
import Link from 'next/link'
|
||||
import { useContext, useState, useEffect } from 'react'
|
||||
import { UserContext } from '../../contexts/UserContext'
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||
import { faPen, faTimes } from '@fortawesome/free-solid-svg-icons'
|
||||
import date from 'date-and-time'
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import FunctionCard from '../../components/FunctionCard/FunctionCard'
|
||||
import Modal from '../../components/Modal'
|
||||
import redirect from '../../utils/redirect'
|
||||
import htmlParser from 'html-react-parser'
|
||||
import Loader from '../../components/Loader'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import CodeBlock from '../../components/CodeBlock'
|
||||
import api from '../../utils/api'
|
||||
import { API_URL } from '../../utils/config/config'
|
||||
import '../../public/css/pages/profile.css'
|
||||
|
||||
const Profile = (props) => {
|
||||
const { isAuth, user, logoutUser } = useContext(UserContext)
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [inputState, setInputState] = useState({})
|
||||
const [message, setMessage] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const { isAuth, user, logoutUser } = useContext(UserContext);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [inputState, setInputState] = useState({});
|
||||
const [message, setMessage] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuth) {
|
||||
setInputState({ name: user.name, email: user.email, biography: user.biography, isPublicEmail: user.isPublicEmail });
|
||||
}
|
||||
}, [isAuth]);
|
||||
|
||||
const toggleModal = () => setIsOpen(!isOpen);
|
||||
|
||||
const handleChange = (event, isTypeCheck = false) => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = (event.target.files != undefined) ? event.target.files[0] : (isTypeCheck) ? event.target.checked : event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
useEffect(() => {
|
||||
if (isAuth) {
|
||||
setInputState({ name: user.name, email: user.email, biography: user.biography, isPublicEmail: user.isPublicEmail })
|
||||
}
|
||||
}, [isAuth])
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
event.preventDefault();
|
||||
const token = user.token;
|
||||
if (isAuth && token != undefined) {
|
||||
setIsLoading(true);
|
||||
const formData = new FormData();
|
||||
formData.append('name', inputState.name);
|
||||
formData.append('email', inputState.email);
|
||||
formData.append('biography', inputState.biography);
|
||||
formData.append('isPublicEmail', inputState.isPublicEmail);
|
||||
formData.append('logo', inputState.logo);
|
||||
|
||||
api.put('/users/', formData, { headers: { 'Authorization': token } })
|
||||
.then(() => {
|
||||
setIsLoading(false);
|
||||
logoutUser();
|
||||
redirect({}, '/users/login?isSuccessEdit=true');
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
|
||||
setIsLoading(false);
|
||||
});
|
||||
}
|
||||
const toggleModal = () => setIsOpen(!isOpen)
|
||||
|
||||
const handleChange = (event, isTypeCheck = false) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = (event.target.files != null) ? event.target.files[0] : (isTypeCheck) ? event.target.checked : event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
event.preventDefault()
|
||||
const token = user.token
|
||||
if (isAuth && token != null) {
|
||||
setIsLoading(true)
|
||||
const formData = new window.FormData()
|
||||
formData.append('name', inputState.name)
|
||||
formData.append('email', inputState.email)
|
||||
formData.append('biography', inputState.biography)
|
||||
formData.append('isPublicEmail', inputState.isPublicEmail)
|
||||
formData.append('logo', inputState.logo)
|
||||
|
||||
api.put('/users/', formData, { headers: { Authorization: token } })
|
||||
.then(() => {
|
||||
setIsLoading(false)
|
||||
logoutUser()
|
||||
redirect({}, '/users/login?isSuccessEdit=true')
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`)
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag title={`${props.name} - FunctionProject`} description={`Profil utilisateur de ${props.name}. ${(props.biography != undefined) ? props.biography : ""}`} />
|
||||
return (
|
||||
<>
|
||||
<HeadTag title={`${props.name} - FunctionProject`} description={`Profil utilisateur de ${props.name}. ${(props.biography != null) ? props.biography : ''}`} />
|
||||
|
||||
{/* Édition du profil */}
|
||||
{(isOpen) ?
|
||||
<Modal toggleModal={toggleModal}>
|
||||
<div className="Profile__container container-fluid">
|
||||
<div className="Profile__row row">
|
||||
<div className="col-24">
|
||||
<div className="Profile__Modal-top-container row">
|
||||
<div className="col-24">
|
||||
<span onClick={toggleModal} style={{ cursor: 'pointer', position: 'absolute', left: 0 }}>
|
||||
<FontAwesomeIcon icon={faTimes} style={{ width: '1.5rem', color: 'red' }} />
|
||||
</span>
|
||||
<h2 className="text-center">Éditer le profil</h2>
|
||||
<p className="text-center"><em>(Vous devrez vous reconnecter après la sauvegarde) <br/> Si vous changez votre adresse email, vous devrez la confirmer comme à l'inscription (vérifier vos emails).</em></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-24">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="name">Nom :</label>
|
||||
<input value={inputState.name} onChange={handleChange} type="text" name="name" id="name" className="form-control" placeholder="Divlo" />
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="email">Email :</label>
|
||||
<input value={inputState.email} onChange={handleChange} type="email" name="email" id="email" className="form-control" placeholder="email@gmail.com" />
|
||||
</div>
|
||||
|
||||
<div className="form-group custom-control custom-switch">
|
||||
<input onChange={(event) => handleChange(event, true)} type="checkbox" name="isPublicEmail" checked={inputState.isPublicEmail} className="custom-control-input" id="isPublicEmail" />
|
||||
<label className="custom-control-label" htmlFor="isPublicEmail">Email Public</label>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="biography">Biographie :</label>
|
||||
<textarea style={{ height: 'auto' }} value={inputState.biography} onChange={handleChange} name="biography" id="biography" className="form-control" rows="5"></textarea>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="logo">Logo <em>(400x400 recommandé)</em> :</label>
|
||||
<p style={{ margin: 0 }}><em>Si aucun fichier est choisi, le logo ne sera pas modifié.</em></p>
|
||||
<input onChange={handleChange} accept="image/jpeg,image/jpg,image/png,image/gif" type="file" name="logo" id="logo" />
|
||||
</div>
|
||||
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Sauvegarder</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="form-result text-center">
|
||||
{
|
||||
(isLoading) ?
|
||||
<Loader />
|
||||
:
|
||||
htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
:
|
||||
|
||||
<div className="container-fluid Profile__container">
|
||||
<div className="row Profile__row">
|
||||
<div className="col-20">
|
||||
<div className="text-center">
|
||||
<h1>Profil de <span className="important">{props.name}</span></h1>
|
||||
</div>
|
||||
<div className="row justify-content-center">
|
||||
|
||||
<div className="col-24 text-center">
|
||||
<img className="Profile__logo" src={API_URL + props.logo} alt={props.name} />
|
||||
</div>
|
||||
|
||||
<div className="col-24 text-center">
|
||||
{(props.biography != undefined) && <p>{props.biography}</p>}
|
||||
{(props.email != undefined) && <p><span className="important">Email :</span> {props.email}</p>}
|
||||
<p><span className="important">Date de création du compte :</span> {date.format(new Date(props.createdAt), 'DD/MM/YYYY à HH:mm', true)}</p>
|
||||
</div>
|
||||
|
||||
{(isAuth && user.name === props.name) &&
|
||||
<button onClick={toggleModal} style={{ marginBottom: '25px' }} className="btn btn-dark">
|
||||
<FontAwesomeIcon icon={faPen} style={{cursor: 'pointer', width: '1rem'}} />
|
||||
Éditez le profil
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(props.favoritesArray.length > 0) &&
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24 text-center">
|
||||
<h2>Dernières fonctions ajoutées aux <span className="important">favoris</span> :</h2>
|
||||
</div>
|
||||
<div className="col-24">
|
||||
<div className="row justify-content-center">
|
||||
{props.favoritesArray.map((favorite) => {
|
||||
return (
|
||||
<FunctionCard key={favorite.id} { ...favorite } />
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
{(props.commentsArray.length > 0) &&
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24 text-center">
|
||||
<h2>Derniers <span className="important">commentaires</span> :</h2>
|
||||
</div>
|
||||
<div className="col-24">
|
||||
{props.commentsArray.map((comment) => (
|
||||
<div key={comment.id} className="row Profile__row Profile__comment">
|
||||
<div className="col-20">
|
||||
<p style={{ textAlign: 'center', marginTop: '30px' }}>
|
||||
Posté sur la fonction
|
||||
<Link href={(comment.function.type === 'form' || comment.function.type === 'article') ? "/functions/[slug]" : `/functions/${comment.function.slug}`} as={`/functions/${comment.function.slug}`}>
|
||||
<a>{comment.function.title}</a>
|
||||
</Link>
|
||||
le {date.format(new Date(comment.createdAt), 'DD/MM/YYYY à HH:mm', true)}
|
||||
</p>
|
||||
<ReactMarkdown source={comment.message} renderers={{ code: CodeBlock }} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
{(props.quotesArray.length > 0) &&
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24 text-center">
|
||||
<h2>Dernières <span className="important">citations</span> proposées (et validées) :</h2>
|
||||
<p>Citations pour la fonction <Link href="/functions/randomQuote"><a>Générateur de citations</a></Link>.</p>
|
||||
</div>
|
||||
<div className="col-24 table-column">
|
||||
<table style={{ marginBottom: '50px' }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="table-row" scope="col">Citation/Proverbe</th>
|
||||
<th className="table-row" scope="col">Auteur</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{props.quotesArray.map((currentQuote, index) => {
|
||||
return (
|
||||
<tr key={index}>
|
||||
<td className="table-row text-center">{currentQuote.quote}</td>
|
||||
<td className="table-row text-center">{currentQuote.author}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
{/* Édition du profil */}
|
||||
{(isOpen)
|
||||
? (
|
||||
<Modal toggleModal={toggleModal}>
|
||||
<div className='Profile__container container-fluid'>
|
||||
<div className='Profile__row row'>
|
||||
<div className='col-24'>
|
||||
<div className='Profile__Modal-top-container row'>
|
||||
<div className='col-24'>
|
||||
<span onClick={toggleModal} style={{ cursor: 'pointer', position: 'absolute', left: 0 }}>
|
||||
<FontAwesomeIcon icon={faTimes} style={{ width: '1.5rem', color: 'red' }} />
|
||||
</span>
|
||||
<h2 className='text-center'>Éditer le profil</h2>
|
||||
<p className='text-center'><em>(Vous devrez vous reconnecter après la sauvegarde) <br /> Si vous changez votre adresse email, vous devrez la confirmer comme à l'inscription (vérifier vos emails).</em></p>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</Fragment>
|
||||
);
|
||||
<div className='col-24'>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='name'>Nom :</label>
|
||||
<input value={inputState.name} onChange={handleChange} type='text' name='name' id='name' className='form-control' placeholder='Divlo' />
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='email'>Email :</label>
|
||||
<input value={inputState.email} onChange={handleChange} type='email' name='email' id='email' className='form-control' placeholder='email@gmail.com' />
|
||||
</div>
|
||||
|
||||
<div className='form-group custom-control custom-switch'>
|
||||
<input onChange={(event) => handleChange(event, true)} type='checkbox' name='isPublicEmail' checked={inputState.isPublicEmail} className='custom-control-input' id='isPublicEmail' />
|
||||
<label className='custom-control-label' htmlFor='isPublicEmail'>Email Public</label>
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='biography'>Biographie :</label>
|
||||
<textarea style={{ height: 'auto' }} value={inputState.biography} onChange={handleChange} name='biography' id='biography' className='form-control' rows='5' />
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='logo'>Logo <em>(400x400 recommandé)</em> :</label>
|
||||
<p style={{ margin: 0 }}><em>Si aucun fichier est choisi, le logo ne sera pas modifié.</em></p>
|
||||
<input onChange={handleChange} accept='image/jpeg,image/jpg,image/png,image/gif' type='file' name='logo' id='logo' />
|
||||
</div>
|
||||
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Sauvegarder</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className='form-result text-center'>
|
||||
{
|
||||
(isLoading)
|
||||
? <Loader />
|
||||
: htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
: (
|
||||
<div className='container-fluid Profile__container'>
|
||||
<div className='row Profile__row'>
|
||||
<div className='col-20'>
|
||||
<div className='text-center'>
|
||||
<h1>Profil de <span className='important'>{props.name}</span></h1>
|
||||
</div>
|
||||
<div className='row justify-content-center'>
|
||||
|
||||
<div className='col-24 text-center'>
|
||||
<img className='Profile__logo' src={API_URL + props.logo} alt={props.name} />
|
||||
</div>
|
||||
|
||||
<div className='col-24 text-center'>
|
||||
{(props.biography != null) && <p>{props.biography}</p>}
|
||||
{(props.email != null) && <p><span className='important'>Email :</span> {props.email}</p>}
|
||||
<p><span className='important'>Date de création du compte :</span> {date.format(new Date(props.createdAt), 'DD/MM/YYYY à HH:mm', true)}</p>
|
||||
</div>
|
||||
|
||||
{(isAuth && user.name === props.name) &&
|
||||
<button onClick={toggleModal} style={{ marginBottom: '25px' }} className='btn btn-dark'>
|
||||
<FontAwesomeIcon icon={faPen} style={{ cursor: 'pointer', width: '1rem' }} />
|
||||
Éditez le profil
|
||||
</button>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(props.favoritesArray.length > 0) &&
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24 text-center'>
|
||||
<h2>Dernières fonctions ajoutées aux <span className='important'>favoris</span> :</h2>
|
||||
</div>
|
||||
<div className='col-24'>
|
||||
<div className='row justify-content-center'>
|
||||
{props.favoritesArray.map((favorite) => {
|
||||
return (
|
||||
<FunctionCard key={favorite.id} {...favorite} />
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{(props.commentsArray.length > 0) &&
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24 text-center'>
|
||||
<h2>Derniers <span className='important'>commentaires</span> :</h2>
|
||||
</div>
|
||||
<div className='col-24'>
|
||||
{props.commentsArray.map((comment) => (
|
||||
<div key={comment.id} className='row Profile__row Profile__comment'>
|
||||
<div className='col-20'>
|
||||
<p style={{ textAlign: 'center', marginTop: '30px' }}>
|
||||
Posté sur la fonction
|
||||
<Link href={(comment.function.type === 'form' || comment.function.type === 'article') ? '/functions/[slug]' : `/functions/${comment.function.slug}`} as={`/functions/${comment.function.slug}`}>
|
||||
<a>{comment.function.title}</a>
|
||||
</Link>
|
||||
le {date.format(new Date(comment.createdAt), 'DD/MM/YYYY à HH:mm', true)}
|
||||
</p>
|
||||
<ReactMarkdown source={comment.message} renderers={{ code: CodeBlock }} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{(props.quotesArray.length > 0) &&
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24 text-center'>
|
||||
<h2>Dernières <span className='important'>citations</span> proposées (et validées) :</h2>
|
||||
<p>Citations pour la fonction <Link href='/functions/randomQuote'><a>Générateur de citations</a></Link>.</p>
|
||||
</div>
|
||||
<div className='col-24 table-column'>
|
||||
<table style={{ marginBottom: '50px' }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className='table-row' scope='col'>Citation/Proverbe</th>
|
||||
<th className='table-row' scope='col'>Auteur</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{props.quotesArray.map((currentQuote, index) => {
|
||||
return (
|
||||
<tr key={index}>
|
||||
<td className='table-row text-center'>{currentQuote.quote}</td>
|
||||
<td className='table-row text-center'>{currentQuote.author}</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
const { name } = context.params;
|
||||
return api.get(`/users/${name}`)
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'));
|
||||
export async function getServerSideProps (context) {
|
||||
const { name } = context.params
|
||||
return api.get(`/users/${name}`)
|
||||
.then((response) => ({ props: response.data }))
|
||||
.catch(() => redirect(context, '/404'))
|
||||
}
|
||||
|
||||
export default Profile;
|
||||
export default Profile
|
||||
|
@ -1,74 +1,71 @@
|
||||
import { Fragment, useState } from 'react';
|
||||
import htmlParser from 'html-react-parser';
|
||||
import Loader from '../../components/Loader';
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import api from '../../utils/api';
|
||||
import withoutAuth from '../../hoc/withoutAuth';
|
||||
import '../../public/css/pages/register-login.css';
|
||||
import { useState } from 'react'
|
||||
import htmlParser from 'html-react-parser'
|
||||
import Loader from '../../components/Loader'
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import api from '../../utils/api'
|
||||
import withoutAuth from '../../hoc/withoutAuth'
|
||||
import '../../public/css/pages/register-login.css'
|
||||
|
||||
const forgotPassword = () => {
|
||||
const [inputState, setInputState] = useState({})
|
||||
const [message, setMessage] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const [inputState, setInputState] = useState({});
|
||||
const [message, setMessage] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
const handleChange = () => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
}
|
||||
const handleSubmit = (event) => {
|
||||
setIsLoading(true)
|
||||
event.preventDefault()
|
||||
api.post('/users/reset-password', inputState)
|
||||
.then(({ data }) => {
|
||||
setMessage(`<p class="form-success"><b>Succès:</b> ${data.result}</p>`)
|
||||
setIsLoading(false)
|
||||
setInputState({})
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`)
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
setIsLoading(true);
|
||||
event.preventDefault();
|
||||
api.post('/users/reset-password', inputState)
|
||||
.then(({ data }) => {
|
||||
setMessage(`<p class="form-success"><b>Succès:</b> ${data.result}</p>`);
|
||||
setIsLoading(false);
|
||||
setInputState({});
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
|
||||
setIsLoading(false);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag
|
||||
title="Mot de passe oublié - FunctionProject"
|
||||
description="Vous vous ne souvenez pas de votre mot de passe ? Demandez une demande de réinitialisation de mot de passe par email."
|
||||
/>
|
||||
<div className="container Register-Login__container">
|
||||
<div className="row Register-Login__row justify-content-center">
|
||||
<div className="col-20">
|
||||
<h1 className="Register-Login__title">Mot de passe oublié ?</h1>
|
||||
<div className="text-center">
|
||||
<p>Demandez une demande de réinitialisation de mot de passe par email.</p>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="name">Email :</label>
|
||||
<input onChange={handleChange} type="email" name="email" id="email" className="form-control" placeholder="email@gmail.com" />
|
||||
</div>
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="form-result text-center">
|
||||
{
|
||||
(isLoading) ?
|
||||
<Loader />
|
||||
:
|
||||
htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
return (
|
||||
<>
|
||||
<HeadTag
|
||||
title='Mot de passe oublié - FunctionProject'
|
||||
description='Vous vous ne souvenez pas de votre mot de passe ? Demandez une demande de réinitialisation de mot de passe par email.'
|
||||
/>
|
||||
<div className='container Register-Login__container'>
|
||||
<div className='row Register-Login__row justify-content-center'>
|
||||
<div className='col-20'>
|
||||
<h1 className='Register-Login__title'>Mot de passe oublié ?</h1>
|
||||
<div className='text-center'>
|
||||
<p>Demandez une demande de réinitialisation de mot de passe par email.</p>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='name'>Email :</label>
|
||||
<input onChange={handleChange} type='email' name='email' id='email' className='form-control' placeholder='email@gmail.com' />
|
||||
</div>
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className='form-result text-center'>
|
||||
{
|
||||
(isLoading)
|
||||
? <Loader />
|
||||
: htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default withoutAuth(forgotPassword);
|
||||
export default withoutAuth(forgotPassword)
|
||||
|
@ -1,109 +1,108 @@
|
||||
import { Fragment, useState, useEffect, useRef, useCallback } from 'react';
|
||||
import Link from 'next/link';
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import Loader from '../../components/Loader';
|
||||
import api from '../../utils/api';
|
||||
import '../../public/css/pages/users.css';
|
||||
import { API_URL } from '../../utils/config/config';
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import Loader from '../../components/Loader'
|
||||
import api from '../../utils/api'
|
||||
import '../../public/css/pages/users.css'
|
||||
import { API_URL } from '../../utils/config/config'
|
||||
|
||||
const Users = () => {
|
||||
let pageUsers = 1
|
||||
|
||||
let pageUsers = 1;
|
||||
|
||||
const [inputSearch, setInputSearch] = useState("");
|
||||
const [usersData, setUsersData] = useState({ totalItems: 0, hasMore: true, rows: [] });
|
||||
const [isLoadingUsers, setLoadingUsers] = useState(true);
|
||||
const [inputSearch, setInputSearch] = useState('')
|
||||
const [usersData, setUsersData] = useState({ totalItems: 0, hasMore: true, rows: [] })
|
||||
const [isLoadingUsers, setLoadingUsers] = useState(true)
|
||||
|
||||
// Récupère les users si la recherche change
|
||||
useEffect(() => {
|
||||
pageUsers = 1;
|
||||
getUsersData().then((data) => setUsersData(data));
|
||||
}, [inputSearch]);
|
||||
// Récupère les users si la recherche change
|
||||
useEffect(() => {
|
||||
pageUsers = 1
|
||||
getUsersData().then((data) => setUsersData(data))
|
||||
}, [inputSearch])
|
||||
|
||||
const getUsersData = async () => {
|
||||
setLoadingUsers(true);
|
||||
const { data } = await api.get(`/users?page=${pageUsers}&limit=15&search=${inputSearch}`);
|
||||
setLoadingUsers(false);
|
||||
return data;
|
||||
}
|
||||
const getUsersData = async () => {
|
||||
setLoadingUsers(true)
|
||||
const { data } = await api.get(`/users?page=${pageUsers}&limit=15&search=${inputSearch}`)
|
||||
setLoadingUsers(false)
|
||||
return data
|
||||
}
|
||||
|
||||
const handleSearchChange = (event) => {
|
||||
setInputSearch(event.target.value);
|
||||
}
|
||||
const handleSearchChange = (event) => {
|
||||
setInputSearch(event.target.value)
|
||||
}
|
||||
|
||||
// Permet la pagination au scroll
|
||||
const observer = useRef();
|
||||
const lastUserCardRef = useCallback((node) => {
|
||||
if (isLoadingUsers) return;
|
||||
if (observer.current) observer.current.disconnect();
|
||||
observer.current = new IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && usersData.hasMore) {
|
||||
pageUsers += 1;
|
||||
getUsersData().then((data) => {
|
||||
setUsersData((oldData) => {
|
||||
return {
|
||||
totalItems: data.totalItems,
|
||||
hasMore: data.hasMore,
|
||||
rows: [...oldData.rows, ...data.rows]
|
||||
}
|
||||
});
|
||||
});
|
||||
// Permet la pagination au scroll
|
||||
const observer = useRef()
|
||||
const lastUserCardRef = useCallback((node) => {
|
||||
if (isLoadingUsers) return
|
||||
if (observer.current) observer.current.disconnect()
|
||||
observer.current = new window.IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && usersData.hasMore) {
|
||||
pageUsers += 1
|
||||
getUsersData().then((data) => {
|
||||
setUsersData((oldData) => {
|
||||
return {
|
||||
totalItems: data.totalItems,
|
||||
hasMore: data.hasMore,
|
||||
rows: [...oldData.rows, ...data.rows]
|
||||
}
|
||||
}, { threshold: 1 });
|
||||
if (node) observer.current.observe(node);
|
||||
}, [isLoadingUsers, usersData.hasMore]);
|
||||
})
|
||||
})
|
||||
}
|
||||
}, { threshold: 1 })
|
||||
if (node) observer.current.observe(node)
|
||||
}, [isLoadingUsers, usersData.hasMore])
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag
|
||||
title="Utilisateurs"
|
||||
description="Liste des utilisateurs."
|
||||
/>
|
||||
return (
|
||||
<>
|
||||
<HeadTag
|
||||
title='Utilisateurs'
|
||||
description='Liste des utilisateurs.'
|
||||
/>
|
||||
|
||||
<div className="container text-center">
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-24">
|
||||
<h1 style={{ marginBottom: 0, paddingTop: "20px" }}>Utilisateurs</h1>
|
||||
<p style={{ marginTop: '5px' }}>La liste des utilisateurs - Total de {usersData.totalItems} utilisateurs :</p>
|
||||
<div className='container text-center'>
|
||||
<div className='row justify-content-center'>
|
||||
<div className='col-24'>
|
||||
<h1 style={{ marginBottom: 0, paddingTop: '20px' }}>Utilisateurs</h1>
|
||||
<p style={{ marginTop: '5px' }}>La liste des utilisateurs - Total de {usersData.totalItems} utilisateurs :</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='Users__search-container row justify-content-center'>
|
||||
<input value={inputSearch} onChange={handleSearchChange} type='search' className='Users__form-control Users__search-input' name='search' id='search' placeholder='🔎 Rechercher...' />
|
||||
</div>
|
||||
|
||||
<div className='row justify-content-center'>
|
||||
{usersData.rows.map((user, index) => {
|
||||
// Si c'est le dernier élément
|
||||
if (usersData.rows.length === index + 1) {
|
||||
return (
|
||||
<div ref={lastUserCardRef} key={user.id} className='UserCard col-sm-24 col-md-10 col-xl-7'>
|
||||
<Link href='/users/[name]' as={`/users/${user.name}`}>
|
||||
<div className='UserCard__container'>
|
||||
<img className='UserCard__logo' src={API_URL + user.logo} alt={user.name} />
|
||||
<h2 className='UserCard__name'>{user.name}</h2>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div key={user.id} className='UserCard col-sm-24 col-md-10 col-xl-7'>
|
||||
<Link href='/users/[name]' as={`/users/${user.name}`}>
|
||||
<div className='UserCard__container'>
|
||||
<img className='UserCard__logo' src={API_URL + user.logo} alt={user.name} />
|
||||
<h2 className='UserCard__name'>{user.name}</h2>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="Users__search-container row justify-content-center">
|
||||
<input value={inputSearch} onChange={handleSearchChange} type="search" className="Users__form-control Users__search-input" name="search" id="search" placeholder="🔎 Rechercher..." />
|
||||
</div>
|
||||
|
||||
<div className="row justify-content-center">
|
||||
{usersData.rows.map((user, index) => {
|
||||
// Si c'est le dernier élément
|
||||
if (usersData.rows.length === index + 1) {
|
||||
return (
|
||||
<div ref={lastUserCardRef} key={user.id} className="UserCard col-sm-24 col-md-10 col-xl-7">
|
||||
<Link href={"/users/[name]"} as={`/users/${user.name}`}>
|
||||
<div className="UserCard__container">
|
||||
<img className="UserCard__logo" src={API_URL + user.logo} alt={user.name} />
|
||||
<h2 className="UserCard__name">{user.name}</h2>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div key={user.id} className="UserCard col-sm-24 col-md-10 col-xl-7">
|
||||
<Link href={"/users/[name]"} as={`/users/${user.name}`}>
|
||||
<div className="UserCard__container">
|
||||
<img className="UserCard__logo" src={API_URL + user.logo} alt={user.name} />
|
||||
<h2 className="UserCard__name">{user.name}</h2>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{isLoadingUsers && <Loader />}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
{isLoadingUsers && <Loader />}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Users;
|
||||
export default Users
|
||||
|
@ -1,77 +1,75 @@
|
||||
import { Fragment, useContext, useState } from 'react';
|
||||
import { useRouter } from 'next/router';
|
||||
import Link from 'next/link';
|
||||
import htmlParser from 'html-react-parser';
|
||||
import Loader from '../../components/Loader';
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import { UserContext } from '../../contexts/UserContext';
|
||||
import withoutAuth from '../../hoc/withoutAuth';
|
||||
import '../../public/css/pages/register-login.css';
|
||||
import { useContext, useState } from 'react'
|
||||
import { useRouter } from 'next/router'
|
||||
import Link from 'next/link'
|
||||
import htmlParser from 'html-react-parser'
|
||||
import Loader from '../../components/Loader'
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import { UserContext } from '../../contexts/UserContext'
|
||||
import withoutAuth from '../../hoc/withoutAuth'
|
||||
import '../../public/css/pages/register-login.css'
|
||||
|
||||
const Login = () => {
|
||||
const router = useRouter()
|
||||
const [inputState, setInputState] = useState({})
|
||||
const { loginUser, messageLogin, loginLoading, isAuth } = useContext(UserContext)
|
||||
|
||||
const router = useRouter();
|
||||
const [inputState, setInputState] = useState({});
|
||||
const { loginUser, messageLogin, loginLoading, isAuth } = useContext(UserContext);
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
const handleSubmit = async (event) => {
|
||||
event.preventDefault()
|
||||
if (!isAuth) {
|
||||
await loginUser(inputState)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async (event) => {
|
||||
event.preventDefault();
|
||||
if (!isAuth) {
|
||||
await loginUser(inputState);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<HeadTag
|
||||
title='Se connecter - FunctionProject'
|
||||
description='Connexion à FunctionProject.'
|
||||
/>
|
||||
<div className='container Register-Login__container'>
|
||||
<div className='row Register-Login__row justify-content-center'>
|
||||
<div className='col-20'>
|
||||
<h1 className='Register-Login__title'>Se connecter</h1>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='email'>Email :</label>
|
||||
<input onChange={handleChange} type='email' name='email' id='email' className='form-control' placeholder='email@gmail.com' />
|
||||
</div>
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag
|
||||
title="Se connecter - FunctionProject"
|
||||
description="Connexion à FunctionProject."
|
||||
/>
|
||||
<div className="container Register-Login__container">
|
||||
<div className="row Register-Login__row justify-content-center">
|
||||
<div className="col-20">
|
||||
<h1 className="Register-Login__title">Se connecter</h1>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="email">Email :</label>
|
||||
<input onChange={handleChange} type="email" name="email" id="email" className="form-control" placeholder="email@gmail.com" />
|
||||
</div>
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='password'>Mot de passe :</label>
|
||||
<input onChange={handleChange} type='password' name='password' id='password' className='form-control' placeholder='******' />
|
||||
<p>
|
||||
<Link href='/users/forgotPassword'>
|
||||
<a className='Register-Login__Forgot-password'>Mot de passe oublié ?</a>
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="password">Mot de passe :</label>
|
||||
<input onChange={handleChange} type="password" name="password" id="password" className="form-control" placeholder="******" />
|
||||
<p>
|
||||
<Link href={"/users/forgotPassword"}>
|
||||
<a className="Register-Login__Forgot-password">Mot de passe oublié ?</a>
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="form-result text-center">
|
||||
{(router.query.isConfirmed !== undefined && messageLogin === "") && <p className="form-success"><b>Succès:</b> Votre compte a bien été confirmé, vous pouvez maintenant vous connectez!</p>}
|
||||
{(router.query.isSuccessEdit !== undefined && messageLogin === "") && <p className="form-success"><b>Succès:</b> Votre profil a bien été modifié, vous pouvez maintenant vous connectez!</p>}
|
||||
{
|
||||
(loginLoading) ?
|
||||
<Loader />
|
||||
:
|
||||
htmlParser(messageLogin)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className='form-result text-center'>
|
||||
{(router.query.isConfirmed !== undefined && messageLogin === '') && <p className='form-success'><b>Succès:</b> Votre compte a bien été confirmé, vous pouvez maintenant vous connectez!</p>}
|
||||
{(router.query.isSuccessEdit !== undefined && messageLogin === '') && <p className='form-success'><b>Succès:</b> Votre profil a bien été modifié, vous pouvez maintenant vous connectez!</p>}
|
||||
{
|
||||
(loginLoading)
|
||||
? <Loader />
|
||||
: htmlParser(messageLogin)
|
||||
}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default withoutAuth(Login);
|
||||
export default withoutAuth(Login)
|
||||
|
@ -1,82 +1,80 @@
|
||||
import { Fragment, useState } from 'react';
|
||||
import htmlParser from 'html-react-parser';
|
||||
import Loader from '../../components/Loader';
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import api from '../../utils/api';
|
||||
import redirect from '../../utils/redirect';
|
||||
import withoutAuth from '../../hoc/withoutAuth';
|
||||
import '../../public/css/pages/register-login.css';
|
||||
import { useState } from 'react'
|
||||
import htmlParser from 'html-react-parser'
|
||||
import Loader from '../../components/Loader'
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import api from '../../utils/api'
|
||||
import redirect from '../../utils/redirect'
|
||||
import withoutAuth from '../../hoc/withoutAuth'
|
||||
import '../../public/css/pages/register-login.css'
|
||||
|
||||
const newPassword = (props) => {
|
||||
const [inputState, setInputState] = useState({})
|
||||
const [message, setMessage] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const [inputState, setInputState] = useState({});
|
||||
const [message, setMessage] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
const handleChange = () => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
}
|
||||
const handleSubmit = (event) => {
|
||||
setIsLoading(true)
|
||||
event.preventDefault()
|
||||
api.put('/users/reset-password', { ...inputState, tempToken: props.token })
|
||||
.then(({ data }) => {
|
||||
setMessage(`<p class="form-success"><b>Succès:</b> ${data.result}</p>`)
|
||||
setIsLoading(false)
|
||||
setInputState({})
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`)
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
setIsLoading(true);
|
||||
event.preventDefault();
|
||||
api.put('/users/reset-password', { ...inputState, tempToken: props.token })
|
||||
.then(({ data }) => {
|
||||
setMessage(`<p class="form-success"><b>Succès:</b> ${data.result}</p>`);
|
||||
setIsLoading(false);
|
||||
setInputState({});
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
|
||||
setIsLoading(false);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag
|
||||
title="Nouveau mot de passe - FunctionProject"
|
||||
description="Mise à jour du mot de passe."
|
||||
/>
|
||||
<div className="container Register-Login__container">
|
||||
<div className="row Register-Login__row justify-content-center">
|
||||
<div className="col-20">
|
||||
<h1 className="Register-Login__title">Nouveau mot de passe</h1>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="password">Mot de passe :</label>
|
||||
<input onChange={handleChange} type="password" name="password" id="password" className="form-control" placeholder="******" />
|
||||
</div>
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="form-result text-center">
|
||||
{
|
||||
(isLoading) ?
|
||||
<Loader />
|
||||
:
|
||||
htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
return (
|
||||
<>
|
||||
<HeadTag
|
||||
title='Nouveau mot de passe - FunctionProject'
|
||||
description='Mise à jour du mot de passe.'
|
||||
/>
|
||||
<div className='container Register-Login__container'>
|
||||
<div className='row Register-Login__row justify-content-center'>
|
||||
<div className='col-20'>
|
||||
<h1 className='Register-Login__title'>Nouveau mot de passe</h1>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='password'>Mot de passe :</label>
|
||||
<input onChange={handleChange} type='password' name='password' id='password' className='form-control' placeholder='******' />
|
||||
</div>
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className='form-result text-center'>
|
||||
{
|
||||
(isLoading)
|
||||
? <Loader />
|
||||
: htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export async function getServerSideProps(context) {
|
||||
if (context.query.token != undefined) {
|
||||
return {
|
||||
props: {
|
||||
token: context.query.token
|
||||
}
|
||||
};
|
||||
export async function getServerSideProps (context) {
|
||||
if (context.query.token != null) {
|
||||
return {
|
||||
props: {
|
||||
token: context.query.token
|
||||
}
|
||||
}
|
||||
return redirect(context, '/404');
|
||||
}
|
||||
return redirect(context, '/404')
|
||||
}
|
||||
|
||||
export default withoutAuth(newPassword);
|
||||
export default withoutAuth(newPassword)
|
||||
|
@ -1,83 +1,81 @@
|
||||
import { Fragment, useState } from 'react';
|
||||
import htmlParser from 'html-react-parser';
|
||||
import Loader from '../../components/Loader';
|
||||
import HeadTag from '../../components/HeadTag';
|
||||
import api from '../../utils/api';
|
||||
import withoutAuth from '../../hoc/withoutAuth';
|
||||
import '../../public/css/pages/register-login.css';
|
||||
import { useState } from 'react'
|
||||
import htmlParser from 'html-react-parser'
|
||||
import Loader from '../../components/Loader'
|
||||
import HeadTag from '../../components/HeadTag'
|
||||
import api from '../../utils/api'
|
||||
import withoutAuth from '../../hoc/withoutAuth'
|
||||
import '../../public/css/pages/register-login.css'
|
||||
|
||||
const Register = () => {
|
||||
|
||||
const [inputState, setInputState] = useState({ name: "", email: "", password: "" });
|
||||
const [message, setMessage] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState };
|
||||
inputStateNew[event.target.name] = event.target.value;
|
||||
setInputState(inputStateNew);
|
||||
}
|
||||
const [inputState, setInputState] = useState({ name: '', email: '', password: '' })
|
||||
const [message, setMessage] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
setIsLoading(true);
|
||||
event.preventDefault();
|
||||
api.post('/users/register', inputState)
|
||||
.then(({ data }) => {
|
||||
setInputState({ name: "", email: "", password: "" });
|
||||
setMessage(`<p class="form-success"><b>Succès:</b> ${data.result}</p>`);
|
||||
setIsLoading(false);
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`);
|
||||
setIsLoading(false);
|
||||
});
|
||||
}
|
||||
const handleChange = (event) => {
|
||||
const inputStateNew = { ...inputState }
|
||||
inputStateNew[event.target.name] = event.target.value
|
||||
setInputState(inputStateNew)
|
||||
}
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<HeadTag
|
||||
title="S'inscrire - FunctionProject"
|
||||
description="Créer un compte."
|
||||
/>
|
||||
<div className="container Register-Login__container">
|
||||
<div className="row Register-Login__row justify-content-center">
|
||||
<div className="col-20">
|
||||
<h1 className="Register-Login__title">S'inscrire</h1>
|
||||
<div className="text-center">
|
||||
<p>En vous inscrivant, vous accéderez à de nombreuses fonctionnalités : publier des commentaires, ajouter des fonctions aux favoris, utiliser certaines fonctions disponibles qu'aux membres (exemple: La To Do list) etc.</p>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="name">Nom :</label>
|
||||
<input value={inputState.name} onChange={handleChange} type="text" name="name" id="name" className="form-control" placeholder="Divlo" />
|
||||
</div>
|
||||
const handleSubmit = (event) => {
|
||||
setIsLoading(true)
|
||||
event.preventDefault()
|
||||
api.post('/users/register', inputState)
|
||||
.then(({ data }) => {
|
||||
setInputState({ name: '', email: '', password: '' })
|
||||
setMessage(`<p class="form-success"><b>Succès:</b> ${data.result}</p>`)
|
||||
setIsLoading(false)
|
||||
})
|
||||
.catch((error) => {
|
||||
setMessage(`<p class="form-error"><b>Erreur:</b> ${error.response.data.message}</p>`)
|
||||
setIsLoading(false)
|
||||
})
|
||||
}
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="name">Email :</label>
|
||||
<input value={inputState.email} onChange={handleChange} type="email" name="email" id="email" className="form-control" placeholder="email@gmail.com" />
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="form-label" htmlFor="name">Mot de passe :</label>
|
||||
<input value={inputState.password} onChange={handleChange} type="password" name="password" id="password" className="form-control" placeholder="******" />
|
||||
</div>
|
||||
|
||||
<div className="form-group text-center">
|
||||
<button type="submit" className="btn btn-dark">Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className="form-result text-center">
|
||||
{
|
||||
(isLoading) ?
|
||||
<Loader />
|
||||
:
|
||||
htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
return (
|
||||
<>
|
||||
<HeadTag
|
||||
title="S'inscrire - FunctionProject"
|
||||
description='Créer un compte.'
|
||||
/>
|
||||
<div className='container Register-Login__container'>
|
||||
<div className='row Register-Login__row justify-content-center'>
|
||||
<div className='col-20'>
|
||||
<h1 className='Register-Login__title'>S'inscrire</h1>
|
||||
<div className='text-center'>
|
||||
<p>En vous inscrivant, vous accéderez à de nombreuses fonctionnalités : publier des commentaires, ajouter des fonctions aux favoris, utiliser certaines fonctions disponibles qu'aux membres (exemple: La To Do list) etc.</p>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='name'>Nom :</label>
|
||||
<input value={inputState.name} onChange={handleChange} type='text' name='name' id='name' className='form-control' placeholder='Divlo' />
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='name'>Email :</label>
|
||||
<input value={inputState.email} onChange={handleChange} type='email' name='email' id='email' className='form-control' placeholder='email@gmail.com' />
|
||||
</div>
|
||||
|
||||
<div className='form-group'>
|
||||
<label className='form-label' htmlFor='name'>Mot de passe :</label>
|
||||
<input value={inputState.password} onChange={handleChange} type='password' name='password' id='password' className='form-control' placeholder='******' />
|
||||
</div>
|
||||
|
||||
<div className='form-group text-center'>
|
||||
<button type='submit' className='btn btn-dark'>Envoyer</button>
|
||||
</div>
|
||||
</form>
|
||||
<div className='form-result text-center'>
|
||||
{
|
||||
(isLoading)
|
||||
? <Loader />
|
||||
: htmlParser(message)
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default withoutAuth(Register);
|
||||
export default withoutAuth(Register)
|
||||
|
@ -1,2 +1,7 @@
|
||||
reactSwipeableExtraHeight = document.querySelector('.react-swipeable-view-container');
|
||||
reactSwipeableExtraHeight.parentElement.style = "height: 400px; overflow-x: hidden;";
|
||||
/* eslint-disable */
|
||||
|
||||
reactSwipeableExtraHeight = document.querySelector(
|
||||
'.react-swipeable-view-container'
|
||||
)
|
||||
reactSwipeableExtraHeight.parentElement.style =
|
||||
'height: 400px; overflow-x: hidden;'
|
||||
|
@ -1,4 +1,4 @@
|
||||
window.addEventListener('load', () => {
|
||||
document.querySelector('.isLoading').classList.remove('isLoading');
|
||||
document.getElementById('preloader').remove();
|
||||
});
|
||||
document.querySelector('.isLoading').classList.remove('isLoading')
|
||||
document.getElementById('preloader').remove()
|
||||
})
|
||||
|
@ -1,28 +1,28 @@
|
||||
/* Modules */
|
||||
const next = require('next');
|
||||
const express = require("express");
|
||||
const redirectToHTTPS = require('express-http-to-https').redirectToHTTPS;
|
||||
const next = require('next')
|
||||
const express = require('express')
|
||||
const redirectToHTTPS = require('express-http-to-https').redirectToHTTPS
|
||||
|
||||
/* Variables */
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const dev = process.env.NODE_ENV !== "production";
|
||||
const app = next({ dev });
|
||||
const handle = app.getRequestHandler();
|
||||
const PORT = process.env.PORT || 3000
|
||||
const dev = process.env.NODE_ENV !== 'production'
|
||||
const app = next({ dev })
|
||||
const handle = app.getRequestHandler()
|
||||
|
||||
app.prepare().then(() => {
|
||||
const server = express();
|
||||
const server = express()
|
||||
|
||||
/* Middlewares */
|
||||
server.use(redirectToHTTPS([/localhost:(\d{4})/]));
|
||||
/* Middlewares */
|
||||
server.use(redirectToHTTPS([/localhost:(\d{4})/]))
|
||||
|
||||
/* Routes */
|
||||
server.all("*", (req, res) => {
|
||||
return handle(req, res);
|
||||
});
|
||||
/* Routes */
|
||||
server.all('*', (req, res) => {
|
||||
return handle(req, res)
|
||||
})
|
||||
|
||||
/* Server */
|
||||
server.listen(PORT, (error) => {
|
||||
if (error) throw error;
|
||||
console.log(`> Ready on http://localhost:${PORT}`);
|
||||
});
|
||||
});
|
||||
/* Server */
|
||||
server.listen(PORT, (error) => {
|
||||
if (error) throw error
|
||||
console.log(`> Ready on http://localhost:${PORT}`)
|
||||
})
|
||||
})
|
||||
|
@ -1,11 +1,11 @@
|
||||
import axios from 'axios';
|
||||
import { API_URL } from './config/config';
|
||||
import axios from 'axios'
|
||||
import { API_URL } from './config/config'
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: API_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
baseURL: API_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
|
||||
export default api;
|
||||
export default api
|
||||
|
@ -1 +0,0 @@
|
||||
export const API_URL = "http://localhost:8080";
|
@ -1 +1 @@
|
||||
export const API_URL = "http://localhost:8080";
|
||||
export const API_URL = process.env.NEXT_PUBLIC_API_URL
|
||||
|
@ -1 +0,0 @@
|
||||
export const API_URL = "https://api.function.divlo.fr";
|
@ -1,10 +1,10 @@
|
||||
function copyToClipboard(text) {
|
||||
const element = document.createElement('textarea');
|
||||
element.value = text;
|
||||
document.body.appendChild(element);
|
||||
element.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(element);
|
||||
function copyToClipboard (text) {
|
||||
const element = document.createElement('textarea')
|
||||
element.value = text
|
||||
document.body.appendChild(element)
|
||||
element.select()
|
||||
document.execCommand('copy')
|
||||
document.body.removeChild(element)
|
||||
}
|
||||
|
||||
export default copyToClipboard;
|
||||
export default copyToClipboard
|
||||
|
@ -1,10 +1,10 @@
|
||||
function redirect(ctx, path) {
|
||||
if (ctx.res != undefined) {
|
||||
ctx.res.writeHead(302, { Location: path });
|
||||
ctx.res.end();
|
||||
} else {
|
||||
document.location.href = path;
|
||||
}
|
||||
function redirect (ctx, path) {
|
||||
if (ctx.res != null) {
|
||||
ctx.res.writeHead(302, { Location: path })
|
||||
ctx.res.end()
|
||||
} else {
|
||||
document.location.href = path
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = redirect;
|
||||
module.exports = redirect
|
||||
|
@ -1,14 +1,14 @@
|
||||
export const complex = [
|
||||
["undo", "redo"],
|
||||
["font", "fontSize", "formatBlock"],
|
||||
["bold", "underline", "italic", "strike", "subscript", "superscript"],
|
||||
["removeFormat"],
|
||||
"/",
|
||||
["fontColor", "hiliteColor"],
|
||||
["outdent", "indent"],
|
||||
["align", "horizontalRule", "list", "table"],
|
||||
["link", "image", "video"],
|
||||
["fullScreen", "showBlocks", "codeView"],
|
||||
["preview", "print"],
|
||||
["save", "template"]
|
||||
];
|
||||
['undo', 'redo'],
|
||||
['font', 'fontSize', 'formatBlock'],
|
||||
['bold', 'underline', 'italic', 'strike', 'subscript', 'superscript'],
|
||||
['removeFormat'],
|
||||
'/',
|
||||
['fontColor', 'hiliteColor'],
|
||||
['outdent', 'indent'],
|
||||
['align', 'horizontalRule', 'list', 'table'],
|
||||
['link', 'image', 'video'],
|
||||
['fullScreen', 'showBlocks', 'codeView'],
|
||||
['preview', 'print'],
|
||||
['save', 'template']
|
||||
]
|
||||
|
Reference in New Issue
Block a user