Input.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /*
  2. * Copyright 2021-2024 Avaiga Private Limited
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  5. * the License. You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  10. * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  11. * specific language governing permissions and limitations under the License.
  12. */
  13. import React, { useState, useEffect, useCallback, useRef, KeyboardEvent, useMemo, CSSProperties } from "react";
  14. import IconButton from "@mui/material/IconButton";
  15. import TextField from "@mui/material/TextField";
  16. import Tooltip from "@mui/material/Tooltip";
  17. import Visibility from "@mui/icons-material/Visibility";
  18. import VisibilityOff from "@mui/icons-material/VisibilityOff";
  19. import ArrowDropUpIcon from "@mui/icons-material/ArrowDropUp";
  20. import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
  21. import { createSendActionNameAction, createSendUpdateAction } from "../../context/taipyReducers";
  22. import { getCssSize, TaipyInputProps } from "./utils";
  23. import { useClassNames, useDispatch, useDynamicProperty, useModule } from "../../utils/hooks";
  24. const AUTHORIZED_KEYS = ["Enter", "Escape", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"];
  25. const getActionKeys = (keys?: string): string[] => {
  26. const ak = (
  27. keys
  28. ? keys
  29. .split(";")
  30. .map((v) => v.trim().toLowerCase())
  31. .filter((v) => AUTHORIZED_KEYS.some((k) => k.toLowerCase() === v))
  32. : []
  33. ).map((v) => AUTHORIZED_KEYS.find((k) => k.toLowerCase() == v) as string);
  34. return ak.length > 0 ? ak : [AUTHORIZED_KEYS[0]];
  35. };
  36. const numberSx = {
  37. "& input[type=number]::-webkit-outer-spin-button, & input[type=number]::-webkit-inner-spin-button": {
  38. display: "none",
  39. },
  40. "& input[type=number]": {
  41. MozAppearance: "textfield",
  42. },
  43. };
  44. const verticalDivStyle: CSSProperties = {
  45. display: "flex",
  46. flexDirection: "column",
  47. gap: 0,
  48. };
  49. const Input = (props: TaipyInputProps) => {
  50. const {
  51. type,
  52. id,
  53. updateVarName,
  54. propagate = true,
  55. defaultValue = "",
  56. onAction,
  57. onChange,
  58. multiline = false,
  59. linesShown = 5,
  60. } = props;
  61. const [value, setValue] = useState(defaultValue);
  62. const dispatch = useDispatch();
  63. const delayCall = useRef(-1);
  64. const [actionKeys] = useState(() => getActionKeys(props.actionKeys));
  65. const module = useModule();
  66. const changeDelay = typeof props.changeDelay === "number" ? (props.changeDelay >= 0 ? props.changeDelay : -1) : 300;
  67. const className = useClassNames(props.libClassName, props.dynamicClassName, props.className);
  68. const active = useDynamicProperty(props.active, props.defaultActive, true);
  69. const hover = useDynamicProperty(props.hoverText, props.defaultHoverText, undefined);
  70. const step = useDynamicProperty(props.step, props.defaultStep, 1);
  71. const stepMultiplier = useDynamicProperty(props.stepMultiplier, props.defaultStepMultiplier, 10);
  72. const min = useDynamicProperty(props.min, props.defaultMin, undefined);
  73. const max = useDynamicProperty(props.max, props.defaultMax, undefined);
  74. const textSx = useMemo(
  75. () =>
  76. props.width
  77. ? {
  78. ...numberSx,
  79. maxWidth: getCssSize(props.width),
  80. }
  81. : numberSx,
  82. [props.width]
  83. );
  84. const updateValueWithDelay = useCallback(
  85. (value: number | string) => {
  86. if (changeDelay === -1) {
  87. return;
  88. }
  89. if (changeDelay === 0) {
  90. // Workaround using microtask to ensure the value is updated before the next action to avoid the bad setState behavior
  91. Promise.resolve().then(() => {
  92. dispatch(createSendUpdateAction(updateVarName, value, module, onChange, propagate));
  93. });
  94. return;
  95. }
  96. if (delayCall.current > 0) {
  97. clearTimeout(delayCall.current);
  98. }
  99. delayCall.current = window.setTimeout(() => {
  100. delayCall.current = -1;
  101. dispatch(createSendUpdateAction(updateVarName, value, module, onChange, propagate));
  102. }, changeDelay);
  103. },
  104. [changeDelay, dispatch, updateVarName, module, onChange, propagate]
  105. );
  106. const handleInput = useCallback(
  107. (e: React.ChangeEvent<HTMLInputElement>) => {
  108. const val = e.target.value;
  109. setValue(val);
  110. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  111. },
  112. [updateVarName, dispatch, propagate, onChange, module]
  113. );
  114. const handleAction = useCallback(
  115. (evt: KeyboardEvent<HTMLDivElement>) => {
  116. if (evt.shiftKey && type === "number") {
  117. if (evt.key === "ArrowUp") {
  118. let val =
  119. Number(evt.currentTarget.querySelector("input")?.value || 0) +
  120. (step || 1) * (stepMultiplier || 10);
  121. if (max !== undefined && val > max) {
  122. val = max;
  123. }
  124. setValue(val.toString());
  125. updateValueWithDelay(val);
  126. evt.preventDefault();
  127. } else if (evt.key === "ArrowDown") {
  128. let val =
  129. Number(evt.currentTarget.querySelector("input")?.value || 0) -
  130. (step || 1) * (stepMultiplier || 10);
  131. if (min !== undefined && val < min) {
  132. val = min;
  133. }
  134. setValue(val.toString());
  135. updateValueWithDelay(val);
  136. evt.preventDefault();
  137. }
  138. } else if (!evt.shiftKey && !evt.ctrlKey && !evt.altKey && actionKeys.includes(evt.key)) {
  139. const val = multiline ? evt.currentTarget.querySelector("textarea")?.value : evt.currentTarget.querySelector("input")?.value;
  140. if (changeDelay > 0 && delayCall.current > 0) {
  141. clearTimeout(delayCall.current);
  142. delayCall.current = -1;
  143. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  144. } else if (changeDelay === -1) {
  145. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  146. }
  147. onAction && dispatch(createSendActionNameAction(id, module, onAction, evt.key, updateVarName, val));
  148. evt.preventDefault();
  149. }
  150. },
  151. [
  152. type,
  153. multiline,
  154. actionKeys,
  155. step,
  156. stepMultiplier,
  157. max,
  158. updateValueWithDelay,
  159. onAction,
  160. dispatch,
  161. id,
  162. module,
  163. updateVarName,
  164. min,
  165. changeDelay,
  166. onChange,
  167. propagate,
  168. ]
  169. );
  170. const roundBasedOnStep = useMemo(() => {
  171. const stepString = (step || 1).toString();
  172. const decimalPlaces = stepString.includes(".") ? stepString.split(".")[1].length : 0;
  173. const multiplier = Math.pow(10, decimalPlaces);
  174. return (value: number) => Math.round(value * multiplier) / multiplier;
  175. }, [step]);
  176. const calculateNewValue = useMemo(() => {
  177. return (prevValue: string, step: number, stepMultiplier: number, shiftKey: boolean, increment: boolean) => {
  178. const multiplier = shiftKey ? stepMultiplier : 1;
  179. const change = step * multiplier * (increment ? 1 : -1);
  180. return roundBasedOnStep(Number(prevValue) + change).toString();
  181. };
  182. }, [roundBasedOnStep]);
  183. const handleStepperMouseDown = useCallback(
  184. (event: React.MouseEvent<HTMLButtonElement>, increment: boolean) => {
  185. setValue((prevValue) => {
  186. const newValue = calculateNewValue(
  187. prevValue,
  188. step || 1,
  189. stepMultiplier || 10,
  190. event.shiftKey,
  191. increment
  192. );
  193. if (min !== undefined && Number(newValue) < min) {
  194. updateValueWithDelay(min);
  195. return min.toString();
  196. }
  197. if (max !== undefined && Number(newValue) > max) {
  198. updateValueWithDelay(max);
  199. return max.toString();
  200. }
  201. updateValueWithDelay(newValue);
  202. return newValue;
  203. });
  204. },
  205. [calculateNewValue, step, stepMultiplier, min, max, updateValueWithDelay]
  206. );
  207. const handleUpStepperMouseDown = useCallback(
  208. (event: React.MouseEvent<HTMLButtonElement>) => {
  209. handleStepperMouseDown(event, true);
  210. },
  211. [handleStepperMouseDown]
  212. );
  213. const handleDownStepperMouseDown = useCallback(
  214. (event: React.MouseEvent<HTMLButtonElement>) => {
  215. handleStepperMouseDown(event, false);
  216. },
  217. [handleStepperMouseDown]
  218. );
  219. // password
  220. const [showPassword, setShowPassword] = useState(false);
  221. const handleClickShowPassword = useCallback(() => setShowPassword((show) => !show), []);
  222. const handleMouseDownPassword = useCallback(
  223. (event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault(),
  224. []
  225. );
  226. const muiInputProps = useMemo(
  227. () =>
  228. type == "password"
  229. ? {
  230. endAdornment: (
  231. <IconButton
  232. aria-label="toggle password visibility"
  233. onClick={handleClickShowPassword}
  234. onMouseDown={handleMouseDownPassword}
  235. edge="end"
  236. >
  237. {showPassword ? <VisibilityOff /> : <Visibility />}
  238. </IconButton>
  239. ),
  240. }
  241. : type == "number"
  242. ? {
  243. endAdornment: (
  244. <div style={verticalDivStyle}>
  245. <IconButton
  246. aria-label="Increment value"
  247. size="small"
  248. onMouseDown={handleUpStepperMouseDown}
  249. >
  250. <ArrowDropUpIcon fontSize="inherit" />
  251. </IconButton>
  252. <IconButton
  253. aria-label="Decrement value"
  254. size="small"
  255. onMouseDown={handleDownStepperMouseDown}
  256. >
  257. <ArrowDropDownIcon fontSize="inherit" />
  258. </IconButton>
  259. </div>
  260. ),
  261. }
  262. : undefined,
  263. [
  264. type,
  265. showPassword,
  266. handleClickShowPassword,
  267. handleMouseDownPassword,
  268. handleUpStepperMouseDown,
  269. handleDownStepperMouseDown,
  270. ]
  271. );
  272. const inputProps = useMemo(
  273. () =>
  274. type == "number"
  275. ? {
  276. step: step ? step : 1,
  277. min: min,
  278. max: max,
  279. }
  280. : type == "password"
  281. ? { autoComplete: "current-password" }
  282. : undefined,
  283. [type, step, min, max]
  284. );
  285. useEffect(() => {
  286. if (props.value !== undefined) {
  287. setValue(props.value);
  288. }
  289. }, [props.value]);
  290. return (
  291. <Tooltip title={hover || ""}>
  292. <TextField
  293. sx={textSx}
  294. margin="dense"
  295. hiddenLabel
  296. value={value ?? ""}
  297. className={className}
  298. type={showPassword && type == "password" ? "text" : type}
  299. id={id}
  300. inputProps={inputProps}
  301. InputProps={muiInputProps}
  302. label={props.label}
  303. onChange={handleInput}
  304. disabled={!active}
  305. onKeyDown={handleAction}
  306. multiline={multiline}
  307. minRows={linesShown}
  308. />
  309. </Tooltip>
  310. );
  311. };
  312. export default Input;