All files / src FirstPage.tsx

44.15% Statements 34/77
29.16% Branches 14/48
25% Functions 8/32
45.33% Lines 34/75

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                                    6x   6x 8x 8x 8x 8x 8x 8x 8x 8x     8x 8x 8x   8x   8x 2x 2x 2x                                       2x     8x 2x     8x 2x 2x   1x       8x                                                                                                   8x                           8x                         8x                                   8x                           8x                             8x                           8x   8x                                                                                                                                                  
import React, { ReactElement, useCallback, useEffect, useState } from "react";
import {Button, Dropdown, Menu, Result, Space, Tabs, Tag, Tooltip} from "antd";
import { useTranslation } from 'react-i18next';
import { fetchCanCreate, getDashboards } from "@utils/FetchUtils";
import { DashboardProps } from "@props/RecordProps";
import { Dashboard } from "./form/dashboard/";
import {
  PlusCircleOutlined, SettingOutlined, ReloadOutlined,
  EditOutlined, FullscreenOutlined
} from "@ant-design/icons";
import { LargeSpin } from "./components";
import { DeleteComponent } from "./form";
import { DynamicFormDomainName } from "@config/domain";
import { RefreshIntervalSelect } from "./form/dashboard";
import RedirectComponent from "./components/redirect/RedirectComponent";
import { useFullScreen } from "@utils/hooks";
import { useTheme } from "@utils/hooks";
 
const { TabPane } = Tabs;
 
