All files / src App.tsx

83.33% Statements 60/72
65.75% Branches 48/73
73.33% Functions 11/15
84.28% Lines 59/70

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                                            3x   3x                                       3x         3x 26x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   24x   24x   5x 5x 5x     24x 5x     5x 5x 5x                         5x       24x 8x 8x 8x     8x 8x     24x 1x 1x       24x 8x 8x 8x 4x 4x 4x 4x 2x 1x         1x 1x 1x 1x   1x   2x   1x 1x 1x 1x 1x     4x       24x   24x                                                                                                                                                                                                                        
import React, { ReactElement, useEffect, useState } from 'react';
import zhCN from 'antd/lib/locale/zh_CN';
import enUS from 'antd/lib/locale/en_US';
import { ConfigProvider, Layout, Result, Space, Spin } from "antd";
import { DoubleLeftOutlined, DoubleRightOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { Link, Routes, useNavigate } from 'react-router-dom';
import { getOrganization } from "@utils/TokenUtils";
 
import { AppNav, RoutersNav } from './menu';
import { fetchTopMenus, fetchDynamicThemeInfo } from '@utils/FetchUtils';
import { loggedIn } from "@utils/LoginUtils";
import { UserProfile } from './userProfile';
import { LeftMenuWidth, SERVER_URL } from "@config/base";
import { ThemeInfoProps } from "@props/RecordProps";
import { getFaviconEl } from '@utils/ComponentUtils';
import RoutersConfig, { DynamicMenuProps } from '@kernel/RoutersConfig';
import { SupportWidget } from './components/supportWidget';
import { AiAssistantWidget } from "./components/assistant";
import { errorToObject } from '@utils/ObjectUtils';
import { Locale } from 'antd/lib/locale';
 
const { Sider } = Layout;
 
const theme = {
  token: {
    colorText: "rgba(0, 0, 0, 0.88)",
    colorPrimary: '#696AAD', // Example of setting a primary color
    colorBgContainer: '#f0f2f5', // Example of setting a background color for containers
  },
  components: {
    Layout: {
      siderBg: "#f0f2f5",
    },
    Menu: {
      colorBgContainer: '#f0f2f5', // Specific customization for Menu component
    },
  },
};
 
export interface ErrorProps {
  status: number;
}
 
const i18nToLocaleMapping: { [propName: string]: Locale } = {
  'zh': zhCN,
  'en': enUS
};
 
const App = (): ReactElement => {
  const { t, i18n } = useTranslation();
  const [loading, setLoading] = useState<boolean>(false);
  const [authorized, setAuthorized] = useState<boolean>(false);
  const [sidebarHide, setSidebarHide] = useState<boolean>(false);
  const [appNav, setAppNav] = useState<ReactElement>();
  const [routerNav, setRouterNav] = useState<ReactElement>();
  const [publicRouterNav, setPublicRouterNav] = useState<ReactElement>();
  const [themeInfo, setThemeInfo] = useState<ThemeInfoProps>();
  const [error, setError] = useState<Error | null>(null);
  const locale = i18nToLocaleMapping[i18n.language] ?? zhCN;
  const navigate = useNavigate();
 
  const [isMobile, setIsMobile] = useState<boolean>(window.innerWidth <= 768);
 
  useEffect((): (() => void) => {
    // Add event listener for resize to detect mobile
    const handleResize: () => void = () => setIsMobile(window.innerWidth <= 768);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
 
  useEffect(() => {
    Iif (themeInfo != null) {
      return;
    }
    fetchDynamicThemeInfo().then(themeInfo => {
      setThemeInfo(themeInfo);
      if (themeInfo.title) {
        document.title = themeInfo.title;
      }
      if (themeInfo.backgroundImage && themeInfo.backgroundImage.length > 0) {
        document.body.style.backgroundImage = "url('" + themeInfo.backgroundImage + "')";
      }
      if (themeInfo.favicon && themeInfo.favicon.length > 0) {
        const faviconEl = getFaviconEl();
        if (faviconEl) {
          faviconEl.href = themeInfo.favicon;
        }
      }
    }).catch((e) => {
      console.error(`Error fetching page title: ${e}`);
    });
  }, [themeInfo]);
 
  const addStyle = (url: string): void => {
    const style = document.createElement("link");
    style.href = url;
    style.rel = "stylesheet";
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    //@ts-ignore
    style.async = true;
    document.head.appendChild(style);
  };
 
  const forwardToLoginPage = (): void => {
    Eif (window.location.pathname !== '/login') {
      window.location.replace("/login");
    }
  };
 
  useEffect(() => {
    const cssUrl = `${SERVER_URL}/theme/dynamicTheme.css`;
    addStyle(cssUrl);
    if (loggedIn()) {
      setAuthorized(true);
      setLoading(true);
      (appNav != null) && setLoading(false);
      (appNav == null) && fetchTopMenus().then((topMenus: Array<DynamicMenuProps> | ErrorProps) => {
        if (Array.isArray(topMenus) && topMenus.length >= 0) {
          setAppNav(<AppNav
            menus={topMenus}
            mode={isMobile ? "horizontal" : "inline"}
            inlineCollapsed={sidebarHide}
          />);
          setRouterNav(<RoutersNav />);
        } else Eif (topMenus != null && typeof topMenus == 'object') {
          Eif ('status' in topMenus && topMenus.status === 401) {
            window.location.replace("/login");
          }
          setAuthorized(false);
        }
        setLoading(false);
      }).catch((error: Error) => {
        setLoading(false);
        setAuthorized(false);
        console.error("Error get menu list", error);
        setError(error);
        forwardToLoginPage();
      });
    } else {
      setPublicRouterNav(<div><Routes>{RoutersConfig({ type: "public", navigate })}</Routes></div>);
    }
  }, [appNav, navigate, sidebarHide, isMobile]);
 
  const stackTrace =  error ?  errorToObject(error)?.stack : "";
 
  return (
    <ConfigProvider locale={locale} theme={theme}>
      {isMobile && (
        <div className="top-bar-menu">
          {appNav}
        </div>
      )}
      <div>{authorized ? (
        <Layout style={{ minHeight: '100vh' }}>
          <Sider
            className="left-menu-container"
            width={LeftMenuWidth}
            collapsed={sidebarHide}
          >
            {!loading && <div className='left-top-menu-container'>
                <div className='menu-logo-container'>
                <Link to="/">
                  {!sidebarHide && <img src={themeInfo?.logo} alt="logo" className='menu-logo' />}
                  {sidebarHide && <img src={themeInfo?.squareLogo ?? themeInfo?.logo} alt="logo" className='menu-logo-square' />}
                </Link>
                </div>
                <div className={`user-org-info user-org-info-${sidebarHide? 'hidden' : 'display'}`}>
                    <UserProfile
                        collapsed={sidebarHide}
                    />
                  {!sidebarHide && <Link to="/" title={getOrganization().name} className="user-org-info-org-name">
                    {getOrganization().name}
                  </Link>}
                </div>
            </div>}
            {!loading && !isMobile && (<div
              className={sidebarHide ? "left-sidebar__hide left-sidebar" : "left-sidebar__show left-sidebar"}
              onClick={() => setSidebarHide(!sidebarHide)}
            >
              {!sidebarHide &&
                  <a href="/#" onClick={(e: React.MouseEvent<unknown>) => e.preventDefault()}>
                      <DoubleLeftOutlined
                          className="link-icon-small"
                          title={t("Click to collapse left menu")}
                      />
                  </a>
              }
              {sidebarHide &&
                  <a
                      title={t("Click to expand menu")}
                      href="/#"
                      style={{ marginLeft: "0.6rem" }}
                      onClick={(e: React.MouseEvent<unknown>) => e.preventDefault()}>
                      <DoubleRightOutlined
                          className="link-icon-small"
                          title={t("Click to expand left menu")}
                      />
                  </a>
              }
            </div>)}
            {!isMobile && (
              <div className="left-menu-container">
                {appNav}
              </div>
            )}
          </Sider>
          {loading && (
            <div style={{ margin: "auto" }}>
              <Spin style={{ margin: "10px" }} />
            </div>
          )}
          {(!loading) &&
            <Layout
              className="site-layout"
            >
              {routerNav}
              <AiAssistantWidget
                zIndex={9999}
              />
            </Layout>
          }
        </Layout>
      ) : (
        <Layout className="login-page-container">
          <Layout className="site-layout">
            {error &&
              <Result
                status="500"
                title={t('Error while fetching top menus')}
                subTitle={
                  <Space direction="vertical" align="start">
                    <pre style={{textAlign: 'left'}}>
                      {stackTrace}
                    </pre>
                  </Space>
                }
              />
            }
            {publicRouterNav}
          </Layout>
 
        </Layout>
      )}
        <SupportWidget
          authorized={authorized}
          zIndex={9999}
        />
      </div>
    </ConfigProvider>
  );
};
 
export default App;