All files / src/components/update_item UpdateItemForm.tsx

0% Statements 0/327
100% Branches 1/1
100% Functions 1/1
0% Lines 0/327

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import { Dispatch, FC, SetStateAction } from 'react';
import { IndividualItemResponse } from '../../models/individualItemResponse';
import { ErrorResponse } from '../../models/errorResponse';
import { updateItemSchema, UpdateItemSchemaType } from '../../validations/updateItem';
import { ErrorMessage } from '@hookform/error-message';
import { zodResolver } from '@hookform/resolvers/zod';
import { Controller, SubmitHandler, useFieldArray, useForm } from 'react-hook-form';
import { OkResponse } from '../../models/okResponse';
import { Pending } from '../../models/pending';
import { useFetchUpdateItem } from '../../hooks/useFetchUpdateItem';
import { AllSelectConnectorResponse } from '../../models/allConnectorsResponse';
import { AllSelectColorResponse } from '../../models/allColorsResponse';
import { ErrorResult, Loading } from '..';
import { useSelectConnector } from '../../hooks/useSelectConnector';
import { useSelectColor } from '../../hooks/useSelectColor';
import Select, { StylesConfig } from 'react-select';
import chroma from 'chroma-js';
import { SelectConnectorResponse } from '../../models/connectorResponse';
import { SelectColorResponse } from '../../models/colorResponse';
import styled from 'styled-components';
import ConnectorIcon from '/connector.svg';
import CableIcon from '/cable.svg';
 
type Props = {
  individualItem: IndividualItemResponse;
  setResult: Dispatch<SetStateAction<OkResponse | ErrorResponse | Pending | null>>;
};
 
// react-select
// connector select
const styleConnectorSelect: StylesConfig<SelectConnectorResponse> = {
  control: (styles, { isFocused }) => ({
    ...styles,
    backgroundColor: 'white',
    borderRadius: 0,
    height: 51,
    fontSize: '1.6rem',
    border: '1.5px solid #6f6f6f',
    margin: '20px 0 0 0',
    '&:hover': {
      border: '1.5px solid #6f6f6f',
    },
    ...(isFocused && {
      outline: '2.5px solid #c7d01c',
    }),
  }),
  option: (styles) => ({ ...styles }),
  input: (styles) => ({
    ...styles,
    fontSize: '1.6rem',
  }),
  placeholder: (styles) => ({
    ...styles,
    fontSize: '1.6rem',
  }),
  singleValue: (styles) => ({
    ...styles,
    fontSize: '1.6rem',
  }),
  indicatorSeparator: (styles) => ({
    ...styles,
    backgroundColor: '#6f6f6f',
  }),
  dropdownIndicator: (styles) => ({
    ...styles,
    color: '#6f6f6f',
  }),
};
 
// color select
const styleColorSelectDot = (color = 'transparent') => ({
  alignItems: 'center',
  display: 'flex',
  ':before': {
    backgroundColor: color,
    borderRadius: 10,
    content: '" "',
    display: 'block',
    marginRight: 8,
    height: 10,
    width: 10,
    border: '0.5px solid #6f6f6f',
  },
});
 
