// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // See License.txt for license information. import $ from 'jquery'; import PropTypes from 'prop-types'; import React from 'react'; import {Client4} from 'mattermost-redux/client'; import * as Utils from 'utils/utils.jsx'; import {uploadBrandImage} from 'actions/admin_actions.jsx'; import FormError from 'components/form_error.jsx'; import {FormattedHTMLMessage, FormattedMessage} from 'react-intl'; const HTTP_STATUS_OK = 200; export default class BrandImageSetting extends React.PureComponent { static propTypes = { /* * Set to disable the setting */ disabled: PropTypes.bool.isRequired } constructor(props) { super(props); this.handleImageChange = this.handleImageChange.bind(this); this.handleImageSubmit = this.handleImageSubmit.bind(this); this.state = { brandImage: null, brandImageExists: false, brandImageTimestamp: Date.now(), uploading: false, uploadCompleted: false, error: '' }; } componentWillMount() { fetch(Client4.getBrandImageUrl(this.state.brandImageTimestamp)).then( (resp) => { if (resp.status === HTTP_STATUS_OK) { this.setState({brandImageExists: true}); } else { this.setState({brandImageExists: false}); } } ); } componentDidUpdate() { if (this.refs.image) { const reader = new FileReader(); const img = this.refs.image; reader.onload = (e) => { $(img).attr('src', e.target.result); }; reader.readAsDataURL(this.state.brandImage); } } handleImageChange() { const element = $(this.refs.fileInput); if (element.prop('files').length > 0) { this.setState({ brandImage: element.prop('files')[0] }); } } handleImageSubmit(e) { e.preventDefault(); if (!this.state.brandImage) { return; } if (this.state.uploading) { return; } $(this.refs.upload).button('loading'); this.setState({ uploading: true, error: '' }); uploadBrandImage( this.state.brandImage, () => { $(this.refs.upload).button('complete'); this.setState({ brandImageExists: true, brandImage: null, brandImageTimestamp: Date.now(), uploading: false }); }, (err) => { $(this.refs.upload).button('reset'); this.setState({ uploading: false, error: err.message }); } ); } render() { let btnPrimaryClass = 'btn'; if (this.state.brandImage) { btnPrimaryClass += ' btn-primary'; } let letbtnDefaultClass = 'btn'; if (!this.props.disabled) { letbtnDefaultClass += ' btn-default'; } let img = null; if (this.state.brandImage) { img = ( ); } else if (this.state.brandImageExists) { img = ( ); } else { img = (

); } return (
{img}

); } }