import React, { Component } from 'react' import { Link } from 'react-router-dom' import { connect } from 'react-redux' import { history } from 'app/store' import { unslugify } from 'app/utils' import actions from 'app/actions' class AudioList extends Component { state = { playing: false, play_id: -1, } constructor(props) { super(props) this.toggleAudio = this.toggleAudio.bind(this) this.upload = this.upload.bind(this) this.audioDidEnd = this.audioDidEnd.bind(this) } componentDidMount() { this.audioElement = document.createElement('audio') this.audioElement.addEventListener('ended', this.audioDidEnd) } componentWillUnmount() { this.audioElement.removeEventListener('ended', this.audioDidEnd) this.audioElement.pause() this.audioElement = null } audioDidEnd() { this.setState({ playing: false }) } upload(e) { e.preventDefault() document.body.className = '' const files = e.dataTransfer ? e.dataTransfer.files : e.target.files let i if (!files.length) return Array.from(files).forEach(file => this.uploadTaggedFile(file, 'audio', file.filename)) } uploadTaggedFile(file, tag, fn) { return new Promise((resolve, reject) => { this.setState({ status: "Uploading " + tag + "..." }) const uploadData = { tag, file, __file_filename: fn, graph_id: this.props.graph.id, username: 'swimmer', } // console.log(uploadData) return actions.upload.upload(uploadData).then(data => { // console.log(data) resolve({ ...data.res, }) }) }) } destroyFile(upload) { return new Promise((resolve, reject) => { actions.upload.destroy(upload) .then(() => { console.log('Destroy successful') resolve() }) .catch(() => { console.log('Error deleting the file') reject() }) }) } toggleAudio(upload) { console.log(upload) let playing = false if (this.state.play_id === upload.id && this.state.playing) { this.audioElement.pause() } else { this.audioElement.src = upload.url this.audioElement.currentTime = 0 this.audioElement.play() playing = true } this.setState({ playing, play_id: upload.id, }) } render() { const { playing, play_id } = this.state const { graph } = this.props // console.log(graph.uploads) return (
{graph.uploads.map(upload => ( upload.tag === 'audio' && (
this.toggleAudio(upload)} >
{unslugify(upload.fn)}
) ))}
) } } const mapStateToProps = state => ({ graph: state.graph.show.res, }) const mapDispatchToProps = dispatch => ({ }) export default connect(mapStateToProps, mapDispatchToProps)(AudioList)