TimezoneInput.tsx (3050B)
1 import React from "react"; 2 3 import { friendlyStr, unfriendlyStr } from "../../utils"; 4 5 import { timezoneList } from "../../utils"; 6 7 import { ITimezoneInput } from "../../utils/interfaces"; 8 9 function TimezoneInput({ 10 autofocus = false, 11 changeValue, 12 clearInput, 13 id = "", 14 placeholder = "Time zone", 15 TZ = "UTC", 16 }: ITimezoneInput): JSX.Element { 17 const options = timezoneList; 18 const [suggestions, setSuggestions] = React.useState<string[]>([]); 19 const [inputValue, setInputValue] = React.useState(friendlyStr(TZ)); 20 const [style, setStyle] = React.useState<object>({ 21 border: 0, 22 borderBottom: "1px solid silver", 23 }); 24 25 function handleBlur(): void { 26 setStyle({ 27 border: 0, 28 borderBottom: "1px solid silver", 29 }); 30 } 31 32 function handleChange(e: React.ChangeEvent<HTMLInputElement>): void { 33 const { value } = e.target; 34 if (clearInput) clearInput(undefined); 35 setInputValue(value); 36 37 let recommendations: string[] | [] = []; 38 if (value.length) { 39 recommendations = options.filter((option) => 40 option.toLowerCase().includes(unfriendlyStr(value).toLowerCase()) 41 ); 42 if (value.length <= 3) 43 recommendations.sort((a, b) => a.length - b.length); 44 } else { 45 recommendations = [...options]; 46 } 47 setSuggestions(recommendations); 48 } 49 50 function handleClick(value: string) { 51 setSuggestions([]); 52 setInputValue(friendlyStr(value)); 53 changeValue(unfriendlyStr(value)); 54 } 55 56 function handleFocus(): void { 57 setStyle({ 58 border: "none", 59 }); 60 } 61 62 function showLI(str: string, index: number, arr: string[]): JSX.Element { 63 return ( 64 <li 65 className="list-group-item list-group-item-action" 66 key={index} 67 onClick={() => handleClick(str)} 68 style={{ cursor: "pointer" }} 69 > 70 {friendlyStr(str)} 71 </li> 72 ); 73 } 74 75 return ( 76 <div className="h4"> 77 <input 78 aria-placeholder={placeholder} 79 autoComplete="false" 80 autoFocus={autofocus} 81 className="w-75" 82 id={id} 83 maxLength={100} 84 name={id} 85 onBlur={handleBlur} 86 onChange={handleChange} 87 onFocus={handleFocus} 88 placeholder={placeholder} 89 role="searchbox" 90 style={style} 91 type="text" 92 value={inputValue} 93 /> 94 <div 95 className="suggestion-list" 96 style={{ 97 boxShadow: 98 suggestions.length > 0 99 ? "0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22)" 100 : "none", 101 left: "15px", 102 maxHeight: "50vh", 103 overflowX: "scroll", 104 scrollbarWidth: "none", 105 position: "absolute", 106 right: "15px", 107 WebkitOverflowScrolling: "touch", 108 zIndex: 2, 109 }} 110 > 111 <div className="h6 mb-0"> 112 <ul className="list-group text-left"> 113 {suggestions.length > 0 ? suggestions.map(showLI) : null} 114 </ul> 115 </div> 116 </div> 117 </div> 118 ); 119 } 120 121 export default TimezoneInput;