KeyValueArray.tsx 13 KB

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