All files / react-app/src/components/Layout index.tsx

91.52% Statements 54/59
85.93% Branches 55/64
100% Functions 16/16
92.85% Lines 52/56

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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431                                                      78x 56x 56x 56x 56x     56x                               186x                             195x   56x                                     78x 22x   22x 1x     22x   1x 1x   1x     22x                                                                                                                                 78x 54x 54x 54x 54x 54x   54x 27x           27x     54x                                                                                                                                                                     78x 56x 56x 56x 56x   56x 1x 1x 1x 1x 1x     56x 1x 1x     56x   39x 82x     39x         39x                                                                                                                                                                                 5x                                         78x 14x                               78x 11x            
import { AwsCognitoOAuthOpts } from "@aws-amplify/auth/lib-esm/types";
import { Bars3Icon, XMarkIcon } from "@heroicons/react/24/outline";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { Auth } from "aws-amplify";
import { useState } from "react";
import { Link, NavLink, NavLinkProps, Outlet, useNavigate } from "react-router";
import { UserRoles } from "shared-types";
 
import { useGetUser } from "@/api";
import { Banner, ScrollToTop, SimplePageContainer, UserPrompt } from "@/components";
import MMDLAlertBanner from "@/components/Banner/MMDLSpaBanner";
import config from "@/config";
import { useMediaQuery } from "@/hooks";
import { useFeatureFlag } from "@/hooks/useFeatureFlag";
import { isFaqPage, isProd } from "@/utils";
import { sendGAEvent } from "@/utils/ReactGA/sendGAEvent";
 
import { Footer } from "../Footer";
import { UsaBanner } from "../UsaBanner";
 
/**
 * Custom hook that generates a list of navigation links based on the user's status and whether the current page is the FAQ page.
 *
 * @returns {Object} An object containing:
 * - `links`: An array of link objects with `name`, `link`, and `condition` properties.
 * - `isFaqPage`: A boolean indicating if the current page is the FAQ page.
 */
const useGetLinks = () => {
  const { isLoading, data: userObj } = useGetUser();
  const hideWebformTab = useFeatureFlag("UAT_HIDE_MMDL_BANNER");
  const toggleFaq = useFeatureFlag("TOGGLE_FAQ");
  const showHome = toggleFaq ? userObj.user : true; // if toggleFAQ is on we want to hide home when not logged in
 
  const links =
    isLoading || isFaqPage
      ? []
      : [
          {
            name: "Home",
            link: "/",
            condition: showHome,
          },
          {
            name: "Dashboard",
            link: "/dashboard",
            condition:
              userObj.user &&
              (userObj.user["custom:cms-roles"] || userObj.user["custom:ismemberof"]) &&
              Object.values(UserRoles).some(
                (role) =>
                  userObj.user["custom:cms-roles"].includes(role) ||
                  userObj.user["custom:ismemberof"] === role,
              ),
          },
          {
            name: "View FAQs",
            link: "/faq",
            condition: !toggleFaq,
          },
          { name: "Support", link: "/support", condition: userObj.user && toggleFaq },
          {
            name: "Webforms",
            link: "/webforms",
            condition: userObj.user && !isProd && !hideWebformTab,
          },
        ].filter((l) => l.condition);
 
  return { links, isFaqPage };
};
 
/**
 * UserDropdownMenu component renders a dropdown menu for user actions.
 *
 * This component provides options for viewing the user's profile and signing out.
 * It uses the `useNavigate` hook for navigation and `Auth.signOut` for logging out.
 *
 * The dropdown menu is not rendered on the FAQ page.
 *
 * @component
 * @example
 * return (
 *   <UserDropdownMenu />
 * )
 *
 * @returns {JSX.Element} The rendered dropdown menu component.
 */
const UserDropdownMenu = () => {
  const navigate = useNavigate();
 
  const handleViewProfile = () => {
    navigate("/profile");
  };
 
  const handleLogout = async () => {
    // Small delay to ensure Amplify completes its internal processes
    setTimeout(() => {
      window.localStorage.clear();
    }, 100);
    await Auth.signOut();
  };
 
  Iif (isFaqPage) return null;
 
  return (
    <DropdownMenu.Root>
      <DropdownMenu.Trigger
        asChild
        className="hover:text-white/70 py-2 pl-3 pr-4 data-[state=open]:bg-white data-[state=open]:text-primary"
      >
        <button className="flex flex-row gap-4 items-center cursor-pointer">
          <p className="flex">My Account</p>
          <svg
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
            strokeWidth={2.0}
            stroke="currentColor"
            className="w-4 h-4 flex"
          >
            <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
          </svg>
        </button>
      </DropdownMenu.Trigger>
      <DropdownMenu.Portal>
        <DropdownMenu.Content
          align="start"
          className="bg-white z-50 flex flex-col gap-4 px-10 py-4 shadow-md rounded-b-sm "
        >
          <DropdownMenu.Item className="flex">
            <button className="text-primary hover:text-primary/70" onClick={handleViewProfile}>
              View Profile
            </button>
          </DropdownMenu.Item>
          <DropdownMenu.Item className="flex">
            <button className="text-primary hover:text-primary/70" onClick={handleLogout}>
              Sign Out
            </button>
          </DropdownMenu.Item>
        </DropdownMenu.Content>
      </DropdownMenu.Portal>
    </DropdownMenu.Root>
  );
};
 
