1
0

Input.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. import { getComponentClassName } from "./TaipyStyle";
  25. const AUTHORIZED_KEYS = ["Enter", "Escape", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"];
  26. const getActionKeys = (keys?: string): string[] => {
  27. const ak = (
  28. keys
  29. ? keys
  30. .split(";")
  31. .map((v) => v.trim().toLowerCase())
  32. .filter((v) => AUTHORIZED_KEYS.some((k) => k.toLowerCase() === v))
  33. : []
  34. ).map((v) => AUTHORIZED_KEYS.find((k) => k.toLowerCase() == v) as string);
  35. return ak.length > 0 ? ak : [AUTHORIZED_KEYS[0]];
  36. };
  37. const numberSx = {
  38. "& input[type=number]::-webkit-outer-spin-button, & input[type=number]::-webkit-inner-spin-button": {
  39. display: "none",
  40. },
  41. "& input[type=number]": {
  42. MozAppearance: "textfield",
  43. },
  44. };
  45. const verticalDivStyle: CSSProperties = {
  46. display: "flex",
  47. flexDirection: "column",
  48. gap: 0,
  49. };
  50. const noPaddingYSx = {py: 0};
  51. const Input = (props: TaipyInputProps) => {
  52. const {
  53. type,
  54. id,
  55. updateVarName,
  56. propagate = true,
  57. defaultValue = "",
  58. onAction,
  59. onChange,
  60. multiline = false,
  61. actionOnBlur = false,
  62. linesShown = 5,
  63. } = props;
  64. const [value, setValue] = useState(defaultValue);
  65. const dispatch = useDispatch();
  66. const delayCall = useRef(-1);
  67. const [actionKeys] = useState(() => getActionKeys(props.actionKeys));
  68. const module = useModule();
  69. const changeDelay = typeof props.changeDelay === "number" ? (props.changeDelay >= 0 ? props.changeDelay : -1) : 300;
  70. const className = useClassNames(props.libClassName, props.dynamicClassName, props.className);
  71. const active = useDynamicProperty(props.active, props.defaultActive, true);
  72. const hover = useDynamicProperty(props.hoverText, props.defaultHoverText, undefined);
  73. const step = useDynamicProperty(props.step, props.defaultStep, 1);
  74. const stepMultiplier = useDynamicProperty(props.stepMultiplier, props.defaultStepMultiplier, 10);
  75. const min = useDynamicProperty(props.min, props.defaultMin, undefined);
  76. const max = useDynamicProperty(props.max, props.defaultMax, undefined);
  77. const textSx = useMemo(
  78. () =>
  79. props.width
  80. ? {
  81. ...numberSx,
  82. maxWidth: getCssSize(props.width),
  83. }
  84. : numberSx,
  85. [props.width]
  86. );
  87. const updateValueWithDelay = useCallback(
  88. (value: number | string) => {
  89. if (changeDelay === -1) {
  90. return;
  91. }
  92. if (changeDelay === 0) {
  93. // Workaround using microtask to ensure the value is updated before the next action to avoid the bad setState behavior
  94. Promise.resolve().then(() => {
  95. dispatch(createSendUpdateAction(updateVarName, value, module, onChange, propagate));
  96. });
  97. return;
  98. }
  99. if (delayCall.current > 0) {
  100. clearTimeout(delayCall.current);
  101. }
  102. delayCall.current = window.setTimeout(() => {
  103. delayCall.current = -1;
  104. dispatch(createSendUpdateAction(updateVarName, value, module, onChange, propagate));
  105. }, changeDelay);
  106. },
  107. [changeDelay, dispatch, updateVarName, module, onChange, propagate]
  108. );
  109. const handleInput = useCallback(
  110. (e: React.ChangeEvent<HTMLInputElement>) => {
  111. const val = e.target.value;
  112. setValue(val);
  113. if (changeDelay === -1) {
  114. return;
  115. }
  116. if (changeDelay === 0) {
  117. Promise.resolve().then(() => {
  118. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  119. });
  120. }
  121. if (delayCall.current > 0) {
  122. clearTimeout(delayCall.current);
  123. }
  124. delayCall.current = window.setTimeout(() => {
  125. delayCall.current = -1;
  126. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  127. }, changeDelay);
  128. },
  129. [changeDelay, dispatch, updateVarName, module, onChange, propagate]
  130. );
  131. const handleBlur = useCallback(
  132. (evt: React.FocusEvent<HTMLInputElement>) => {
  133. const val = (type === "number")
  134. ? Number(evt.currentTarget.querySelector("input")?.value)
  135. : (multiline
  136. ? evt.currentTarget.querySelector("textarea")?.value
  137. : evt.currentTarget.querySelector("input")?.value)
  138. ;
  139. if (delayCall.current > 0) {
  140. if (changeDelay > 0) {
  141. clearTimeout(delayCall.current);
  142. delayCall.current = -1;
  143. }
  144. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  145. }
  146. onAction && dispatch(createSendActionNameAction(id, module, onAction, "Tab", updateVarName, val));
  147. evt.preventDefault();
  148. },
  149. [dispatch, type, updateVarName, module, onChange, propagate, changeDelay, id, multiline, onAction]
  150. );
  151. const handleAction = useCallback(
  152. (evt: KeyboardEvent<HTMLDivElement>) => {
  153. if (evt.shiftKey && type === "number") {
  154. if (evt.key === "ArrowUp") {
  155. let val =
  156. Number(evt.currentTarget.querySelector("input")?.value || 0) +
  157. (step || 1) * (stepMultiplier || 10);
  158. if (max !== undefined && val > max) {
  159. val = max;
  160. }
  161. setValue(val.toString());
  162. updateValueWithDelay(val);
  163. evt.preventDefault();
  164. } else if (evt.key === "ArrowDown") {
  165. let val =
  166. Number(evt.currentTarget.querySelector("input")?.value || 0) -
  167. (step || 1) * (stepMultiplier || 10);
  168. if (min !== undefined && val < min) {
  169. val = min;
  170. }
  171. setValue(val.toString());
  172. updateValueWithDelay(val);
  173. evt.preventDefault();
  174. }
  175. } else if (!evt.shiftKey && !evt.ctrlKey && !evt.altKey && actionKeys.includes(evt.key)) {
  176. const val = multiline
  177. ? evt.currentTarget.querySelector("textarea")?.value
  178. : evt.currentTarget.querySelector("input")?.value;
  179. if (changeDelay > 0 && delayCall.current > 0) {
  180. clearTimeout(delayCall.current);
  181. delayCall.current = -1;
  182. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  183. } else if (changeDelay === -1) {
  184. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  185. }
  186. onAction && dispatch(createSendActionNameAction(id, module, onAction, evt.key, updateVarName, val));
  187. evt.preventDefault();
  188. }
  189. },
  190. [
  191. type,
  192. multiline,
  193. actionKeys,
  194. step,
  195. stepMultiplier,
  196. max,
  197. updateValueWithDelay,
  198. onAction,
  199. dispatch,
  200. id,
  201. module,
  202. updateVarName,
  203. min,
  204. changeDelay,
  205. onChange,
  206. propagate,
  207. ]
  208. );
  209. const roundBasedOnStep = useMemo(() => {
  210. const stepString = (step || 1).toString();
  211. const decimalPlaces = stepString.includes(".") ? stepString.split(".")[1].length : 0;
  212. const multiplier = Math.pow(10, decimalPlaces);
  213. return (value: number) => Math.round(value * multiplier) / multiplier;
  214. }, [step]);
  215. const calculateNewValue = useMemo(() => {
  216. return (prevValue: string, step: number, stepMultiplier: number, shiftKey: boolean, increment: boolean) => {
  217. const multiplier = shiftKey ? stepMultiplier : 1;
  218. const change = step * multiplier * (increment ? 1 : -1);
  219. return roundBasedOnStep(Number(prevValue) + change).toString();
  220. };
  221. }, [roundBasedOnStep]);
  222. const handleStepperMouseDown = useCallback(
  223. (event: React.MouseEvent<HTMLButtonElement>, increment: boolean) => {
  224. setValue((prevValue) => {
  225. const newValue = calculateNewValue(
  226. prevValue,
  227. step || 1,
  228. stepMultiplier || 10,
  229. event.shiftKey,
  230. increment
  231. );
  232. if (min !== undefined && Number(newValue) < min) {
  233. updateValueWithDelay(min);
  234. return min.toString();
  235. }
  236. if (max !== undefined && Number(newValue) > max) {
  237. updateValueWithDelay(max);
  238. return max.toString();
  239. }
  240. updateValueWithDelay(newValue);
  241. return newValue;
  242. });
  243. },
  244. [calculateNewValue, step, stepMultiplier, min, max, updateValueWithDelay]
  245. );
  246. const handleUpStepperMouseDown = useCallback(
  247. (event: React.MouseEvent<HTMLButtonElement>) => {
  248. handleStepperMouseDown(event, true);
  249. },
  250. [handleStepperMouseDown]
  251. );
  252. const handleDownStepperMouseDown = useCallback(
  253. (event: React.MouseEvent<HTMLButtonElement>) => {
  254. handleStepperMouseDown(event, false);
  255. },
  256. [handleStepperMouseDown]
  257. );
  258. // password
  259. const [showPassword, setShowPassword] = useState(false);
  260. const handleClickShowPassword = useCallback(() => setShowPassword((show) => !show), []);
  261. const handleMouseDownPassword = useCallback(
  262. (event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault(),
  263. []
  264. );
  265. const inputProps = useMemo(
  266. () =>
  267. type == "number"
  268. ? {
  269. htmlInput: {
  270. step: step ? step : 1,
  271. min: min,
  272. max: max,
  273. },
  274. input: {
  275. endAdornment: (
  276. <div style={verticalDivStyle}>
  277. <IconButton
  278. aria-label="Increment value"
  279. size="small"
  280. onMouseDown={handleUpStepperMouseDown}
  281. disabled={!active}
  282. sx={noPaddingYSx}
  283. >
  284. <ArrowDropUpIcon fontSize="inherit" />
  285. </IconButton>
  286. <IconButton
  287. aria-label="Decrement value"
  288. size="small"
  289. onMouseDown={handleDownStepperMouseDown}
  290. disabled={!active}
  291. sx={noPaddingYSx}
  292. >
  293. <ArrowDropDownIcon fontSize="inherit" />
  294. </IconButton>
  295. </div>
  296. ),
  297. },
  298. }
  299. : type == "password"
  300. ? {
  301. htmlInput: { autoComplete: "current-password" },
  302. input: {
  303. endAdornment: (
  304. <IconButton
  305. aria-label="toggle password visibility"
  306. onClick={handleClickShowPassword}
  307. onMouseDown={handleMouseDownPassword}
  308. edge="end"
  309. >
  310. {showPassword ? <VisibilityOff /> : <Visibility />}
  311. </IconButton>
  312. ),
  313. },
  314. }
  315. : undefined,
  316. [
  317. active,
  318. type,
  319. step,
  320. min,
  321. max,
  322. showPassword,
  323. handleClickShowPassword,
  324. handleMouseDownPassword,
  325. handleUpStepperMouseDown,
  326. handleDownStepperMouseDown,
  327. ]
  328. );
  329. useEffect(() => {
  330. if (props.value !== undefined) {
  331. setValue(props.value);
  332. }
  333. }, [props.value]);
  334. return (
  335. <Tooltip title={hover || ""}>
  336. <>
  337. <TextField
  338. sx={textSx}
  339. margin="dense"
  340. hiddenLabel
  341. value={value ?? ""}
  342. className={`${className} ${getComponentClassName(props.children)}`}
  343. type={showPassword && type == "password" ? "text" : type}
  344. id={id}
  345. slotProps={inputProps}
  346. label={props.label}
  347. onChange={handleInput}
  348. onBlur={actionOnBlur ? handleBlur : undefined}
  349. disabled={!active}
  350. onKeyDown={handleAction}
  351. multiline={multiline}
  352. minRows={linesShown}
  353. />
  354. {props.children}
  355. </>
  356. </Tooltip>
  357. );
  358. };
  359. export default Input;