Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

5.7 KB
Raw Blame
import cx from "classnames";
import { useFormik } from "formik";
import { useCallback, useEffect } from "react";
import { t } from "ttag";

import { LeaveConfirmModal } from "metabase/common/components/LeaveConfirmModal";
import Animation from "metabase/css/core/animation.module.css";
import { Box, Button, Center, Flex, Loader, Modal } from "metabase/ui";
import type { RowValue } from "metabase-types/api";

import type {
  DescribeActionFormResponse,
  RowCellsWithPkValue,
  TableActionFormParameter,
} from "../../api/types";

import { ModalParameterActionInput } from "./ModalParameterActionInput";
import S from "./TableActionFormModal.module.css";
import { TableActionFormModalParameter } from "./TableActionFormModalParameter";
import { useActionFormUnsavedLeaveConfirmation } from "./use-action-form-unsaved-leave-confirmation";

interface UpdateRowActionFormModalProps {
  opened: boolean;
  description?: DescribeActionFormResponse;
  isLoading: boolean;
  isDeleting: boolean;
  initialValues?: RowCellsWithPkValue;
  onClose: () => void;
  onSubmit: (data: RowCellsWithPkValue) => Promise<boolean>;
  onDelete: () => Promise<boolean>;
}

export function UpdateRowActionFormModal({
  opened,
  description,
  isLoading,
  initialValues,
  onClose,
  onSubmit,
}: UpdateRowActionFormModalProps) {
  const validateForm = useCallback(
    (values: RowCellsWithPkValue) => {
      const errors: Record<string, string> = {};

      const updatedKeys = Object.keys(values);
      if (updatedKeys.length === 0) {
        errors.all = t`No changes to save`;
      }

      for (const key of updatedKeys) {
        const parameter = description?.parameters.find((p) => p.id === key);
        const isRequired = !parameter?.optional;
        if (isRequired && !values[key]) {
          errors[key] = t`This column is required`;
        }
      }

      return errors;
    },
    [description?.parameters],
  );

  const handleFormikSubmit = useCallback(
    async (values: RowCellsWithPkValue) => {
      const success = await onSubmit(values);
      if (success) {
        onClose();
      }
    },
    [onClose, onSubmit],
  );

  const {
    isValid,
    values,
    resetForm,
    setFieldValue,
    handleSubmit,
    validateForm: revalidateForm,
  } = useFormik<Record<string, RowValue>>({
    // We want to track only changed values, not all values
    initialValues: {},
    onSubmit: handleFormikSubmit,
    validate: validateForm,
    validateOnMount: true,
  });

  // Reset form when modal is opened
  useEffect(() => {
    if (opened) {
      resetForm();
      revalidateForm({});
    }
  }, [opened, resetForm, revalidateForm]);

  const shouldShowLeaveConfirmation = useCallback(() => {
    return Object.keys(values).length > 0;
  }, [values]);

  const {
    showLeaveConfirmation,
    handleClose,
    handleContinue,
    handleLeaveConfirmation,
  } = useActionFormUnsavedLeaveConfirmation({
    shouldShowLeaveConfirmation,
    onClose,
  });

  return (
    <>
      <LeaveConfirmModal
        opened={showLeaveConfirmation}
        onConfirm={handleLeaveConfirmation}
        onClose={handleContinue}
      />
      <Modal.Root opened={opened} onClose={handleClose}>
        <Modal.Overlay />
        <Modal.Content
          transitionProps={{ transition: "slide-left" }}
          classNames={{
            content: cx(S.modalContent, Animation.slideLeft),
          }}
        >
          <form onSubmit={handleSubmit}>
            <Modal.Header px="xxl" pb="0" className={S.modalHeader}>
              <Modal.Title>{t`Edit record`}</Modal.Title>
            </Modal.Header>
            <Modal.Body px="xxl" py="xl" className={cx(S.modalBody)}>
              <Box className={S.modalBodyGrid}>
                {!description ? (
                  <Center className={S.modalBodyLoader}>
                    <Loader />
                  </Center>
                ) : (
                  description.parameters.map((parameter) => {
                    return (
                      <TableActionFormModalParameter
                        key={parameter.id}
                        parameter={parameter}
                      >
                        <ModalFormInput
                          initialValue={
                            values[parameter.id] ??
                            initialValues?.[parameter.id]
                          }
                          parameter={parameter}
                          onChange={setFieldValue}
                        />
                      </TableActionFormModalParameter>
                    );
                  })
                )}
              </Box>
            </Modal.Body>
            <Flex
              px="xxl"
              className={S.modalFooter}
              gap="xl"
              justify="flex-end"
            >
              <Button variant="subtle" color="neutral" onClick={handleClose}>
                {t`Cancel`}
              </Button>
              <Button
                disabled={isLoading || !isValid}
                variant="filled"
                type="submit"
                data-testid="update-row-save-button"
              >
                {t`Save changes`}
              </Button>
            </Flex>
          </form>
        </Modal.Content>
      </Modal.Root>
    </>
  );
}

type ModalFormInputProps = {
  initialValue?: RowValue;
  parameter: TableActionFormParameter;
  onChange: (field: string, value: RowValue) => void;
};

export function ModalFormInput({
  initialValue,
  parameter,
  onChange,
}: ModalFormInputProps) {
  const handleChange = useCallback(
    (value: RowValue) => {
      onChange(parameter.id, value);
    },
    [parameter.id, onChange],
  );

  return (
    <ModalParameterActionInput
      initialValue={initialValue?.toString()}
      parameter={parameter}
      onChange={handleChange}
    />
  );
}