const styleColorSelect: StylesConfig<SelectColorResponse> = {
  control: (styles, { isFocused }) => ({
    ...styles,
    backgroundColor: 'white',
    borderRadius: 0,
    height: 51,
    fontSize: '1.6rem',
    border: '1.5px solid #6f6f6f',
    margin: '20px 0 0 0',
    '&:hover': {
      border: '1.5px solid #6f6f6f',
    },
    ...(isFocused && {
      outline: '2.5px solid #c7d01c',
    }),
  }),
  option: (styles, { data, isDisabled, isFocused, isSelected }) => {
    const color = chroma(data.hex_color_code);
    return {
      ...styles,
      fontSize: '1.6rem',
      backgroundColor: isDisabled
        ? undefined
        : isSelected
        ? color.css()
        : isFocused
        ? color.alpha(0.1).css()
        : undefined,
      color: isDisabled
        ? '#b3b3b3'
        : isSelected
        ? chroma.contrast(color, 'white') > 2
          ? 'white'
          : 'black'
        : data.hex_color_code,
      cursor: isDisabled ? 'not-allowed' : 'default',
      ':active': {
        ...styles[':active'],
        backgroundColor: !isDisabled ? (isSelected ? color.css() : color.alpha(0.3).css()) : undefined,
      },
    };
  },
  input: (styles) => ({
    ...styles,
    fontSize: '1.6rem',
    ...styleColorSelectDot(),
  }),
  placeholder: (styles) => ({
    ...styles,
    fontSize: '1.6rem',
    ...styleColorSelectDot('#b3b3b3'),
  }),
  singleValue: (styles, { data }) => {
    const color = chroma(data.hex_color_code);
    return {
      ...styles,
      fontSize: '1.6rem',
      ...styleColorSelectDot(color.css()),
    };
  },
  noOptionsMessage: (styles) => ({
    ...styles,
    fontSize: '1.6rem',
  }),
  indicatorSeparator: (styles) => ({
    ...styles,
    backgroundColor: '#6f6f6f',
  }),
  dropdownIndicator: (styles) => ({
    ...styles,
    color: '#6f6f6f',
  }),
};
 
// styled-components
const StyledBox = styled.div`
  margin: 60px auto 100px auto;
  padding: 0;
  width: 90%;
  max-width: 600px;
`;
 
const StyledInput = styled.input`
  width: 100%;
  max-width: 569px;
  font-size: 1.6rem;
  height: 48px;
  margin: 0;
  padding: 0 14px;
  border: 1.5px solid #6f6f6f;
  border-radius: 0;
  &:focus {
    outline: 2.5px solid #c7d01c;
  }
`;
 
const StyledLabel = styled.label`
  display: block;
  font-size: 1.6rem;
  margin: 20px 0 5px 0;
  padding: 0;
`;
 
const StyledAddWrapper = styled.div`
  display: flex;
  justify-content: center;
  width: 100%;
  margin: 50px 0 10px 0;
`;
 
const StyledAddInput = styled.input`
  padding: 5px 20px;
  background-color: #caad63;
  border: none;
  font-size: 1.6rem;
  cursor: pointer;
  width: 200px;
`;
 
const StyledSubmitWrapper = styled.div`
  display: flex;
  justify-content: center;
  width: 100%;
  margin: 50px 0 10px 0;
`;
 
const StyledSubmitInput = styled.input`
  padding: 5px 20px;
  background-color: #caad63;
  border: none;
  font-size: 2rem;
  cursor: pointer;
`;
 
const StyledToggleLabelWrapper = styled.div`
  display: flex;
  justify-content: center;
  width: 100%;
  margin: 25px 0 0 0;
  padding: 0;
`;
 
const StyledDeleteInput = styled.input`
  width: 40px;
  height: 40px;
  font-size: 20px;
  color: #6f6f6f;
  background-color: #f6f6f6;
  border: 1px solid #6f6f6f;
  display: block;
  margin: 10px auto 0 auto;
  cursor: pointer;
`;
 
const StyledToggleLabel = styled.label`
  display: inline-block;
  position: relative;
  width: 80px;
  height: 35px;
  border-radius: 50px;
  background-color: #f6f6f6;
  border: 1px solid #b3b3b3;
  cursor: pointer;
  transition: background-color 0.4s;
  &:has(:checked) {
    background-color: #c7d01c;
  }
  &::after {
    position: absolute;
    top: 2px;
    left: 2px;
    width: 31px;
    height: 31px;
    border-radius: 50%;
    box-shadow: 0 0 5px rgb(0 0 0 / 20%);
    background-color: #ffffff;
    content: '';
    transition: left 0.4s;
  }
  &:has(:checked)::after {
    left: 46.5px;
  }
`;
 
const StyledToggleInput = styled.input`
  display: none;
`;
 
const StyledIconBox = styled.div`
  display: flex;
  justify-content: center;
  width: 100%;
  margin: 0;
  padding: 0;
`;
 
