All files / public/details/integrations/components/App App.tsx

70.76% Statements 46/65
75% Branches 39/52
78.94% Functions 15/19
69.35% Lines 43/62

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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282                              1x       4x 4x 4x         4x   4x 4x 2x     2x   4x         2x         2x     1x 15x 15x 15x 15x   15x   2x               15x   15x   10x           15x   11x                 15x 36x   36x 12x     24x       24x     15x               15x 24x 48x   24x     24x                 72x 36x                                                                             36x               15x                                                                                                           8x 8x                     36x                                                                                        
import type { IFilterChip, IInterfaceData } from "../../types";
import { useQuery } from "react-query";
import { useMemo, useState } from "react";
import {
  Row,
  Col,
  Spinner,
  SearchAndFilter,
  Chip,
} from "@canonical/react-components";
import { InterfaceItem } from "../InterfaceItem";
import { useRecoilState, useRecoilValue } from "recoil";
import { filterChipsSelector, filterState } from "../../state";
import { SearchAndFilterChip } from "@canonical/react-components/dist/components/SearchAndFilter/types";
 
export const getIntegrations = async (
  charm: string
): Promise<IInterfaceData[]> => {
  let resp;
  const url = new URL(document.location.href);
  const selectedChannel = url.searchParams.get("channel");
  Iif (selectedChannel) {
    resp = await fetch(
      `/${charm}/integrations.json?channel=${selectedChannel}`
    );
  } else {
    resp = await fetch(`/${charm}/integrations.json`);
  }
  const json = await resp.json();
  if (!json.grouped_relations) {
    return [];
  }
 
  const data = json.grouped_relations;
  const provides =
    data?.provides.map((item: IInterfaceData) => ({
      ...item,
      type: "provides",
    })) ?? [];
  const requires =
    data?.requires.map((item: IInterfaceData) => ({
      ...item,
      type: "requires",
    })) ?? [];
 
  return [...provides, ...requires];
};
 
