import * as React from 'react' ; import { NavDropdown } from 'react-bootstrap' ; import { CanaryConfig } from '../../domain/Kayenta' ; import { boundMethod } from 'autobind-decorator' ; import log from '../../util/LoggerFactory' ; import { EVENT , trackEvent } from '../../util/MetricUtils' ; import { safeGet } from '../../util/OptionalUtils' ; interface Props { onLoad : ( config : CanaryConfig ) => void ; onError : ( error : any ) => void ; } export default class LoadCanaryConfigNavItem extends React . Component < Props > { private fileInput : any ; private fileReader = new FileReader ( ) ; constructor ( props ) { super ( props ) ; this . fileInput = React . createRef ( ) ; this . fileReader . onloadend = ( ) => { this . onFileLoad ( ) ; } ; } @ boundMethod private handleClick ( ) { this . fileInput . click ( ) ; } @ boundMethod private handleFileSelect ( event , onLoad , onError ) { const file = event . target . files [ 0 ] ; log . info ( `Processing file: ${ file ? file . name : 'unknown' }` ) ; try { this . fileReader . readAsText ( file ) ; } catch ( e ) { onError ( e ) ; } } @ boundMethod private onFileLoad ( ) { const unvalidatedJsonObject = JSON . parse ( this . fileReader . result as any ) ; this . props . onLoad ( unvalidatedJsonObject ) ; trackEvent ( EVENT . LOAD_CONFIG , { source : 'file' , name : safeGet ( ( ) => unvalidatedJsonObject . name ) . orElse ( 'UNKNOWN' ) } ) ; alert ( 'Successfully loaded canary config from file' ) ; } render ( ) { const { onLoad , onError } = this . props ; return ( < div > < NavDropdown . Item onClick = { this . handleClick } > Load Existing Kayenta Config from File < /NavDropdown.Item> < input className = "hidden" onChange = { e => { this . handleFileSelect ( e , onLoad , onError ) ; } } ref = { input => ( this . fileInput = input ) } type = "file" accept = ".json" id = "file-input" / > < /div>); } }