const StyledIconWrapper = styled.div`
  width: fit-content;
`;
 
const UpdateItemForm: FC<Props> = (props) => {
  const connectors: ErrorResponse | Pending | AllSelectConnectorResponse = useSelectConnector();
  const colors: ErrorResponse | Pending | AllSelectColorResponse = useSelectColor();
  const {
    register,
    handleSubmit,
    formState: { errors },
    control,
  } = useForm<UpdateItemSchemaType>({
    resolver: zodResolver(updateItemSchema),
    defaultValues: {
      name: props.individualItem === null ? '' : props.individualItem.name,
      visible_id: props.individualItem === null ? '' : props.individualItem.visible_id,
      product_number: props.individualItem === null ? '' : props.individualItem.product_number,
      description: props.individualItem === null ? '' : props.individualItem.description,
      purchase_year: props.individualItem === null ? null : props.individualItem.purchase_year,
      purchase_price: props.individualItem === null ? null : props.individualItem.purchase_price,
      durability: props.individualItem === null ? null : props.individualItem.durability,
      is_depreciation: props.individualItem === null ? false : props.individualItem.is_depreciation,
      connector:
        props.individualItem === null ? [] : props.individualItem.connector.map((connector: string) => ({ connector })),
      color:
        props.individualItem === null ? [] : props.individualItem.color.split('^').map((color: string) => ({ color })),
    },
  });
 
  const onSubmit: SubmitHandler<UpdateItemSchemaType> = async (formData) => {
    props.setResult('pending');
    const result: ErrorResponse | OkResponse = await useFetchUpdateItem(formData, props.individualItem.id);
    props.setResult(result);
  };
 
  const connectorArray = useFieldArray({
    name: 'connector',
    control,
  });
  const colorArray = useFieldArray({
    name: 'color',
    control,
  });
  return (
    <StyledBox>
      <form onSubmit={handleSubmit(onSubmit)}>
        <StyledLabel htmlFor="name">物品名</StyledLabel>
        <StyledInput id="name" type="text" {...register('name')} />
        <br />
        <ErrorMessage errors={errors} name="name" message={errors.name?.message} />
        <br />
        <StyledLabel htmlFor="visible_id">ラベルID</StyledLabel>
        <StyledInput id="visible_id" type="text" {...register('visible_id')} />
        <br />
        <ErrorMessage errors={errors} name="visible_id" message={errors.visible_id?.message} />
        <br />
        <StyledLabel htmlFor="product_number">型番</StyledLabel>
        <StyledInput id="product_number" type="text" {...register('product_number')} />
        <br />
        <ErrorMessage errors={errors} name="product_number" message={errors.product_number?.message} />
        <br />
        <StyledLabel htmlFor="description">備考</StyledLabel>
        <StyledInput id="description" type="text" {...register('description')} />
        <br />
        <ErrorMessage errors={errors} name="description" message={errors.description?.message} />
        <br />
        <StyledLabel htmlFor="purchase_year">購入年度</StyledLabel>
        <StyledInput id="purchase_year" type="number" {...register('purchase_year', { valueAsNumber: true })} />
        <br />
        <ErrorMessage errors={errors} name="purchase_year" message={errors.purchase_year?.message} />
        <br />
        <StyledLabel htmlFor="purchase_price">購入金額</StyledLabel>
        <StyledInput id="purchase_price" type="number" {...register('purchase_price', { valueAsNumber: true })} />
        <br />
        <ErrorMessage errors={errors} name="purchase_price" message={errors.purchase_price?.message} />
        <br />
        <StyledLabel htmlFor="durability">耐久年数</StyledLabel>
        <StyledInput id="durability" type="number" {...register('durability', { valueAsNumber: true })} />
        <br />
        <ErrorMessage errors={errors} name="durability" message={errors.durability?.message} />
        <br />
        <StyledLabel htmlFor="is_depreciation">減価償却対象かどうか</StyledLabel>
        <StyledToggleLabelWrapper>
          <StyledToggleLabel>
            <StyledToggleInput id="is_depreciation" type="checkbox" {...register('is_depreciation')} />
          </StyledToggleLabel>
        </StyledToggleLabelWrapper>
        <br />
        <ErrorMessage errors={errors} name="is_depreciation" message={errors.is_depreciation?.message} />
        <br />
        <StyledLabel htmlFor="connector">接続名</StyledLabel>
        {connectors === 'pending' ? (
          <Loading />
        ) : 'code' in connectors && 'message' in connectors ? (
          <ErrorResult result={connectors} />
        ) : (
          // connector field
          <>
            {connectorArray.fields.map((field, index: number) => (
              <div key={field.id}>
                <Controller
                  name={`connector.${index}.connector`}
                  control={control}
                  render={({ field }) => (
                    <Select
                      styles={styleConnectorSelect}
                      options={connectors.all_connectors}
                      isSearchable={true}
                      noOptionsMessage={() => '存在しない端子名です。'}
                      isOptionDisabled={(option) => option.status === 'Archive'}
                      value={connectors.all_connectors.find((element) => element.label === field.value)}
                      getOptionLabel={(option) =>
                        option.label + (option.status === 'Archive' ? ' (非推奨の端子名です)' : '')
                      }
                      onChange={(newValue) => field.onChange((newValue as SelectColorResponse)?.value)}
                    />
                  )}
                />
                {index >= 0 && (
                  <StyledDeleteInput type="submit" value="✕" onClick={() => connectorArray.remove(index)} />
                )}
              </div>
            ))}
            <br />
            <ErrorMessage errors={errors} name="connector" message={errors.connector?.message} />
            <br />
            <StyledAddWrapper>
              <StyledAddInput
                type="button"
                value="端子名の追加"
                onClick={() => connectorArray.append({ connector: connectors.all_connectors[0].label })}
              />
            </StyledAddWrapper>
          </>
        )}
        {colors === 'pending' ? (
          <Loading />
        ) : 'code' in colors && 'message' in colors ? (
          <ErrorResult result={colors} />
        ) : (
          // color field
          <>
            <StyledLabel htmlFor="color">ケーブル識別色のパターン</StyledLabel>
            <StyledIconBox>
              <StyledIconWrapper>
                <img src={ConnectorIcon} alt="menu" width={70} height={215.767} />
              </StyledIconWrapper>
            </StyledIconBox>
            {colorArray.fields.map((field, index: number) => (
              <div key={field.id}>
                <Controller
                  name={`color.${index}.color`}
                  control={control}
                  render={({ field }) => (
                    <Select
                      styles={styleColorSelect}
                      options={colors.all_colors}
                      isSearchable={true}
                      noOptionsMessage={() => '存在しない色です。'}
                      isOptionDisabled={(option) => option.status === 'Archive'}
                      value={colors.all_colors.find((element) => element.label === field.value)}
                      getOptionLabel={(option) =>
                        option.label + (option.status === 'Archive' ? ' (非推奨の色です)' : '')
                      }
                      onChange={(newValue) => field.onChange((newValue as SelectColorResponse)?.value)}
                    />
                  )}
                />
                {index >= 0 && <StyledDeleteInput type="submit" value="✕" onClick={() => colorArray.remove(index)} />}
              </div>
            ))}
            <br />
            <ErrorMessage errors={errors} name="color" message={errors.color?.message} />
            <br />
            <StyledIconBox>
              <StyledIconWrapper>
                <img src={CableIcon} alt="menu" width={32} height={81.6334} />
              </StyledIconWrapper>
            </StyledIconBox>
            <StyledAddWrapper>
              <StyledAddInput
                type="button"
                value="ケーブル識別色の追加"
                onClick={() => colorArray.append({ color: colors.all_colors[0].label })}
              />
            </StyledAddWrapper>
          </>
        )}
        <br />
        <StyledSubmitWrapper>
          <StyledSubmitInput type="submit" value="物品情報の更新" />
        </StyledSubmitWrapper>
      </form>
    </StyledBox>
  );
};
 
export default UpdateItemForm;