All files / maas-ui/src/app/domains/components/DomainDetailsHeader/DeleteDomainForm DeleteDomainForm.tsx

95.83% Statements 23/24
83.33% Branches 5/6
100% Functions 5/5
95.45% Lines 21/22

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                                    10x 10x 10x 10x     10x 3x 3x 3x 6x   3x 3x 3x 4x   3x       3x 3x 3x 2x     3x             1x 1x                                          
import { useCallback } from "react";
 
import { Icon } from "@canonical/react-components";
import { useDispatch, useSelector } from "react-redux";
 
import FormikForm from "@/app/base/components/FormikForm";
import { useSidePanel } from "@/app/base/side-panel-context-new";
import type { EmptyObject } from "@/app/base/types";
import urls from "@/app/base/urls";
import { domainActions } from "@/app/store/domain";
import domainSelectors from "@/app/store/domain/selectors";
import type { Domain } from "@/app/store/domain/types";
import type { RootState } from "@/app/store/root/types";
 
type Props = {
  id: Domain["id"];
};
 
export enum Labels {
  DeleteLabel = "Delete domain",
  AreYouSure = "Are you sure you want to delete this domain?",
  CannotDelete = "Domain cannot be deleted because it has resource records. Remove all resource records from the domain to allow deletion.",
}
 
const DeleteDomainForm = ({ id }: Props): React.ReactElement | null => {
  const { closeSidePanel } = useSidePanel();
  const dispatch = useDispatch();
  const domain = useSelector((state: RootState) =>
    domainSelectors.getById(state, id)
  );
  const errors = useSelector(domainSelectors.errors);
  const saved = useSelector(domainSelectors.saved);
  const saving = useSelector(domainSelectors.saving);
  const cleanup = useCallback(() => domainActions.cleanup(), []);
 
  Iif (!domain) {
    return null;
  }
 
  const canBeDeleted = domain.resource_count === 0;
  let message = Labels.AreYouSure;
  if (!canBeDeleted) {
    message = Labels.CannotDelete;
  }
 
  return (
    <FormikForm<EmptyObject>
      cleanup={cleanup}
      errors={errors}
      initialValues={{}}
      onCancel={closeSidePanel}
      onSubmit={() => {
        dispatch(cleanup());
        dispatch(domainActions.delete(id));
      }}
      saved={saved}
      savedRedirect={urls.domains.index}
      saving={saving}
      submitAppearance="negative"
      submitDisabled={!canBeDeleted}
      submitLabel={Labels.DeleteLabel}
    >
      <p
        className="u-no-margin--bottom u-no-max-width"
        data-testid="delete-message"
      >
        <Icon className="is-inline" name="error" />
        {message}
      </p>
    </FormikForm>
  );
};
 
export default DeleteDomainForm;