2021-10-10 20:13:10 +00:00
|
|
|
import { useField } from 'formik';
|
2021-09-13 05:50:12 +00:00
|
|
|
import React, { useEffect, useState } from 'react';
|
2021-10-10 20:13:10 +00:00
|
|
|
import { WithRelationships } from '@/api/admin';
|
2021-10-24 20:14:04 +00:00
|
|
|
import { Egg, searchEggs } from '@/api/admin/egg';
|
|
|
|
import Label from '@/components/elements/Label';
|
|
|
|
import Select from '@/components/elements/Select';
|
2021-09-13 05:50:12 +00:00
|
|
|
|
2021-10-10 20:13:10 +00:00
|
|
|
interface Props {
|
|
|
|
nestId?: number;
|
|
|
|
selectedEggId?: number;
|
|
|
|
onEggSelect: (egg: Egg | null) => void;
|
|
|
|
}
|
2021-09-16 20:59:22 +00:00
|
|
|
|
2021-10-10 20:13:10 +00:00
|
|
|
export default ({ nestId, selectedEggId, onEggSelect }: Props) => {
|
|
|
|
const [ , , { setValue, setTouched } ] = useField<Record<string, string | undefined>>('environment');
|
|
|
|
const [ eggs, setEggs ] = useState<WithRelationships<Egg, 'variables'>[] | null>(null);
|
2021-09-13 05:50:12 +00:00
|
|
|
|
2021-10-24 20:14:04 +00:00
|
|
|
const selectEgg = (egg: Egg | null) => {
|
|
|
|
if (egg === null) {
|
|
|
|
onEggSelect(null);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Clear values
|
|
|
|
setValue({});
|
|
|
|
setTouched(true);
|
|
|
|
|
|
|
|
onEggSelect(egg);
|
|
|
|
|
|
|
|
const values: Record<string, any> = {};
|
|
|
|
egg.relationships.variables?.forEach(v => { values[v.environmentVariable] = v.defaultValue; });
|
|
|
|
setValue(values);
|
|
|
|
setTouched(true);
|
|
|
|
};
|
|
|
|
|
2021-10-10 20:13:10 +00:00
|
|
|
useEffect(() => {
|
2021-10-24 20:14:04 +00:00
|
|
|
if (!nestId) {
|
|
|
|
setEggs(null);
|
|
|
|
return;
|
|
|
|
}
|
2021-09-16 20:59:22 +00:00
|
|
|
|
2021-10-24 20:14:04 +00:00
|
|
|
searchEggs(nestId, {})
|
|
|
|
.then(eggs => {
|
|
|
|
setEggs(eggs);
|
|
|
|
selectEgg(eggs[0] || null);
|
|
|
|
})
|
|
|
|
.catch(error => console.error(error));
|
2021-10-10 20:13:10 +00:00
|
|
|
}, [ nestId ]);
|
2021-09-16 20:59:22 +00:00
|
|
|
|
2021-10-10 20:13:10 +00:00
|
|
|
const onSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
2021-10-24 20:14:04 +00:00
|
|
|
selectEgg(eggs?.find(egg => egg.id.toString() === e.currentTarget.value) || null);
|
2021-10-10 20:13:10 +00:00
|
|
|
};
|
2021-09-13 05:50:12 +00:00
|
|
|
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
<Label>Egg</Label>
|
2021-10-10 20:13:10 +00:00
|
|
|
<Select id={'eggId'} name={'eggId'} defaultValue={selectedEggId} onChange={onSelectChange}>
|
|
|
|
{!eggs ?
|
|
|
|
<option disabled>Loading...</option>
|
|
|
|
:
|
|
|
|
eggs.map(v => (
|
|
|
|
<option key={v.id} value={v.id.toString()}>
|
|
|
|
{v.name}
|
|
|
|
</option>
|
|
|
|
))
|
|
|
|
}
|
2021-09-13 05:50:12 +00:00
|
|
|
</Select>
|
|
|
|
</>
|
|
|
|
);
|
|
|
|
};
|