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

63.63% Statements 21/33
50% Branches 13/26
42.85% Functions 3/7
63.63% Lines 21/33

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                                                                6x 5x             5x   5x 5x 5x 5x 5x 5x 5x 5x 5x   5x   5x       5x 4x 4x   4x           4x 4x       5x                                                                                                                                                                                                                      
import { useState, useEffect, ReactNode } from "react";
import { useSetRecoilState, useRecoilValue } from "recoil";
import {
  Link,
  useParams,
  useLocation,
  useNavigate,
  useSearchParams,
} from "react-router-dom";
import { Row, Col, Notification, Icon } from "@canonical/react-components";
import { UseQueryResult } from "react-query";
 
import {
  modelsListFilterState,
  modelsListState,
  policiesListState,
  newModelState,
  brandIdState,
} from "../../atoms";
import { brandStoreState } from "../../selectors";
 
import Filter from "../Filter";
import ModelsTable from "./ModelsTable";
import CreateModelForm from "./CreateModelForm";
import Navigation from "../Navigation";
 
import { useModels } from "../../hooks";
import { isClosedPanel, setPageTitle, getPolicies } from "../../utils";
 
import type { Model as ModelType, Policy } from "../../types/shared";
 
function Models(): ReactNode {
  const { id } = useParams();
  const brandId = useRecoilValue(brandIdState);
 
  const {
    data: models,
    isLoading: modelsIsLoading,
    error: modelsError,
    isError: modelsIsError,
  }: UseQueryResult<ModelType[]> = useModels(brandId);
 
  const location = useLocation();
  const navigate = useNavigate();
  const setModelsList = useSetRecoilState<Array<ModelType>>(modelsListState);
  const setPolicies = useSetRecoilState<Array<Policy>>(policiesListState);
  const setNewModel = useSetRecoilState(newModelState);
  const setFilter = useSetRecoilState<string>(modelsListFilterState);
  const brandStore = useRecoilValue(brandStoreState(id));
  const [searchParams] = useSearchParams();
  const [showNotification, setShowNotification] = useState<boolean>(false);
  const [showErrorNotification, setShowErrorNotification] =
    useState<boolean>(false);
 
  brandStore
    ? setPageTitle(`Models in ${brandStore.name}`)
    : setPageTitle("Models");
 
  useEffect(() => {
    const controller = new AbortController();
    const signal = controller.signal;
 
    Iif (!modelsIsLoading && !modelsError && models) {
      setModelsList(models);
      setFilter(searchParams.get("filter") || "");
      getPolicies({ models, id, setPolicies, signal });
    }
 
    return () => {
      controller.abort();
    };
  }, [modelsIsLoading, modelsError, models]);
 
  return (
    <div className="l-application" role="presentation">
      <Navigation sectionName="models" />
      <main className="l-main">
        <div className="p-panel u-flex-column">
          <div className="p-panel__content u-flex-column u-flex-grow">
            <div className="u-fixed-width">
              <h1 className="p-heading--4">Models</h1>
            </div>
            {showNotification && (
              <div className="u-fixed-width">
                <Notification
                  severity="positive"
                  onDismiss={() => {
                    setShowNotification(false);
                  }}
                >
                  New model created
                </Notification>
              </div>
            )}
            {showErrorNotification && (
              <div className="u-fixed-width">
                <Notification
                  severity="negative"
                  onDismiss={() => {
                    setShowErrorNotification(false);
                  }}
                >
                  Unable to create model
                </Notification>
              </div>
            )}
            <Row>
              <Col size={6}>
                <Filter
                  state={modelsListFilterState}
                  label="Search models"
                  placeholder="Search models"
                />
              </Col>
              <Col size={6} className="u-align--right">
                <Link
                  className="p-button--positive"
                  to={`/admin/${id}/models/create`}
                >
                  Create new model
                </Link>
              </Col>
            </Row>
            <div className="u-fixed-width u-flex-column u-flex-grow">
              <div>
                {modelsIsError && modelsError instanceof Error && (
                  <Notification severity="negative">
                    Error: {modelsError.message}
                  </Notification>
                )}
                {modelsIsLoading ? (
                  <p>
                    <Icon name="spinner" className="u-animation--spin" />
                    &nbsp;Fetching models...
                  </p>
                ) : (
                  <div className="u-flex-column u-flex-grow">
                    <ModelsTable />
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </main>
      <div
        className={`l-aside__overlay ${
          isClosedPanel(location.pathname, "create") ? "u-hide" : ""
        }`}
        onClick={() => {
          navigate(`/admin/${id}/models`);
          setShowErrorNotification(false);
          setNewModel({ name: "", apiKey: "" });
        }}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === " ") {
            navigate(`/admin/${id}/models`);
            setShowErrorNotification(false);
            setNewModel({ name: "", apiKey: "" });
          }
        }}
        role="button"
        tabIndex={0}
        aria-label="Navigate to models page"
      ></div>
      <aside
        className={`l-aside ${
          isClosedPanel(location.pathname, "create") ? "is-collapsed" : ""
        }`}
      >
        <CreateModelForm
          setShowNotification={setShowNotification}
          setShowErrorNotification={setShowErrorNotification}
        />
      </aside>
    </div>
  );
}
 
export default Models;