1
0

Input.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 } from "react";
  14. import TextField from "@mui/material/TextField";
  15. import Tooltip from "@mui/material/Tooltip";
  16. import { styled } from "@mui/material/styles";
  17. import IconButton from "@mui/material/IconButton";
  18. import ArrowDropUpIcon from "@mui/icons-material/ArrowDropUp";
  19. import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
  20. import { createSendActionNameAction, createSendUpdateAction } from "../../context/taipyReducers";
  21. import { TaipyInputProps } from "./utils";
  22. import { useClassNames, useDispatch, useDynamicProperty, useModule } from "../../utils/hooks";
  23. const AUTHORIZED_KEYS = ["Enter", "Escape", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"];
  24. const StyledTextField = styled(TextField)({
  25. "& input[type=number]::-webkit-outer-spin-button, & input[type=number]::-webkit-inner-spin-button": {
  26. display: "none",
  27. },
  28. "& input[type=number]": {
  29. MozAppearance: "textfield",
  30. },
  31. });
  32. const getActionKeys = (keys?: string): string[] => {
  33. const ak = (
  34. keys
  35. ? keys
  36. .split(";")
  37. .map((v) => v.trim().toLowerCase())
  38. .filter((v) => AUTHORIZED_KEYS.some((k) => k.toLowerCase() === v))
  39. : []
  40. ).map((v) => AUTHORIZED_KEYS.find((k) => k.toLowerCase() == v) as string);
  41. return ak.length > 0 ? ak : [AUTHORIZED_KEYS[0]];
  42. };
  43. const Input = (props: TaipyInputProps) => {
  44. const {
  45. type,
  46. id,
  47. updateVarName,
  48. propagate = true,
  49. defaultValue = "",
  50. onAction,
  51. onChange,
  52. multiline = false,
  53. linesShown = 5,
  54. min,
  55. max,
  56. } = props;
  57. const [value, setValue] = useState(defaultValue);
  58. const dispatch = useDispatch();
  59. const delayCall = useRef(-1);
  60. const [actionKeys] = useState(() => getActionKeys(props.actionKeys));
  61. const module = useModule();
  62. const changeDelay = typeof props.changeDelay === "number" ? (props.changeDelay >= 0 ? props.changeDelay : -1) : 300;
  63. const className = useClassNames(props.libClassName, props.dynamicClassName, props.className);
  64. const active = useDynamicProperty(props.active, props.defaultActive, true);
  65. const hover = useDynamicProperty(props.hoverText, props.defaultHoverText, undefined);
  66. const step = useDynamicProperty(props.step, props.defaultStep, 1);
  67. const stepMultiplier = useDynamicProperty(props.stepMultiplier, props.defaultStepMultiplier, 10);
  68. const handleInput = useCallback(
  69. (e: React.ChangeEvent<HTMLInputElement>) => {
  70. const val = e.target.value;
  71. setValue(val);
  72. if (changeDelay === 0) {
  73. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  74. return;
  75. }
  76. if (changeDelay > 0) {
  77. if (delayCall.current > 0) {
  78. clearTimeout(delayCall.current);
  79. }
  80. delayCall.current = window.setTimeout(() => {
  81. delayCall.current = -1;
  82. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  83. }, changeDelay);
  84. }
  85. },
  86. [updateVarName, dispatch, propagate, onChange, changeDelay, module],
  87. );
  88. const handleAction = useCallback(
  89. (evt: KeyboardEvent<HTMLDivElement>) => {
  90. if (evt.shiftKey && evt.key === "ArrowUp") {
  91. setValue(
  92. (
  93. Number(evt.currentTarget.querySelector("input")?.value || 0) +
  94. (step || 1) * (stepMultiplier || 10) -
  95. (step || 1)
  96. ).toString(),
  97. );
  98. }
  99. if (evt.shiftKey && evt.key === "ArrowDown") {
  100. setValue(
  101. (
  102. Number(evt.currentTarget.querySelector("input")?.value || 0) -
  103. (step || 1) * (stepMultiplier || 10) +
  104. (step || 1)
  105. ).toString(),
  106. );
  107. }
  108. if (!evt.shiftKey && !evt.ctrlKey && !evt.altKey && actionKeys.includes(evt.key)) {
  109. const val = evt.currentTarget.querySelector("input")?.value;
  110. if (changeDelay > 0 && delayCall.current > 0) {
  111. clearTimeout(delayCall.current);
  112. delayCall.current = -1;
  113. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  114. } else if (changeDelay === -1) {
  115. dispatch(createSendUpdateAction(updateVarName, val, module, onChange, propagate));
  116. }
  117. onAction && dispatch(createSendActionNameAction(id, module, onAction, evt.key, updateVarName, val));
  118. evt.preventDefault();
  119. }
  120. },
  121. [
  122. actionKeys,
  123. step,
  124. stepMultiplier,
  125. changeDelay,
  126. onAction,
  127. dispatch,
  128. id,
  129. module,
  130. updateVarName,
  131. onChange,
  132. propagate,
  133. ],
  134. );
  135. const roundBasedOnStep = useMemo(() => {
  136. const stepString = (step || 1).toString();
  137. const decimalPlaces = stepString.includes(".") ? stepString.split(".")[1].length : 0;
  138. const multiplier = Math.pow(10, decimalPlaces);
  139. return (value: number) => Math.round(value * multiplier) / multiplier;
  140. }, [step]);
  141. const calculateNewValue = useMemo(() => {
  142. return (prevValue: string, step: number, stepMultiplier: number, shiftKey: boolean, increment: boolean) => {
  143. const multiplier = shiftKey ? stepMultiplier : 1;
  144. const change = step * multiplier * (increment ? 1 : -1);
  145. return roundBasedOnStep(Number(prevValue) + change).toString();
  146. };
  147. }, [roundBasedOnStep]);
  148. const handleStepperMouseDown = useCallback(
  149. (event: React.MouseEvent<HTMLButtonElement>, increment: boolean) => {
  150. setValue((prevValue) => {
  151. const newValue = calculateNewValue(
  152. prevValue,
  153. step || 1,
  154. stepMultiplier || 10,
  155. event.shiftKey,
  156. increment,
  157. );
  158. if (min !== undefined && Number(newValue) < min) {
  159. return min.toString();
  160. }
  161. if (max !== undefined && Number(newValue) > max) {
  162. return max.toString();
  163. }
  164. return newValue;
  165. });
  166. },
  167. [min, max, step, stepMultiplier, calculateNewValue],
  168. );
  169. const handleUpStepperMouseDown = useCallback(
  170. (event: React.MouseEvent<HTMLButtonElement>) => {
  171. handleStepperMouseDown(event, true);
  172. },
  173. [handleStepperMouseDown],
  174. );
  175. const handleDownStepperMouseDown = useCallback(
  176. (event: React.MouseEvent<HTMLButtonElement>) => {
  177. handleStepperMouseDown(event, false);
  178. },
  179. [handleStepperMouseDown],
  180. );
  181. useEffect(() => {
  182. if (props.value !== undefined) {
  183. setValue(props.value);
  184. }
  185. }, [props.value]);
  186. return (
  187. <Tooltip title={hover || ""}>
  188. <StyledTextField
  189. margin="dense"
  190. hiddenLabel
  191. value={value ?? ""}
  192. className={className}
  193. type={type}
  194. id={id}
  195. inputProps={{
  196. step: step ? step : 1,
  197. }}
  198. InputProps={{
  199. endAdornment: (
  200. <>
  201. <IconButton size="small" onMouseDown={handleUpStepperMouseDown}>
  202. <ArrowDropUpIcon />
  203. </IconButton>
  204. <IconButton size="small" onMouseDown={handleDownStepperMouseDown}>
  205. <ArrowDropDownIcon />
  206. </IconButton>
  207. </>
  208. ),
  209. }}
  210. label={props.label}
  211. onChange={handleInput}
  212. disabled={!active}
  213. onKeyDown={handleAction}
  214. multiline={multiline}
  215. minRows={linesShown}
  216. />
  217. </Tooltip>
  218. );
  219. };
  220. export default Input;