-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathGroupAttributeValueField.tsx
102 lines (94 loc) · 2.96 KB
/
GroupAttributeValueField.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { Autocomplete, Box, TextField, Typography } from "@mui/material";
import { styled } from "@mui/material/styles";
import React, { FC } from "react";
import { Control, Controller } from "react-hook-form";
import { UseFormSetValue } from "react-hook-form/dist/types/form";
import { useAsyncWithThrow } from "../../../hooks/useAsyncWithThrow";
import { aironeApiClient } from "../../../repository/AironeApiClient";
import { Schema } from "./EntryFormSchema";
const StyledTypography = styled(Typography)(({}) => ({
color: "rgba(0, 0, 0, 0.6)",
}));
const StyledBox = styled(Box)(({}) => ({
display: "flex",
alignItems: "center",
}));
interface Props {
attrId: number;
control: Control<Schema>;
setValue: UseFormSetValue<Schema>;
multiple?: boolean;
isDisabled?: boolean;
}
export const GroupAttributeValueField: FC<Props> = ({
multiple,
attrId,
control,
setValue,
isDisabled = false,
}) => {
const groups = useAsyncWithThrow(async () => {
const _groups = await aironeApiClient.getGroups();
return _groups.results?.map((g) => ({ id: g.id, name: g.name }));
}, []);
const handleChange = (
value: { id: number; name: string } | { id: number; name: string }[] | null
) => {
if (multiple === true) {
if (value != null && !Array.isArray(value)) {
throw new Error("value must be an array");
}
setValue(`attrs.${attrId}.value.asArrayGroup`, value ?? [], {
shouldDirty: true,
shouldValidate: true,
});
} else {
if (value != null && Array.isArray(value)) {
throw new Error("value must not be an array");
}
setValue(`attrs.${attrId}.value.asGroup`, value, {
shouldDirty: true,
shouldValidate: true,
});
}
};
return (
<Box>
<StyledTypography variant="caption">グループを選択</StyledTypography>
<StyledBox>
<Controller
name={
multiple === true
? `attrs.${attrId}.value.asArrayGroup`
: `attrs.${attrId}.value.asGroup`
}
control={control}
render={({ field, fieldState: { error } }) => (
<Autocomplete
fullWidth
multiple={multiple}
loading={groups.loading}
options={groups.value ?? []}
value={field.value}
getOptionLabel={(option: { id: number; name: string }) =>
option.name
}
isOptionEqualToValue={(option, value) => option.id === value.id}
onChange={(_e, value) => handleChange(value)}
renderInput={(params) => (
<TextField
{...params}
error={error != null}
helperText={error?.message}
size="small"
placeholder={multiple ? "" : "-NOT SET-"}
/>
)}
disabled={isDisabled}
/>
)}
/>
</StyledBox>
</Box>
);
};