KeyValueArray.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. import React from "react";
  2. import {
  3. GetFinalVariablesFunction,
  4. KeyValueArrayField,
  5. KeyValueArrayFieldState,
  6. } from "../types";
  7. import sliders from "../../../assets/sliders.svg";
  8. import upload from "../../../assets/upload.svg";
  9. import styled from "styled-components";
  10. import useFormField from "../hooks/useFormField";
  11. import Modal from "../../../main/home/modals/Modal";
  12. import LoadEnvGroupModal from "../../../main/home/modals/LoadEnvGroupModal";
  13. import EnvEditorModal from "../../../main/home/modals/EnvEditorModal";
  14. interface Props extends KeyValueArrayField {
  15. id: string;
  16. }
  17. const KeyValueArray: React.FC<Props> = (props) => {
  18. const { state, setState, variables } = useFormField<KeyValueArrayFieldState>(
  19. props.id,
  20. {
  21. initState: {
  22. values:
  23. props.value && props.value[0]
  24. ? (Object.entries(props.value[0])?.map(([k, v]) => {
  25. return { key: k, value: v };
  26. }) as any[])
  27. : [],
  28. showEnvModal: false,
  29. showEditorModal: false,
  30. },
  31. }
  32. );
  33. if (state == undefined) return <></>;
  34. const parseEnv = (src: any, options: any) => {
  35. const debug = Boolean(options && options.debug);
  36. const obj = {} as Record<string, string>;
  37. const NEWLINE = "\n";
  38. const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/;
  39. const RE_NEWLINES = /\\n/g;
  40. const NEWLINES_MATCH = /\n|\r|\r\n/;
  41. // convert Buffers before splitting into lines and processing
  42. src
  43. .toString()
  44. .split(NEWLINES_MATCH)
  45. .forEach(function (line: any, idx: any) {
  46. // matching "KEY' and 'VAL' in 'KEY=VAL'
  47. const keyValueArr = line.match(RE_INI_KEY_VAL);
  48. // matched?
  49. if (keyValueArr != null) {
  50. const key = keyValueArr[1];
  51. // default undefined or missing values to empty string
  52. let val = keyValueArr[2] || "";
  53. const end = val.length - 1;
  54. const isDoubleQuoted = val[0] === '"' && val[end] === '"';
  55. const isSingleQuoted = val[0] === "'" && val[end] === "'";
  56. // if single or double quoted, remove quotes
  57. if (isSingleQuoted || isDoubleQuoted) {
  58. val = val.substring(1, end);
  59. // if double quoted, expand newlines
  60. if (isDoubleQuoted) {
  61. val = val.replace(RE_NEWLINES, NEWLINE);
  62. }
  63. } else {
  64. // remove surrounding whitespace
  65. val = val.trim();
  66. }
  67. obj[key] = val;
  68. } else if (debug) {
  69. console.log(
  70. `did not match key and value when parsing line ${idx + 1}: ${line}`
  71. );
  72. }
  73. });
  74. return obj;
  75. };
  76. const readFile = (env: string) => {
  77. let envObj = parseEnv(env, null);
  78. let push = true;
  79. for (let key in envObj) {
  80. for (var i = 0; i < state.values.length; i++) {
  81. let existingKey = state.values[i]["key"];
  82. if (key === existingKey) {
  83. state.values[i]["value"] = envObj[key];
  84. push = false;
  85. }
  86. }
  87. if (push) {
  88. setState((prev) => {
  89. return {
  90. values: [...prev.values, { key, value: envObj[key] }],
  91. };
  92. });
  93. }
  94. }
  95. };
  96. const renderEditorModal = () => {
  97. if (state.showEditorModal) {
  98. return (
  99. <Modal
  100. onRequestClose={() =>
  101. setState(() => {
  102. return { showEditorModal: false };
  103. })
  104. }
  105. width="60%"
  106. height="80%"
  107. >
  108. <EnvEditorModal
  109. closeModal={() =>
  110. setState(() => {
  111. return { showEditorModal: false };
  112. })
  113. }
  114. setEnvVariables={(envFile: string) => readFile(envFile)}
  115. />
  116. </Modal>
  117. );
  118. }
  119. };
  120. const getProcessedValues = (
  121. objectArray: { key: string; value: string }[]
  122. ): any => {
  123. let obj = {} as any;
  124. objectArray?.forEach(({ key, value }) => {
  125. obj[key] = value;
  126. });
  127. return obj;
  128. };
  129. const renderEnvModal = () => {
  130. if (state.showEnvModal) {
  131. return (
  132. <Modal
  133. onRequestClose={() =>
  134. setState(() => {
  135. return { showEnvModal: false };
  136. })
  137. }
  138. width="765px"
  139. height="542px"
  140. >
  141. <LoadEnvGroupModal
  142. existingValues={getProcessedValues(state.values)}
  143. namespace={variables.namespace}
  144. clusterId={variables.clusterId}
  145. closeModal={() =>
  146. setState(() => {
  147. return {
  148. showEnvModal: false,
  149. };
  150. })
  151. }
  152. setValues={(values) => {
  153. setState((prev) => {
  154. return {
  155. // might be broken
  156. values: [
  157. ...prev.values,
  158. ...Object.entries(values)?.map(([k, v]) => {
  159. return {
  160. key: k,
  161. value: v,
  162. };
  163. }),
  164. ],
  165. };
  166. });
  167. }}
  168. />
  169. </Modal>
  170. );
  171. }
  172. };
  173. const renderDeleteButton = (i: number) => {
  174. if (!props.isReadOnly) {
  175. return (
  176. <DeleteButton
  177. onClick={() => {
  178. state.values.splice(i, 1);
  179. setState((prev) => {
  180. return {
  181. values: prev.values
  182. .slice(0, i + 1)
  183. .concat(prev.values.slice(i + 1, prev.values.length)),
  184. };
  185. });
  186. }}
  187. >
  188. <i className="material-icons">cancel</i>
  189. </DeleteButton>
  190. );
  191. }
  192. };
  193. const renderHiddenOption = (hidden: boolean, i: number) => {
  194. if (props.secretOption && hidden) {
  195. return (
  196. <HideButton>
  197. <i className="material-icons">lock</i>
  198. </HideButton>
  199. );
  200. }
  201. };
  202. const renderInputList = () => {
  203. return (
  204. <>
  205. {state.values?.map((entry: any, i: number) => {
  206. // Preprocess non-string env values set via raw Helm values
  207. let { value } = entry;
  208. if (typeof value === "object") {
  209. value = JSON.stringify(value);
  210. } else if (typeof value === "number" || typeof value === "boolean") {
  211. value = value.toString();
  212. }
  213. return (
  214. <InputWrapper key={i}>
  215. <Input
  216. placeholder="ex: key"
  217. width="270px"
  218. value={entry.key}
  219. onChange={(e: any) => {
  220. e.persist();
  221. setState((prev) => {
  222. return {
  223. values: prev.values?.map((t, j) => {
  224. if (j == i) {
  225. return {
  226. ...t,
  227. key: e.target.value,
  228. };
  229. }
  230. return t;
  231. }),
  232. };
  233. });
  234. }}
  235. disabled={props.isReadOnly || value.includes("PORTERSECRET")}
  236. spellCheck={false}
  237. />
  238. <Spacer />
  239. <Input
  240. placeholder="ex: value"
  241. width="270px"
  242. value={value}
  243. onChange={(e: any) => {
  244. e.persist();
  245. setState((prev) => {
  246. return {
  247. values: prev.values?.map((t, j) => {
  248. if (j == i) {
  249. return {
  250. ...t,
  251. value: e.target.value,
  252. };
  253. }
  254. return t;
  255. }),
  256. };
  257. });
  258. }}
  259. disabled={props.isReadOnly || value.includes("PORTERSECRET")}
  260. type={value.includes("PORTERSECRET") ? "password" : "text"}
  261. spellCheck={false}
  262. />
  263. {renderDeleteButton(i)}
  264. {renderHiddenOption(value.includes("PORTERSECRET"), i)}
  265. </InputWrapper>
  266. );
  267. })}
  268. </>
  269. );
  270. };
  271. return (
  272. <>
  273. <StyledInputArray>
  274. <Label>{props.label}</Label>
  275. {state.values.length === 0 ? <></> : renderInputList()}
  276. {props.isReadOnly ? (
  277. <></>
  278. ) : (
  279. <InputWrapper>
  280. <AddRowButton
  281. onClick={() => {
  282. setState((prev) => {
  283. return {
  284. values: [...prev.values, { key: "", value: "" }],
  285. };
  286. });
  287. }}
  288. >
  289. <i className="material-icons">add</i> Add Row
  290. </AddRowButton>
  291. <Spacer />
  292. {variables.namespace && props.envLoader && (
  293. <LoadButton
  294. onClick={() =>
  295. setState((prev) => {
  296. return {
  297. showEnvModal: !prev.showEnvModal,
  298. };
  299. })
  300. }
  301. >
  302. <img src={sliders} /> Load from Env Group
  303. </LoadButton>
  304. )}
  305. {props.fileUpload && (
  306. <UploadButton
  307. onClick={() => {
  308. setState((prev) => {
  309. return {
  310. showEditorModal: true,
  311. };
  312. });
  313. }}
  314. >
  315. <img src={upload} /> Copy from File
  316. </UploadButton>
  317. )}
  318. </InputWrapper>
  319. )}
  320. </StyledInputArray>
  321. {renderEnvModal()}
  322. {renderEditorModal()}
  323. </>
  324. );
  325. };
  326. export const getFinalVariablesForKeyValueArray: GetFinalVariablesFunction = (
  327. vars,
  328. props: KeyValueArrayField,
  329. state: KeyValueArrayFieldState
  330. ) => {
  331. console.log(vars);
  332. console.log(props);
  333. console.log(state);
  334. if (!state) {
  335. return {
  336. [props.variable]: props.value ? props.value[0] : [],
  337. };
  338. }
  339. let obj = {} as any;
  340. const rg = /(?:^|[^\\])(\\n)/g;
  341. const fixNewlines = (s: string) => {
  342. while (rg.test(s)) {
  343. s = s.replace(rg, (str) => {
  344. if (str.length == 2) return "\n";
  345. if (str[0] != "\\") return str[0] + "\n";
  346. return "\\n";
  347. });
  348. }
  349. return s;
  350. };
  351. const isNumber = (s: string) => {
  352. return !isNaN(!s ? NaN : Number(String(s).trim()));
  353. };
  354. state.values.forEach((entry: any, i: number) => {
  355. if (isNumber(entry.value)) {
  356. obj[entry.key] = entry.value;
  357. } else {
  358. obj[entry.key] = fixNewlines(entry.value);
  359. }
  360. });
  361. return {
  362. [props.variable]: obj,
  363. };
  364. };
  365. export default KeyValueArray;
  366. const Spacer = styled.div`
  367. width: 10px;
  368. height: 20px;
  369. `;
  370. const AddRowButton = styled.div`
  371. display: flex;
  372. align-items: center;
  373. width: 270px;
  374. font-size: 13px;
  375. color: #aaaabb;
  376. height: 32px;
  377. border-radius: 3px;
  378. cursor: pointer;
  379. background: #ffffff11;
  380. :hover {
  381. background: #ffffff22;
  382. }
  383. > i {
  384. color: #ffffff44;
  385. font-size: 16px;
  386. margin-left: 8px;
  387. margin-right: 10px;
  388. display: flex;
  389. align-items: center;
  390. justify-content: center;
  391. }
  392. `;
  393. const LoadButton = styled(AddRowButton)`
  394. background: none;
  395. border: 1px solid #ffffff55;
  396. > i {
  397. color: #ffffff44;
  398. font-size: 16px;
  399. margin-left: 8px;
  400. margin-right: 10px;
  401. display: flex;
  402. align-items: center;
  403. justify-content: center;
  404. }
  405. > img {
  406. width: 14px;
  407. margin-left: 10px;
  408. margin-right: 12px;
  409. }
  410. `;
  411. const UploadButton = styled(AddRowButton)`
  412. background: none;
  413. position: relative;
  414. margin-left: 10px;
  415. border: 1px solid #ffffff55;
  416. > i {
  417. color: #ffffff44;
  418. font-size: 16px;
  419. margin-left: 8px;
  420. margin-right: 10px;
  421. display: flex;
  422. align-items: center;
  423. justify-content: center;
  424. }
  425. > img {
  426. width: 14px;
  427. margin-left: 10px;
  428. margin-right: 12px;
  429. }
  430. `;
  431. const DeleteButton = styled.div`
  432. width: 15px;
  433. height: 15px;
  434. display: flex;
  435. align-items: center;
  436. margin-left: 8px;
  437. margin-top: -3px;
  438. justify-content: center;
  439. > i {
  440. font-size: 17px;
  441. color: #ffffff44;
  442. display: flex;
  443. align-items: center;
  444. justify-content: center;
  445. cursor: pointer;
  446. :hover {
  447. color: #ffffff88;
  448. }
  449. }
  450. `;
  451. const HideButton = styled(DeleteButton)`
  452. margin-top: -5px;
  453. > i {
  454. font-size: 19px;
  455. cursor: default;
  456. :hover {
  457. color: #ffffff44;
  458. }
  459. }
  460. `;
  461. const InputWrapper = styled.div`
  462. display: flex;
  463. align-items: center;
  464. margin-top: 5px;
  465. `;
  466. const Input = styled.input`
  467. outline: none;
  468. border: none;
  469. margin-bottom: 5px;
  470. font-size: 13px;
  471. background: #ffffff11;
  472. border: 1px solid #ffffff55;
  473. border-radius: 3px;
  474. width: ${(props: { disabled?: boolean; width: string }) =>
  475. props.width ? props.width : "270px"};
  476. color: ${(props: { disabled?: boolean; width: string }) =>
  477. props.disabled ? "#ffffff44" : "white"};
  478. padding: 5px 10px;
  479. height: 35px;
  480. `;
  481. const Label = styled.div`
  482. color: #ffffff;
  483. margin-bottom: 10px;
  484. `;
  485. const StyledInputArray = styled.div`
  486. margin-bottom: 15px;
  487. margin-top: 22px;
  488. `;