2021-09-13 05:50:12 +00:00
|
|
|
import Label from '@/components/elements/Label';
|
|
|
|
import Select from '@/components/elements/Select';
|
2021-09-16 20:59:22 +00:00
|
|
|
import { useFormikContext } from 'formik';
|
2021-09-13 05:50:12 +00:00
|
|
|
import React, { useEffect, useState } from 'react';
|
|
|
|
import { Egg } from '@/api/admin/eggs/getEgg';
|
|
|
|
import searchEggs from '@/api/admin/nests/searchEggs';
|
|
|
|
|
2021-09-16 03:19:39 +00:00
|
|
|
export default ({ nestId, egg, setEgg }: { nestId: number | null; egg: Egg | null, setEgg: (value: Egg | null) => void }) => {
|
2021-09-16 20:59:22 +00:00
|
|
|
const { setFieldValue } = useFormikContext();
|
|
|
|
|
2021-09-13 05:50:12 +00:00
|
|
|
const [ eggs, setEggs ] = useState<Egg[]>([]);
|
|
|
|
|
2021-09-16 20:59:22 +00:00
|
|
|
/**
|
|
|
|
* So you may be asking yourself, "what cluster-fuck of code is this?"
|
|
|
|
*
|
|
|
|
* Well, this code makes sure that when the egg changes, that the environment
|
|
|
|
* object has empty string values instead of undefined so React doesn't think
|
|
|
|
* the variable fields are uncontrolled.
|
|
|
|
*/
|
|
|
|
const setEgg2 = (newEgg: Egg | null) => {
|
|
|
|
if (newEgg === null) {
|
|
|
|
setEgg(null);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reset all variables to be empty, don't inherit the previous values.
|
|
|
|
const newVariables = newEgg?.relations.variables;
|
|
|
|
newVariables?.forEach(v => setFieldValue('environment.' + v.envVariable, ''));
|
|
|
|
const variables = egg?.relations.variables?.filter(v => newVariables?.find(v2 => v2.envVariable === v.envVariable) === undefined);
|
|
|
|
|
|
|
|
setEgg(newEgg);
|
|
|
|
|
|
|
|
// Clear any variables that don't exist on the new egg.
|
|
|
|
variables?.forEach(v => setFieldValue('environment.' + v.envVariable, undefined));
|
|
|
|
};
|
|
|
|
|
2021-09-13 05:50:12 +00:00
|
|
|
useEffect(() => {
|
|
|
|
if (nestId === null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-16 03:19:39 +00:00
|
|
|
searchEggs(nestId, {}, [ 'variables' ])
|
|
|
|
.then(eggs => {
|
|
|
|
setEggs(eggs);
|
|
|
|
if (eggs.length < 1) {
|
2021-09-16 20:59:22 +00:00
|
|
|
setEgg2(null);
|
2021-09-16 03:19:39 +00:00
|
|
|
return;
|
|
|
|
}
|
2021-09-16 20:59:22 +00:00
|
|
|
setEgg2(eggs[0]);
|
2021-09-16 03:19:39 +00:00
|
|
|
})
|
2021-09-13 05:50:12 +00:00
|
|
|
.catch(error => console.error(error));
|
|
|
|
}, [ nestId ]);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
<Label>Egg</Label>
|
2021-09-16 03:19:39 +00:00
|
|
|
<Select
|
|
|
|
defaultValue={egg?.id || undefined}
|
|
|
|
id={'eggId'}
|
|
|
|
name={'eggId'}
|
2021-09-16 20:59:22 +00:00
|
|
|
onChange={e => setEgg2(eggs.find(egg => egg.id.toString() === e.currentTarget.value) || null)}
|
2021-09-16 03:19:39 +00:00
|
|
|
>
|
2021-09-13 05:50:12 +00:00
|
|
|
{eggs.map(v => (
|
|
|
|
<option key={v.id} value={v.id.toString()}>
|
|
|
|
{v.name}
|
|
|
|
</option>
|
|
|
|
))}
|
|
|
|
</Select>
|
|
|
|
</>
|
|
|
|
);
|
|
|
|
};
|