-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patharray-input.tsx
78 lines (73 loc) · 2.4 KB
/
array-input.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import React from 'react';
import { List, ListItem } from '@chakra-ui/react';
import {
SchemaFieldArray,
schemaToFormDataStructure,
WidgetProps
} from '@stac-manager/data-core';
import { FieldArray, useFormikContext } from 'formik';
import { get } from 'lodash-es';
import { getArrayLabel } from '../utils';
import { ArrayFieldset } from '../components/elements';
import { WidgetInput } from './input';
export function WidgetArrayInput(props: WidgetProps) {
const { pointer, isRequired } = props;
const field = props.field as SchemaFieldArray;
const { values } = useFormikContext();
const fields: any[] = get(values, pointer) || [];
const minItems = field.minItems || 0;
const maxItems = field.maxItems || Infinity;
const isFixed = minItems === maxItems;
return (
<FieldArray
name={pointer}
render={({ remove, push }) => (
<ArrayFieldset
isRequired={isRequired}
label={field.label}
onAdd={
isFixed
? undefined
: () => {
push(schemaToFormDataStructure(field.items));
}
}
addDisabled={fields.length >= maxItems}
>
{fields.length ? (
<List display='flex' gap={4} flexDir={isFixed ? 'row' : 'column'}>
{fields.map((_, index) => (
<ListItem
key={index /* eslint-disable-line react/no-array-index-key */}
display='flex'
width='100%'
>
<WidgetInput
pointer={`${pointer}.${index}`}
type={field.items.type}
field={field.items}
label={getArrayLabel(field.items, index)?.formatted}
isDeletable={!isFixed}
onDeleteClick={() => {
remove(index);
}}
transformValue={(v) => {
if (field.items.type === 'number') {
const n = Number(v);
return isNaN(n) ? null : n;
}
return v;
}}
isDeleteDisabled={fields.length <= minItems}
/>
</ListItem>
))}
</List>
) : (
<p>No items</p>
)}
</ArrayFieldset>
)}
/>
);
}