Raw
1 import React from "react"
2 import { InputText } from "../../../../components/Input/Text"
3 import setObjValue from "../../../../utils/set-obj-value"
4 import { ApiRunnerParamObjectInput } from "../Object"
5 import { ApiRunnerParamArrayInput } from "../Array"
6
7 export type ApiRunnerParamInputProps = {
8 paramName: string
9 paramValue: unknown
10 objPath: string
11 setValue: React.Dispatch<React.SetStateAction<unknown>>
12 }
13
14 export const ApiRunnerParamInput = ({
15 paramName,
16 paramValue,
17 objPath,
18 setValue,
19 }: ApiRunnerParamInputProps) => {
20 if (Array.isArray(paramValue)) {
21 return (
22 <ApiRunnerParamArrayInput
23 paramName={paramName}
24 paramValue={paramValue}
25 objPath={objPath}
26 setValue={setValue}
27 />
28 )
29 }
30 if (typeof paramValue === "object") {
31 return (
32 <ApiRunnerParamObjectInput
33 paramName={paramName}
34 paramValue={paramValue}
35 objPath={objPath}
36 setValue={setValue}
37 />
38 )
39 }
40
41 return (
42 <InputText
43 name={paramName}
44 onChange={(e) => {
45 setValue((prev: unknown) => {
46 if (Array.isArray(prev)) {
47 // try to get index from param name
48 const splitPath = objPath.split(".")
49 // if param is in an object in the array, the index is
50 // the last item of the `objPath`. Otherwise, it's in the param name
51 const index = (
52 objPath.length > 0 ? splitPath[splitPath.length - 1] : paramName
53 )
54 .replace("[", "")
55 .replace("]", "")
56 const intIndex = parseInt(index)
57
58 // if we can't get the index from the param name or obj path
59 // just insert the value to the end of the array.
60 if (Number.isNaN(intIndex)) {
61 return [...prev, e.target.value]
62 }
63
64 // if the param is within an object, the value to be set
65 // is the updated value of the object. Otherwise, it's just the
66 // value of the item.
67 const transformedValue =
68 prev.length > 0 && typeof prev[0] === "object"
69 ? setObjValue({
70 obj: { ...prev[intIndex] },
71 value: e.target.value,
72 path: paramName,
73 })
74 : e.target.value
75
76 return [
77 ...prev.slice(0, intIndex),
78 transformedValue,
79 ...prev.slice(intIndex + 1),
80 ]
81 }
82
83 return typeof prev === "object"
84 ? setObjValue({
85 obj: { ...prev },
86 value: e.target.value,
87 path: `${objPath.length ? `${objPath}.` : ""}${paramName}`,
88 })
89 : e.target.value
90 })
91 }}
92 placeholder={paramName}
93 value={
94 typeof paramValue === "string"
95 ? (paramValue as string)
96 : typeof paramValue === "number"
97 ? (paramValue as number)
98 : `${paramValue}`
99 }
100 className="w-full"
101 />
102 )
103 }