export const App = () => {
  const charm = window.location.pathname.split("/")[1];
  const [filterData, setFilterData] = useRecoilState(filterState);
  const availableFilters = useRecoilValue(filterChipsSelector);
  const [fragment, setFragment] = useState(window.location.hash || "");
 
  const { data, status } = useQuery(
    ["integrations", charm],
    () => getIntegrations(charm),
    {
      refetchOnMount: false,
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
    }
  );
 
  const integrationCount = useMemo(() => data?.length ?? 0, [data]);
 
  const filterValues = useMemo(
    () =>
      filterData
        .filter((item: IFilterChip) => item.lead === "Integration")
        .map((item: IFilterChip) => item.value),
    [filterData]
  );
 
  const filteredData = useMemo(
    () =>
      filterValues.length === 0
        ? data
        : data?.filter((item) => {
            const key = `${item.key} | ${item.interface}`;
            return filterValues.includes(key);
          }),
    [data, filterValues]
  );
 
  const isActive = (id: string, index: number) => {
    const hash = fragment;
 
    if (!hash && index === 0) {
      return true;
    }
 
    Iif (hash && hash === id) {
      return true;
    }
 
    return false;
  };
 
  Iif (fragment) {
    const currentSection = document.querySelector(fragment);
 
    if (currentSection) {
      currentSection.scrollIntoView();
    }
  }
 
  const renderSideNav = (data: IInterfaceData[], type: string) => {
    const hasItems = data.some(
      (interfaceItem: IInterfaceData) => interfaceItem.type === type
    );
    Iif (!hasItems) {
      return null;
    } else {
      return (
        <>
          <h3
            className="p-side-navigation__heading"
            style={{ paddingLeft: 0, paddingTop: 10 }}
          >
            {type.toUpperCase()}
          </h3>
          {data.map((interfaceItem: IInterfaceData, index) => {
            if (interfaceItem.type === type) {
              return (
                <li
                  key={`${interfaceItem.key}|${interfaceItem.interface}`}
                  className="p-side-navigation__item"
                >
                  <a
                    className={`p-side-navigation__link ${
                      isActive(`#${interfaceItem.key}`, index)
                        ? "is-active"
                        : ""
                    }`}
                    href={`#${interfaceItem.key}`}
                    onClick={(e) => {
                      e.preventDefault();
                      const target = e.target as HTMLLinkElement;
                      const targetElId = target.getAttribute("href");
 
                      if (targetElId) {
                        const targetEl = document.querySelector(targetElId);
                        targetEl?.scrollIntoView();
                        setFragment(targetElId);
                        window.location.hash = targetElId;
                        target.classList.add("is-active");
                      }
                    }}
                  >
                    {`${interfaceItem.key}`}
                    {interfaceItem.required === true && (
                      <Chip
                        value="Required"
                        appearance="negative"
                        className="u-no-margin--bottom"
                        style={{ marginLeft: "10px" }}
                      />
                    )}
                  </a>
                </li>
              );
            } else {
              return null;
            }
          })}
        </>
      );
    }
  };
 
  return (
    <Col size={12}>
      {!data && (
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            minHeight: "10rem",
          }}
        >
          <Spinner text="Loading..." />
        </div>
      )}
      {data && integrationCount > 0 && (
        <Row className="p-details-tab__content">
          <Col size={3} className="p-details-tab__content__sidebar">
            <div
              className="p-side-navigation"
              style={{ position: "sticky", top: "0" }}
            >
              <ul className="p-side-navigation__list">
                {filteredData && renderSideNav(filteredData, "provides")}
                {filteredData && renderSideNav(filteredData, "requires")}
              </ul>
            </div>
          </Col>
          <Col size={9} className="p-details-tab__content__body">
            <Row>
              <Col size={5}>
                <h2 className="p-heading--3 p-details-tab__content__body__title">
                  {integrationCount} integration
                  {integrationCount > 1 ? "s" : ""}
                </h2>
                <p className="p-heading--4 p-details-tab__content__body__link">
                  <a href="https://juju.is/docs/juju/relation">
                    Learn about integrations&nbsp;&gt;
                  </a>
                </p>
              </Col>
              <Col size={4}>
                <div
                  style={{
                    position: "relative",
                    zIndex: 1,
                    width: "100%",
                    minHeight: "3rem",
                  }}
                >
                  <div style={{ position: "absolute", width: "100%" }}>
                    <SearchAndFilter
                      // @ts-expect-error: id mismatch (number instead of string) but doesn't matter in reality
                      filterPanelData={availableFilters}
                      returnSearchData={(searchData: SearchAndFilterChip[]) => {
                        setFilterData((prev) =>
                          prev !== searchData
                            ? (searchData as IFilterChip[])
                            : prev
                        );
                      }}
                    />
                  </div>
                </div>
              </Col>
            </Row>
            {filteredData?.map((interfaceItem: IInterfaceData) => (
              <InterfaceItem
                key={`${interfaceItem.key}|${interfaceItem.interface}`}
                interfaceType={interfaceItem!.type!}
                interfaceData={interfaceItem}
                charmName={charm}
              />
            ))}
          </Col>
        </Row>
      )}
      {status === "success" && integrationCount === 0 && (
        <div className="p-strip u-no-padding--top">
          <div className="u-fixed-width u-equal-height">
            <div className="charm-empty-docs-icon u-vertically-center">
              <img
                src="https://assets.ubuntu.com/v1/8acd8f55-Integrations.svg"
                alt=""
                width="121"
                height="121"
              />
            </div>
            <div className="col-9 charm-empty-docs-content">
              <h4>No Integrations have been added for this charm</h4>
              <p>
                Integration is a connection an application supports by virtue of
                having a particular endpoint.
              </p>
              <p className="u-no-margin--bottom">
                <a
                  className="p-button--positive u-no-margin--bottom"
                  href="https://juju.is/docs/juju/relation"
                >
                  Learn how to manage charm integrations
                </a>
              </p>
            </div>
          </div>
        </div>
      )}
    </Col>
  );
};
 
export default App;