github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/ui/src/views/app/components/Search/index.tsx (about) 1 // Copyright 2018 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 import { Button, Form, Input } from "antd"; 12 import { InputProps } from "antd/lib/input"; 13 import CancelIcon from "assets/cancel.svg"; 14 import SearchIcon from "assets/search.svg"; 15 import React from "react"; 16 import "./search.styl"; 17 18 interface ISearchProps { 19 onSubmit: (value: string) => void; 20 onClear?: () => void; 21 defaultValue?: string; 22 } 23 24 interface ISearchState { 25 value: string; 26 submitted: boolean; 27 submit?: boolean; 28 } 29 30 type TSearchProps = ISearchProps & InputProps; 31 32 export class Search extends React.Component<TSearchProps, ISearchState> { 33 state = { 34 value: this.props.defaultValue || "", 35 submitted: false, 36 }; 37 38 onSubmit = () => { 39 const { value } = this.state; 40 const { onSubmit } = this.props; 41 onSubmit(value); 42 if (value.length > 0) { 43 this.setState({ 44 submitted: true, 45 }); 46 } 47 } 48 49 onChange = (event: React.ChangeEvent<HTMLInputElement>) => { 50 const value: string = event.target.value; 51 const submitted = value.length === 0; 52 this.setState({ value, submitted }, () => submitted && this.onSubmit()); 53 } 54 55 onClear = () => { 56 const { onClear } = this.props; 57 this.setState({ value: "", submit: false }); 58 onClear(); 59 } 60 61 renderSuffix = () => { 62 const { value, submitted } = this.state; 63 if (value.length > 0) { 64 if (submitted) { 65 return <Button onClick={this.onClear} type="default" className="_clear-search"><img className="_suffix-icon" src={CancelIcon} /></Button>; 66 } 67 return <Button type="default" htmlType="submit" className="_submit-search">Enter</Button>; 68 } 69 return null; 70 } 71 72 render() { 73 const { value, submitted } = this.state; 74 const className = submitted ? "_submitted" : ""; 75 76 /* 77 current antdesign (3.25.3) has Input.d.ts incompatible with latest @types/react 78 temporary fix, remove as soon antd can be updated 79 */ 80 81 // tslint:disable-next-line: variable-name 82 const MyInput = Input as any; 83 84 return ( 85 <Form onSubmit={this.onSubmit} className="_search-form"> 86 <Form.Item> 87 <MyInput 88 className={className} 89 placeholder="Search Statement" 90 onChange={this.onChange} 91 prefix={<img className="_prefix-icon" src={SearchIcon} />} 92 suffix={this.renderSuffix()} 93 value={value} 94 {...this.props} 95 /> 96 </Form.Item> 97 </Form> 98 ); 99 } 100 }