/**
 * Layout component that serves as the main structure of the application.
 * It includes a navigation bar, main content area, and footer.
 *
 * @returns {JSX.Element} The rendered Layout component.
 *
 * @component
 * @example
 * return (
 *   <Layout />
 * )
 *
 * @remarks
 * - Uses `useMediaQuery` to determine if the screen width is at least 768px.
 * - Fetches user data using `useGetUser` hook.
 * - Displays a `UserPrompt` component.
 * - Displays a `UsaBanner` component, indicating if the user is missing a role.
 * - Contains a navigation bar with a logo and a `ResponsiveNav` component.
 * - The logo is a clickable `Link` unless on the FAQ page, where it is a non-clickable `div`.
 * - The main content area includes a `SimplePageContainer` with a `Banner` and an `Outlet` for nested routes.
 * - The footer displays contact information.
 */
export const Layout = () => {
  const hideLogin = useFeatureFlag("LOGIN_PAGE");
  const isDesktop = useMediaQuery("(min-width: 768px)");
  const { data: user } = useGetUser();
  const customUserRoles = user?.user?.["custom:cms-roles"] || "";
  const customisMemberOf = user?.user?.["custom:ismemberof"] || "";
 
  if (customUserRoles.length > 0) {
    Eif (
      customUserRoles.includes("onemac-state-user") ||
      customUserRoles.includes("onemac-helpdesk") ||
      customUserRoles.includes("onemac-micro-readonly")
    ) {
      // TBD weather to add states to the login event since users may have a states array with multiple states.
      sendGAEvent("Login", customUserRoles, null);
    }
  }
  Iif (customisMemberOf.length > 0) {
    if (customisMemberOf.includes("ONEMAC_USER")) {
      sendGAEvent("Login", customisMemberOf, null);
    }
  }
  // TODO: add logic for super user when/if super user goes into effect
 
  return (
    <div className="min-h-full flex flex-col">
      <ScrollToTop />
      <UserPrompt />
      {user?.user && !isFaqPage && <MMDLAlertBanner />}
      <UsaBanner isUserMissingRole={user?.user && customUserRoles === undefined} />
      <nav data-testid="nav-banner-d" className="bg-primary">
        <div className="max-w-screen-xl mx-auto px-4 lg:px-8">
          <div className="h-[70px] relative flex gap-12 items-center text-white">
            {!isFaqPage ? (
              // This is the original Link component
              <Link to={user?.user || hideLogin ? "/" : "/login"}>
                <img
                  className="h-10 w-28 min-w-[112px] resize-none"
                  src="/onemac-logo.png"
                  alt="onemac site logo"
                />
              </Link>
            ) : (
              // This is a non-clickable element that looks the same
              <div>
                <img
                  className="h-10 w-28 min-w-[112px] resize-none"
                  src="/onemac-logo.png"
                  alt="onemac site logo"
                />
              </div>
            )}
            <ResponsiveNav isDesktop={isDesktop} />
          </div>
        </div>
      </nav>
      <main className="flex-1">
        <SimplePageContainer>
          <Banner />
        </SimplePageContainer>
        <Outlet />
      </main>
      <Footer
        email="OneMAC_Helpdesk@cms.hhs.gov"
        address={{
          city: "Baltimore",
          state: "MD",
          street: "7500 Security Boulevard",
          zip: 21244,
        }}
      />
    </div>
  );
};
 
type ResponsiveNavProps = {
  isDesktop: boolean;
};
 
/**
 * ResponsiveNav component renders a navigation bar that adapts to desktop and mobile views.
 * It displays navigation links and user authentication buttons (Sign In/Register) based on the user's authentication status.
 *
 * @param {ResponsiveNavProps} props - The properties for the ResponsiveNav component.
 * @param {boolean} props.isDesktop - A boolean indicating if the current view is desktop.
 *
 * @returns {JSX.Element | null} The rendered navigation bar component.
 *
 * @component
 *
 * @example
 * // Usage example:
 * <ResponsiveNav isDesktop={true} />
 *
 * @remarks
 * - The component uses `useGetLinks` to fetch navigation links.
 * - The component uses `useGetUser` to fetch user data.
 * - The component conditionally renders different layouts for desktop and mobile views.
 * - The component handles user authentication redirection for login and registration.
 */
