kara-module-downloader
Version:
kara module download
125 lines (115 loc) • 3.67 kB
JavaScript
/* eslint-disable */
import React from 'react'
import css from './download.scss'
import FileAgent from './api/fileAgent';
export default class Component extends React.Component {
constructor(props) {
super(props)
this.state = {
fold: false, // 模态框是否折叠
fileIds: [], // 下载文件的ID
percent: 0, // 堆栈最后一个文件的下载进度
}
}
componentDidMount () {
const agent = new FileAgent()
agent.token = this.props.token
agent.apiRoot = this.props.apiRoot
window.$emitter.on('DOWNLOAD_FILE', ({fileId, percent, progress, cancel})=>{
// fileId 文件唯一标识
// percent 下载进度
// progress: start(开始下载)、downloading(正在下载)、end(下载完成)、cancel(取消下载)、failure(下载失败)A
const { fileIds } = this.state
const lastId = fileIds.length > 0 ? fileIds[fileIds.length-1] : null
if(progress === 'start') {
// 开始下载
this.setState((old)=>({
fold: false, // 不折叠
fileIds: old.fileIds.concat(fileId),
percent: 0, // 重置
}))
} else if (progress === 'downloading' && lastId && lastId === fileId) {
// 只取最后一个的进度
if(this.cancel) {
cancel(); //取消下载
const { fileIds } = this.state
if(fileIds.length === 1) {
this.setState({
fileIds: []
})
}else {
const fileIdsClone = fileIds.slice()
_.remove(fileIdsClone, function(id) {
return id === fileId;
});
this.setState({
fileIds: fileIdsClone,
fold: true
})
}
this.cancel = false
}
this.setState({
percent: parseInt(percent*100,10)
})
} else if (progress === 'end') {
// 下载完成
const fileIdsClone = fileIds.slice()
_.remove(fileIdsClone, function(id) {
return id === fileId;
});
this.setState({
fileIds: fileIdsClone
})
}
})
}
modalFold = () => {
this.setState({fold:true})
}
modalUnFold = () => {
this.setState({fold:false})
}
cancelDownLoad = () => {
// 只能取消最后一个
this.cancel = true
}
render(){
const { fold, percent, fileIds } = this.state
if(fileIds.length === 0) {
return null
}
return (
<div className={css.download}>
{fold ? <div className={`${css.tost}`}>
<i style={{'width':`${percent}%`}}></i>
<span>{percent}%</span>
<a onClick={this.modalUnFold}>还原</a>
</div>
:<div className={css.modal}>
<div className={css.main}>
<div className={css.title}>
<span className={css.status}>正在加载...</span>
<span className={css.handle}>
<i className="i-f i-min" onClick={this.modalFold}></i>
<i className="i-f i-close" onClick={this.cancelDownLoad}></i>
</span>
</div>
<div className={css.cartoon} >
<i className={`${css.windmill} ${css.rotate}`}/>
</div>
<div className={css.progress}>
<span className={css.bar}>
<i style={{"width":`${percent}%`}}></i>
</span>
<span className={css.percent}>
<em>{percent}</em>
<i>%</i>
</span>
</div>
</div>
</div>}
</div>
);
}
}