import { Component, linkEvent } from 'inferno'; import { Prompt } from 'inferno-router'; import { Site, SiteForm as SiteFormI } from '../interfaces'; import { WebSocketService } from '../services'; import { capitalizeFirstLetter, randomStr, setupTribute } from '../utils'; import autosize from 'autosize'; import Tribute from 'tributejs/src/Tribute.js'; import { i18n } from '../i18next'; interface SiteFormProps { site?: Site; // If a site is given, that means this is an edit onCancel?(): any; } interface SiteFormState { siteForm: SiteFormI; loading: boolean; } export class SiteForm extends Component { private id = `site-form-${randomStr()}`; private tribute: Tribute; private emptyState: SiteFormState = { siteForm: { enable_downvotes: true, open_registration: true, enable_nsfw: true, name: null, }, loading: false, }; constructor(props: any, context: any) { super(props, context); this.tribute = setupTribute(); this.state = this.emptyState; if (this.props.site) { this.state.siteForm = { name: this.props.site.name, description: this.props.site.description, enable_downvotes: this.props.site.enable_downvotes, open_registration: this.props.site.open_registration, enable_nsfw: this.props.site.enable_nsfw, }; } } componentDidMount() { var textarea: any = document.getElementById(this.id); autosize(textarea); this.tribute.attach(textarea); textarea.addEventListener('tribute-replaced', () => { this.state.siteForm.description = textarea.value; this.setState(this.state); autosize.update(textarea); }); } // Necessary to stop the loading componentWillReceiveProps() { this.state.loading = false; this.setState(this.state); } componentDidUpdate() { if ( !this.state.loading && !this.props.site && (this.state.siteForm.name || this.state.siteForm.description) ) { window.onbeforeunload = () => true; } else { window.onbeforeunload = undefined; } } componentWillUnmount() { window.onbeforeunload = null; } render() { return ( <>
{`${ this.props.site ? capitalizeFirstLetter(i18n.t('save')) : capitalizeFirstLetter(i18n.t('name')) } ${i18n.t('your_site')}`}