import React from 'react'; import { connect } from 'react-redux'; import { makeGetRequest } from '../utils/xhr.js'; import UrlMiddle from '../components/PublishUrlMiddle.jsx'; import {updateError, updateClaim} from '../actions'; class UrlChooser extends React.Component { constructor (props) { super(props); this.state = { host : 'spee.ch', urlMiddle: null, }; this.handleInput = this.handleInput.bind(this); this.cleanseInput = this.cleanseInput.bind(this); this.setClaimNameFromFileName = this.setClaimNameFromFileName.bind(this); this.checkClaimIsAvailable = this.checkClaimIsAvailable.bind(this); } componentWillMount () { if (!this.props.claim || this.props.claim === '') { this.setClaimNameFromFileName(); } } componentWillReceiveProps ({claim: newClaim}) { if (newClaim) { this.checkClaimIsAvailable(newClaim); } else { this.props.onUrlError('Please enter a URL'); } } handleInput (event) { event.preventDefault(); let value = event.target.value; value = this.cleanseInput(value); // update the state this.props.onClaimChange(value); } cleanseInput (input) { input = input.replace(/\s+/g, '-'); // replace spaces with dashes input = input.replace(/[^A-Za-z0-9-]/g, ''); // remove all characters that are not A-Z, a-z, 0-9, or '-' return input; } setClaimNameFromFileName () { const fileName = this.props.fileName; const fileNameWithoutEnding = fileName.substring(0, fileName.lastIndexOf('.')); const cleanClaimName = this.cleanseInput(fileNameWithoutEnding); this.props.onClaimChange(cleanClaimName); } checkClaimIsAvailable (claim) { const that = this; makeGetRequest(`/api/claim-is-available/${claim}`) .then(response => { if (response) { that.props.onUrlError(null); } else { that.props.onUrlError('That url has already been claimed'); } }) .catch((error) => { that.props.onUrlError(error.message); }); } render () { return (

{this.props.urlError}

{this.state.host} / { (this.props.claim && !this.props.urlError) && {'\u2713'} }
); } } const mapStateToProps = state => { return { fileName : state.file.name, loggedInChannelName : state.loggedInChannel.name, loggedInChannelShortId: state.loggedInChannel.shortId, publishInChannel : state.publishInChannel, claim : state.claim, urlError : state.error.url, }; }; const mapDispatchToProps = dispatch => { return { onClaimChange: (value) => { dispatch(updateClaim(value)); dispatch(updateError('publishSubmit', null)); }, onUrlError: (value) => { dispatch(updateError('url', value)); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)(UrlChooser);