const ResponsiveNav = ({ isDesktop }: ResponsiveNavProps) => {
  const [prevMediaQuery, setPrevMediaQuery] = useState(isDesktop);
  const [isOpen, setIsOpen] = useState(false);
  const { links } = useGetLinks();
  const { isLoading, isError, data } = useGetUser();
 
  const handleLogin = () => {
    const authConfig = Auth.configure();
    const { domain, redirectSignIn, responseType } = authConfig.oauth as AwsCognitoOAuthOpts;
    const clientId = authConfig.userPoolWebClientId;
    const url = `https://${domain}/oauth2/authorize?redirect_uri=${redirectSignIn}&response_type=${responseType}&client_id=${clientId}`;
    window.location.assign(url);
  };
 
  const handleRegister = () => {
    const url = `${config.idm.home_url}/signin/login.html`;
    window.location.assign(url);
  };
 
  if (isLoading || isError) return null;
 
  const setClassBasedOnNav: NavLinkProps["className"] = ({ isActive }) =>
    isActive
      ? "underline underline-offset-4 decoration-4 hover:text-white/70"
      : "hover:text-white/70";
  Iif (prevMediaQuery !== isDesktop) {
    setPrevMediaQuery(isDesktop);
    setIsOpen(false);
  }
 
  if (isDesktop) {
    return (
      <>
        {links.map((link) => (
          <NavLink
            data-testid={`${link.name}-d`}
            to={link.link}
            target={link.link === "/faq" ? "_blank" : "_self"}
            key={link.name}
            className={setClassBasedOnNav}
          >
            {link.name}
          </NavLink>
        ))}
        <div className="flex-1"></div>
        {data.user ? (
          // When the user is signed in
          <UserDropdownMenu />
        ) : (
          !isFaqPage && (
            // When the user is not signed in
            <>
              <button
                data-testid="sign-in-button-d"
                className="text-white hover:text-white/70"
                onClick={handleLogin}
              >
                Sign In
              </button>
              <button
                data-testid="register-button-d"
                className="text-white hover:text-white/70"
                onClick={handleRegister}
              >
                Register
              </button>
            </>
          )
        )}
      </>
    );
  }
 
  return (
    <>
      <div className="flex-1"></div>
      {isOpen && (
        <div className="w-full absolute top-[100px] sm:top-[70px] left-0 z-50">
          <ul className="font-medium flex flex-col items-start p-4 md:p-0 -mx-4 gap-4 rounded-b-lg bg-primary">
            {links.map((link) => (
              <li key={link.link}>
                <Link
                  data-testid={`${link.name}-m`}
                  className="block py-2 pl-3 pr-4 text-white rounded"
                  to={link.link}
                  target={link.link === "/faq" ? "_blank" : "_self"}
                >
                  {link.name}
                </Link>
              </li>
            ))}
            {data.user ? (
              // When the user is signed in
              <UserDropdownMenu />
            ) : (
              !isFaqPage && (
                // When the user is not signed in
                <>
                  <button
                    className="text-left block py-2 pl-3 pr-4 text-white rounded"
                    onClick={handleLogin}
                  >
                    Sign In
                  </button>
                  <button
                    className="text-left block py-2 pl-3 pr-4 text-white rounded"
                    onClick={handleRegister}
                  >
                    Register
                  </button>
                </>
              )
            )}
          </ul>
        </div>
      )}
      <button
        data-testid="mobile-menu-button"
        onClick={() => {
          setIsOpen((prev) => !prev);
        }}
      >
        {!isOpen && <Bars3Icon className="w-6 h-6 min-w-[24px]" />}
        {isOpen && <XMarkIcon className="w-6 h-6 min-w-[24px]" />}
      </button>
    </>
  );
};
 
/**
 * SubNavHeader component
 *
 * This component renders a sub-navigation header with a background color and
 * centers its children content within a maximum width container.
 *
 * @param {Object} props - The properties object.
 * @param {React.ReactNode} props.children - The content to be displayed inside the sub-navigation header.
 *
 * @returns {JSX.Element} The rendered sub-navigation header component.
 */
export const SubNavHeader = ({ children }: { children: React.ReactNode }) => (
  <div className="bg-sky-100" data-testid="sub-nav-header">
    <div className="max-w-screen-xl m-auto px-4 lg:px-8">
      <div className="flex items-center">
        <div className="flex align-middle py-4">{children}</div>
      </div>
    </div>
  </div>
);
 
type SupportSubNavHeaderProps = {
  /*
   * The content to be displayed inside the sub-navigation header
   */
  children: React.ReactNode;
};
 
export const SupportSubNavHeader = ({ children }: SupportSubNavHeaderProps) => (
  <div className="bg-primary-dark sticky top-0" data-testid="sub-faq-nav-header">
    <div className="max-w-screen-lg m-auto px-4 lg:px-8">
      <div className="flex justify-between py-2 text-white">{children}</div>
    </div>
  </div>
);