const FirstPage = (): ReactElement => {
  const { t } = useTranslation();
  const [current, setCurrent] = useState<DashboardProps>();
  const [showEditDashboardModal, setShowEditDashboardModal] = useState<boolean>(false);
  const [showAddWidgetModal, setShowAddWidgetModal] = useState<boolean>(false);
  const [showAddDashboardModal, setShowAddDashboardModal] = useState<boolean>(false);
  const [dashboards, setDashboards] = useState<Array<DashboardProps>>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [canCreateDashboard, setCanCreateDashboard] = useState<boolean>(false);
  //DESIGN BACKGROUND: triggerDashboardRefresh is use to refresh list of dashboard
  // widgets when user add a new widget to current displaying dashboard
  const [triggerDashboardRefresh, setTriggerDashboardRefresh] = useState<false | number>(false);
  const { fullScreen, toggleFullScreen } = useFullScreen(); // <-- Use the custom hook
  const [refreshIntervals, setRefreshIntervals] = useState<Array<{ id: number; refreshInterval?: number }>>([]);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const themeInfo = useTheme();
 
  const refreshData = useCallback((): void => {
    getDashboards().then(ds => {
      Eif (ds == null || ds.length === 0) {
        return;
      }
      if (current == null) {
        setCurrent(ds?.[0]);
      }
      //If current display dashboard been deleted
      //Set current to first dashboard
      if (current != null && ds?.filter(d => d.id === current?.id).length === 0) {
        setCurrent(ds?.[0]);
      }
      setDashboards(ds);
      //Loop over dashboards and put the extInfo.refreshInterval to a list
      const refreshIntervals: Array<{ id: number; refreshInterval?: number }> = [];
      ds.forEach(d => {
        refreshIntervals.push({ id: d.id, refreshInterval: d.extInfo?.refreshInterval });
      });
      setRefreshIntervals(refreshIntervals);
      //Each time refresh list of data, give triggerDashboardRefresh a random number
      //To trigger dashboard widget list refresh
      setTriggerDashboardRefresh(Math.random());
    }).finally(() => setLoading(false));
  }, [current]);
 
  useEffect(() => {
    refreshData();
  }, [refreshData]);
 
  useEffect(() => {
    fetchCanCreate("DynamicForm")
      .then(json => setCanCreateDashboard(json.create))
      .catch(e => {
        console.error(`Failed to get canCreate of domain DynamicForm: ${e}`);
      });
  }, []);
 
  const getMenu = (d: DashboardProps): ReactElement => (
    <Menu>
      <Menu.Item key="1">
        <span onClick={() => {
          toggleFullScreen();
        }}>
          <FullscreenOutlined /> {t("Fullscreen")}
        </span>
      </Menu.Item>
      <Menu.Item>
        <span onClick={() => {
          setLoading(true);
          refreshData();
        }}><ReloadOutlined /> {t('Refresh data')}</span>
      </Menu.Item>
      {d.canUpdate &&
        <Menu.Item>
          <span onClick={() => setShowEditDashboardModal(true)}>
            <EditOutlined /> {t('Edit dashboard information')}
          </span>
        </Menu.Item>
      }
      {
        d.canCreateWidget &&
        <Menu.Item>
          <span onClick={() => setShowAddWidgetModal(true)}>
            <PlusCircleOutlined /> {t('Add new widget')}
          </span>
        </Menu.Item>
      }
      {
        d.canDelete &&
        <Menu.Item>
          <DeleteComponent
            domainName="DynamicForm"
            id={d.id}
            callback={() => {
              setLoading(true);
              refreshData();
            }}
            trigger="click"
            renderWithoutContainer={true}
            text={t("Delete dashboard")}
          />
        </Menu.Item>
      }
    </Menu >
  );
 
  const createDashboardIcon = (
    <Tooltip
      title={t("Create new dashboard")}
      placement="left"
    >
      <a href="/#" onClick={(e: React.MouseEvent<unknown>) => e.preventDefault()} title={t("Create new dashboard")}>
        <PlusCircleOutlined
          onClick={() => setShowAddDashboardModal(true)}
          className="link-icon"
        />
      </a>
    </Tooltip>
  );
 
  const createDashboardBigIcon = (
    <Result
      title={t("No dashboard defined(or you don't have access to any)")}
      extra={canCreateDashboard && (
        <Button
          type="primary"
          onClick={() => setShowAddDashboardModal(true)}
        >
          Create new dashboard
        </Button>
      )}
    />
  );
 
  const addWidgetModal = <>{showAddWidgetModal &&
    <RedirectComponent
      forMultiple={false}
      fetchDataCallback={() => {
        refreshData();
        setShowAddWidgetModal(false);
      }}
      redirect={`/DynamicDashboardWidget/create`}
      //Use 7 to make sure it appears on top of dashboard widgets
      zIndex={7}
      showText={false}
      ownerClass={DynamicFormDomainName}
      ownerId={current?.id}
      columnNameInOwnerClass="dashboardWidgets"
      hasRelateObjectField={true}
    />
  }</>;
 
  const editDashboardModal = <>{showEditDashboardModal &&
    <RedirectComponent
      forMultiple={false}
      fetchDataCallback={() => {
        refreshData();
        setShowEditDashboardModal(false);
      }}
      redirect={`/DynamicForm/${current?.id}/update`}
      //Use 7 to make sure it appears on top of dashboard widgets
      zIndex={7}
      showText={false}
    />
  }</>;
 
  const addDashboardModal = <>{
    showAddDashboardModal && <RedirectComponent
      forMultiple={false}
      fetchDataCallback={() => {
        refreshData();
        setShowAddDashboardModal(false);
      }}
      redirect={`/DynamicForm/create`}
      //Use 7 to make sure it appears on top of dashboard widgets
      zIndex={7}
      showText={false}
      hasRelateObjectField={false}
    />
  }</>;
 
  const getDashboard = useCallback((dashboardMeta: DashboardProps, isActive: boolean): ReactElement => {
    const myRefreshInterval = refreshIntervals.find(ri => ri.id === dashboardMeta.id)?.refreshInterval;
    return (<>
      {loading && <LargeSpin />}
      {!loading && <Dashboard
          meta={dashboardMeta}
          display={isActive}
          triggerRefresh={triggerDashboardRefresh}
          addWidgetCallback={() => setShowAddWidgetModal(true)}
          refreshInterval={myRefreshInterval}
      />}
    </>);
  },[refreshIntervals, triggerDashboardRefresh, loading]);
 
  const dashboardSkeletonClassName: string = fullScreen? "dashboard-skeleton-fullscreen" : "";
 
  return (
    <div className={`dashboard-skeleton ${dashboardSkeletonClassName}`}>
      {addWidgetModal}
      {editDashboardModal}
      {addDashboardModal}
      {!loading && dashboards.length === 0 && createDashboardBigIcon}
      {
        dashboards.length > 0
        && fullScreen
        && dashboards.filter(d => d.id === current?.id).length > 0
        && getDashboard(dashboards.filter(d => d.id === current?.id)[0], true)
      }
      {dashboards.length > 0 && !fullScreen &&
        <Tabs
          defaultActiveKey={current?.id.toString()}
          activeKey={current?.id.toString()}
          tabBarExtraContent={{
            right: (
              <Space>
                {(canCreateDashboard ? createDashboardIcon : <></>)}
              </Space>
            ),
          }}
        >
          {dashboards?.map(d => {
            const isActive = (current?.id === d.id);
            return (<TabPane
              tab={
                <Space>
                  <span
                    onClick={() => setCurrent(d)}
                  >{d.label ?? d.name}</span>
                  {isActive && (
                      <Space direction="horizontal" size={2}>
                        <Dropdown
                            overlay={getMenu(d)}
                            trigger={["click"]}
                        >
                          <a title={t("Change dashboard settings")}>
                            <Tag><SettingOutlined/>{t('设置')}</Tag>
                          </a>
                        </Dropdown>
                        <RefreshIntervalSelect
                            setRefreshIntervalCallback={(interval?: number) => {
                              //Find the value from refreshIntervals by dashboard id and update it
                              const newRefreshIntervals = [...refreshIntervals];
                              newRefreshIntervals.forEach((ri: { id: number; refreshInterval?: number }) => {
                                if (ri.id == d.id) {
                                  ri.refreshInterval = interval;
                                }
                              });
                              setRefreshIntervals(newRefreshIntervals);
                            }}
                            refreshInterval={refreshIntervals.find(ri => ri.id === d.id)?.refreshInterval}
                        />
                      </Space>
                    )}
                </Space>
              }
              key={d.id.toString()}
            >
              {getDashboard(d, isActive)}
            </TabPane>
            );
          })}
        </Tabs>
      }
    </div>
  );
};
 
export default FirstPage;