All files / brand-store/components/Models CreateModelForm.tsx

35.71% Statements 20/56
66.66% Branches 8/12
17.64% Functions 3/17
37.73% Lines 20/53

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                                                        24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   24x   24x                         24x                                                                                                 24x 3x         24x                                                                     15x 15x                                             1x                                                                                          
import { Dispatch, ReactNode, SetStateAction, useState } from "react";
import { useNavigate, useParams, useLocation, Link } from "react-router-dom";
import { useRecoilState, useRecoilValue, useSetRecoilState } from "recoil";
import { useMutation, useQueryClient } from "react-query";
import { Input, Button, Icon } from "@canonical/react-components";
import randomstring from "randomstring";
 
import { checkModelNameExists, setPageTitle } from "../../utils";
 
import {
  brandStoresState,
  modelsListState,
  newModelState,
  brandIdState,
} from "../../atoms";
import { filteredModelsListState, brandStoreState } from "../../selectors";
 
import type { Store, Model } from "../../types/shared";
 
type Props = {
  setShowNotification: Dispatch<SetStateAction<boolean>>;
  setShowErrorNotification: Dispatch<SetStateAction<boolean>>;
};
 
function CreateModelForm({
  setShowNotification,
  setShowErrorNotification,
}: Props): ReactNode {
  const navigate = useNavigate();
  const location = useLocation();
  const { id } = useParams();
  const brandId = useRecoilValue(brandIdState);
  const [newModel, setNewModel] = useRecoilState(newModelState);
  const stores = useRecoilState(brandStoresState);
  const currentStore = stores[0].find((store: Store) => store.id === id);
  const modelsList = useRecoilValue(filteredModelsListState);
  const brandStore = useRecoilValue(brandStoreState(id));
  const setModelsList = useSetRecoilState<Array<Model>>(modelsListState);
  const [isSaving, setIsSaving] = useState(false);
 
  const queryClient = useQueryClient();
 
  const handleError = () => {
    setShowErrorNotification(true);
    setIsSaving(false);
    setModelsList((oldModelsList: Array<Model>) => {
      return oldModelsList.filter((model) => model.name !== newModel.name);
    });
    navigate(`/admin/${id}/models`);
    setNewModel({ name: "", apiKey: "" });
    setTimeout(() => {
      setShowErrorNotification(false);
    }, 5000);
  };
 
  const mutation = useMutation({
    mutationFn: (newModel: { name: string; apiKey: string }) => {
      setIsSaving(true);
 
      const formData = new FormData();
 
      formData.set("csrf_token", window.CSRF_TOKEN);
      formData.set("name", newModel.name);
      formData.set("api_key", newModel.apiKey);
 
      setNewModel({ name: "", apiKey: "" });
 
      setModelsList((oldModelsList: Array<Model>) => {
        return [
          {
            "api-key": newModel.apiKey,
            "created-at": new Date().toISOString(),
            name: newModel.name,
          },
          ...oldModelsList,
        ];
      });
 
      return fetch(`/admin/store/${brandId}/models`, {
        method: "POST",
        body: formData,
      });
    },
    onMutate: async (newModel) => {
      await queryClient.cancelQueries({ queryKey: ["models"] });
      queryClient.setQueryData(["models"], () => [newModel]);
      return { previousModels: modelsList };
    },
    onError: ({ context }) => {
      queryClient.setQueryData(["models"], context?.previousModels);
      handleError();
      throw new Error("Unable to create a new model");
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ["models"] });
      setShowNotification(true);
      setIsSaving(false);
      navigate(`/admin/${id}/models`);
      setTimeout(() => {
        setShowNotification(false);
      }, 5000);
    },
  });
 
  if (location.pathname.includes("/create")) {
    brandStore
      ? setPageTitle(`Create model in ${brandStore.name}`)
      : setPageTitle("Create model");
  }
 
  return (
    <form
      onSubmit={(event) => {
        event.preventDefault();
        mutation.mutate({ name: newModel.name, apiKey: newModel.apiKey });
      }}
      style={{ height: "100%" }}
    >
      <div className="p-panel is-flex-column">
        <div className="p-panel__header">
          <h4 className="p-panel__title">Create new model</h4>
        </div>
        <div className="p-panel__content">
          <div className="u-fixed-width" style={{ marginBottom: "30px" }}>
            {currentStore && (
              <p>
                Brand
                <br />
                <strong>{currentStore.name}</strong>
              </p>
            )}
            {isSaving && (
              <p>
                <Icon name="spinner" className="u-animation--spin" />
                &nbsp;Creating new model...
              </p>
            )}
            <Input
              type="text"
              id="model-name-field"
              placeholder="e.g. display-name-123"
              label="Name"
              help="Name should contain lowercase alphanumeric characters and hyphens only"
              value={newModel.name}
              onChange={(e) => {
                const value = e.target.value;
                setNewModel({ ...newModel, name: value });
              }}
              error={
                checkModelNameExists(newModel.name, modelsList)
                  ? `Model ${newModel.name} already exists`
                  : null
              }
              required
            />
            <Input
              type="text"
              id="api-key-field"
              label="API key"
              value={newModel.apiKey}
              placeholder="yx6dnxsWQ3XUB5gza8idCuMvwmxtk1xBpa9by8TuMit5dgGnv"
              className="read-only-dark"
              style={{ color: "#000" }}
              readOnly
            />
            <Button
              type="button"
              className="u-no-margin--bottom"
              onClick={() => {
                setNewModel({
                  ...newModel,
                  apiKey: randomstring.generate({
                    length: 50,
                  }),
                });
              }}
            >
              Generate key
            </Button>
          </div>
          <div className="u-fixed-width">
            <hr />
            <p>* Mandatory field</p>
            <div className="u-align--right">
              <Link
                className="p-button u-no-margin--bottom"
                to={`/admin/${id}/models`}
                onClick={() => {
                  setNewModel({ name: "", apiKey: "" });
                  setShowErrorNotification(false);
                }}
              >
                Cancel
              </Link>
              <Button
                type="submit"
                appearance="positive"
                className="u-no-margin--bottom u-no-margin--right"
                disabled={
                  !newModel.name ||
                  checkModelNameExists(newModel.name, modelsList)
                }
              >
                Add model
              </Button>
            </div>
          </div>
        </div>
      </div>
    </form>
  );
}
 
export default CreateModelForm;