/* @flow */ import React, { Component } from 'react'; import { getDuplicateInstanceNumber } from 'reducers/utils'; import type { Props } from './index'; type State = { defaultName: string; instance: number; instanceName: ?string; isUsed: boolean; } export default class DuplicateDevice extends Component { keyboardHandler: (event: KeyboardEvent) => void; state: State; input: ?HTMLInputElement; constructor(props: Props) { super(props); const device = props.modal.opened ? props.modal.device : null; if (!device) return; const instance = getDuplicateInstanceNumber(props.devices, device); this.state = { defaultName: `${device.label} (${instance.toString()})`, instance, instanceName: null, isUsed: false, }; } keyboardHandler(event: KeyboardEvent): void { if (event.keyCode === 13 && !this.state.isUsed) { event.preventDefault(); this.submit(); } } componentDidMount(): void { // one time autofocus if (this.input) this.input.focus(); this.keyboardHandler = this.keyboardHandler.bind(this); window.addEventListener('keydown', this.keyboardHandler, false); } componentWillUnmount(): void { window.removeEventListener('keydown', this.keyboardHandler, false); } onNameChange = (value: string): void => { let isUsed: boolean = false; if (value.length > 0) { isUsed = (this.props.devices.find(d => d.instanceName === value) !== undefined); } this.setState({ instanceName: value.length > 0 ? value : null, isUsed, }); } submit() { if (!this.props.modal.opened) return; const extended: Object = { instanceName: this.state.instanceName, instance: this.state.instance }; this.props.modalActions.onDuplicateDevice({ ...this.props.modal.device, ...extended }); } render() { if (!this.props.modal.opened) return null; const { device } = this.props.modal; const { onCancel, onDuplicateDevice } = this.props.modalActions; const { defaultName, instanceName, isUsed, } = this.state; return (
); } }