All files / interfaces/components/InterfacesIndex InterfacesIndex.tsx

64.7% Statements 33/51
61.29% Branches 19/31
57.14% Functions 8/14
64% Lines 32/50

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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244                                12x   12x 6x 6x   6x     12x       22x       22x       22x               19x   19x   19x 19x 19x 19x 19x     19x       19x   19x 6x       6x 6x       19x 6x 6x 6x                                               19x 12x     19x 6x     19x                                                                                                                                           25x                                                                                                                                    
import { useState, useEffect } from "react";
import { Link, useSearchParams } from "react-router-dom";
import {
  Strip,
  Row,
  Col,
  Button,
  MainTable,
  Notification,
  Pagination,
  StatusLabel,
} from "@canonical/react-components";
 
import type { InterfaceItem } from "../../types";
 
function pageArray<T>(items: T[], count: number) {
  const result: T[][] = [];
 
  for (let i = 0; i < Math.ceil(items.length / count); i++) {
    const start = i * count;
    const end = start + count;
 
    result.push(items.slice(start, end));
  }
 
  return result;
}
 
function sortInterfaces(a: InterfaceItem, b: InterfaceItem) {
  Iif (a.status === "live" && b.status !== "live") {
    return -1;
  }
 
  Iif (a.status !== "live" && b.status === "live") {
    return 1;
  }
 
  return 0;
}
 
type Props = {
  interfacesList: Array<InterfaceItem>;
};
 
function InterfacesIndex({ interfacesList }: Props) {
  const ITEMS_PER_PAGE = 10;
 
  const [searchParams, setSearchParams] = useSearchParams();
 
  const [interfaces, setInterfaces] = useState<Array<InterfaceItem>>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  const [currentItems, setCurrentItems] = useState<InterfaceItem[]>([]);
  const [currentPageNumber, setCurrentPageNumber] = useState(
    parseInt(searchParams.get("page") || "1")
  );
  const [currentPageIndex, setCurrentPageIndex] = useState(
    currentPageNumber - 1
  );
 
  const pageParam = searchParams.get("page");
 
  useEffect(() => {
    Iif (pageParam !== null) {
      setCurrentPageNumber(parseInt(pageParam));
      setCurrentPageIndex(parseInt(pageParam) - 1);
    } else {
      setCurrentPageNumber(1);
      setCurrentPageIndex(0);
    }
  }, [pageParam]);
 
  useEffect(() => {
    Eif (interfacesList) {
      setInterfaces(interfacesList.sort(sortInterfaces));
      return;
    }
 
    setLoading(true);
 
    fetch("./interfaces.json")
      .then((response) => {
        if (response.status === 200) {
          return response.json();
        }
 
        throw response;
      })
      .then((data) => {
        setInterfaces(data?.interfaces.sort(sortInterfaces));
      })
      .catch(() => {
        setError(true);
      })
      .finally(() => {
        setLoading(false);
      });
  }, [interfacesList]);
 
  useEffect(() => {
    setCurrentItems(pageArray(interfaces, ITEMS_PER_PAGE)[currentPageIndex]);
  }, [currentPageIndex, interfaces]);
 
  useEffect(() => {
    document.title = "Charmhub | Interface catalogue";
  }, []);
 
  return (
    <>
      <Strip type="light">
        <Row>
          <Col size={4}>
            <h1>Interfaces</h1>
          </Col>
          <Col size={8}>
            <p>
              Interfaces describe the relation between two charms. This
              interface catalogue shows opinionated, standardized interface
              specifications for charm relations. Each interface outlines the
              behavior and requirements of charms relating to one another.
            </p>
            <p>
              Most of the content of these pages can be collaboratively
              discussed and changed. You can help us improve these pages by
              clicking the button below.
            </p>
            <p className="u-no-margin--bottom">
              <Button
                element="a"
                href="https://github.com/canonical/charm-relation-interfaces"
                appearance="positive"
              >
                Contribute
              </Button>
            </p>
          </Col>
        </Row>
      </Strip>
      <Strip>
        {error && (
          <Notification
            severity="negative"
            title="Error"
            onDismiss={() => {
              setError(false);
            }}
          >
            There was a problem fetching interfaces. Please try again in a few
            moments.
          </Notification>
        )}
        <h2 className="p-heading--4">
          {currentItems && interfaces.length > ITEMS_PER_PAGE && (
            <>
              {ITEMS_PER_PAGE * currentPageIndex + 1} &ndash;{" "}
              {ITEMS_PER_PAGE * currentPageIndex + currentItems.length} of{" "}
              {interfaces.length} interfaces
            </>
          )}
        </h2>
        <MainTable
          headers={[
            {
              content: "Interface name",
              heading: "Interface name",
            },
            {
              content: "Version",
              heading: "Version",
              style: {
                width: "80px",
              },
            },
          ]}
          rows={
            currentItems &&
            currentItems.map((item: InterfaceItem) => {
              return {
                columns: [
                  {
                    content: (
                      <div
                        style={{
                          display: "flex",
                        }}
                      >
                        {item?.status === "live" && (
                          <Link to={`/integrations/${item?.name}`}>
                            {item?.name}
                          </Link>
                        )}
                        {item?.status !== "live" && (
                          <>
                            <StatusLabel style={{ marginRight: "1rem" }}>
                              {item?.status}
                            </StatusLabel>
                            <Link
                              to={`/integrations/${item?.name}/${item?.status}`}
                            >
                              {item?.name}
                            </Link>
                          </>
                        )}
                      </div>
                    ),
                  },
                  {
                    content: item?.version,
                    className: "u-align--right",
                  },
                ],
              };
            })
          }
          emptyStateMsg={`${
            loading ? "Fetching interfaces..." : "No interfaces available"
          }`}
          responsive
        />
        <div className="u-align--right">
          <Pagination
            currentPage={currentPageNumber}
            itemsPerPage={ITEMS_PER_PAGE}
            paginate={(pageNumber) => {
              setCurrentPageNumber(pageNumber);
              setCurrentPageIndex(pageNumber - 1);
 
              if (pageNumber > 1) {
                setSearchParams({ page: pageNumber.toString() });
              } else {
                setSearchParams({});
              }
            }}
            totalItems={interfaces.length}
            scrollToTop
          />
        </div>
      </Strip>
    </>
  );
}
 
export default InterfacesIndex;