All files / src/components/PageForm index.tsx

100% Statements 16/16
86.66% Branches 13/15
100% Functions 2/2
100% Lines 16/16

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                                                    18x 18x 18x 18x 18x   18x 7x 1x   6x 6x 6x 6x   2x   6x 6x       18x                                                  
import React, { CSSProperties, type JSX, useRef, useState } from 'react';
 
import { Box, useTheme } from '@mui/material';
 
import useDeviceInfo from '../../utils/useDeviceInfo';
import BusySpinner from '../BusySpinner';
import FormBottomBar, { FormButton } from '../FormBottomBar';
 
export type PageFormProps = {
  children: React.ReactNode;
  cancelID: string;
  saveID: string;
  onCancel: () => void;
  onSave: () => void | Promise<unknown>;
  cancelButtonText: string;
  saveButtonText: string;
  saveDisabled?: boolean;
  cancelDisabled?: boolean;
  className?: string;
  hideEdit?: boolean;
  additionalRightButtons?: FormButton[];
  style?: CSSProperties;
  desktopOffset?: string;
};
 
export default function PageForm(props: PageFormProps): JSX.Element {
  const { children, className, hideEdit, onSave, style, ...bottomBarProps } = props;
  const theme = useTheme();
  const { isMobile } = useDeviceInfo();
  const [processing, setProcessing] = useState(false);
  const processingRef = useRef(false);
 
  const handleSave = async () => {
    if (processingRef.current) {
      return;
    }
    processingRef.current = true;
    setProcessing(true);
    try {
      await onSave();
    } catch (error) {
      console.error(error);
    } finally {
      processingRef.current = false;
      setProcessing(false);
    }
  };
 
  return (
    <>
      {processing && <BusySpinner withSkrim={true} />}
      <Box
        className={className}
        paddingBottom={hideEdit ? theme.spacing(4) : theme.spacing(isMobile ? 25 : 15)}
        style={style}
      >
        {children}
      </Box>
      {!hideEdit && (
        <FormBottomBar
          {...bottomBarProps}
          onSave={() => void handleSave()}
          saveDisabled={processing || bottomBarProps.saveDisabled}
          cancelDisabled={processing || bottomBarProps.cancelDisabled}
          additionalRightButtons={bottomBarProps.additionalRightButtons?.map((button) => ({
            ...button,
            disabled: processing || button.disabled,
          }))}
        />
      )}
    </>
  );
}