bo/src/Vegetable.js
2018-09-20 10:12:05 +02:00

478 lines
14 KiB
JavaScript

import React, {
Component,
} from 'react';
import {
Container,
Row,
Col,
Form,
FormGroup,
Button,
Label,
Input,
TabContent,
TabPane,
Nav,
NavItem,
NavLink,
Carousel,
CarouselItem,
CarouselControl,
CarouselIndicators,
} from 'reactstrap';
import classnames from 'classnames';
import {
FaEdit,
FaMapMarkerAlt,
FaFileImage,
} from 'react-icons/fa';
import Navigation from './Navigation';
import Header from './Header';
import API from './Api';
import './Vegetable.css';
const Map = {
width: 734,
height: 530,
};
class Vegetable extends Component {
constructor(props) {
super(props);
this.state = {
Vegetable: {
name: '',
lat: 0,
lng: 0,
description: '',
Pictures: [],
},
imagePreviewUrl: '',
imagesPreviewUrls: [],
Map: {
width: '20px',
height: '20px',
},
activeTab: '1',
activeIndex: 0,
};
this.getVegetable = this.getVegetable.bind(this);
this.updateVegetable = this.updateVegetable.bind(this);
this.handleChange = this.handleChange.bind(this);
this.setMap = this.setMap.bind(this);
this.onImageChange = this.onImageChange.bind(this);
this.onPictureChange = this.onPictureChange.bind(this);
this.toggle = this.toggle.bind(this);
this.next = this.next.bind(this);
this.previous = this.previous.bind(this);
this.goToIndex = this.goToIndex.bind(this);
this.onExiting = this.onExiting.bind(this);
this.onExited = this.onExited.bind(this);
this.postPicture = this.postPicture.bind(this);
this.getVegetable(props.match.params.categoryId, props.match.params.vegetableId);
}
toggle(tab) {
if (this.state.activeTab !== tab) {
this.setState({
activeTab: tab,
}, () => {
this.setMap();
});
}
}
componentDidMount() {
window.addEventListener('resize', this.setMap);
this.setMap();
}
componentWillUnmount() {
window.removeEventListener('resize', this.setMap);
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState(prevState => ({
Vegetable: {
...prevState.Vegetable,
[name]: value,
},
}));
}
onImageChange(e) {
e.preventDefault();
const reader = new FileReader();
const file = e.target.files[0];
reader.onloadend = () => {
this.setState(prevState => ({
Vegetable: {
...prevState.Vegetable,
mainPictureImported: file,
},
imagePreviewUrl: reader.result,
}));
};
reader.readAsDataURL(file);
}
onPictureChange(e) {
e.preventDefault();
const reader = new FileReader();
const file = e.target.files[0];
reader.onloadend = () => {
this.setState(prevState => ({
Vegetable: {
...prevState.Vegetable,
Pictures: [
...prevState.Vegetable.Pictures,
file
]
},
imagesPreviewUrls: [
...prevState.imagesPreviewUrls,
reader.result
],
activeIndex: prevState.imagesPreviewUrls.length
}));
};
this.postPicture(file);
reader.readAsDataURL(file);
}
updateVegetable(event) {
event.preventDefault(); // Let's stop this event.
event.stopPropagation(); // Really this time.
const fd = new FormData();
if (this.state.imagePreviewUrl) {
fd.append('mainPicture', this.state.Vegetable.mainPictureImported);
}
Object.keys(this.state.Vegetable).map((objectKey) => {
if (objectKey !== 'mainPicture' && objectKey !== 'mainPictureImported') {
fd.append(objectKey, this.state.Vegetable[objectKey]);
}
return true;
});
API.patch(`types/${this.state.Vegetable.Type.id}/vegetables/${this.state.Vegetable.id}`, fd)
.then((res) => {
// this.setState({ Category: res.data });
})
.catch(() => {
alert('Impossile de mettre à jour ce végétal');
});
}
postPicture(picture) {
const fd = new FormData();
fd.append('picture', picture);
API.post(`types/${this.state.Vegetable.Type.id}/vegetables/${this.state.Vegetable.id}/pictures`, fd)
.then((res) => {
// this.setState({ Category: res.data });
})
.catch(() => {
alert('Impossile d\'ajouter cette image');
});
}
getVegetable(categoryId, vegetableId) {
API.get(`types/${categoryId}/vegetables/${vegetableId}`)
.then((res) => {
if (res.status === 200) {
const item = res.data;
let images = [];
if (item.description === null) {
item.description = ' ';
}
if (item.Pictures.length > 0) {
for (let i = 0; i < item.Pictures.length; i += 1) {
images.push(item.Pictures[i].url);
}
}
this.setState(prevState => ({
...prevState,
Vegetable: item,
imagesPreviewUrls: images
}));
}
})
.catch((e) => {
alert('Erreur lors de la récupération de ce végétal');
});
}
setMap() {
const width = document.getElementById('MapContainer').clientWidth;
let MapWidth = Map.width;
let MapHeight = Map.height;
if (width < Map.width) {
MapWidth = width;
MapHeight = Math.round(Map.height * MapWidth / Map.width);
}
this.setState({
Map: {
width: MapWidth,
height: MapHeight,
},
});
}
onExiting() {
this.animating = true;
}
onExited() {
this.animating = false;
}
next() {
if (this.animating) return;
const nextIndex = this.state.activeIndex === this.state.imagesPreviewUrls.length - 1 ? 0 : this.state.activeIndex + 1;
this.setState({
activeIndex: nextIndex,
});
}
previous() {
if (this.animating) return;
const nextIndex = this.state.activeIndex === 0 ? this.state.imagesPreviewUrls.length - 1 : this.state.activeIndex - 1;
this.setState({
activeIndex: nextIndex,
});
}
goToIndex(newIndex) {
if (this.animating) return;
this.setState({
activeIndex: newIndex,
});
}
render() {
const {
activeIndex,
} = this.state;
const {
imagePreviewUrl,
} = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<img src={imagePreviewUrl} alt="Preview" />);
} else if (this.state.Vegetable.mainPicture) {
$imagePreview = (<img src={this.state.Vegetable.mainPicture} alt="Preview" />);
} else {
$imagePreview = (<div className="previewText" />);
}
return (
<div>
<Header />
<Container className="Vegetable">
<Navigation categoryId={this.state.Vegetable.Type ? this.state.Vegetable.Type.id : 1} categoryName={this.state.Vegetable.Type ? this.state.Vegetable.Type.name : null} vegetableId={this.state.Vegetable.id || 1} vegetableName={this.state.Vegetable.name} />
<Form onSubmit={this.updateVegetable}>
<Nav tabs>
<NavItem>
<NavLink
className={classnames({ active: this.state.activeTab === '1' })}
onClick={() => { this.toggle('1'); }}
>
Informations générales
</NavLink>
</NavItem>
<NavItem>
<NavLink
className={classnames({ active: this.state.activeTab === '2' })}
onClick={() => { this.toggle('2'); }}
>
Carte
</NavLink>
</NavItem>
<NavItem>
<NavLink
className={classnames({ active: this.state.activeTab === '3' })}
onClick={() => { this.toggle('3'); }}
>
Galerie
</NavLink>
</NavItem>
</Nav>
<TabContent activeTab={this.state.activeTab}>
<TabPane tabId="1">
<Row>
<Col xs={12} sm={4}>
<FormGroup row>
<Label for="name" sm={4}>Nom</Label>
<Col sm={8}>
<Input
type="text"
name="name"
id="name"
value={this.state.Vegetable.name}
placeholder="Nom"
onChange={this.handleChange}
/>
</Col>
</FormGroup>
<FormGroup row>
<Label for="description" sm={4}>Description</Label>
<Col sm={8}>
<Input
type="textarea"
name="description"
id="description"
value={this.state.Vegetable.description}
placeholder="Description"
onChange={this.handleChange}
/>
</Col>
</FormGroup>
<FormGroup row>
<Label for="mainPicture" sm={4}>Photo principale</Label>
<Col sm={8}>
<Label className="mainPictureButton btn btn-success" for="mainPicture" sm={12}>
<FaFileImage />
</Label>
<Input
type="file"
id="mainPicture"
onChange={e => this.onImageChange(e)}
/>
</Col>
</FormGroup>
</Col>
<Col xs={12} sm={8}>
<div className="imgPreview">
{$imagePreview}
</div>
</Col>
</Row>
</TabPane>
<TabPane tabId="2">
<Row>
<Col xs={12} sm={4}>
<FormGroup row>
<Label for="lat" sm={4}>Latitude (%)</Label>
<Col sm={8}>
<Input
type="number"
min="0"
max="100"
step="1"
name="lat"
id="lat"
value={this.state.Vegetable.lat}
placeholder="Latitude"
onChange={this.handleChange}
/>
</Col>
</FormGroup>
<FormGroup row>
<Label for="lng" sm={4}>Longitude (%)</Label>
<Col sm={8}>
<Input
type="number"
min="0"
max="100"
step="1"
name="lng"
id="lng"
value={this.state.Vegetable.lng}
placeholder="Longitude"
onChange={this.handleChange}
/>
</Col>
</FormGroup>
</Col>
<Col xs={12} sm={8}>
<div id="MapContainer">
<div className="map" style={{ width: this.state.Map.width, height: this.state.Map.height }}>
<div className="mapMarker" style={{ left: `calc(${this.state.Vegetable.lat}% - 16px)`, top: `calc(${this.state.Vegetable.lng}% - 16px)` }}><FaMapMarkerAlt /></div>
</div>
</div>
</Col>
</Row>
</TabPane>
<TabPane tabId="3">
<Row>
<Col xs={12} sm={4}>
<FormGroup row>
<Col sm={12}>
<Label className="btn btn-success" for="Pictures" sm={12}>
<FaFileImage />
{' '}
Ajouter une photo
</Label>
<Input
type="file"
id="Pictures"
onChange={e => this.onPictureChange(e)}
/>
</Col>
</FormGroup>
</Col>
<Col xs={12} sm={8}>
{this.state.imagesPreviewUrls
&& this.state.imagesPreviewUrls.length > 0
? (<Carousel
activeIndex={activeIndex}
next={this.next}
previous={this.previous}
>
<CarouselIndicators items={this.state.imagesPreviewUrls} activeIndex={activeIndex} onClickHandler={this.goToIndex} />
{this.state.imagesPreviewUrls.map( (item, key) => (
<CarouselItem
onExiting={this.onExiting}
onExited={this.onExited}
key={`Carousel_${key}`}
>
<img src={item} alt="Carousel" />
</CarouselItem>
))}
<CarouselControl direction="prev" directionText="Previous" onClickHandler={this.previous} />
<CarouselControl direction="next" directionText="Next" onClickHandler={this.next} />
</Carousel>)
: (null)
}
</Col>
</Row>
</TabPane>
</TabContent>
<Button color="primary" style={{ marginTop: '16px' }} className={this.state.activeTab === '3' ? 'd-none' : ''}>
<FaEdit />
{' '}
Mettre à jour
</Button>
</Form>
</Container>
</div>
);
}
}
export default Vegetable;