Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: new dashboard page is updated (#3385)

Palash Guptae7a5eb7b2228
diff --git a/frontend/public/locales/en-GB/dashboard.json b/frontend/public/locales/en-GB/dashboard.json
index b643f4727d..b69113483d 100644
--- a/frontend/public/locales/en-GB/dashboard.json
+++ b/frontend/public/locales/en-GB/dashboard.json
@@ -13,5 +13,12 @@
"import_dashboard_by_pasting": "Import dashboard by pasting JSON or importing JSON file",
"error_loading_json": "Error loading JSON file",
"empty_json_not_allowed": "Empty JSON is not allowed",
- "new_dashboard_title": "Sample Title"
+ "new_dashboard_title": "Sample Title",
+ "layout_saved_successfully": "Layout saved successfully",
+ "add_panel": "Add Panel",
+ "save_layout": "Save Layout",
+ "variable_updated_successfully": "Variable updated successfully",
+ "error_while_updating_variable": "Error while updating variable",
+ "dashboard_has_been_updated": "Dashboard has been updated",
+ "do_you_want_to_refresh_the_dashboard": "Do you want to refresh the dashboard?"
}
diff --git a/frontend/public/locales/en/dashboard.json b/frontend/public/locales/en/dashboard.json
index b643f4727d..b69113483d 100644
--- a/frontend/public/locales/en/dashboard.json
+++ b/frontend/public/locales/en/dashboard.json
@@ -13,5 +13,12 @@
"import_dashboard_by_pasting": "Import dashboard by pasting JSON or importing JSON file",
"error_loading_json": "Error loading JSON file",
"empty_json_not_allowed": "Empty JSON is not allowed",
- "new_dashboard_title": "Sample Title"
+ "new_dashboard_title": "Sample Title",
+ "layout_saved_successfully": "Layout saved successfully",
+ "add_panel": "Add Panel",
+ "save_layout": "Save Layout",
+ "variable_updated_successfully": "Variable updated successfully",
+ "error_while_updating_variable": "Error while updating variable",
+ "dashboard_has_been_updated": "Dashboard has been updated",
+ "do_you_want_to_refresh_the_dashboard": "Do you want to refresh the dashboard?"
}
diff --git a/frontend/src/AppRoutes/index.tsx b/frontend/src/AppRoutes/index.tsx
index 56ba19fdf4..c2a0db3da1 100644
--- a/frontend/src/AppRoutes/index.tsx
+++ b/frontend/src/AppRoutes/index.tsx
@@ -12,6 +12,7 @@ import useGetFeatureFlag from 'hooks/useGetFeatureFlag';
import { NotificationProvider } from 'hooks/useNotifications';
import { ResourceProvider } from 'hooks/useResourceAttribute';
import history from 'lib/history';
+import { DashboardProvider } from 'providers/Dashboard/Dashboard';
import { QueryBuilderProvider } from 'providers/QueryBuilder';
import { Suspense, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
@@ -110,22 +111,24 @@ function App(): JSX.Element {
<PrivateRoute>
<ResourceProvider>
<QueryBuilderProvider>
- <AppLayout>
- <Suspense fallback={<Spinner size="large" tip="Loading..." />}>
- <Switch>
- {routes.map(({ path, component, exact }) => (
- <Route
- key={`${path}`}
- exact={exact}
- path={path}
- component={component}
- />
- ))}
-
- <Route path="*" component={NotFound} />
- </Switch>
- </Suspense>
- </AppLayout>
+ <DashboardProvider>
+ <AppLayout>
+ <Suspense fallback={<Spinner size="large" tip="Loading..." />}>
+ <Switch>
+ {routes.map(({ path, component, exact }) => (
+ <Route
+ key={`${path}`}
+ exact={exact}
+ path={path}
+ component={component}
+ />
+ ))}
+
+ <Route path="*" component={NotFound} />
+ </Switch>
+ </Suspense>
+ </AppLayout>
+ </DashboardProvider>
</QueryBuilderProvider>
</ResourceProvider>
</PrivateRoute>
diff --git a/frontend/src/api/dashboard/delete.ts b/frontend/src/api/dashboard/delete.ts
index 2f7c8f16b9..8faf711383 100644
--- a/frontend/src/api/dashboard/delete.ts
+++ b/frontend/src/api/dashboard/delete.ts
@@ -1,24 +1,9 @@
import axios from 'api';
-import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
-import { AxiosError } from 'axios';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-import { Props } from 'types/api/dashboard/delete';
+import { PayloadProps, Props } from 'types/api/dashboard/delete';
-const deleteDashboard = async (
- props: Props,
-): Promise<SuccessResponse<undefined> | ErrorResponse> => {
- try {
- const response = await axios.delete(`/dashboards/${props.uuid}`);
-
- return {
- statusCode: 200,
- error: null,
- message: response.data.status,
- payload: response.data.data,
- };
- } catch (error) {
- return ErrorResponseHandler(error as AxiosError);
- }
-};
+const deleteDashboard = (props: Props): Promise<PayloadProps> =>
+ axios
+ .delete<PayloadProps>(`/dashboards/${props.uuid}`)
+ .then((response) => response.data);
export default deleteDashboard;
diff --git a/frontend/src/api/dashboard/get.ts b/frontend/src/api/dashboard/get.ts
index 6c9c953e7d..9b10f6467d 100644
--- a/frontend/src/api/dashboard/get.ts
+++ b/frontend/src/api/dashboard/get.ts
@@ -1,24 +1,11 @@
import axios from 'api';
-import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
-import { AxiosError } from 'axios';
-import { ErrorResponse, SuccessResponse } from 'types/api';
-import { PayloadProps, Props } from 'types/api/dashboard/get';
+import { ApiResponse } from 'types/api';
+import { Props } from 'types/api/dashboard/get';
+import { Dashboard } from 'types/api/dashboard/getAll';
-const get = async (
- props: Props,
-): Promise<SuccessResponse<PayloadProps> | ErrorResponse> => {
- try {
- const response = await axios.get(`/dashboards/${props.uuid}`);
-
- return {
- statusCode: 200,
- error: null,
- message: response.data.status,
- payload: response.data.data,
- };
- } catch (error) {
- return ErrorResponseHandler(error as AxiosError);
- }
-};
+const get = (props: Props): Promise<Dashboard> =>
+ axios
+ .get<ApiResponse<Dashboard>>(`/dashboards/${props.uuid}`)
+ .then((res) => res.data.data);
export default get;
diff --git a/frontend/src/constants/reactQueryKeys.ts b/frontend/src/constants/reactQueryKeys.ts
index 1f984ebd46..9a368510a1 100644
--- a/frontend/src/constants/reactQueryKeys.ts
+++ b/frontend/src/constants/reactQueryKeys.ts
@@ -3,5 +3,7 @@ export const REACT_QUERY_KEY = {
GET_QUERY_RANGE: 'GET_QUERY_RANGE',
GET_ALL_DASHBOARDS: 'GET_ALL_DASHBOARDS',
GET_TRIGGERED_ALERTS: 'GET_TRIGGERED_ALERTS',
+ DASHBOARD_BY_ID: 'DASHBOARD_BY_ID',
GET_FEATURES_FLAGS: 'GET_FEATURES_FLAGS',
+ DELETE_DASHBOARD: 'DELETE_DASHBOARD',
};
diff --git a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx b/frontend/src/container/FormAlertRules/ChartPreview/index.tsx
index f6bf35cbd7..d73003f06e 100644
--- a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx
+++ b/frontend/src/container/FormAlertRules/ChartPreview/index.tsx
@@ -127,7 +127,7 @@ function ChartPreview({
<GridPanelSwitch
panelType={graphType}
title={name}
- data={chartDataSet}
+ data={chartDataSet.data}
isStacked
name={name || 'Chart Preview'}
staticLine={staticLine}
diff --git a/frontend/src/container/GridGraphLayout/EmptyWidget/index.tsx b/frontend/src/container/GridCardLayout/EmptyWidget/index.tsx
similarity index 100%
rename from frontend/src/container/GridGraphLayout/EmptyWidget/index.tsx
rename to frontend/src/container/GridCardLayout/EmptyWidget/index.tsx
diff --git a/frontend/src/container/GridGraphLayout/EmptyWidget/styles.ts b/frontend/src/container/GridCardLayout/EmptyWidget/styles.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/EmptyWidget/styles.ts
rename to frontend/src/container/GridCardLayout/EmptyWidget/styles.ts
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/GraphManager.styles.scss b/frontend/src/container/GridCardLayout/GridCard/FullView/GraphManager.styles.scss
similarity index 100%
rename from frontend/src/container/GridGraphLayout/Graph/FullView/GraphManager.styles.scss
rename to frontend/src/container/GridCardLayout/GridCard/FullView/GraphManager.styles.scss
diff --git a/frontend/src/container/GridCardLayout/GridCard/FullView/GraphManager.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/GraphManager.tsx
new file mode 100644
index 0000000000..e6c6e26c0b
--- /dev/null
+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/GraphManager.tsx
@@ -0,0 +1,136 @@
+import './GraphManager.styles.scss';
+
+import { Button, Input } from 'antd';
+import { CheckboxChangeEvent } from 'antd/es/checkbox';
+import { ResizeTable } from 'components/ResizeTable';
+import { useNotifications } from 'hooks/useNotifications';
+import { memo, useCallback, useState } from 'react';
+
+import { getGraphManagerTableColumns } from './TableRender/GraphManagerColumns';
+import { ExtendedChartDataset, GraphManagerProps } from './types';
+import {
+ getDefaultTableDataSet,
+ saveLegendEntriesToLocalStorage,
+} from './utils';
+
+function GraphManager({
+ data,
+ name,
+ yAxisUnit,
+ onToggleModelHandler,
+ setGraphsVisibilityStates,
+ graphsVisibilityStates = [],
+ lineChartRef,
+ parentChartRef,
+}: GraphManagerProps): JSX.Element {
+ const [tableDataSet, setTableDataSet] = useState<ExtendedChartDataset[]>(
+ getDefaultTableDataSet(data),
+ );
+
+ const { notifications } = useNotifications();
+
+ const checkBoxOnChangeHandler = useCallback(
+ (e: CheckboxChangeEvent, index: number): void => {
+ const newStates = [...graphsVisibilityStates];
+
+ newStates[index] = e.target.checked;
+
+ lineChartRef?.current?.toggleGraph(index, e.target.checked);
+
+ setGraphsVisibilityStates([...newStates]);
+ },
+ [graphsVisibilityStates, setGraphsVisibilityStates, lineChartRef],
+ );
+
+ const labelClickedHandler = useCallback(
+ (labelIndex: number): void => {
+ const newGraphVisibilityStates = Array<boolean>(data.datasets.length).fill(
+ false,
+ );
+ newGraphVisibilityStates[labelIndex] = true;
+
+ newGraphVisibilityStates.forEach((state, index) => {
+ lineChartRef?.current?.toggleGraph(index, state);
+ parentChartRef?.current?.toggleGraph(index, state);
+ });
+ setGraphsVisibilityStates(newGraphVisibilityStates);
+ },
+ [
+ data.datasets.length,
+ setGraphsVisibilityStates,
+ lineChartRef,
+ parentChartRef,
+ ],
+ );
+
+ const columns = getGraphManagerTableColumns({
+ data,
+ checkBoxOnChangeHandler,
+ graphVisibilityState: graphsVisibilityStates || [],
+ labelClickedHandler,
+ yAxisUnit,
+ });
+
+ const filterHandler = useCallback(
+ (event: React.ChangeEvent<HTMLInputElement>): void => {
+ const value = event.target.value.toString().toLowerCase();
+ const updatedDataSet = tableDataSet.map((item) => {
+ if (item.label?.toLocaleLowerCase().includes(value)) {
+ return { ...item, show: true };
+ }
+ return { ...item, show: false };
+ });
+ setTableDataSet(updatedDataSet);
+ },
+ [tableDataSet],
+ );
+
+ const saveHandler = useCallback((): void => {
+ saveLegendEntriesToLocalStorage({
+ data,
+ graphVisibilityState: graphsVisibilityStates || [],
+ name,
+ });
+ notifications.success({
+ message: 'The updated graphs & legends are saved',
+ });
+ if (onToggleModelHandler) {
+ onToggleModelHandler();
+ }
+ }, [data, graphsVisibilityStates, name, notifications, onToggleModelHandler]);
+
+ const dataSource = tableDataSet.filter((item) => item.show);
+
+ return (
+ <div className="graph-manager-container">
+ <div className="filter-table-container">
+ <Input onChange={filterHandler} placeholder="Filter Series" />
+ <ResizeTable
+ columns={columns}
+ dataSource={dataSource}
+ rowKey="index"
+ pagination={false}
+ scroll={{ y: 240 }}
+ />
+ </div>
+ <div className="save-cancel-container">
+ <span className="save-cancel-button">
+ <Button type="default" onClick={onToggleModelHandler}>
+ Cancel
+ </Button>
+ </span>
+ <span className="save-cancel-button">
+ <Button onClick={saveHandler} type="primary">
+ Save
+ </Button>
+ </span>
+ </div>
+ </div>
+ );
+}
+
+GraphManager.defaultProps = {
+ graphVisibilityStateHandler: undefined,
+};
+
+export default memo(GraphManager);
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/CustomCheckBox.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/TableRender/CustomCheckBox.tsx
similarity index 59%
rename from frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/CustomCheckBox.tsx
rename to frontend/src/container/GridCardLayout/GridCard/FullView/TableRender/CustomCheckBox.tsx
index 22ae630bb8..eda971c1e4 100644
--- a/frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/CustomCheckBox.tsx
+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/TableRender/CustomCheckBox.tsx
@@ -1,3 +1,4 @@
+import { grey } from '@ant-design/colors';
import { Checkbox, ConfigProvider } from 'antd';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
@@ -6,7 +7,7 @@ import { CheckBoxProps } from '../types';
function CustomCheckBox({
data,
index,
- graphVisibilityState,
+ graphVisibilityState = [],
checkBoxOnChangeHandler,
}: CheckBoxProps): JSX.Element {
const { datasets } = data;
@@ -15,17 +16,21 @@ function CustomCheckBox({
checkBoxOnChangeHandler(e, index);
};
+ const color = datasets[index]?.borderColor?.toString() || grey[0];
+
+ const isChecked = graphVisibilityState[index] || false;
+
return (
<ConfigProvider
theme={{
token: {
- colorPrimary: datasets[index].borderColor?.toString(),
- colorBorder: datasets[index].borderColor?.toString(),
- colorBgContainer: datasets[index].borderColor?.toString(),
+ colorPrimary: color,
+ colorBorder: color,
+ colorBgContainer: color,
},
}}
>
- <Checkbox onChange={onChangeHandler} checked={graphVisibilityState[index]} />
+ <Checkbox onChange={onChangeHandler} checked={isChecked} />
</ConfigProvider>
);
}
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/GetLabel.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/TableRender/GetLabel.tsx
similarity index 100%
rename from frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/GetLabel.tsx
rename to frontend/src/container/GridCardLayout/GridCard/FullView/TableRender/GetLabel.tsx
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/GraphManagerColumns.ts b/frontend/src/container/GridCardLayout/GridCard/FullView/TableRender/GraphManagerColumns.tsx
similarity index 87%
rename from frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/GraphManagerColumns.ts
rename to frontend/src/container/GridCardLayout/GridCard/FullView/TableRender/GraphManagerColumns.tsx
index cc10f83f00..3702a9b3e0 100644
--- a/frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/GraphManagerColumns.ts
+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/TableRender/GraphManagerColumns.tsx
@@ -5,7 +5,7 @@ import { ChartData } from 'chart.js';
import { ColumnsKeyAndDataIndex, ColumnsTitle } from '../contants';
import { DataSetProps } from '../types';
import { getGraphManagerTableHeaderTitle } from '../utils';
-import { getCheckBox } from './GetCheckBox';
+import CustomCheckBox from './CustomCheckBox';
import { getLabel } from './GetLabel';
export const getGraphManagerTableColumns = ({
@@ -20,11 +20,14 @@ export const getGraphManagerTableColumns = ({
width: 50,
dataIndex: ColumnsKeyAndDataIndex.Index,
key: ColumnsKeyAndDataIndex.Index,
- ...getCheckBox({
- checkBoxOnChangeHandler,
- graphVisibilityState,
- data,
- }),
+ render: (_: string, __: DataSetProps, index: number): JSX.Element => (
+ <CustomCheckBox
+ data={data}
+ index={index}
+ checkBoxOnChangeHandler={checkBoxOnChangeHandler}
+ graphVisibilityState={graphVisibilityState}
+ />
+ ),
},
{
title: ColumnsTitle[ColumnsKeyAndDataIndex.Label],
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/Label.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/TableRender/Label.tsx
similarity index 100%
rename from frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/Label.tsx
rename to frontend/src/container/GridCardLayout/GridCard/FullView/TableRender/Label.tsx
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/contants.ts b/frontend/src/container/GridCardLayout/GridCard/FullView/contants.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/Graph/FullView/contants.ts
rename to frontend/src/container/GridCardLayout/GridCard/FullView/contants.ts
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
similarity index 80%
rename from frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx
rename to frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
index 1437a29157..02391bdc0c 100644
--- a/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx
+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
@@ -12,17 +12,16 @@ import { useStepInterval } from 'hooks/queryBuilder/useStepInterval';
import { useChartMutable } from 'hooks/useChartMutable';
import { getDashboardVariables } from 'lib/dashbaordVariables/getDashboardVariables';
import getChartData from 'lib/getChartData';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
import { GlobalReducer } from 'types/reducer/globalTime';
-import { toggleGraphsVisibilityInChart } from '../utils';
import { PANEL_TYPES_VS_FULL_VIEW_TABLE } from './contants';
import GraphManager from './GraphManager';
import { GraphContainer, TimeContainer } from './styles';
import { FullViewProps } from './types';
-import { getIsGraphLegendToggleAvailable } from './utils';
function FullView({
widget,
@@ -34,45 +33,29 @@ function FullView({
isDependedDataLoaded = false,
graphsVisibilityStates,
onToggleModelHandler,
+ setGraphsVisibilityStates,
+ parentChartRef,
}: FullViewProps): JSX.Element {
const { selectedTime: globalSelectedTime } = useSelector<
AppState,
GlobalReducer
>((state) => state.globalTime);
+ const { selectedDashboard } = useDashboard();
+
const getSelectedTime = useCallback(
() =>
timeItems.find((e) => e.enum === (widget?.timePreferance || 'GLOBAL_TIME')),
[widget],
);
- const canModifyChart = useChartMutable({
- panelType: widget.panelTypes,
- panelTypeAndGraphManagerVisibility: PANEL_TYPES_VS_FULL_VIEW_TABLE,
- });
-
const lineChartRef = useRef<ToggleGraphProps>();
- useEffect(() => {
- if (graphsVisibilityStates && canModifyChart && lineChartRef.current) {
- toggleGraphsVisibilityInChart({
- graphsVisibilityStates,
- lineChartRef,
- });
- }
- }, [graphsVisibilityStates, canModifyChart]);
-
const [selectedTime, setSelectedTime] = useState<timePreferance>({
name: getSelectedTime()?.name || '',
enum: widget?.timePreferance || 'GLOBAL_TIME',
});
- const queryKey = useMemo(
- () =>
- `FullViewGetMetricsQueryRange-${selectedTime.enum}-${globalSelectedTime}-${widget.id}`,
- [selectedTime, globalSelectedTime, widget],
- );
-
const updatedQuery = useStepInterval(widget?.query);
const response = useGetQueryRange(
@@ -81,14 +64,19 @@ function FullView({
graphType: widget.panelTypes,
query: updatedQuery,
globalSelectedInterval: globalSelectedTime,
- variables: getDashboardVariables(),
+ variables: getDashboardVariables(selectedDashboard?.data.variables),
},
{
- queryKey,
+ queryKey: `FullViewGetMetricsQueryRange-${selectedTime.enum}-${globalSelectedTime}-${widget.id}`,
enabled: !isDependedDataLoaded,
},
);
+ const canModifyChart = useChartMutable({
+ panelType: widget.panelTypes,
+ panelTypeAndGraphManagerVisibility: PANEL_TYPES_VS_FULL_VIEW_TABLE,
+ });
+
const chartDataSet = useMemo(
() =>
getChartData({
@@ -101,9 +89,14 @@ function FullView({
[response],
);
- const isGraphLegendToggleAvailable = getIsGraphLegendToggleAvailable(
- widget.panelTypes,
- );
+ useEffect(() => {
+ if (!response.isFetching && lineChartRef.current) {
+ graphsVisibilityStates?.forEach((e, i) => {
+ lineChartRef?.current?.toggleGraph(i, e);
+ parentChartRef?.current?.toggleGraph(i, e);
+ });
+ }
+ }, [graphsVisibilityStates, parentChartRef, response.isFetching]);
if (response.isFetching) {
return <Spinner height="100%" size="large" tip="Loading..." />;
@@ -128,10 +121,10 @@ function FullView({
</TimeContainer>
)}
- <GraphContainer isGraphLegendToggleAvailable={isGraphLegendToggleAvailable}>
+ <GraphContainer isGraphLegendToggleAvailable={canModifyChart}>
<GridPanelSwitch
panelType={widget.panelTypes}
- data={chartDataSet}
+ data={chartDataSet.data}
isStacked={widget.isStacked}
opacity={widget.opacity}
title={widget.title}
@@ -147,10 +140,14 @@ function FullView({
{canModifyChart && (
<GraphManager
- data={chartDataSet}
+ data={chartDataSet.data}
name={name}
yAxisUnit={yAxisUnit}
onToggleModelHandler={onToggleModelHandler}
+ setGraphsVisibilityStates={setGraphsVisibilityStates}
+ graphsVisibilityStates={graphsVisibilityStates}
+ lineChartRef={lineChartRef}
+ parentChartRef={parentChartRef}
/>
)}
</>
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/styles.ts b/frontend/src/container/GridCardLayout/GridCard/FullView/styles.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/Graph/FullView/styles.ts
rename to frontend/src/container/GridCardLayout/GridCard/FullView/styles.ts
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/types.ts b/frontend/src/container/GridCardLayout/GridCard/FullView/types.ts
similarity index 76%
rename from frontend/src/container/GridGraphLayout/Graph/FullView/types.ts
rename to frontend/src/container/GridCardLayout/GridCard/FullView/types.ts
index 7d329e1399..ae686496e5 100644
--- a/frontend/src/container/GridGraphLayout/Graph/FullView/types.ts
+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/types.ts
@@ -1,7 +1,8 @@
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import { ChartData, ChartDataset } from 'chart.js';
-import { GraphOnClickHandler } from 'components/Graph/types';
+import { GraphOnClickHandler, ToggleGraphProps } from 'components/Graph/types';
import { PANEL_TYPES } from 'constants/queryBuilder';
+import { MutableRefObject } from 'react';
import { Widgets } from 'types/api/dashboard/getAll';
export interface DataSetProps {
@@ -40,11 +41,29 @@ export interface LabelProps {
label: string;
}
+export interface FullViewProps {
+ widget: Widgets;
+ fullViewOptions?: boolean;
+ onClickHandler?: GraphOnClickHandler;
+ name: string;
+ yAxisUnit?: string;
+ onDragSelect?: (start: number, end: number) => void;
+ isDependedDataLoaded?: boolean;
+ graphsVisibilityStates?: boolean[];
+ onToggleModelHandler?: GraphManagerProps['onToggleModelHandler'];
+ setGraphsVisibilityStates: (graphsVisibilityStates: boolean[]) => void;
+ parentChartRef: GraphManagerProps['lineChartRef'];
+}
+
export interface GraphManagerProps {
data: ChartData;
name: string;
yAxisUnit?: string;
onToggleModelHandler?: () => void;
+ setGraphsVisibilityStates: FullViewProps['setGraphsVisibilityStates'];
+ graphsVisibilityStates: FullViewProps['graphsVisibilityStates'];
+ lineChartRef?: MutableRefObject<ToggleGraphProps | undefined>;
+ parentChartRef?: MutableRefObject<ToggleGraphProps | undefined>;
}
export interface CheckBoxProps {
@@ -54,18 +73,6 @@ export interface CheckBoxProps {
checkBoxOnChangeHandler: (e: CheckboxChangeEvent, index: number) => void;
}
-export interface FullViewProps {
- widget: Widgets;
- fullViewOptions?: boolean;
- onClickHandler?: GraphOnClickHandler;
- name: string;
- yAxisUnit?: string;
- onDragSelect?: (start: number, end: number) => void;
- isDependedDataLoaded?: boolean;
- graphsVisibilityStates?: boolean[];
- onToggleModelHandler?: GraphManagerProps['onToggleModelHandler'];
-}
-
export interface SaveLegendEntriesToLocalStoreProps {
data: ChartData;
graphVisibilityState: boolean[];
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/utils.ts b/frontend/src/container/GridCardLayout/GridCard/FullView/utils.ts
similarity index 94%
rename from frontend/src/container/GridGraphLayout/Graph/FullView/utils.ts
rename to frontend/src/container/GridCardLayout/GridCard/FullView/utils.ts
index 256bc39050..b1ffb3a032 100644
--- a/frontend/src/container/GridGraphLayout/Graph/FullView/utils.ts
+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/utils.ts
@@ -1,6 +1,5 @@
import { ChartData, ChartDataset } from 'chart.js';
import { LOCALSTORAGE } from 'constants/localStorage';
-import { PANEL_TYPES } from 'constants/queryBuilder';
import {
ExtendedChartDataset,
@@ -110,10 +109,6 @@ export const saveLegendEntriesToLocalStorage = ({
}
};
-export const getIsGraphLegendToggleAvailable = (
- panelType: PANEL_TYPES,
-): boolean => panelType === PANEL_TYPES.TIME_SERIES;
-
export const getGraphManagerTableHeaderTitle = (
title: string,
yAxisUnit?: string,
diff --git a/frontend/src/container/GridGraphLayout/Graph/Graph.test.tsx b/frontend/src/container/GridCardLayout/GridCard/Graph.test.tsx
similarity index 100%
rename from frontend/src/container/GridGraphLayout/Graph/Graph.test.tsx
rename to frontend/src/container/GridCardLayout/GridCard/Graph.test.tsx
diff --git a/frontend/src/container/GridCardLayout/GridCard/WidgetGraphComponent.tsx b/frontend/src/container/GridCardLayout/GridCard/WidgetGraphComponent.tsx
new file mode 100644
index 0000000000..c011ca2471
--- /dev/null
+++ b/frontend/src/container/GridCardLayout/GridCard/WidgetGraphComponent.tsx
@@ -0,0 +1,277 @@
+import { Typography } from 'antd';
+import { ToggleGraphProps } from 'components/Graph/types';
+import { SOMETHING_WENT_WRONG } from 'constants/api';
+import GridPanelSwitch from 'container/GridPanelSwitch';
+import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
+import { useNotifications } from 'hooks/useNotifications';
+import createQueryParams from 'lib/createQueryParams';
+import history from 'lib/history';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import { useSelector } from 'react-redux';
+import { useLocation } from 'react-router-dom';
+import { AppState } from 'store/reducers';
+import { Dashboard } from 'types/api/dashboard/getAll';
+import AppReducer from 'types/reducer/app';
+import { v4 } from 'uuid';
+
+import WidgetHeader from '../WidgetHeader';
+import FullView from './FullView';
+import { FullViewContainer, Modal } from './styles';
+import { WidgetGraphComponentProps } from './types';
+import { getGraphVisibilityStateOnDataChange } from './utils';
+
+function WidgetGraphComponent({
+ data,
+ widget,
+ queryResponse,
+ errorMessage,
+ name,
+ onDragSelect,
+ onClickHandler,
+ threshold,
+ headerMenuList,
+ isWarning,
+}: WidgetGraphComponentProps): JSX.Element {
+ const [deleteModal, setDeleteModal] = useState(false);
+ const [modal, setModal] = useState<boolean>(false);
+ const [hovered, setHovered] = useState(false);
+ const { notifications } = useNotifications();
+ const { pathname } = useLocation();
+
+ const lineChartRef = useRef<ToggleGraphProps>();
+
+ const { graphVisibilityStates: localStoredVisibilityStates } = useMemo(
+ () =>
+ getGraphVisibilityStateOnDataChange({
+ data,
+ isExpandedName: true,
+ name,
+ }),
+ [data, name],
+ );
+
+ useEffect(() => {
+ if (!lineChartRef.current) return;
+
+ localStoredVisibilityStates.forEach((state, index) => {
+ lineChartRef.current?.toggleGraph(index, state);
+ });
+ }, [localStoredVisibilityStates]);
+
+ const { setLayouts, selectedDashboard, setSelectedDashboard } = useDashboard();
+
+ const [graphsVisibilityStates, setGraphsVisibilityStates] = useState<
+ boolean[]
+ >(localStoredVisibilityStates);
+
+ const { featureResponse } = useSelector<AppState, AppReducer>(
+ (state) => state.app,
+ );
+ const onToggleModal = useCallback(
+ (func: Dispatch<SetStateAction<boolean>>) => {
+ func((value) => !value);
+ },
+ [],
+ );
+
+ const updateDashboardMutation = useUpdateDashboard();
+
+ const onDeleteHandler = (): void => {
+ if (!selectedDashboard) return;
+
+ const updatedWidgets = selectedDashboard?.data?.widgets?.filter(
+ (e) => e.id !== widget.id,
+ );
+
+ const updatedLayout =
+ selectedDashboard.data.layout?.filter((e) => e.i !== widget.id) || [];
+
+ const updatedSelectedDashboard: Dashboard = {
+ ...selectedDashboard,
+ data: {
+ ...selectedDashboard.data,
+ widgets: updatedWidgets,
+ layout: updatedLayout,
+ },
+ uuid: selectedDashboard.uuid,
+ };
+
+ updateDashboardMutation.mutateAsync(updatedSelectedDashboard, {
+ onSuccess: (updatedDashboard) => {
+ if (setLayouts) setLayouts(updatedDashboard.payload?.data?.layout || []);
+ if (setSelectedDashboard && updatedDashboard.payload) {
+ setSelectedDashboard(updatedDashboard.payload);
+ }
+ featureResponse.refetch();
+ },
+ onError: () => {
+ notifications.error({
+ message: SOMETHING_WENT_WRONG,
+ });
+ },
+ });
+ };
+
+ const onCloneHandler = async (): Promise<void> => {
+ if (!selectedDashboard) return;
+
+ const uuid = v4();
+
+ const layout = [
+ ...(selectedDashboard.data.layout || []),
+ {
+ i: uuid,
+ w: 6,
+ x: 0,
+ h: 2,
+ y: 0,
+ },
+ ];
+
+ updateDashboardMutation.mutateAsync(
+ {
+ ...selectedDashboard,
+ data: {
+ ...selectedDashboard.data,
+ layout,
+ widgets: [
+ ...(selectedDashboard.data.widgets || []),
+ {
+ ...{
+ ...widget,
+ id: uuid,
+ },
+ },
+ ],
+ },
+ },
+ {
+ onSuccess: () => {
+ notifications.success({
+ message: 'Panel cloned successfully, redirecting to new copy.',
+ });
+ const queryParams = {
+ graphType: widget?.panelTypes,
+ widgetId: uuid,
+ };
+ history.push(`${pathname}/new?${createQueryParams(queryParams)}`);
+ },
+ },
+ );
+ };
+
+ const handleOnView = (): void => {
+ onToggleModal(setModal);
+ };
+
+ const handleOnDelete = (): void => {
+ onToggleModal(setDeleteModal);
+ };
+
+ const onDeleteModelHandler = (): void => {
+ onToggleModal(setDeleteModal);
+ };
+
+ const onToggleModelHandler = (): void => {
+ onToggleModal(setModal);
+ };
+
+ return (
+ <span
+ onMouseOver={(): void => {
+ setHovered(true);
+ }}
+ onFocus={(): void => {
+ setHovered(true);
+ }}
+ onMouseOut={(): void => {
+ setHovered(false);
+ }}
+ onBlur={(): void => {
+ setHovered(false);
+ }}
+ >
+ <Modal
+ destroyOnClose
+ onCancel={onDeleteModelHandler}
+ open={deleteModal}
+ title="Delete"
+ height="10vh"
+ onOk={onDeleteHandler}
+ centered
+ >
+ <Typography>Are you sure you want to delete this widget</Typography>
+ </Modal>
+
+ <Modal
+ title="View"
+ footer={[]}
+ centered
+ open={modal}
+ onCancel={onToggleModelHandler}
+ width="85%"
+ destroyOnClose
+ >
+ <FullViewContainer>
+ <FullView
+ name={`${name}expanded`}
+ widget={widget}
+ yAxisUnit={widget.yAxisUnit}
+ graphsVisibilityStates={graphsVisibilityStates}
+ onToggleModelHandler={onToggleModelHandler}
+ setGraphsVisibilityStates={setGraphsVisibilityStates}
+ parentChartRef={lineChartRef}
+ />
+ </FullViewContainer>
+ </Modal>
+
+ <div className="drag-handle">
+ <WidgetHeader
+ parentHover={hovered}
+ title={widget?.title}
+ widget={widget}
+ onView={handleOnView}
+ onDelete={handleOnDelete}
+ onClone={onCloneHandler}
+ queryResponse={queryResponse}
+ errorMessage={errorMessage}
+ threshold={threshold}
+ headerMenuList={headerMenuList}
+ isWarning={isWarning}
+ />
+ </div>
+ <GridPanelSwitch
+ panelType={widget.panelTypes}
+ data={data}
+ isStacked={widget.isStacked}
+ opacity={widget.opacity}
+ title={' '}
+ name={name}
+ yAxisUnit={widget.yAxisUnit}
+ onClickHandler={onClickHandler}
+ onDragSelect={onDragSelect}
+ panelData={queryResponse.data?.payload?.data.newResult.data.result || []}
+ query={widget.query}
+ ref={lineChartRef}
+ />
+ </span>
+ );
+}
+
+WidgetGraphComponent.defaultProps = {
+ yAxisUnit: undefined,
+ setLayout: undefined,
+ onDragSelect: undefined,
+ onClickHandler: undefined,
+};
+
+export default WidgetGraphComponent;
diff --git a/frontend/src/container/GridGraphLayout/Graph/__mock__/mockChartData.ts b/frontend/src/container/GridCardLayout/GridCard/__mock__/mockChartData.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/Graph/__mock__/mockChartData.ts
rename to frontend/src/container/GridCardLayout/GridCard/__mock__/mockChartData.ts
diff --git a/frontend/src/container/GridGraphLayout/Graph/__mock__/mockLegendEntryData.ts b/frontend/src/container/GridCardLayout/GridCard/__mock__/mockLegendEntryData.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/Graph/__mock__/mockLegendEntryData.ts
rename to frontend/src/container/GridCardLayout/GridCard/__mock__/mockLegendEntryData.ts
diff --git a/frontend/src/container/GridCardLayout/GridCard/index.tsx b/frontend/src/container/GridCardLayout/GridCard/index.tsx
new file mode 100644
index 0000000000..59e58fb74a
--- /dev/null
+++ b/frontend/src/container/GridCardLayout/GridCard/index.tsx
@@ -0,0 +1,133 @@
+import { Skeleton } from 'antd';
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
+import { useStepInterval } from 'hooks/queryBuilder/useStepInterval';
+import { getDashboardVariables } from 'lib/dashbaordVariables/getDashboardVariables';
+import getChartData from 'lib/getChartData';
+import isEmpty from 'lodash-es/isEmpty';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { memo, useMemo, useState } from 'react';
+import { useInView } from 'react-intersection-observer';
+import { useDispatch, useSelector } from 'react-redux';
+import { UpdateTimeInterval } from 'store/actions';
+import { AppState } from 'store/reducers';
+import { GlobalReducer } from 'types/reducer/globalTime';
+
+import EmptyWidget from '../EmptyWidget';
+import { MenuItemKeys } from '../WidgetHeader/contants';
+import { GridCardGraphProps } from './types';
+import WidgetGraphComponent from './WidgetGraphComponent';
+
+function GridCardGraph({
+ widget,
+ name,
+ onClickHandler,
+ headerMenuList = [MenuItemKeys.View],
+ isQueryEnabled,
+ threshold,
+}: GridCardGraphProps): JSX.Element {
+ const dispatch = useDispatch();
+ const [errorMessage, setErrorMessage] = useState<string>();
+
+ const onDragSelect = (start: number, end: number): void => {
+ const startTimestamp = Math.trunc(start);
+ const endTimestamp = Math.trunc(end);
+
+ if (startTimestamp !== endTimestamp) {
+ dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
+ }
+ };
+
+ const { ref: graphRef, inView: isGraphVisible } = useInView({
+ threshold: 0,
+ triggerOnce: true,
+ initialInView: false,
+ });
+
+ const { selectedDashboard } = useDashboard();
+
+ const { minTime, maxTime, selectedTime: globalSelectedInterval } = useSelector<
+ AppState,
+ GlobalReducer
+ >((state) => state.globalTime);
+
+ const updatedQuery = useStepInterval(widget?.query);
+
+ const isEmptyWidget =
+ widget?.id === PANEL_TYPES.EMPTY_WIDGET || isEmpty(widget);
+
+ const queryResponse = useGetQueryRange(
+ {
+ selectedTime: widget?.timePreferance,
+ graphType: widget?.panelTypes,
+ query: updatedQuery,
+ globalSelectedInterval,
+ variables: getDashboardVariables(selectedDashboard?.data.variables),
+ },
+ {
+ queryKey: [
+ maxTime,
+ minTime,
+ globalSelectedInterval,
+ selectedDashboard?.data?.variables,
+ widget?.query,
+ widget?.panelTypes,
+ ],
+ keepPreviousData: true,
+ enabled: isGraphVisible && !isEmptyWidget && isQueryEnabled,
+ refetchOnMount: false,
+ onError: (error) => {
+ setErrorMessage(error.message);
+ },
+ },
+ );
+
+ const chartData = useMemo(
+ () =>
+ getChartData({
+ queryData: [
+ {
+ queryData: queryResponse?.data?.payload?.data?.result || [],
+ },
+ ],
+ createDataset: undefined,
+ isWarningLimit: true,
+ }),
+ [queryResponse],
+ );
+
+ const isEmptyLayout = widget?.id === PANEL_TYPES.EMPTY_WIDGET;
+
+ if (queryResponse.isLoading) {
+ return <Skeleton />;
+ }
+
+ return (
+ <span ref={graphRef}>
+ <WidgetGraphComponent
+ widget={widget}
+ queryResponse={queryResponse}
+ errorMessage={errorMessage}
+ data={chartData.data}
+ isWarning={chartData.isWarning}
+ name={name}
+ onDragSelect={onDragSelect}
+ threshold={threshold}
+ headerMenuList={headerMenuList}
+ onClickHandler={onClickHandler}
+ />
+
+ {isEmptyLayout && <EmptyWidget />}
+ </span>
+ );
+}
+
+GridCardGraph.defaultProps = {
+ onDragSelect: undefined,
+ onClickHandler: undefined,
+ isQueryEnabled: true,
+ threshold: undefined,
+ headerMenuList: [MenuItemKeys.View],
+};
+
+export default memo(GridCardGraph);
diff --git a/frontend/src/container/GridGraphLayout/Graph/styles.ts b/frontend/src/container/GridCardLayout/GridCard/styles.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/Graph/styles.ts
rename to frontend/src/container/GridCardLayout/GridCard/styles.ts
diff --git a/frontend/src/container/GridGraphLayout/Graph/types.ts b/frontend/src/container/GridCardLayout/GridCard/types.ts
similarity index 67%
rename from frontend/src/container/GridGraphLayout/Graph/types.ts
rename to frontend/src/container/GridCardLayout/GridCard/types.ts
index 49b637a178..fccf488dc8 100644
--- a/frontend/src/container/GridGraphLayout/Graph/types.ts
+++ b/frontend/src/container/GridCardLayout/GridCard/types.ts
@@ -1,15 +1,11 @@
import { ChartData } from 'chart.js';
import { GraphOnClickHandler, ToggleGraphProps } from 'components/Graph/types';
-import { Dispatch, MutableRefObject, ReactNode, SetStateAction } from 'react';
-import { Layout } from 'react-grid-layout';
+import { MutableRefObject, ReactNode } from 'react';
import { UseQueryResult } from 'react-query';
-import { DeleteWidgetProps } from 'store/actions/dashboard/deleteWidget';
-import AppActions from 'types/actions';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { Widgets } from 'types/api/dashboard/getAll';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
-import { LayoutProps } from '..';
import { MenuItemKeys } from '../WidgetHeader/contants';
import { LegendEntryProps } from './FullView/types';
@@ -18,15 +14,7 @@ export interface GraphVisibilityLegendEntryProps {
legendEntry: LegendEntryProps[];
}
-export interface DispatchProps {
- deleteWidget: ({
- widgetId,
- }: DeleteWidgetProps) => (dispatch: Dispatch<AppActions>) => void;
-}
-
-export interface WidgetGraphComponentProps extends DispatchProps {
- enableModel: boolean;
- enableWidgetHeader: boolean;
+export interface WidgetGraphComponentProps {
widget: Widgets;
queryResponse: UseQueryResult<
SuccessResponse<MetricRangePayloadProps> | ErrorResponse
@@ -34,21 +22,16 @@ export interface WidgetGraphComponentProps extends DispatchProps {
errorMessage: string | undefined;
data: ChartData;
name: string;
- yAxisUnit?: string;
- layout?: Layout[];
- setLayout?: Dispatch<SetStateAction<LayoutProps[]>>;
onDragSelect?: (start: number, end: number) => void;
onClickHandler?: GraphOnClickHandler;
threshold?: ReactNode;
headerMenuList: MenuItemKeys[];
+ isWarning: boolean;
}
export interface GridCardGraphProps {
widget: Widgets;
name: string;
- yAxisUnit: string | undefined;
- layout?: Layout[];
- setLayout?: Dispatch<SetStateAction<LayoutProps[]>>;
onDragSelect?: (start: number, end: number) => void;
onClickHandler?: GraphOnClickHandler;
threshold?: ReactNode;
diff --git a/frontend/src/container/GridGraphLayout/Graph/utils.ts b/frontend/src/container/GridCardLayout/GridCard/utils.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/Graph/utils.ts
rename to frontend/src/container/GridCardLayout/GridCard/utils.ts
diff --git a/frontend/src/container/GridCardLayout/GridCardLayout.tsx b/frontend/src/container/GridCardLayout/GridCardLayout.tsx
new file mode 100644
index 0000000000..ac60e54146
--- /dev/null
+++ b/frontend/src/container/GridCardLayout/GridCardLayout.tsx
@@ -0,0 +1,131 @@
+import { PlusOutlined, SaveFilled } from '@ant-design/icons';
+import { SOMETHING_WENT_WRONG } from 'constants/api';
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
+import useComponentPermission from 'hooks/useComponentPermission';
+import { useIsDarkMode } from 'hooks/useDarkMode';
+import { useNotifications } from 'hooks/useNotifications';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { useTranslation } from 'react-i18next';
+import { useSelector } from 'react-redux';
+import { AppState } from 'store/reducers';
+import { Dashboard, Widgets } from 'types/api/dashboard/getAll';
+import AppReducer from 'types/reducer/app';
+
+import { headerMenuList } from './config';
+import GridCard from './GridCard';
+import {
+ Button,
+ ButtonContainer,
+ Card,
+ CardContainer,
+ ReactGridLayout,
+} from './styles';
+import { GraphLayoutProps } from './types';
+
+function GraphLayout({
+ onAddPanelHandler,
+ widgets,
+}: GraphLayoutProps): JSX.Element {
+ const { selectedDashboard, layouts, setLayouts } = useDashboard();
+ const { t } = useTranslation(['dashboard']);
+
+ const { featureResponse, role } = useSelector<AppState, AppReducer>(
+ (state) => state.app,
+ );
+
+ const isDarkMode = useIsDarkMode();
+
+ const updateDashboardMutation = useUpdateDashboard();
+
+ const { notifications } = useNotifications();
+
+ const [saveLayoutPermission, addPanelPermission] = useComponentPermission(
+ ['save_layout', 'add_panel'],
+ role,
+ );
+
+ const onSaveHandler = (): void => {
+ if (!selectedDashboard) return;
+
+ const updatedDashboard: Dashboard = {
+ ...selectedDashboard,
+ data: {
+ ...selectedDashboard.data,
+ layout: layouts.filter((e) => e.i !== PANEL_TYPES.EMPTY_WIDGET),
+ },
+ uuid: selectedDashboard.uuid,
+ };
+
+ updateDashboardMutation.mutate(updatedDashboard, {
+ onSuccess: () => {
+ featureResponse.refetch();
+
+ notifications.success({
+ message: t('dashboard:layout_saved_successfully'),
+ });
+ },
+ onError: () => {
+ notifications.error({
+ message: SOMETHING_WENT_WRONG,
+ });
+ },
+ });
+ };
+
+ return (
+ <>
+ <ButtonContainer>
+ {saveLayoutPermission && (
+ <Button
+ loading={updateDashboardMutation.isLoading}
+ onClick={onSaveHandler}
+ icon={<SaveFilled />}
+ disabled={updateDashboardMutation.isLoading}
+ >
+ {t('dashboard:save_layout')}
+ </Button>
+ )}
+
+ {addPanelPermission && (
+ <Button onClick={onAddPanelHandler} icon={<PlusOutlined />}>
+ {t('dashboard:add_panel')}
+ </Button>
+ )}
+ </ButtonContainer>
+
+ <ReactGridLayout
+ cols={12}
+ rowHeight={100}
+ autoSize
+ width={100}
+ isDraggable={addPanelPermission}
+ isDroppable={addPanelPermission}
+ isResizable={addPanelPermission}
+ allowOverlap={false}
+ onLayoutChange={setLayouts}
+ draggableHandle=".drag-handle"
+ layout={layouts}
+ >
+ {layouts.map((layout) => {
+ const { i: id } = layout;
+ const currentWidget = (widgets || [])?.find((e) => e.id === id);
+
+ return (
+ <CardContainer isDarkMode={isDarkMode} key={id} data-grid={layout}>
+ <Card $panelType={currentWidget?.panelTypes || PANEL_TYPES.TIME_SERIES}>
+ <GridCard
+ widget={currentWidget || ({ id } as Widgets)}
+ name={currentWidget?.id || ''}
+ headerMenuList={headerMenuList}
+ />
+ </Card>
+ </CardContainer>
+ );
+ })}
+ </ReactGridLayout>
+ </>
+ );
+}
+
+export default GraphLayout;
diff --git a/frontend/src/container/GridGraphLayout/WidgetHeader/DisplayThreshold.tsx b/frontend/src/container/GridCardLayout/WidgetHeader/DisplayThreshold.tsx
similarity index 100%
rename from frontend/src/container/GridGraphLayout/WidgetHeader/DisplayThreshold.tsx
rename to frontend/src/container/GridCardLayout/WidgetHeader/DisplayThreshold.tsx
diff --git a/frontend/src/container/GridGraphLayout/WidgetHeader/config.ts b/frontend/src/container/GridCardLayout/WidgetHeader/config.ts
similarity index 61%
rename from frontend/src/container/GridGraphLayout/WidgetHeader/config.ts
rename to frontend/src/container/GridCardLayout/WidgetHeader/config.ts
index 1e15697049..68e9dd5b6c 100644
--- a/frontend/src/container/GridGraphLayout/WidgetHeader/config.ts
+++ b/frontend/src/container/GridCardLayout/WidgetHeader/config.ts
@@ -3,7 +3,11 @@ import { CSSProperties } from 'react';
const positionCss: CSSProperties['position'] = 'absolute';
-export const spinnerStyles = { position: positionCss, right: '0.5rem' };
+export const spinnerStyles = {
+ position: positionCss,
+ top: '0',
+ right: '0',
+};
export const tooltipStyles = {
fontSize: '1rem',
top: '0.313rem',
@@ -21,3 +25,6 @@ export const overlayStyles: CSSProperties = {
justifyContent: 'center',
position: 'absolute',
};
+
+export const WARNING_MESSAGE =
+ 'Too many timeseries in the result. UI has restricted to showing the top 20. Please check the query if this is needed and contact [email protected] if you need to show >20 timeseries in the panel';
diff --git a/frontend/src/container/GridGraphLayout/WidgetHeader/contants.ts b/frontend/src/container/GridCardLayout/WidgetHeader/contants.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/WidgetHeader/contants.ts
rename to frontend/src/container/GridCardLayout/WidgetHeader/contants.ts
diff --git a/frontend/src/container/GridGraphLayout/WidgetHeader/index.tsx b/frontend/src/container/GridCardLayout/WidgetHeader/index.tsx
similarity index 92%
rename from frontend/src/container/GridGraphLayout/WidgetHeader/index.tsx
rename to frontend/src/container/GridCardLayout/WidgetHeader/index.tsx
index 20ad222e55..a916534082 100644
--- a/frontend/src/container/GridGraphLayout/WidgetHeader/index.tsx
+++ b/frontend/src/container/GridCardLayout/WidgetHeader/index.tsx
@@ -5,10 +5,12 @@ import {
EditFilled,
ExclamationCircleOutlined,
FullscreenOutlined,
+ WarningOutlined,
} from '@ant-design/icons';
import { Dropdown, MenuProps, Tooltip, Typography } from 'antd';
import Spinner from 'components/Spinner';
import { QueryParams } from 'constants/query';
+import { PANEL_TYPES } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import useComponentPermission from 'hooks/useComponentPermission';
import history from 'lib/history';
@@ -27,6 +29,7 @@ import {
overlayStyles,
spinnerStyles,
tooltipStyles,
+ WARNING_MESSAGE,
} from './config';
import { MENUITEM_KEYS_VS_LABELS, MenuItemKeys } from './contants';
import {
@@ -52,6 +55,7 @@ interface IWidgetHeaderProps {
errorMessage: string | undefined;
threshold?: ReactNode;
headerMenuList?: MenuItemKeys[];
+ isWarning: boolean;
}
function WidgetHeader({
@@ -65,7 +69,8 @@ function WidgetHeader({
errorMessage,
threshold,
headerMenuList,
-}: IWidgetHeaderProps): JSX.Element {
+ isWarning,
+}: IWidgetHeaderProps): JSX.Element | null {
const [localHover, setLocalHover] = useState(false);
const [isOpen, setIsOpen] = useState<boolean>(false);
@@ -126,7 +131,7 @@ function WidgetHeader({
icon: <FullscreenOutlined />,
label: MENUITEM_KEYS_VS_LABELS[MenuItemKeys.View],
isVisible: headerMenuList?.includes(MenuItemKeys.View) || false,
- disabled: queryResponse.isLoading,
+ disabled: queryResponse.isFetching,
},
{
key: MenuItemKeys.Edit,
@@ -158,7 +163,7 @@ function WidgetHeader({
disabled: false,
},
],
- [queryResponse.isLoading, headerMenuList, editWidget, deleteWidget],
+ [headerMenuList, queryResponse.isFetching, editWidget, deleteWidget],
);
const updatedMenuList = useMemo(() => generateMenuList(actions), [actions]);
@@ -175,6 +180,10 @@ function WidgetHeader({
[updatedMenuList, onMenuItemSelectHandler],
);
+ if (widget.id === PANEL_TYPES.EMPTY_WIDGET) {
+ return null;
+ }
+
return (
<WidgetHeaderContainer>
<Dropdown
@@ -202,6 +211,7 @@ function WidgetHeader({
</HeaderContentContainer>
</HeaderContainer>
</Dropdown>
+
<ThesholdContainer>{threshold}</ThesholdContainer>
{queryResponse.isFetching && !queryResponse.isError && (
<Spinner height="5vh" style={spinnerStyles} />
@@ -211,6 +221,12 @@ function WidgetHeader({
<ExclamationCircleOutlined style={tooltipStyles} />
</Tooltip>
)}
+
+ {isWarning && (
+ <Tooltip title={WARNING_MESSAGE} placement={errorTooltipPosition}>
+ <WarningOutlined style={tooltipStyles} />
+ </Tooltip>
+ )}
</WidgetHeaderContainer>
);
}
diff --git a/frontend/src/container/GridGraphLayout/WidgetHeader/styles.ts b/frontend/src/container/GridCardLayout/WidgetHeader/styles.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/WidgetHeader/styles.ts
rename to frontend/src/container/GridCardLayout/WidgetHeader/styles.ts
diff --git a/frontend/src/container/GridGraphLayout/WidgetHeader/types.ts b/frontend/src/container/GridCardLayout/WidgetHeader/types.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/WidgetHeader/types.ts
rename to frontend/src/container/GridCardLayout/WidgetHeader/types.ts
diff --git a/frontend/src/container/GridGraphLayout/WidgetHeader/utils.ts b/frontend/src/container/GridCardLayout/WidgetHeader/utils.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/WidgetHeader/utils.ts
rename to frontend/src/container/GridCardLayout/WidgetHeader/utils.ts
diff --git a/frontend/src/container/GridCardLayout/config.ts b/frontend/src/container/GridCardLayout/config.ts
new file mode 100644
index 0000000000..3fa9e8e569
--- /dev/null
+++ b/frontend/src/container/GridCardLayout/config.ts
@@ -0,0 +1,17 @@
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import { MenuItemKeys } from 'container/GridCardLayout/WidgetHeader/contants';
+
+export const headerMenuList = [
+ MenuItemKeys.View,
+ MenuItemKeys.Clone,
+ MenuItemKeys.Delete,
+ MenuItemKeys.Edit,
+];
+
+export const EMPTY_WIDGET_LAYOUT = {
+ i: PANEL_TYPES.EMPTY_WIDGET,
+ w: 6,
+ x: 0,
+ h: 2,
+ y: 0,
+};
diff --git a/frontend/src/container/GridCardLayout/index.tsx b/frontend/src/container/GridCardLayout/index.tsx
new file mode 100644
index 0000000000..e715d7d539
--- /dev/null
+++ b/frontend/src/container/GridCardLayout/index.tsx
@@ -0,0 +1,35 @@
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { useCallback } from 'react';
+import { Layout } from 'react-grid-layout';
+
+import { EMPTY_WIDGET_LAYOUT } from './config';
+import GraphLayoutContainer from './GridCardLayout';
+
+function GridGraph(): JSX.Element {
+ const {
+ selectedDashboard,
+ setLayouts,
+ handleToggleDashboardSlider,
+ } = useDashboard();
+
+ const { data } = selectedDashboard || {};
+ const { widgets } = data || {};
+
+ const onEmptyWidgetHandler = useCallback(() => {
+ handleToggleDashboardSlider(true);
+
+ setLayouts((preLayout: Layout[]) => [
+ EMPTY_WIDGET_LAYOUT,
+ ...(preLayout || []),
+ ]);
+ }, [handleToggleDashboardSlider, setLayouts]);
+
+ return (
+ <GraphLayoutContainer
+ onAddPanelHandler={onEmptyWidgetHandler}
+ widgets={widgets}
+ />
+ );
+}
+
+export default GridGraph;
diff --git a/frontend/src/container/GridGraphLayout/styles.ts b/frontend/src/container/GridCardLayout/styles.ts
similarity index 100%
rename from frontend/src/container/GridGraphLayout/styles.ts
rename to frontend/src/container/GridCardLayout/styles.ts
diff --git a/frontend/src/container/GridCardLayout/types.ts b/frontend/src/container/GridCardLayout/types.ts
new file mode 100644
index 0000000000..0d2b678af6
--- /dev/null
+++ b/frontend/src/container/GridCardLayout/types.ts
@@ -0,0 +1,6 @@
+import { Widgets } from 'types/api/dashboard/getAll';
+
+export interface GraphLayoutProps {
+ onAddPanelHandler: VoidFunction;
+ widgets?: Widgets[];
+}
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/GraphManager.tsx b/frontend/src/container/GridGraphLayout/Graph/FullView/GraphManager.tsx
deleted file mode 100644
index 31f528a410..0000000000
--- a/frontend/src/container/GridGraphLayout/Graph/FullView/GraphManager.tsx
+++ /dev/null
@@ -1,203 +0,0 @@
-import './GraphManager.styles.scss';
-
-import { Button, Input } from 'antd';
-import { CheckboxChangeEvent } from 'antd/es/checkbox';
-import { ResizeTable } from 'components/ResizeTable';
-import { Events } from 'constants/events';
-import { useNotifications } from 'hooks/useNotifications';
-import isEqual from 'lodash-es/isEqual';
-import { memo, useCallback, useEffect, useMemo, useState } from 'react';
-import { eventEmitter } from 'utils/getEventEmitter';
-
-import { getGraphVisibilityStateOnDataChange } from '../utils';
-import { getGraphManagerTableColumns } from './TableRender/GraphManagerColumns';
-import { ExtendedChartDataset, GraphManagerProps } from './types';
-import {
- getDefaultTableDataSet,
- saveLegendEntriesToLocalStorage,
-} from './utils';
-
-function GraphManager({
- data,
- name,
- yAxisUnit,
- onToggleModelHandler,
-}: GraphManagerProps): JSX.Element {
- const {
- graphVisibilityStates: localstoredVisibilityStates,
- legendEntry,
- } = useMemo(
- () =>
- getGraphVisibilityStateOnDataChange({
- data,
- isExpandedName: false,
- name,
- }),
- [data, name],
- );
-
- const [graphVisibilityState, setGraphVisibilityState] = useState<boolean[]>(
- localstoredVisibilityStates,
- );
-
- const [tableDataSet, setTableDataSet] = useState<ExtendedChartDataset[]>(
- getDefaultTableDataSet(data),
- );
-
- const { notifications } = useNotifications();
-
- // useEffect for updating graph visibility state on data change
- useEffect(() => {
- const newGraphVisibilityStates = Array<boolean>(data.datasets.length).fill(
- true,
- );
- data.datasets.forEach((dataset, i) => {
- const index = legendEntry.findIndex(
- (entry) => entry.label === dataset.label,
- );
- if (index !== -1) {
- newGraphVisibilityStates[i] = legendEntry[index].show;
- }
- });
- eventEmitter.emit(Events.UPDATE_GRAPH_VISIBILITY_STATE, {
- name,
- graphVisibilityStates: newGraphVisibilityStates,
- });
- setGraphVisibilityState(newGraphVisibilityStates);
- }, [data, name, legendEntry]);
-
- // useEffect for listening to events event graph legend is clicked
- useEffect(() => {
- const eventListener = eventEmitter.on(
- Events.UPDATE_GRAPH_MANAGER_TABLE,
- (data) => {
- if (data.name === name) {
- const newGraphVisibilityStates = graphVisibilityState;
- newGraphVisibilityStates[data.index] = !newGraphVisibilityStates[
- data.index
- ];
- eventEmitter.emit(Events.UPDATE_GRAPH_VISIBILITY_STATE, {
- name,
- graphVisibilityStates: newGraphVisibilityStates,
- });
- setGraphVisibilityState([...newGraphVisibilityStates]);
- }
- },
- );
- return (): void => {
- eventListener.off(Events.UPDATE_GRAPH_MANAGER_TABLE);
- };
- }, [graphVisibilityState, name]);
-
- const checkBoxOnChangeHandler = useCallback(
- (e: CheckboxChangeEvent, index: number): void => {
- graphVisibilityState[index] = e.target.checked;
- setGraphVisibilityState([...graphVisibilityState]);
- eventEmitter.emit(Events.UPDATE_GRAPH_VISIBILITY_STATE, {
- name,
- graphVisibilityStates: [...graphVisibilityState],
- });
- },
- [graphVisibilityState, name],
- );
-
- const labelClickedHandler = useCallback(
- (labelIndex: number): void => {
- const newGraphVisibilityStates = Array<boolean>(data.datasets.length).fill(
- false,
- );
- newGraphVisibilityStates[labelIndex] = true;
- setGraphVisibilityState([...newGraphVisibilityStates]);
- eventEmitter.emit(Events.UPDATE_GRAPH_VISIBILITY_STATE, {
- name,
- graphVisibilityStates: newGraphVisibilityStates,
- });
- },
- [data.datasets.length, name],
- );
-
- const columns = useMemo(
- () =>
- getGraphManagerTableColumns({
- data,
- checkBoxOnChangeHandler,
- graphVisibilityState,
- labelClickedHandler,
- yAxisUnit,
- }),
- [
- checkBoxOnChangeHandler,
- data,
- graphVisibilityState,
- labelClickedHandler,
- yAxisUnit,
- ],
- );
-
- const filterHandler = useCallback(
- (event: React.ChangeEvent<HTMLInputElement>): void => {
- const value = event.target.value.toString().toLowerCase();
- const updatedDataSet = tableDataSet.map((item) => {
- if (item.label?.toLocaleLowerCase().includes(value)) {
- return { ...item, show: true };
- }
- return { ...item, show: false };
- });
- setTableDataSet(updatedDataSet);
- },
- [tableDataSet],
- );
-
- const saveHandler = useCallback((): void => {
- saveLegendEntriesToLocalStorage({
- data,
- graphVisibilityState,
- name,
- });
- notifications.success({
- message: 'The updated graphs & legends are saved',
- });
- if (onToggleModelHandler) {
- onToggleModelHandler();
- }
- }, [data, graphVisibilityState, name, notifications, onToggleModelHandler]);
-
- const dataSource = tableDataSet.filter((item) => item.show);
-
- return (
- <div className="graph-manager-container">
- <div className="filter-table-container">
- <Input onChange={filterHandler} placeholder="Filter Series" />
- <ResizeTable
- columns={columns}
- dataSource={dataSource}
- rowKey="index"
- pagination={false}
- scroll={{ y: 200 }}
- />
- </div>
- <div className="save-cancel-container">
- <span className="save-cancel-button">
- <Button type="default" onClick={onToggleModelHandler}>
- Cancel
- </Button>
- </span>
- <span className="save-cancel-button">
- <Button onClick={saveHandler} type="primary">
- Save
- </Button>
- </span>
- </div>
- </div>
- );
-}
-
-GraphManager.defaultProps = {
- graphVisibilityStateHandler: undefined,
-};
-
-export default memo(
- GraphManager,
- (prevProps, nextProps) =>
- isEqual(prevProps.data, nextProps.data) && prevProps.name === nextProps.name,
-);
diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/GetCheckBox.tsx b/frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/GetCheckBox.tsx
deleted file mode 100644
index 55485be5ad..0000000000
--- a/frontend/src/container/GridGraphLayout/Graph/FullView/TableRender/GetCheckBox.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { CheckboxChangeEvent } from 'antd/es/checkbox';
-import { ColumnType } from 'antd/es/table';
-import { ChartData } from 'chart.js';
-
-import { DataSetProps } from '../types';
-import CustomCheckBox from './CustomCheckBox';
-
-export const getCheckBox = ({
- data,
- checkBoxOnChangeHandler,
- graphVisibilityState,
-}: GetCheckBoxProps): ColumnType<DataSetProps> => ({
- render: (index: number): JSX.Element => (
- <CustomCheckBox
- data={data}
- index={index}
- checkBoxOnChangeHandler={checkBoxOnChangeHandler}
- graphVisibilityState={graphVisibilityState}
- />
- ),
-});
-
-interface GetCheckBoxProps {
- data: ChartData;
- checkBoxOnChangeHandler: (e: CheckboxChangeEvent, index: number) => void;
- graphVisibilityState: boolean[];
-}
diff --git a/frontend/src/container/GridGraphLayout/Graph/WidgetGraphComponent.tsx b/frontend/src/container/GridGraphLayout/Graph/WidgetGraphComponent.tsx
deleted file mode 100644
index f40d1e4190..0000000000
--- a/frontend/src/container/GridGraphLayout/Graph/WidgetGraphComponent.tsx
+++ /dev/null
@@ -1,334 +0,0 @@
-import { Typography } from 'antd';
-import { ToggleGraphProps } from 'components/Graph/types';
-import { Events } from 'constants/events';
-import GridPanelSwitch from 'container/GridPanelSwitch';
-import { useChartMutable } from 'hooks/useChartMutable';
-import { useNotifications } from 'hooks/useNotifications';
-import createQueryParams from 'lib/createQueryParams';
-import history from 'lib/history';
-import { isEmpty, isEqual } from 'lodash-es';
-import {
- Dispatch,
- memo,
- SetStateAction,
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from 'react';
-import { useTranslation } from 'react-i18next';
-import { connect, useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
-import { bindActionCreators } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
-import { DeleteWidget } from 'store/actions/dashboard/deleteWidget';
-import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
-import AppReducer from 'types/reducer/app';
-import DashboardReducer from 'types/reducer/dashboards';
-import { eventEmitter } from 'utils/getEventEmitter';
-import { v4 } from 'uuid';
-
-import { UpdateDashboard } from '../utils';
-import WidgetHeader from '../WidgetHeader';
-import FullView from './FullView';
-import { PANEL_TYPES_VS_FULL_VIEW_TABLE } from './FullView/contants';
-import { FullViewContainer, Modal } from './styles';
-import { DispatchProps, WidgetGraphComponentProps } from './types';
-import {
- getGraphVisibilityStateOnDataChange,
- toggleGraphsVisibilityInChart,
-} from './utils';
-
-function WidgetGraphComponent({
- enableModel,
- enableWidgetHeader,
- data,
- widget,
- queryResponse,
- errorMessage,
- name,
- yAxisUnit,
- layout = [],
- deleteWidget,
- setLayout,
- onDragSelect,
- onClickHandler,
- threshold,
- headerMenuList,
-}: WidgetGraphComponentProps): JSX.Element {
- const [deleteModal, setDeleteModal] = useState(false);
- const [modal, setModal] = useState<boolean>(false);
- const [hovered, setHovered] = useState(false);
- const { notifications } = useNotifications();
- const { t } = useTranslation(['common']);
- const { pathname } = useLocation();
-
- const { graphVisibilityStates: localstoredVisibilityStates } = useMemo(
- () =>
- getGraphVisibilityStateOnDataChange({
- data,
- isExpandedName: true,
- name,
- }),
- [data, name],
- );
-
- const [graphsVisibilityStates, setGraphsVisilityStates] = useState<boolean[]>(
- localstoredVisibilityStates,
- );
-
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
- const [selectedDashboard] = dashboards;
-
- const canModifyChart = useChartMutable({
- panelType: widget.panelTypes,
- panelTypeAndGraphManagerVisibility: PANEL_TYPES_VS_FULL_VIEW_TABLE,
- });
-
- const lineChartRef = useRef<ToggleGraphProps>();
-
- // Updating the visibility state of the graph on data change according to global time range
- useEffect(() => {
- if (canModifyChart) {
- const newGraphVisibilityState = getGraphVisibilityStateOnDataChange({
- data,
- isExpandedName: true,
- name,
- });
- setGraphsVisilityStates(newGraphVisibilityState.graphVisibilityStates);
- }
- }, [canModifyChart, data, name]);
-
- useEffect(() => {
- const eventListener = eventEmitter.on(
- Events.UPDATE_GRAPH_VISIBILITY_STATE,
- (data) => {
- if (data.name === `${name}expanded` && canModifyChart) {
- setGraphsVisilityStates([...data.graphVisibilityStates]);
- }
- },
- );
- return (): void => {
- eventListener.off(Events.UPDATE_GRAPH_VISIBILITY_STATE);
- };
- }, [canModifyChart, name]);
-
- useEffect(() => {
- if (canModifyChart && lineChartRef.current) {
- toggleGraphsVisibilityInChart({
- graphsVisibilityStates,
- lineChartRef,
- });
- }
- }, [graphsVisibilityStates, canModifyChart]);
-
- const { featureResponse } = useSelector<AppState, AppReducer>(
- (state) => state.app,
- );
- const onToggleModal = useCallback(
- (func: Dispatch<SetStateAction<boolean>>) => {
- func((value) => !value);
- },
- [],
- );
-
- const onDeleteHandler = useCallback(() => {
- const isEmptyWidget = widget?.id === 'empty' || isEmpty(widget);
- const widgetId = isEmptyWidget ? layout[0].i : widget?.id;
-
- featureResponse
- .refetch()
- .then(() => {
- deleteWidget({ widgetId, setLayout });
- onToggleModal(setDeleteModal);
- })
- .catch(() => {
- notifications.error({
- message: t('common:something_went_wrong'),
- });
- });
- }, [
- widget,
- layout,
- featureResponse,
- deleteWidget,
- setLayout,
- onToggleModal,
- notifications,
- t,
- ]);
-
- const onCloneHandler = async (): Promise<void> => {
- const uuid = v4();
-
- const layout = [
- {
- i: uuid,
- w: 6,
- x: 0,
- h: 2,
- y: 0,
- },
- ...(selectedDashboard.data.layout || []),
- ];
-
- if (widget) {
- await UpdateDashboard(
- {
- data: selectedDashboard.data,
- generateWidgetId: uuid,
- graphType: widget?.panelTypes,
- selectedDashboard,
- layout,
- widgetData: widget,
- isRedirected: false,
- },
- notifications,
- ).then(() => {
- notifications.success({
- message: 'Panel cloned successfully, redirecting to new copy.',
- });
-
- const queryParams = {
- graphType: widget?.panelTypes,
- widgetId: uuid,
- };
- history.push(`${pathname}/new?${createQueryParams(queryParams)}`);
- });
- }
- };
-
- const handleOnView = (): void => {
- onToggleModal(setModal);
- };
-
- const handleOnDelete = (): void => {
- onToggleModal(setDeleteModal);
- };
-
- const onDeleteModelHandler = (): void => {
- onToggleModal(setDeleteModal);
- };
-
- const onToggleModelHandler = (): void => {
- onToggleModal(setModal);
- };
-
- const getModals = (): JSX.Element => (
- <>
- <Modal
- destroyOnClose
- onCancel={onDeleteModelHandler}
- open={deleteModal}
- title="Delete"
- height="10vh"
- onOk={onDeleteHandler}
- centered
- >
- <Typography>Are you sure you want to delete this widget</Typography>
- </Modal>
-
- <Modal
- title="View"
- footer={[]}
- centered
- open={modal}
- onCancel={onToggleModelHandler}
- width="85%"
- destroyOnClose
- >
- <FullViewContainer>
- <FullView
- name={`${name}expanded`}
- widget={widget}
- yAxisUnit={yAxisUnit}
- graphsVisibilityStates={graphsVisibilityStates}
- onToggleModelHandler={onToggleModelHandler}
- />
- </FullViewContainer>
- </Modal>
- </>
- );
-
- return (
- <span
- onMouseOver={(): void => {
- setHovered(true);
- }}
- onFocus={(): void => {
- setHovered(true);
- }}
- onMouseOut={(): void => {
- setHovered(false);
- }}
- onBlur={(): void => {
- setHovered(false);
- }}
- >
- {enableModel && getModals()}
- {!isEmpty(widget) && data && (
- <>
- {enableWidgetHeader && (
- <div className="drag-handle">
- <WidgetHeader
- parentHover={hovered}
- title={widget?.title}
- widget={widget}
- onView={handleOnView}
- onDelete={handleOnDelete}
- onClone={onCloneHandler}
- queryResponse={queryResponse}
- errorMessage={errorMessage}
- threshold={threshold}
- headerMenuList={headerMenuList}
- />
- </div>
- )}
- <GridPanelSwitch
- panelType={widget.panelTypes}
- data={data}
- isStacked={widget.isStacked}
- opacity={widget.opacity}
- title={' '}
- name={name}
- yAxisUnit={yAxisUnit}
- onClickHandler={onClickHandler}
- onDragSelect={onDragSelect}
- panelData={queryResponse.data?.payload?.data.newResult.data.result || []}
- query={widget.query}
- ref={lineChartRef}
- />
- </>
- )}
- </span>
- );
-}
-
-WidgetGraphComponent.defaultProps = {
- yAxisUnit: undefined,
- layout: undefined,
- setLayout: undefined,
- onDragSelect: undefined,
- onClickHandler: undefined,
-};
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- deleteWidget: bindActionCreators(DeleteWidget, dispatch),
-});
-
-export default connect(
- null,
- mapDispatchToProps,
-)(
- memo(
- WidgetGraphComponent,
- (prevProps, nextProps) =>
- isEqual(prevProps.data, nextProps.data) && prevProps.name === nextProps.name,
- ),
-);
diff --git a/frontend/src/container/GridGraphLayout/Graph/index.tsx b/frontend/src/container/GridGraphLayout/Graph/index.tsx
deleted file mode 100644
index 94b9d10252..0000000000
--- a/frontend/src/container/GridGraphLayout/Graph/index.tsx
+++ /dev/null
@@ -1,187 +0,0 @@
-import { ChartData } from 'chart.js';
-import Spinner from 'components/Spinner';
-import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
-import { useStepInterval } from 'hooks/queryBuilder/useStepInterval';
-import usePreviousValue from 'hooks/usePreviousValue';
-import { getDashboardVariables } from 'lib/dashbaordVariables/getDashboardVariables';
-import getChartData from 'lib/getChartData';
-import isEmpty from 'lodash-es/isEmpty';
-import { memo, useMemo, useState } from 'react';
-import { useInView } from 'react-intersection-observer';
-import { useSelector } from 'react-redux';
-import { AppState } from 'store/reducers';
-import DashboardReducer from 'types/reducer/dashboards';
-import { GlobalReducer } from 'types/reducer/globalTime';
-import { getSelectedDashboardVariable } from 'utils/dashboard/selectedDashboard';
-
-import EmptyWidget from '../EmptyWidget';
-import { MenuItemKeys } from '../WidgetHeader/contants';
-import { GridCardGraphProps } from './types';
-import WidgetGraphComponent from './WidgetGraphComponent';
-
-function GridCardGraph({
- widget,
- name,
- yAxisUnit,
- layout = [],
- setLayout,
- onDragSelect,
- onClickHandler,
- headerMenuList = [MenuItemKeys.View],
- isQueryEnabled,
- threshold,
-}: GridCardGraphProps): JSX.Element {
- const { isAddWidget } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
-
- const { ref: graphRef, inView: isGraphVisible } = useInView({
- threshold: 0,
- triggerOnce: true,
- initialInView: false,
- });
-
- const [errorMessage, setErrorMessage] = useState<string | undefined>('');
-
- const { minTime, maxTime, selectedTime: globalSelectedInterval } = useSelector<
- AppState,
- GlobalReducer
- >((state) => state.globalTime);
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
-
- const variables = getSelectedDashboardVariable(dashboards);
-
- const updatedQuery = useStepInterval(widget?.query);
-
- const isEmptyWidget = useMemo(
- () => widget?.id === 'empty' || isEmpty(widget),
- [widget],
- );
-
- const queryResponse = useGetQueryRange(
- {
- selectedTime: widget?.timePreferance,
- graphType: widget?.panelTypes,
- query: updatedQuery,
- globalSelectedInterval,
- variables: getDashboardVariables(),
- },
- {
- queryKey: [
- `GetMetricsQueryRange-${widget?.timePreferance}-${globalSelectedInterval}-${widget?.id}`,
- maxTime,
- minTime,
- globalSelectedInterval,
- variables,
- widget?.query,
- widget?.panelTypes,
- ],
- keepPreviousData: true,
- enabled: isGraphVisible && !isEmptyWidget && isQueryEnabled && !isAddWidget,
- refetchOnMount: false,
- onError: (error) => {
- setErrorMessage(error.message);
- },
- },
- );
-
- const chartData = useMemo(
- () =>
- getChartData({
- queryData: [
- {
- queryData: queryResponse?.data?.payload?.data?.result || [],
- },
- ],
- }),
- [queryResponse],
- );
-
- const prevChartDataSetRef = usePreviousValue<ChartData>(chartData);
-
- const isEmptyLayout = widget?.id === 'empty' || isEmpty(widget);
-
- if (queryResponse.isRefetching || queryResponse.isLoading) {
- return <Spinner height="20vh" tip="Loading..." />;
- }
-
- if ((queryResponse.isError && !isEmptyLayout) || !isQueryEnabled) {
- return (
- <span ref={graphRef}>
- {!isEmpty(widget) && prevChartDataSetRef && (
- <WidgetGraphComponent
- enableModel
- enableWidgetHeader
- widget={widget}
- queryResponse={queryResponse}
- errorMessage={errorMessage}
- data={prevChartDataSetRef}
- name={name}
- yAxisUnit={yAxisUnit}
- layout={layout}
- setLayout={setLayout}
- threshold={threshold}
- headerMenuList={headerMenuList}
- />
- )}
- </span>
- );
- }
-
- if (!isEmpty(widget) && prevChartDataSetRef?.labels) {
- return (
- <span ref={graphRef}>
- <WidgetGraphComponent
- enableModel
- enableWidgetHeader
- widget={widget}
- queryResponse={queryResponse}
- errorMessage={errorMessage}
- data={prevChartDataSetRef}
- name={name}
- yAxisUnit={yAxisUnit}
- layout={layout}
- setLayout={setLayout}
- threshold={threshold}
- headerMenuList={headerMenuList}
- onClickHandler={onClickHandler}
- />
- </span>
- );
- }
-
- return (
- <span ref={graphRef}>
- {!isEmpty(widget) && !!queryResponse.data?.payload && (
- <WidgetGraphComponent
- enableModel={!isEmptyLayout}
- enableWidgetHeader={!isEmptyLayout}
- widget={widget}
- queryResponse={queryResponse}
- errorMessage={errorMessage}
- data={chartData}
- name={name}
- yAxisUnit={yAxisUnit}
- onDragSelect={onDragSelect}
- threshold={threshold}
- headerMenuList={headerMenuList}
- onClickHandler={onClickHandler}
- />
- )}
-
- {isEmptyLayout && <EmptyWidget />}
- </span>
- );
-}
-
-GridCardGraph.defaultProps = {
- onDragSelect: undefined,
- onClickHandler: undefined,
- isQueryEnabled: true,
- threshold: undefined,
- headerMenuList: [MenuItemKeys.View],
-};
-
-export default memo(GridCardGraph);
diff --git a/frontend/src/container/GridGraphLayout/GraphLayout.tsx b/frontend/src/container/GridGraphLayout/GraphLayout.tsx
deleted file mode 100644
index 6fc6aca63f..0000000000
--- a/frontend/src/container/GridGraphLayout/GraphLayout.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-import { PlusOutlined, SaveFilled } from '@ant-design/icons';
-import { PANEL_TYPES } from 'constants/queryBuilder';
-import useComponentPermission from 'hooks/useComponentPermission';
-import { useIsDarkMode } from 'hooks/useDarkMode';
-import { Dispatch, SetStateAction } from 'react';
-import { Layout } from 'react-grid-layout';
-import { useSelector } from 'react-redux';
-import { AppState } from 'store/reducers';
-import { Widgets } from 'types/api/dashboard/getAll';
-import AppReducer from 'types/reducer/app';
-import DashboardReducer from 'types/reducer/dashboards';
-
-import { LayoutProps, State } from '.';
-import {
- Button,
- ButtonContainer,
- Card,
- CardContainer,
- ReactGridLayout,
-} from './styles';
-
-function GraphLayout({
- layouts,
- saveLayoutState,
- onLayoutSaveHandler,
- addPanelLoading,
- onAddPanelHandler,
- onLayoutChangeHandler,
- widgets,
- setLayout,
-}: GraphLayoutProps): JSX.Element {
- const { isAddWidget } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
- const { role } = useSelector<AppState, AppReducer>((state) => state.app);
- const isDarkMode = useIsDarkMode();
-
- const [saveLayoutPermission, addPanelPermission] = useComponentPermission(
- ['save_layout', 'add_panel'],
- role,
- );
-
- return (
- <>
- <ButtonContainer>
- {saveLayoutPermission && (
- <Button
- loading={saveLayoutState.loading}
- onClick={(): Promise<void> => onLayoutSaveHandler(layouts)}
- icon={<SaveFilled />}
- danger={saveLayoutState.error}
- >
- Save Layout
- </Button>
- )}
-
- {addPanelPermission && (
- <Button
- loading={addPanelLoading}
- disabled={addPanelLoading || isAddWidget}
- onClick={onAddPanelHandler}
- icon={<PlusOutlined />}
- >
- Add Panel
- </Button>
- )}
- </ButtonContainer>
-
- <ReactGridLayout
- cols={12}
- rowHeight={100}
- autoSize
- width={100}
- isDraggable={addPanelPermission}
- isDroppable={addPanelPermission}
- isResizable={addPanelPermission}
- useCSSTransforms
- allowOverlap={false}
- onLayoutChange={onLayoutChangeHandler}
- draggableHandle=".drag-handle"
- >
- {layouts.map(({ Component, ...rest }) => {
- const currentWidget = (widgets || [])?.find((e) => e.id === rest.i);
-
- return (
- <CardContainer
- isDarkMode={isDarkMode}
- key={currentWidget?.id || 'empty'} // don't change this key
- data-grid={rest}
- >
- <Card $panelType={currentWidget?.panelTypes || PANEL_TYPES.TIME_SERIES}>
- <Component setLayout={setLayout} />
- </Card>
- </CardContainer>
- );
- })}
- </ReactGridLayout>
- </>
- );
-}
-
-interface GraphLayoutProps {
- layouts: LayoutProps[];
- saveLayoutState: State;
- onLayoutSaveHandler: (layout: Layout[]) => Promise<void>;
- addPanelLoading: boolean;
- onAddPanelHandler: VoidFunction;
- onLayoutChangeHandler: (layout: Layout[]) => Promise<void>;
- widgets: Widgets[] | undefined;
- setLayout: Dispatch<SetStateAction<LayoutProps[]>>;
-}
-
-export default GraphLayout;
diff --git a/frontend/src/container/GridGraphLayout/config.ts b/frontend/src/container/GridGraphLayout/config.ts
deleted file mode 100644
index 0357c7795c..0000000000
--- a/frontend/src/container/GridGraphLayout/config.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { MenuItemKeys } from 'container/GridGraphLayout/WidgetHeader/contants';
-
-export const headerMenuList = [
- MenuItemKeys.View,
- MenuItemKeys.Clone,
- MenuItemKeys.Delete,
- MenuItemKeys.Edit,
-];
diff --git a/frontend/src/container/GridGraphLayout/index.tsx b/frontend/src/container/GridGraphLayout/index.tsx
deleted file mode 100644
index fe65154fd9..0000000000
--- a/frontend/src/container/GridGraphLayout/index.tsx
+++ /dev/null
@@ -1,383 +0,0 @@
-/* eslint-disable react/no-unstable-nested-components */
-
-import updateDashboardApi from 'api/dashboard/update';
-import { PANEL_TYPES } from 'constants/queryBuilder';
-import useComponentPermission from 'hooks/useComponentPermission';
-import { useNotifications } from 'hooks/useNotifications';
-import {
- Dispatch,
- SetStateAction,
- useCallback,
- useEffect,
- useState,
-} from 'react';
-import { Layout } from 'react-grid-layout';
-import { useTranslation } from 'react-i18next';
-import { connect, useDispatch, useSelector } from 'react-redux';
-import { bindActionCreators, Dispatch as ReduxDispatch } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
-import { AppDispatch } from 'store';
-import { UpdateTimeInterval } from 'store/actions';
-import {
- ToggleAddWidget,
- ToggleAddWidgetProps,
-} from 'store/actions/dashboard/toggleAddWidget';
-import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
-import { UPDATE_DASHBOARD } from 'types/actions/dashboard';
-import { Dashboard, Widgets } from 'types/api/dashboard/getAll';
-import AppReducer from 'types/reducer/app';
-import DashboardReducer from 'types/reducer/dashboards';
-
-import { headerMenuList } from './config';
-import Graph from './Graph';
-import GraphLayoutContainer from './GraphLayout';
-import { UpdateDashboard } from './utils';
-
-export const getPreLayouts = (
- widgets: Widgets[] | undefined,
- layout: Layout[],
-): LayoutProps[] =>
- layout.map((e, index) => ({
- ...e,
- Component: ({ setLayout }: ComponentProps): JSX.Element => {
- const widget = widgets?.find((widget) => widget.id === e.i);
-
- return (
- <Graph
- name={e.i + index}
- widget={widget as Widgets}
- yAxisUnit={widget?.yAxisUnit}
- layout={layout}
- setLayout={setLayout}
- headerMenuList={headerMenuList}
- />
- );
- },
- }));
-
-function GridGraph(props: Props): JSX.Element {
- const { toggleAddWidget } = props;
- const [addPanelLoading, setAddPanelLoading] = useState(false);
- const { t } = useTranslation(['common']);
- const { dashboards, isAddWidget } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
- const { role } = useSelector<AppState, AppReducer>((state) => state.app);
-
- const [saveLayoutPermission] = useComponentPermission(['save_layout'], role);
- const [saveLayoutState, setSaveLayoutState] = useState<State>({
- loading: false,
- error: false,
- errorMessage: '',
- payload: [],
- });
- const [selectedDashboard] = dashboards;
- const { data } = selectedDashboard;
- const { widgets } = data;
- const dispatch: AppDispatch = useDispatch<ReduxDispatch<AppActions>>();
-
- const [layouts, setLayout] = useState<LayoutProps[]>(
- getPreLayouts(widgets, selectedDashboard.data.layout || []),
- );
-
- const onDragSelect = useCallback(
- (start: number, end: number) => {
- const startTimestamp = Math.trunc(start);
- const endTimestamp = Math.trunc(end);
-
- if (startTimestamp !== endTimestamp) {
- dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
- }
- },
- [dispatch],
- );
-
- const { notifications } = useNotifications();
-
- useEffect(() => {
- (async (): Promise<void> => {
- if (!isAddWidget) {
- const isEmptyLayoutPresent = layouts.find((e) => e.i === 'empty');
- if (isEmptyLayoutPresent) {
- // non empty layout
- const updatedLayout = layouts.filter((e) => e.i !== 'empty');
- // non widget
- const updatedWidget = widgets?.filter((e) => e.id !== 'empty');
- setLayout(updatedLayout);
-
- const updatedDashboard: Dashboard = {
- ...selectedDashboard,
- data: {
- ...selectedDashboard.data,
- layout: updatedLayout,
- widgets: updatedWidget,
- },
- };
-
- await updateDashboardApi({
- data: updatedDashboard.data,
- uuid: updatedDashboard.uuid,
- });
-
- dispatch({
- type: UPDATE_DASHBOARD,
- payload: updatedDashboard,
- });
- }
- }
- })();
- }, [dispatch, isAddWidget, layouts, selectedDashboard, widgets]);
-
- const { featureResponse } = useSelector<AppState, AppReducer>(
- (state) => state.app,
- );
-
- const errorMessage = t('common:something_went_wrong');
-
- const onLayoutSaveHandler = useCallback(
- async (layout: Layout[]) => {
- try {
- setSaveLayoutState((state) => ({
- ...state,
- error: false,
- errorMessage: '',
- loading: true,
- }));
-
- featureResponse
- .refetch()
- .then(async () => {
- const updatedDashboard: Dashboard = {
- ...selectedDashboard,
- data: {
- title: data.title,
- description: data.description,
- name: data.name,
- tags: data.tags,
- widgets: data.widgets,
- variables: data.variables,
- layout,
- },
- uuid: selectedDashboard.uuid,
- };
- // Save layout only when users has the has the permission to do so.
- if (saveLayoutPermission) {
- const response = await updateDashboardApi(updatedDashboard);
- if (response.statusCode === 200) {
- setSaveLayoutState((state) => ({
- ...state,
- error: false,
- errorMessage: '',
- loading: false,
- }));
- dispatch({
- type: UPDATE_DASHBOARD,
- payload: updatedDashboard,
- });
- } else {
- setSaveLayoutState((state) => ({
- ...state,
- error: true,
- errorMessage: response.error || errorMessage,
- loading: false,
- }));
- }
- }
- })
- .catch(() => {
- setSaveLayoutState((state) => ({
- ...state,
- error: true,
- errorMessage,
- loading: false,
- }));
- notifications.error({
- message: errorMessage,
- });
- });
- } catch (error) {
- notifications.error({
- message: errorMessage,
- });
- }
- },
- [
- data.description,
- data.name,
- data.tags,
- data.title,
- data.variables,
- data.widgets,
- dispatch,
- errorMessage,
- featureResponse,
- notifications,
- saveLayoutPermission,
- selectedDashboard,
- ],
- );
-
- const setLayoutFunction = useCallback(
- (layout: Layout[]) => {
- setLayout(
- layout.map((e) => {
- const currentWidget =
- widgets?.find((widget) => widget.id === e.i) || ({} as Widgets);
-
- return {
- ...e,
- Component: (): JSX.Element => (
- <Graph
- name={currentWidget.id}
- widget={currentWidget}
- yAxisUnit={currentWidget?.yAxisUnit}
- layout={layout}
- setLayout={setLayout}
- onDragSelect={onDragSelect}
- headerMenuList={headerMenuList}
- />
- ),
- };
- }),
- );
- },
- [widgets, onDragSelect],
- );
-
- const onEmptyWidgetHandler = useCallback(async () => {
- try {
- const id = 'empty';
-
- const layout = [
- {
- i: id,
- w: 6,
- x: 0,
- h: 2,
- y: 0,
- },
- ...(data.layout || []),
- ];
-
- await UpdateDashboard(
- {
- data,
- generateWidgetId: id,
- graphType: PANEL_TYPES.EMPTY_WIDGET,
- selectedDashboard,
- layout,
- isRedirected: false,
- },
- notifications,
- );
-
- setLayoutFunction(layout);
- } catch (error) {
- notifications.error({
- message: error instanceof Error ? error.toString() : errorMessage,
- });
- }
- }, [data, selectedDashboard, setLayoutFunction, notifications, errorMessage]);
-
- const onLayoutChangeHandler = async (layout: Layout[]): Promise<void> => {
- setLayoutFunction(layout);
-
- // await onLayoutSaveHandler(layout);
- };
-
- const onAddPanelHandler = useCallback(() => {
- try {
- setAddPanelLoading(true);
- featureResponse
- .refetch()
- .then(() => {
- const isEmptyLayoutPresent =
- layouts.find((e) => e.i === 'empty') !== undefined;
-
- if (!isEmptyLayoutPresent) {
- onEmptyWidgetHandler()
- .then(() => {
- setAddPanelLoading(false);
- toggleAddWidget(true);
- })
- .catch(() => {
- notifications.error({
- message: errorMessage,
- });
- });
- } else {
- toggleAddWidget(true);
- setAddPanelLoading(false);
- }
- })
- .catch(() =>
- notifications.error({
- message: errorMessage,
- }),
- );
- } catch (error) {
- notifications.error({
- message: errorMessage,
- });
- }
- }, [
- featureResponse,
- layouts,
- onEmptyWidgetHandler,
- toggleAddWidget,
- notifications,
- errorMessage,
- ]);
-
- useEffect(
- () => (): void => {
- toggleAddWidget(false);
- },
- [toggleAddWidget],
- );
-
- return (
- <GraphLayoutContainer
- addPanelLoading={addPanelLoading}
- layouts={layouts}
- onAddPanelHandler={onAddPanelHandler}
- onLayoutChangeHandler={onLayoutChangeHandler}
- onLayoutSaveHandler={onLayoutSaveHandler}
- saveLayoutState={saveLayoutState}
- setLayout={setLayout}
- widgets={widgets}
- />
- );
-}
-
-interface ComponentProps {
- setLayout: Dispatch<SetStateAction<LayoutProps[]>>;
-}
-
-export interface LayoutProps extends Layout {
- Component: (props: ComponentProps) => JSX.Element;
-}
-
-export interface State {
- loading: boolean;
- error: boolean;
- payload: Layout[];
- errorMessage: string;
-}
-
-interface DispatchProps {
- toggleAddWidget: (
- props: ToggleAddWidgetProps,
- ) => (dispatch: ReduxDispatch<AppActions>) => void;
-}
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- toggleAddWidget: bindActionCreators(ToggleAddWidget, dispatch),
-});
-
-type Props = DispatchProps;
-
-export default connect(null, mapDispatchToProps)(GridGraph);
diff --git a/frontend/src/container/GridGraphLayout/utils.ts b/frontend/src/container/GridGraphLayout/utils.ts
deleted file mode 100644
index a18fe52886..0000000000
--- a/frontend/src/container/GridGraphLayout/utils.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { NotificationInstance } from 'antd/es/notification/interface';
-import updateDashboardApi from 'api/dashboard/update';
-import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
-import { Layout } from 'react-grid-layout';
-import store from 'store';
-import { Dashboard, Widgets } from 'types/api/dashboard/getAll';
-
-export const UpdateDashboard = async (
- {
- data,
- graphType,
- generateWidgetId,
- layout,
- selectedDashboard,
- isRedirected,
- widgetData,
- }: UpdateDashboardProps,
- notify: NotificationInstance,
-): Promise<Dashboard | undefined> => {
- const copyTitle = `${widgetData?.title} - Copy`;
- const updatedSelectedDashboard: Dashboard = {
- ...selectedDashboard,
- data: {
- title: data.title,
- description: data.description,
- name: data.name,
- tags: data.tags,
- variables: data.variables,
- widgets: [
- ...(data.widgets || []),
- {
- description: widgetData?.description || '',
- id: generateWidgetId,
- isStacked: false,
- nullZeroValues: widgetData?.nullZeroValues || '',
- opacity: '',
- panelTypes: graphType,
- query: widgetData?.query || initialQueriesMap.metrics,
- timePreferance: widgetData?.timePreferance || 'GLOBAL_TIME',
- title: widgetData ? copyTitle : '',
- yAxisUnit: widgetData?.yAxisUnit,
- },
- ],
- layout,
- },
- uuid: selectedDashboard.uuid,
- };
-
- const response = await updateDashboardApi(updatedSelectedDashboard);
-
- if (response.payload) {
- store.dispatch({
- type: 'UPDATE_DASHBOARD',
- payload: response.payload,
- });
- }
-
- if (isRedirected) {
- if (response.statusCode === 200) {
- return response.payload;
- }
- notify.error({
- message: response.error || 'Something went wrong',
- });
- return undefined;
- }
- return undefined;
-};
-
-interface UpdateDashboardProps {
- data: Dashboard['data'];
- graphType: PANEL_TYPES;
- generateWidgetId: string;
- layout: Layout[];
- selectedDashboard: Dashboard;
- isRedirected: boolean;
- widgetData?: Widgets;
-}
diff --git a/frontend/src/container/ListOfDashboard/ImportJSON/index.tsx b/frontend/src/container/ListOfDashboard/ImportJSON/index.tsx
index 3a7f406b4e..aa658d56cc 100644
--- a/frontend/src/container/ListOfDashboard/ImportJSON/index.tsx
+++ b/frontend/src/container/ListOfDashboard/ImportJSON/index.tsx
@@ -9,11 +9,7 @@ import { useNotifications } from 'hooks/useNotifications';
import history from 'lib/history';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useDispatch } from 'react-redux';
import { generatePath } from 'react-router-dom';
-import { Dispatch } from 'redux';
-import AppActions from 'types/actions';
-import { FLUSH_DASHBOARD } from 'types/actions/dashboard';
import { DashboardData } from 'types/api/dashboard/getAll';
import { EditorContainer, FooterContainer } from './styles';
@@ -31,8 +27,6 @@ function ImportJSON({
);
const [isFeatureAlert, setIsFeatureAlert] = useState<boolean>(false);
- const dispatch = useDispatch<Dispatch<AppActions>>();
-
const [dashboardCreating, setDashboardCreating] = useState<boolean>(false);
const [editorValue, setEditorValue] = useState<string>('');
@@ -77,16 +71,11 @@ function ImportJSON({
});
if (response.statusCode === 200) {
- dispatch({
- type: FLUSH_DASHBOARD,
- });
- setTimeout(() => {
- history.push(
- generatePath(ROUTES.DASHBOARD, {
- dashboardId: response.payload.uuid,
- }),
- );
- }, 10);
+ history.push(
+ generatePath(ROUTES.DASHBOARD, {
+ dashboardId: response.payload.uuid,
+ }),
+ );
} else if (response.error === 'feature usage exceeded') {
setIsFeatureAlert(true);
notifications.error({
diff --git a/frontend/src/container/ListOfDashboard/TableComponents/DeleteButton.tsx b/frontend/src/container/ListOfDashboard/TableComponents/DeleteButton.tsx
index 39d3c02a23..03c0ac9912 100644
--- a/frontend/src/container/ListOfDashboard/TableComponents/DeleteButton.tsx
+++ b/frontend/src/container/ListOfDashboard/TableComponents/DeleteButton.tsx
@@ -1,37 +1,36 @@
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Modal } from 'antd';
+import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
+import { useDeleteDashboard } from 'hooks/dashboard/useDeleteDashboard';
import { useCallback } from 'react';
-import { connect } from 'react-redux';
-import { bindActionCreators, Dispatch } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
-import { DeleteDashboard, DeleteDashboardProps } from 'store/actions';
-import AppActions from 'types/actions';
+import { useQueryClient } from 'react-query';
import { Data } from '../index';
import { TableLinkText } from './styles';
-function DeleteButton({
- deleteDashboard,
- id,
- refetchDashboardList,
-}: DeleteButtonProps): JSX.Element {
+function DeleteButton({ id }: Data): JSX.Element {
const [modal, contextHolder] = Modal.useModal();
+ const queryClient = useQueryClient();
+
+ const deleteDashboardMutation = useDeleteDashboard(id);
+
const openConfirmationDialog = useCallback((): void => {
modal.confirm({
title: 'Do you really want to delete this dashboard?',
icon: <ExclamationCircleOutlined style={{ color: '#e42b35' }} />,
onOk() {
- deleteDashboard({
- uuid: id,
- refetch: refetchDashboardList,
+ deleteDashboardMutation.mutateAsync(undefined, {
+ onSuccess: () => {
+ queryClient.invalidateQueries([REACT_QUERY_KEY.GET_ALL_DASHBOARDS]);
+ },
});
},
okText: 'Delete',
okButtonProps: { danger: true },
centered: true,
});
- }, [modal, deleteDashboard, id, refetchDashboardList]);
+ }, [modal, deleteDashboardMutation, queryClient]);
return (
<>
@@ -44,37 +43,12 @@ function DeleteButton({
);
}
-interface DispatchProps {
- deleteDashboard: ({
- uuid,
- }: DeleteDashboardProps) => (dispatch: Dispatch<AppActions>) => void;
-}
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- deleteDashboard: bindActionCreators(DeleteDashboard, dispatch),
-});
-
-export type DeleteButtonProps = Data & DispatchProps;
-
-const WrapperDeleteButton = connect(null, mapDispatchToProps)(DeleteButton);
-
// This is to avoid the type collision
function Wrapper(props: Data): JSX.Element {
- const {
- createdBy,
- description,
- id,
- key,
- refetchDashboardList,
- lastUpdatedTime,
- name,
- tags,
- } = props;
+ const { createdBy, description, id, key, lastUpdatedTime, name, tags } = props;
return (
- <WrapperDeleteButton
+ <DeleteButton
{...{
createdBy,
description,
@@ -83,7 +57,6 @@ function Wrapper(props: Data): JSX.Element {
lastUpdatedTime,
name,
tags,
- refetchDashboardList,
}}
/>
);
diff --git a/frontend/src/container/ListOfDashboard/index.tsx b/frontend/src/container/ListOfDashboard/index.tsx
index 6041b8baf4..87f47e54af 100644
--- a/frontend/src/container/ListOfDashboard/index.tsx
+++ b/frontend/src/container/ListOfDashboard/index.tsx
@@ -17,21 +17,11 @@ import SearchFilter from 'container/ListOfDashboard/SearchFilter';
import { useGetAllDashboard } from 'hooks/dashboard/useGetAllDashboard';
import useComponentPermission from 'hooks/useComponentPermission';
import history from 'lib/history';
-import {
- Dispatch,
- Key,
- useCallback,
- useEffect,
- useMemo,
- useState,
-} from 'react';
+import { Key, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { UseQueryResult } from 'react-query';
-import { useDispatch, useSelector } from 'react-redux';
+import { useSelector } from 'react-redux';
import { generatePath } from 'react-router-dom';
import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
-import { GET_ALL_DASHBOARD_SUCCESS } from 'types/actions/dashboard';
import { Dashboard } from 'types/api/dashboard/getAll';
import AppReducer from 'types/reducer/app';
import { popupContainer } from 'utils/selectPopupContainer';
@@ -40,9 +30,7 @@ import ImportJSON from './ImportJSON';
import { ButtonContainer, NewDashboardButton, TableContainer } from './styles';
import Createdby from './TableComponents/CreatedBy';
import DateComponent from './TableComponents/Date';
-import DeleteButton, {
- DeleteButtonProps,
-} from './TableComponents/DeleteButton';
+import DeleteButton from './TableComponents/DeleteButton';
import Name from './TableComponents/Name';
import Tags from './TableComponents/Tags';
@@ -53,7 +41,6 @@ function ListOfAllDashboard(): JSX.Element {
refetch: refetchDashboardList,
} = useGetAllDashboard();
- const dispatch = useDispatch<Dispatch<AppActions>>();
const { role } = useSelector<AppState, AppReducer>((state) => state.app);
const [action, createNewDashboard, newDashboard] = useComponentPermission(
@@ -134,31 +121,12 @@ function ListOfAllDashboard(): JSX.Element {
title: 'Action',
dataIndex: '',
width: 40,
- render: ({
- createdBy,
- description,
- id,
- key,
- lastUpdatedTime,
- name,
- tags,
- }: DeleteButtonProps) => (
- <DeleteButton
- description={description}
- id={id}
- key={key}
- lastUpdatedTime={lastUpdatedTime}
- name={name}
- tags={tags}
- createdBy={createdBy}
- refetchDashboardList={refetchDashboardList}
- />
- ),
+ render: DeleteButton,
});
}
return tableColumns;
- }, [action, refetchDashboardList]);
+ }, [action]);
const data: Data[] =
filteredDashboards?.map((e) => ({
@@ -186,10 +154,6 @@ function ListOfAllDashboard(): JSX.Element {
});
if (response.statusCode === 200) {
- dispatch({
- type: GET_ALL_DASHBOARD_SUCCESS,
- payload: [],
- });
history.push(
generatePath(ROUTES.DASHBOARD, {
dashboardId: response.payload.uuid,
@@ -210,7 +174,7 @@ function ListOfAllDashboard(): JSX.Element {
errorMessage: (error as AxiosError).toString() || 'Something went Wrong',
});
}
- }, [newDashboardState, t, dispatch]);
+ }, [newDashboardState, t]);
const getText = useCallback(() => {
if (!newDashboardState.error && !newDashboardState.loading) {
@@ -352,7 +316,6 @@ export interface Data {
createdBy: string;
lastUpdatedTime: string;
id: string;
- refetchDashboardList: UseQueryResult['refetch'];
}
export default ListOfAllDashboard;
diff --git a/frontend/src/container/LiveLogs/LiveLogsContainer/index.tsx b/frontend/src/container/LiveLogs/LiveLogsContainer/index.tsx
index 49a071d17e..e47ae535a6 100644
--- a/frontend/src/container/LiveLogs/LiveLogsContainer/index.tsx
+++ b/frontend/src/container/LiveLogs/LiveLogsContainer/index.tsx
@@ -11,11 +11,11 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import useDebouncedFn from 'hooks/useDebouncedFunction';
import { useEventSourceEvent } from 'hooks/useEventSourceEvent';
import { useNotifications } from 'hooks/useNotifications';
+import { prepareQueryRangePayload } from 'lib/dashboard/prepareQueryRangePayload';
import { useEventSource } from 'providers/EventSource';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
-import { prepareQueryRangePayload } from 'store/actions/dashboard/prepareQueryRangePayload';
import { AppState } from 'store/reducers';
import { ILog } from 'types/api/logs/log';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
diff --git a/frontend/src/container/LogsExplorerChart/index.tsx b/frontend/src/container/LogsExplorerChart/index.tsx
index a64f8eb382..ec329907f3 100644
--- a/frontend/src/container/LogsExplorerChart/index.tsx
+++ b/frontend/src/container/LogsExplorerChart/index.tsx
@@ -48,7 +48,7 @@ function LogsExplorerChart({
) : (
<Graph
name="logsExplorerChart"
- data={graphData}
+ data={graphData.data}
type="bar"
containerHeight="100%"
animate
diff --git a/frontend/src/container/MetricsApplication/MetricsApplication.factory.ts b/frontend/src/container/MetricsApplication/MetricsApplication.factory.ts
index 26400a7541..31e949111f 100644
--- a/frontend/src/container/MetricsApplication/MetricsApplication.factory.ts
+++ b/frontend/src/container/MetricsApplication/MetricsApplication.factory.ts
@@ -7,6 +7,7 @@ export const getWidgetQueryBuilder = ({
query,
title = '',
panelTypes,
+ yAxisUnit = '',
}: GetWidgetQueryBuilderProps): Widgets => ({
description: '',
id: v4(),
@@ -17,4 +18,5 @@ export const getWidgetQueryBuilder = ({
query,
timePreferance: 'GLOBAL_TIME',
title,
+ yAxisUnit,
});
diff --git a/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx b/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx
index 83e6da6db2..15af9981c0 100644
--- a/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx
@@ -1,6 +1,6 @@
import { Col } from 'antd';
import { PANEL_TYPES } from 'constants/queryBuilder';
-import Graph from 'container/GridGraphLayout/Graph/';
+import Graph from 'container/GridCardLayout/GridCard';
import {
databaseCallsAvgDuration,
databaseCallsRPS,
@@ -65,6 +65,7 @@ function DBCall(): JSX.Element {
},
title: GraphTitle.DATABASE_CALLS_RPS,
panelTypes: PANEL_TYPES.TIME_SERIES,
+ yAxisUnit: 'reqps',
}),
[servicename, tagFilterItems],
);
@@ -83,6 +84,7 @@ function DBCall(): JSX.Element {
},
title: GraphTitle.DATABASE_CALLS_AVG_DURATION,
panelTypes: PANEL_TYPES.TIME_SERIES,
+ yAxisUnit: 'ms',
}),
[servicename, tagFilterItems],
);
@@ -107,7 +109,6 @@ function DBCall(): JSX.Element {
<Graph
name="database_call_rps"
widget={databaseCallsRPSWidget}
- yAxisUnit="reqps"
onClickHandler={(ChartEvent, activeElements, chart, data): void => {
onGraphClickHandler(setSelectedTimeStamp)(
ChartEvent,
@@ -135,12 +136,12 @@ function DBCall(): JSX.Element {
>
View Traces
</Button>
+
<Card>
<GraphContainer>
<Graph
name="database_call_avg_duration"
widget={databaseCallsAverageDurationWidget}
- yAxisUnit="ms"
onClickHandler={(ChartEvent, activeElements, chart, data): void => {
onGraphClickHandler(setSelectedTimeStamp)(
ChartEvent,
diff --git a/frontend/src/container/MetricsApplication/Tabs/External.tsx b/frontend/src/container/MetricsApplication/Tabs/External.tsx
index 3abe8d4ca4..cda6e9275c 100644
--- a/frontend/src/container/MetricsApplication/Tabs/External.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/External.tsx
@@ -1,6 +1,6 @@
import { Col } from 'antd';
import { PANEL_TYPES } from 'constants/queryBuilder';
-import Graph from 'container/GridGraphLayout/Graph/';
+import Graph from 'container/GridCardLayout/GridCard';
import {
externalCallDuration,
externalCallDurationByAddress,
@@ -56,6 +56,7 @@ function External(): JSX.Element {
},
title: GraphTitle.EXTERNAL_CALL_ERROR_PERCENTAGE,
panelTypes: PANEL_TYPES.TIME_SERIES,
+ yAxisUnit: '%',
}),
[servicename, tagFilterItems],
);
@@ -80,6 +81,7 @@ function External(): JSX.Element {
},
title: GraphTitle.EXTERNAL_CALL_DURATION,
panelTypes: PANEL_TYPES.TIME_SERIES,
+ yAxisUnit: 'ms',
}),
[servicename, tagFilterItems],
);
@@ -100,6 +102,7 @@ function External(): JSX.Element {
},
title: GraphTitle.EXTERNAL_CALL_RPS_BY_ADDRESS,
panelTypes: PANEL_TYPES.TIME_SERIES,
+ yAxisUnit: 'reqps',
}),
[servicename, tagFilterItems],
);
@@ -120,6 +123,7 @@ function External(): JSX.Element {
},
title: GraphTitle.EXTERNAL_CALL_DURATION_BY_ADDRESS,
panelTypes: PANEL_TYPES.TIME_SERIES,
+ yAxisUnit: 'ms',
}),
[servicename, tagFilterItems],
);
@@ -146,7 +150,6 @@ function External(): JSX.Element {
<Graph
name="external_call_error_percentage"
widget={externalCallErrorWidget}
- yAxisUnit="%"
onClickHandler={(ChartEvent, activeElements, chart, data): void => {
onGraphClickHandler(setSelectedTimeStamp)(
ChartEvent,
@@ -181,7 +184,6 @@ function External(): JSX.Element {
<Graph
name="external_call_duration"
widget={externalCallDurationWidget}
- yAxisUnit="ms"
onClickHandler={(ChartEvent, activeElements, chart, data): void => {
onGraphClickHandler(setSelectedTimeStamp)(
ChartEvent,
@@ -217,7 +219,6 @@ function External(): JSX.Element {
<Graph
name="external_call_rps_by_address"
widget={externalCallRPSWidget}
- yAxisUnit="reqps"
onClickHandler={(ChartEvent, activeElements, chart, data): void => {
onGraphClickHandler(setSelectedTimeStamp)(
ChartEvent,
@@ -252,7 +253,6 @@ function External(): JSX.Element {
<Graph
name="external_call_duration_by_address"
widget={externalCallDurationAddressWidget}
- yAxisUnit="ms"
onClickHandler={(ChartEvent, activeElements, chart, data): void => {
onGraphClickHandler(setSelectedTimeStamp)(
ChartEvent,
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview.tsx
index b7ab171ccd..d67053e1e0 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview.tsx
@@ -131,6 +131,7 @@ function Application(): JSX.Element {
},
title: GraphTitle.RATE_PER_OPS,
panelTypes: PANEL_TYPES.TIME_SERIES,
+ yAxisUnit: 'ops',
}),
[servicename, tagFilterItems, topLevelOperationsRoute],
);
@@ -151,6 +152,7 @@ function Application(): JSX.Element {
},
title: GraphTitle.ERROR_PERCENTAGE,
panelTypes: PANEL_TYPES.TIME_SERIES,
+ yAxisUnit: '%',
}),
[servicename, tagFilterItems, topLevelOperationsRoute],
);
@@ -222,7 +224,6 @@ function Application(): JSX.Element {
topLevelOperationsIsError={topLevelOperationsIsError}
name="operations_per_sec"
widget={operationPerSecWidget}
- yAxisUnit="ops"
opName="Rate"
/>
</Col>
@@ -267,7 +268,6 @@ function Application(): JSX.Element {
topLevelOperationsIsError={topLevelOperationsIsError}
name="error_percentage_%"
widget={errorPercentageWidget}
- yAxisUnit="%"
opName="Error"
/>
</ColErrorContainer>
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetrics.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetrics.tsx
index b20613bae7..ade8a1bec3 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetrics.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetrics.tsx
@@ -6,8 +6,8 @@ import {
apDexToolTipUrlText,
} from 'constants/apDex';
import { PANEL_TYPES } from 'constants/queryBuilder';
-import Graph from 'container/GridGraphLayout/Graph';
-import DisplayThreshold from 'container/GridGraphLayout/WidgetHeader/DisplayThreshold';
+import Graph from 'container/GridCardLayout/GridCard';
+import DisplayThreshold from 'container/GridCardLayout/WidgetHeader/DisplayThreshold';
import { GraphTitle } from 'container/MetricsApplication/constant';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
import { apDexMetricsQueryBuilderQueries } from 'container/MetricsApplication/MetricsPageQueries/OverviewQueries';
@@ -87,7 +87,6 @@ function ApDexMetrics({
widget={apDexMetricsWidget}
onDragSelect={onDragSelect}
onClickHandler={handleGraphClick('ApDex')}
- yAxisUnit=""
threshold={threshold}
isQueryEnabled={isQueryEnabled}
/>
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexTraces.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexTraces.tsx
index bf6297785f..1b2e5ba0cd 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexTraces.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexTraces.tsx
@@ -1,7 +1,7 @@
// This component is not been used in the application as we support only metrics for ApDex as of now.
// This component is been kept for future reference.
import { PANEL_TYPES } from 'constants/queryBuilder';
-import Graph from 'container/GridGraphLayout/Graph';
+import Graph from 'container/GridCardLayout/GridCard';
import { GraphTitle } from 'container/MetricsApplication/constant';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
import { apDexTracesQueryBuilderQueries } from 'container/MetricsApplication/MetricsPageQueries/OverviewQueries';
@@ -52,7 +52,6 @@ function ApDexTraces({
widget={apDexTracesWidget}
onDragSelect={onDragSelect}
onClickHandler={handleGraphClick('ApDex')}
- yAxisUnit=""
threshold={thresholdValue}
isQueryEnabled={isQueryEnabled}
/>
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/ServiceOverview.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/ServiceOverview.tsx
index 52014ac48b..cb124f545a 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/ServiceOverview.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/ServiceOverview.tsx
@@ -1,7 +1,7 @@
import Spinner from 'components/Spinner';
import { FeatureKeys } from 'constants/features';
import { PANEL_TYPES } from 'constants/queryBuilder';
-import Graph from 'container/GridGraphLayout/Graph/';
+import Graph from 'container/GridCardLayout/GridCard';
import { GraphTitle } from 'container/MetricsApplication/constant';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
import { latency } from 'container/MetricsApplication/MetricsPageQueries/OverviewQueries';
@@ -59,6 +59,7 @@ function ServiceOverview({
},
title: GraphTitle.LATENCY,
panelTypes: PANEL_TYPES.TIME_SERIES,
+ yAxisUnit: 'ns',
}),
[servicename, isSpanMetricEnable, topLevelOperationsRoute, tagFilterItems],
);
@@ -93,7 +94,6 @@ function ServiceOverview({
name="service_latency"
onDragSelect={onDragSelect}
widget={latencyWidget}
- yAxisUnit="ns"
onClickHandler={handleGraphClick('Service')}
isQueryEnabled={isQueryEnabled}
/>
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/TopLevelOperations.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/TopLevelOperations.tsx
index 903ff3a15f..f71a0f7301 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/TopLevelOperations.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/TopLevelOperations.tsx
@@ -2,7 +2,7 @@ import { Typography } from 'antd';
import axios from 'axios';
import Spinner from 'components/Spinner';
import { SOMETHING_WENT_WRONG } from 'constants/api';
-import Graph from 'container/GridGraphLayout/Graph/';
+import Graph from 'container/GridCardLayout/GridCard';
import { Card, GraphContainer } from 'container/MetricsApplication/styles';
import { Widgets } from 'types/api/dashboard/getAll';
@@ -17,7 +17,6 @@ function TopLevelOperation({
onDragSelect,
handleGraphClick,
widget,
- yAxisUnit,
}: TopLevelOperationProps): JSX.Element {
return (
<Card>
@@ -37,7 +36,6 @@ function TopLevelOperation({
name={name}
widget={widget}
onClickHandler={handleGraphClick(opName)}
- yAxisUnit={yAxisUnit}
onDragSelect={onDragSelect}
/>
)}
@@ -56,7 +54,6 @@ interface TopLevelOperationProps {
onDragSelect: (start: number, end: number) => void;
handleGraphClick: (type: string) => ClickHandlerType;
widget: Widgets;
- yAxisUnit: string;
}
export default TopLevelOperation;
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperationMetrics.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperationMetrics.tsx
index 4ca191b68c..b0385e2ab0 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperationMetrics.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperationMetrics.tsx
@@ -7,9 +7,7 @@ import { useStepInterval } from 'hooks/queryBuilder/useStepInterval';
import { useNotifications } from 'hooks/useNotifications';
import useResourceAttribute from 'hooks/useResourceAttribute';
import { convertRawQueriesToTraceSelectedTags } from 'hooks/useResourceAttribute/utils';
-import { getDashboardVariables } from 'lib/dashbaordVariables/getDashboardVariables';
import { RowData } from 'lib/query/createTableColumnsFromQuery';
-import { isEmpty } from 'lodash-es';
import { ReactNode, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { useParams } from 'react-router-dom';
@@ -58,10 +56,7 @@ function TopOperationMetrics(): JSX.Element {
const updatedQuery = useStepInterval(keyOperationWidget.query);
- const isEmptyWidget = useMemo(
- () => keyOperationWidget.id === 'empty' || isEmpty(keyOperationWidget),
- [keyOperationWidget],
- );
+ const isEmptyWidget = keyOperationWidget.id === PANEL_TYPES.EMPTY_WIDGET;
const { data, isLoading } = useGetQueryRange(
{
@@ -69,7 +64,7 @@ function TopOperationMetrics(): JSX.Element {
graphType: keyOperationWidget?.panelTypes,
query: updatedQuery,
globalSelectedInterval,
- variables: getDashboardVariables(),
+ variables: {},
},
{
queryKey: [
diff --git a/frontend/src/container/MetricsApplication/TopOperationsTable.tsx b/frontend/src/container/MetricsApplication/TopOperationsTable.tsx
index e753a965a5..4c895716e7 100644
--- a/frontend/src/container/MetricsApplication/TopOperationsTable.tsx
+++ b/frontend/src/container/MetricsApplication/TopOperationsTable.tsx
@@ -10,7 +10,7 @@ import { GlobalReducer } from 'types/reducer/globalTime';
import { getErrorRate, navigateToTrace } from './utils';
-function TopOperationsTable(props: TopOperationsTableProps): JSX.Element {
+function TopOperationsTable({ data }: TopOperationsTableProps): JSX.Element {
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
@@ -20,8 +20,6 @@ function TopOperationsTable(props: TopOperationsTableProps): JSX.Element {
convertRawQueriesToTraceSelectedTags(queries) || [],
);
- const { data } = props;
-
const params = useParams<{ servicename: string }>();
const handleOnClick = (operation: string): void => {
diff --git a/frontend/src/container/MetricsApplication/types.ts b/frontend/src/container/MetricsApplication/types.ts
index d9a7251745..f87ce66a2a 100644
--- a/frontend/src/container/MetricsApplication/types.ts
+++ b/frontend/src/container/MetricsApplication/types.ts
@@ -8,6 +8,7 @@ export interface GetWidgetQueryBuilderProps {
query: Widgets['query'];
title?: ReactNode;
panelTypes: Widgets['panelTypes'];
+ yAxisUnit?: Widgets['yAxisUnit'];
}
export interface NavigateToTraceProps {
diff --git a/frontend/src/container/NewDashboard/ComponentsSlider/index.tsx b/frontend/src/container/NewDashboard/ComponentsSlider/index.tsx
index da6e28ccca..c9c1c6dde1 100644
--- a/frontend/src/container/NewDashboard/ComponentsSlider/index.tsx
+++ b/frontend/src/container/NewDashboard/ComponentsSlider/index.tsx
@@ -1,67 +1,97 @@
+import { SOMETHING_WENT_WRONG } from 'constants/api';
import { QueryParams } from 'constants/query';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
+import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useNotifications } from 'hooks/useNotifications';
import createQueryParams from 'lib/createQueryParams';
import history from 'lib/history';
-import { CSSProperties, useCallback } from 'react';
-import { connect, useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
-import { bindActionCreators, Dispatch } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
-import {
- ToggleAddWidget,
- ToggleAddWidgetProps,
-} from 'store/actions/dashboard/toggleAddWidget';
-import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
-import DashboardReducer from 'types/reducer/dashboards';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { CSSProperties } from 'react';
+import { v4 as uuid } from 'uuid';
import menuItems from './menuItems';
import { Card, Container, Text } from './styles';
-function DashboardGraphSlider({ toggleAddWidget }: Props): JSX.Element {
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
+function DashboardGraphSlider(): JSX.Element {
+ const isDarkMode = useIsDarkMode();
+
+ const {
+ handleToggleDashboardSlider,
+ layouts,
+ selectedDashboard,
+ } = useDashboard();
- const { pathname } = useLocation();
+ const { data } = selectedDashboard || {};
const { notifications } = useNotifications();
- const [selectedDashboard] = dashboards;
- const { data } = selectedDashboard;
+ const updateDashboardMutation = useUpdateDashboard();
- const onClickHandler = useCallback(
- (name: PANEL_TYPES) => (): void => {
- try {
- const emptyLayout = data.layout?.find((e) => e.i === 'empty');
+ const onClickHandler = (name: PANEL_TYPES) => (): void => {
+ const id = uuid();
- if (emptyLayout === undefined) {
- notifications.error({
- message: 'Please click on Add Panel Button',
- });
- return;
- }
+ updateDashboardMutation.mutateAsync(
+ {
+ uuid: selectedDashboard?.uuid || '',
+ data: {
+ title: data?.title || '',
+ variables: data?.variables || {},
+ description: data?.description || '',
+ name: data?.name || '',
+ tags: data?.tags || [],
+ layout: [
+ {
+ i: id,
+ w: 6,
+ x: 0,
+ h: 2,
+ y: 0,
+ },
+ ...(layouts.filter((layout) => layout.i !== PANEL_TYPES.EMPTY_WIDGET) ||
+ []),
+ ],
+ widgets: [
+ ...(data?.widgets || []),
+ {
+ id,
+ title: '',
+ description: '',
+ isStacked: false,
+ nullZeroValues: '',
+ opacity: '',
+ panelTypes: name,
+ query: initialQueriesMap.metrics,
+ timePreferance: 'GLOBAL_TIME',
+ },
+ ],
+ },
+ },
+ {
+ onSuccess: (data) => {
+ if (data.payload) {
+ handleToggleDashboardSlider(false);
- toggleAddWidget(false);
+ const queryParams = {
+ graphType: name,
+ widgetId: id,
+ [QueryParams.compositeQuery]: JSON.stringify(initialQueriesMap.metrics),
+ };
- const queryParams = {
- graphType: name,
- widgetId: emptyLayout.i,
- [QueryParams.compositeQuery]: JSON.stringify(initialQueriesMap.metrics),
- };
+ history.push(
+ `${history.location.pathname}/new?${createQueryParams(queryParams)}`,
+ );
+ }
+ },
+ onError: () => {
+ notifications.success({
+ message: SOMETHING_WENT_WRONG,
+ });
+ },
+ },
+ );
+ };
- history.push(`${pathname}/new?${createQueryParams(queryParams)}`);
- } catch (error) {
- notifications.error({
- message: 'Something went wrong',
- });
- }
- },
- [data, toggleAddWidget, notifications, pathname],
- );
- const isDarkMode = useIsDarkMode();
const fillColor: CSSProperties['color'] = isDarkMode ? 'white' : 'black';
return (
@@ -76,18 +106,4 @@ function DashboardGraphSlider({ toggleAddWidget }: Props): JSX.Element {
);
}
-interface DispatchProps {
- toggleAddWidget: (
- props: ToggleAddWidgetProps,
- ) => (dispatch: Dispatch<AppActions>) => void;
-}
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- toggleAddWidget: bindActionCreators(ToggleAddWidget, dispatch),
-});
-
-type Props = DispatchProps;
-
-export default connect(null, mapDispatchToProps)(DashboardGraphSlider);
+export default DashboardGraphSlider;
diff --git a/frontend/src/container/NewDashboard/DashboardSettings/General/index.tsx b/frontend/src/container/NewDashboard/DashboardSettings/General/index.tsx
index a8f1892fa4..3f6eec23b4 100644
--- a/frontend/src/container/NewDashboard/DashboardSettings/General/index.tsx
+++ b/frontend/src/container/NewDashboard/DashboardSettings/General/index.tsx
@@ -1,33 +1,23 @@
import { SaveOutlined } from '@ant-design/icons';
import { Col, Divider, Input, Space, Typography } from 'antd';
+import { SOMETHING_WENT_WRONG } from 'constants/api';
import AddTags from 'container/NewDashboard/DashboardSettings/General/AddTags';
-import { useCallback, useState } from 'react';
+import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
+import { useNotifications } from 'hooks/useNotifications';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { connect, useSelector } from 'react-redux';
-import { bindActionCreators, Dispatch } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
-import {
- UpdateDashboardTitleDescriptionTags,
- UpdateDashboardTitleDescriptionTagsProps,
-} from 'store/actions';
-import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
-import DashboardReducer from 'types/reducer/dashboards';
import { Button } from './styles';
-function GeneralDashboardSettings({
- updateDashboardTitleDescriptionTags,
-}: DescriptionOfDashboardProps): JSX.Element {
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
+function GeneralDashboardSettings(): JSX.Element {
+ const { selectedDashboard, setSelectedDashboard } = useDashboard();
+
+ const updateDashboardMutation = useUpdateDashboard();
+
+ const selectedData = selectedDashboard?.data;
- const [selectedDashboard] = dashboards;
- const selectedData = selectedDashboard.data;
- const { title } = selectedData;
- const { tags } = selectedData;
- const { description } = selectedData;
+ const { title = '', tags = [], description = '' } = selectedData || {};
const [updatedTitle, setUpdatedTitle] = useState<string>(title);
const [updatedTags, setUpdatedTags] = useState<string[]>(tags || []);
@@ -37,27 +27,35 @@ function GeneralDashboardSettings({
const { t } = useTranslation('common');
- const onSaveHandler = useCallback(() => {
- const dashboard = selectedDashboard;
- // @TODO need to update this function to take title,description,tags only
- updateDashboardTitleDescriptionTags({
- dashboard: {
- ...dashboard,
+ const { notifications } = useNotifications();
+
+ const onSaveHandler = (): void => {
+ if (!selectedDashboard) return;
+
+ updateDashboardMutation.mutateAsync(
+ {
+ ...selectedDashboard,
data: {
- ...dashboard.data,
+ ...selectedDashboard.data,
description: updatedDescription,
tags: updatedTags,
title: updatedTitle,
},
},
- });
- }, [
- updatedTitle,
- updatedTags,
- updatedDescription,
- selectedDashboard,
- updateDashboardTitleDescriptionTags,
- ]);
+ {
+ onSuccess: (updatedDashboard) => {
+ if (updatedDashboard.payload) {
+ setSelectedDashboard(updatedDashboard.payload);
+ }
+ },
+ onError: () => {
+ notifications.error({
+ message: SOMETHING_WENT_WRONG,
+ });
+ },
+ },
+ );
+ };
return (
<Col>
@@ -83,7 +81,13 @@ function GeneralDashboardSettings({
</div>
<div>
<Divider />
- <Button icon={<SaveOutlined />} onClick={onSaveHandler} type="primary">
+ <Button
+ disabled={updateDashboardMutation.isLoading}
+ loading={updateDashboardMutation.isLoading}
+ icon={<SaveOutlined />}
+ onClick={onSaveHandler}
+ type="primary"
+ >
{t('save')}
</Button>
</div>
@@ -92,21 +96,4 @@ function GeneralDashboardSettings({
);
}
-interface DispatchProps {
- updateDashboardTitleDescriptionTags: (
- props: UpdateDashboardTitleDescriptionTagsProps,
- ) => (dispatch: Dispatch<AppActions>) => void;
-}
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- updateDashboardTitleDescriptionTags: bindActionCreators(
- UpdateDashboardTitleDescriptionTags,
- dispatch,
- ),
-});
-
-type DescriptionOfDashboardProps = DispatchProps;
-
-export default connect(null, mapDispatchToProps)(GeneralDashboardSettings);
+export default GeneralDashboardSettings;
diff --git a/frontend/src/container/NewDashboard/DashboardSettings/Variables/index.tsx b/frontend/src/container/NewDashboard/DashboardSettings/Variables/index.tsx
index 3f90bf565b..388dffc286 100644
--- a/frontend/src/container/NewDashboard/DashboardSettings/Variables/index.tsx
+++ b/frontend/src/container/NewDashboard/DashboardSettings/Variables/index.tsx
@@ -1,39 +1,28 @@
import { blue, red } from '@ant-design/colors';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Modal, Row, Space, Tag } from 'antd';
-import { NotificationInstance } from 'antd/es/notification/interface';
import { ResizeTable } from 'components/ResizeTable';
+import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
import { useNotifications } from 'hooks/useNotifications';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import { useRef, useState } from 'react';
-import { connect, useSelector } from 'react-redux';
-import { bindActionCreators, Dispatch } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
-import { UpdateDashboardVariables } from 'store/actions/dashboard/updatedDashboardVariables';
-import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
-import { IDashboardVariable } from 'types/api/dashboard/getAll';
-import DashboardReducer from 'types/reducer/dashboards';
+import { useTranslation } from 'react-i18next';
+import { Dashboard, IDashboardVariable } from 'types/api/dashboard/getAll';
import { TVariableViewMode } from './types';
import VariableItem from './VariableItem/VariableItem';
-function VariablesSetting({
- updateDashboardVariables,
-}: DispatchProps): JSX.Element {
+function VariablesSetting(): JSX.Element {
const variableToDelete = useRef<string | null>(null);
const [deleteVariableModal, setDeleteVariableModal] = useState(false);
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
+ const { t } = useTranslation(['dashboard']);
- const { notifications } = useNotifications();
+ const { selectedDashboard, setSelectedDashboard } = useDashboard();
- const [selectedDashboard] = dashboards;
+ const { notifications } = useNotifications();
- const {
- data: { variables = {} },
- } = selectedDashboard;
+ const { variables = {} } = selectedDashboard?.data || {};
const variablesTableData = Object.keys(variables).map((variableName) => ({
key: variableName,
@@ -64,6 +53,41 @@ function VariablesSetting({
setVariableViewMode(viewType);
};
+ const updateMutation = useUpdateDashboard();
+
+ const updateVariables = (
+ updatedVariablesData: Dashboard['data']['variables'],
+ ): void => {
+ if (!selectedDashboard) {
+ return;
+ }
+
+ updateMutation.mutateAsync(
+ {
+ ...selectedDashboard,
+ data: {
+ ...selectedDashboard.data,
+ variables: updatedVariablesData,
+ },
+ },
+ {
+ onSuccess: (updatedDashboard) => {
+ if (updatedDashboard.payload) {
+ setSelectedDashboard(updatedDashboard.payload);
+ notifications.success({
+ message: t('variable_updated_successfully'),
+ });
+ }
+ },
+ onError: () => {
+ notifications.error({
+ message: t('error_while_updating_variable'),
+ });
+ },
+ },
+ );
+ };
+
const onVariableSaveHandler = (
name: string,
variableData: IDashboardVariable,
@@ -79,7 +103,7 @@ function VariablesSetting({
if (oldName) {
delete newVariables[oldName];
}
- updateDashboardVariables(newVariables, notifications);
+ updateVariables(newVariables);
onDoneVariableViewMode();
};
@@ -91,7 +115,7 @@ function VariablesSetting({
const handleDeleteConfirm = (): void => {
const newVariables = { ...variables };
if (variableToDelete?.current) delete newVariables[variableToDelete?.current];
- updateDashboardVariables(newVariables, notifications);
+ updateVariables(newVariables);
variableToDelete.current = null;
setDeleteVariableModal(false);
};
@@ -182,20 +206,4 @@ function VariablesSetting({
);
}
-interface DispatchProps {
- updateDashboardVariables: (
- props: Record<string, IDashboardVariable>,
- notify: NotificationInstance,
- ) => (dispatch: Dispatch<AppActions>) => void;
-}
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- updateDashboardVariables: bindActionCreators(
- UpdateDashboardVariables,
- dispatch,
- ),
-});
-
-export default connect(null, mapDispatchToProps)(VariablesSetting);
+export default VariablesSetting;
diff --git a/frontend/src/container/NewDashboard/DashboardSettings/index.tsx b/frontend/src/container/NewDashboard/DashboardSettings/index.tsx
index 50a69495fa..5a1bc6afac 100644
--- a/frontend/src/container/NewDashboard/DashboardSettings/index.tsx
+++ b/frontend/src/container/NewDashboard/DashboardSettings/index.tsx
@@ -3,12 +3,12 @@ import { Tabs } from 'antd';
import GeneralDashboardSettings from './General';
import VariablesSetting from './Variables';
-function DashboardSettingsContent(): JSX.Element {
- const items = [
- { label: 'General', key: 'general', children: <GeneralDashboardSettings /> },
- { label: 'Variables', key: 'variables', children: <VariablesSetting /> },
- ];
+const items = [
+ { label: 'General', key: 'general', children: <GeneralDashboardSettings /> },
+ { label: 'Variables', key: 'variables', children: <VariablesSetting /> },
+];
+function DashboardSettingsContent(): JSX.Element {
return <Tabs items={items} />;
}
diff --git a/frontend/src/container/NewDashboard/DashboardVariablesSelection/index.tsx b/frontend/src/container/NewDashboard/DashboardVariablesSelection/index.tsx
index d318e684f8..561af111ae 100644
--- a/frontend/src/container/NewDashboard/DashboardVariablesSelection/index.tsx
+++ b/frontend/src/container/NewDashboard/DashboardVariablesSelection/index.tsx
@@ -1,34 +1,25 @@
import { Row } from 'antd';
-import { NotificationInstance } from 'antd/es/notification/interface';
+import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
import { useNotifications } from 'hooks/useNotifications';
import { map, sortBy } from 'lodash-es';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import { useState } from 'react';
-import { connect, useSelector } from 'react-redux';
-import { bindActionCreators, Dispatch } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
-import { UpdateDashboardVariables } from 'store/actions/dashboard/updatedDashboardVariables';
+import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
-import { IDashboardVariable } from 'types/api/dashboard/getAll';
+import { Dashboard, IDashboardVariable } from 'types/api/dashboard/getAll';
import AppReducer from 'types/reducer/app';
-import DashboardReducer from 'types/reducer/dashboards';
import VariableItem from './VariableItem';
-function DashboardVariableSelection({
- updateDashboardVariables,
-}: DispatchProps): JSX.Element {
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
- const [selectedDashboard] = dashboards;
- const {
- data: { variables = {} },
- } = selectedDashboard;
+function DashboardVariableSelection(): JSX.Element | null {
+ const { selectedDashboard, setSelectedDashboard } = useDashboard();
+
+ const { data } = selectedDashboard || {};
+
+ const { variables } = data || {};
const [update, setUpdate] = useState<boolean>(false);
const [lastUpdatedVar, setLastUpdatedVar] = useState<string>('');
- const { notifications } = useNotifications();
const { role } = useSelector<AppState, AppReducer>((state) => state.app);
@@ -37,6 +28,42 @@ function DashboardVariableSelection({
setUpdate(!update);
};
+ const updateMutation = useUpdateDashboard();
+ const { notifications } = useNotifications();
+
+ const updateVariables = (
+ updatedVariablesData: Dashboard['data']['variables'],
+ ): void => {
+ if (!selectedDashboard) {
+ return;
+ }
+
+ updateMutation.mutateAsync(
+ {
+ ...selectedDashboard,
+ data: {
+ ...selectedDashboard.data,
+ variables: updatedVariablesData,
+ },
+ },
+ {
+ onSuccess: (updatedDashboard) => {
+ if (updatedDashboard.payload) {
+ setSelectedDashboard(updatedDashboard.payload);
+ notifications.success({
+ message: 'Variable updated successfully',
+ });
+ }
+ },
+ onError: () => {
+ notifications.error({
+ message: 'Error while updating variable',
+ });
+ },
+ },
+ );
+ };
+
const onValueUpdate = (
name: string,
value: IDashboardVariable['selectedValue'],
@@ -44,8 +71,8 @@ function DashboardVariableSelection({
const updatedVariablesData = { ...variables };
updatedVariablesData[name].selectedValue = value;
- if (role !== 'VIEWER') {
- updateDashboardVariables(updatedVariablesData, notifications);
+ if (role !== 'VIEWER' && selectedDashboard) {
+ updateVariables(updatedVariablesData);
}
onVarChanged(name);
@@ -58,13 +85,17 @@ function DashboardVariableSelection({
updatedVariablesData[name].allSelected = value;
if (role !== 'VIEWER') {
- updateDashboardVariables(updatedVariablesData, notifications);
+ updateVariables(updatedVariablesData);
}
onVarChanged(name);
};
+ if (!variables) {
+ return null;
+ }
+
return (
- <Row style={{ gap: '1rem' }}>
+ <Row>
{map(sortBy(Object.keys(variables)), (variableName) => (
<VariableItem
key={`${variableName}${variables[variableName].modificationUUID}`}
@@ -74,8 +105,8 @@ function DashboardVariableSelection({
...variables[variableName],
change: update,
}}
- onValueUpdate={onValueUpdate as never}
- onAllSelectedUpdate={onAllSelectedUpdate as never}
+ onValueUpdate={onValueUpdate}
+ onAllSelectedUpdate={onAllSelectedUpdate}
lastUpdatedVar={lastUpdatedVar}
/>
))}
@@ -83,20 +114,4 @@ function DashboardVariableSelection({
);
}
-interface DispatchProps {
- updateDashboardVariables: (
- props: Parameters<typeof UpdateDashboardVariables>[0],
- notify: NotificationInstance,
- ) => (dispatch: Dispatch<AppActions>) => void;
-}
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- updateDashboardVariables: bindActionCreators(
- UpdateDashboardVariables,
- dispatch,
- ),
-});
-
-export default connect(null, mapDispatchToProps)(DashboardVariableSelection);
+export default DashboardVariableSelection;
diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/SettingsDrawer.tsx b/frontend/src/container/NewDashboard/DescriptionOfDashboard/SettingsDrawer.tsx
index 72a10a3f30..fc51efd69a 100644
--- a/frontend/src/container/NewDashboard/DescriptionOfDashboard/SettingsDrawer.tsx
+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/SettingsDrawer.tsx
@@ -6,7 +6,7 @@ import DashboardSettingsContent from '../DashboardSettings';
import { DrawerContainer } from './styles';
function SettingsDrawer(): JSX.Element {
- const [visible, setVisible] = useState(false); // TODO Make it False
+ const [visible, setVisible] = useState<boolean>(false);
const showDrawer = (): void => {
setVisible(true);
@@ -25,7 +25,7 @@ function SettingsDrawer(): JSX.Element {
placement="right"
width="70%"
onClose={onClose}
- visible={visible}
+ open={visible}
>
<DashboardSettingsContent />
</DrawerContainer>
diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsx b/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsx
index 2faafd7cbb..3c6ca326a3 100644
--- a/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsx
+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsx
@@ -1,25 +1,22 @@
import { ShareAltOutlined } from '@ant-design/icons';
import { Button, Card, Col, Row, Space, Tag, Typography } from 'antd';
import useComponentPermission from 'hooks/useComponentPermission';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
import AppReducer from 'types/reducer/app';
-import DashboardReducer from 'types/reducer/dashboards';
import DashboardVariableSelection from '../DashboardVariablesSelection';
import SettingsDrawer from './SettingsDrawer';
import ShareModal from './ShareModal';
function DescriptionOfDashboard(): JSX.Element {
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
+ const { selectedDashboard } = useDashboard();
- const [selectedDashboard] = dashboards;
- const selectedData = selectedDashboard.data;
- const { title, tags, description } = selectedData;
+ const selectedData = selectedDashboard?.data;
+ const { title, tags, description } = selectedData || {};
const [isJSONModalVisible, isIsJSONModalVisible] = useState<boolean>(false);
@@ -34,26 +31,29 @@ function DescriptionOfDashboard(): JSX.Element {
return (
<Card>
<Row>
- <Col style={{ flex: 1 }}>
+ <Col flex={1}>
<Typography.Title level={4} style={{ padding: 0, margin: 0 }}>
{title}
</Typography.Title>
<Typography>{description}</Typography>
+
<div style={{ margin: '0.5rem 0' }}>
- {tags?.map((e) => (
- <Tag key={e}>{e}</Tag>
+ {tags?.map((tag) => (
+ <Tag key={tag}>{tag}</Tag>
))}
</div>
+
<DashboardVariableSelection />
</Col>
<Col>
- <ShareModal
- {...{
- isJSONModalVisible,
- onToggleHandler,
- selectedData,
- }}
- />
+ {selectedData && (
+ <ShareModal
+ isJSONModalVisible={isJSONModalVisible}
+ onToggleHandler={onToggleHandler}
+ selectedData={selectedData}
+ />
+ )}
+
<Space direction="vertical">
{editDashboard && <SettingsDrawer />}
<Button
diff --git a/frontend/src/container/NewDashboard/GridGraphs/index.tsx b/frontend/src/container/NewDashboard/GridGraphs/index.tsx
index b6fb01700a..eff1d26baf 100644
--- a/frontend/src/container/NewDashboard/GridGraphs/index.tsx
+++ b/frontend/src/container/NewDashboard/GridGraphs/index.tsx
@@ -1,19 +1,15 @@
-import GridGraphLayout from 'container/GridGraphLayout';
+import GridGraphLayout from 'container/GridCardLayout';
import ComponentsSlider from 'container/NewDashboard/ComponentsSlider';
-import { useSelector } from 'react-redux';
-import { AppState } from 'store/reducers';
-import DashboardReducer from 'types/reducer/dashboards';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import { GridComponentSliderContainer } from './styles';
function GridGraphs(): JSX.Element {
- const { isAddWidget } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
+ const { isDashboardSliderOpen } = useDashboard();
return (
<GridComponentSliderContainer>
- {isAddWidget && <ComponentsSlider />}
+ {isDashboardSliderOpen && <ComponentsSlider />}
<GridGraphLayout />
</GridComponentSliderContainer>
diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx
index 52f4bbc92c..7042e46f3e 100644
--- a/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx
+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx
@@ -9,28 +9,25 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
import { updateStepInterval } from 'hooks/queryBuilder/useStepInterval';
import useUrlQuery from 'hooks/useUrlQuery';
-import { useCallback, useMemo } from 'react';
-import { connect, useSelector } from 'react-redux';
-import { bindActionCreators, Dispatch } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import {
- UpdateQuery,
- UpdateQueryProps,
-} from 'store/actions/dashboard/updateQuery';
+ getNextWidgets,
+ getPreviousWidgets,
+ getSelectedWidgetIndex,
+} from 'providers/Dashboard/util';
+import { useCallback, useMemo } from 'react';
+import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
import { Widgets } from 'types/api/dashboard/getAll';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import AppReducer from 'types/reducer/app';
-import DashboardReducer from 'types/reducer/dashboards';
import { GlobalReducer } from 'types/reducer/globalTime';
import ClickHouseQueryContainer from './QueryBuilder/clickHouse';
import PromQLQueryContainer from './QueryBuilder/promQL';
function QuerySection({
- updateQuery,
selectedGraph,
selectedTime,
}: QueryProps): JSX.Element {
@@ -45,17 +42,14 @@ function QuerySection({
(state) => state.app,
);
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
+ const { selectedDashboard, setSelectedDashboard } = useDashboard();
const getWidgetQueryRange = useGetWidgetQueryRange({
graphType: selectedGraph,
selectedTime: selectedTime.enum,
});
- const [selectedDashboards] = dashboards;
- const { widgets } = selectedDashboards.data;
+ const { widgets } = selectedDashboard?.data || {};
const getWidget = useCallback(() => {
const widgetId = urlQuery.get('widgetId');
@@ -69,24 +63,49 @@ function QuerySection({
useShareBuilderUrl(query);
const handleStageQuery = useCallback(
- (updatedQuery: Query): void => {
- updateQuery({
- widgetId: urlQuery.get('widgetId') || '',
- yAxisUnit: selectedWidget.yAxisUnit,
- });
+ (query: Query): void => {
+ if (selectedDashboard === undefined) {
+ return;
+ }
- redirectWithQueryBuilderData(
- updateStepInterval(updatedQuery, maxTime, minTime),
+ const updatedQuery = updateStepInterval(query, maxTime, minTime);
+
+ const selectedWidgetIndex = getSelectedWidgetIndex(
+ selectedDashboard,
+ selectedWidget.id,
+ );
+
+ const previousWidgets = getPreviousWidgets(
+ selectedDashboard,
+ selectedWidgetIndex,
);
- },
+ const nextWidgets = getNextWidgets(selectedDashboard, selectedWidgetIndex);
+
+ setSelectedDashboard({
+ ...selectedDashboard,
+ data: {
+ ...selectedDashboard?.data,
+ widgets: [
+ ...previousWidgets,
+ {
+ ...selectedWidget,
+ query: updatedQuery,
+ },
+ ...nextWidgets,
+ ],
+ },
+ });
+
+ redirectWithQueryBuilderData(updatedQuery);
+ },
[
- updateQuery,
- urlQuery,
- selectedWidget.yAxisUnit,
- redirectWithQueryBuilderData,
+ selectedDashboard,
maxTime,
minTime,
+ selectedWidget,
+ setSelectedDashboard,
+ redirectWithQueryBuilderData,
],
);
@@ -157,21 +176,9 @@ function QuerySection({
);
}
-interface DispatchProps {
- updateQuery: (
- props: UpdateQueryProps,
- ) => (dispatch: Dispatch<AppActions>) => void;
-}
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- updateQuery: bindActionCreators(UpdateQuery, dispatch),
-});
-
-interface QueryProps extends DispatchProps {
+interface QueryProps {
selectedGraph: PANEL_TYPES;
selectedTime: WidgetGraphProps['selectedTime'];
}
-export default connect(null, mapDispatchToProps)(QuerySection);
+export default QuerySection;
diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx
index 6f4430ec38..c3edb0a9f1 100644
--- a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx
+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx
@@ -1,14 +1,18 @@
-import { Card, Typography } from 'antd';
+import { WarningOutlined } from '@ant-design/icons';
+import { Card, Tooltip, Typography } from 'antd';
import Spinner from 'components/Spinner';
+import {
+ errorTooltipPosition,
+ tooltipStyles,
+ WARNING_MESSAGE,
+} from 'container/GridCardLayout/WidgetHeader/config';
import GridPanelSwitch from 'container/GridPanelSwitch';
import { WidgetGraphProps } from 'container/NewWidget/types';
import { useGetWidgetQueryRange } from 'hooks/queryBuilder/useGetWidgetQueryRange';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import getChartData from 'lib/getChartData';
-import { useSelector } from 'react-redux';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import { useLocation } from 'react-router-dom';
-import { AppState } from 'store/reducers';
-import DashboardReducer from 'types/reducer/dashboards';
import { NotFoundContainer } from './styles';
@@ -18,13 +22,10 @@ function WidgetGraph({
selectedTime,
}: WidgetGraphProps): JSX.Element {
const { stagedQuery } = useQueryBuilder();
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
- const [selectedDashboard] = dashboards;
- const { data } = selectedDashboard;
- const { widgets = [] } = data;
+ const { selectedDashboard } = useDashboard();
+
+ const { widgets = [] } = selectedDashboard?.data || {};
const { search } = useLocation();
const params = new URLSearchParams(search);
@@ -65,22 +66,32 @@ function WidgetGraph({
queryData: [
{ queryData: getWidgetQueryRange.data?.payload.data.result ?? [] },
],
+ createDataset: undefined,
+ isWarningLimit: true,
});
return (
- <GridPanelSwitch
- title={title}
- isStacked={isStacked}
- opacity={opacity}
- data={chartDataSet}
- panelType={selectedGraph}
- name={widgetId || 'legend_widget'}
- yAxisUnit={yAxisUnit}
- panelData={
- getWidgetQueryRange.data?.payload.data.newResult.data.result || []
- }
- query={stagedQuery || query}
- />
+ <>
+ {chartDataSet.isWarning && (
+ <Tooltip title={WARNING_MESSAGE} placement={errorTooltipPosition}>
+ <WarningOutlined style={tooltipStyles} />
+ </Tooltip>
+ )}
+
+ <GridPanelSwitch
+ title={title}
+ isStacked={isStacked}
+ opacity={opacity}
+ data={chartDataSet.data}
+ panelType={selectedGraph}
+ name={widgetId || 'legend_widget'}
+ yAxisUnit={yAxisUnit}
+ panelData={
+ getWidgetQueryRange.data?.payload.data.newResult.data.result || []
+ }
+ query={stagedQuery || query}
+ />
+ </>
);
}
diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsx b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsx
index 62cab5f861..8bc4f57d1a 100644
--- a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsx
+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsx
@@ -1,12 +1,10 @@
import { InfoCircleOutlined } from '@ant-design/icons';
-import { Card } from 'container/GridGraphLayout/styles';
+import { Card } from 'container/GridCardLayout/styles';
import { useGetWidgetQueryRange } from 'hooks/queryBuilder/useGetWidgetQueryRange';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import { memo } from 'react';
-import { useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
-import { AppState } from 'store/reducers';
-import DashboardReducer from 'types/reducer/dashboards';
import { WidgetGraphProps } from '../../types';
import PlotTag from './PlotTag';
@@ -19,16 +17,11 @@ function WidgetGraph({
selectedTime,
}: WidgetGraphProps): JSX.Element {
const { currentQuery } = useQueryBuilder();
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
+ const { selectedDashboard } = useDashboard();
- const [selectedDashboard] = dashboards;
const { search } = useLocation();
- const { data } = selectedDashboard;
-
- const { widgets = [] } = data;
+ const { widgets = [] } = selectedDashboard?.data || {};
const params = new URLSearchParams(search);
const widgetId = params.get('widgetId');
diff --git a/frontend/src/container/NewWidget/index.tsx b/frontend/src/container/NewWidget/index.tsx
index a8079b992b..e9e21de2c6 100644
--- a/frontend/src/container/NewWidget/index.tsx
+++ b/frontend/src/container/NewWidget/index.tsx
@@ -1,29 +1,29 @@
import { LockFilled } from '@ant-design/icons';
import { Button, Modal, Tooltip, Typography } from 'antd';
+import { SOMETHING_WENT_WRONG } from 'constants/api';
import { FeatureKeys } from 'constants/features';
import { PANEL_TYPES } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
+import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { MESSAGE, useIsFeatureDisabled } from 'hooks/useFeatureFlag';
import { useNotifications } from 'hooks/useNotifications';
+import useUrlQuery from 'hooks/useUrlQuery';
import history from 'lib/history';
import { DashboardWidgetPageParams } from 'pages/DashboardWidget';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+import {
+ getNextWidgets,
+ getPreviousWidgets,
+ getSelectedWidgetIndex,
+} from 'providers/Dashboard/util';
import { useCallback, useMemo, useState } from 'react';
-import { connect, useDispatch, useSelector } from 'react-redux';
+import { useSelector } from 'react-redux';
import { generatePath, useLocation, useParams } from 'react-router-dom';
-import { bindActionCreators, Dispatch } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
-import {
- SaveDashboard,
- SaveDashboardProps,
-} from 'store/actions/dashboard/saveDashboard';
import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
-import { FLUSH_DASHBOARD } from 'types/actions/dashboard';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
import AppReducer from 'types/reducer/app';
-import DashboardReducer from 'types/reducer/dashboards';
import LeftContainer from './LeftContainer';
import QueryTypeTag from './LeftContainer/QueryTypeTag';
@@ -38,11 +38,8 @@ import {
} from './styles';
import { NewWidgetProps } from './types';
-function NewWidget({ selectedGraph, saveSettingOfPanel }: Props): JSX.Element {
- const dispatch = useDispatch();
- const { dashboards } = useSelector<AppState, DashboardReducer>(
- (state) => state.dashboards,
- );
+function NewWidget({ selectedGraph }: NewWidgetProps): JSX.Element {
+ const { selectedDashboard } = useDashboard();
const { currentQuery } = useQueryBuilder();
@@ -50,13 +47,11 @@ function NewWidget({ selectedGraph, saveSettingOfPanel }: Props): JSX.Element {
(state) => state.app,
);
- const [selectedDashboard] = dashboards;
-
- const { widgets } = selectedDashboard.data;
+ const { widgets = [] } = selectedDashboard?.data || {};
const { search } = useLocation();
- const query = useMemo(() => new URLSearchParams(search), [search]);
+ const query = useUrlQuery();
const { dashboardId } = useParams<DashboardWidgetPageParams>();
@@ -87,6 +82,7 @@ function NewWidget({ selectedGraph, saveSettingOfPanel }: Props): JSX.Element {
const [saveModal, setSaveModal] = useState(false);
const [graphType, setGraphType] = useState(selectedGraph);
+
const getSelectedTime = useCallback(
() =>
TimeItems.find(
@@ -102,58 +98,86 @@ function NewWidget({ selectedGraph, saveSettingOfPanel }: Props): JSX.Element {
const { notifications } = useNotifications();
+ const updateDashboardMutation = useUpdateDashboard();
+
const onClickSaveHandler = useCallback(() => {
- // update the global state
- featureResponse
- .refetch()
- .then(() => {
- saveSettingOfPanel({
- uuid: selectedDashboard.uuid,
- description,
- isStacked: stacked,
- nullZeroValues: selectedNullZeroValue,
- opacity,
- timePreferance: selectedTime.enum,
- title,
- yAxisUnit,
- widgetId: query.get('widgetId') || '',
- dashboardId,
- graphType,
- });
- })
- .catch(() => {
- notifications.error({
- message: 'Something went wrong',
- });
- });
+ if (!selectedDashboard) {
+ return;
+ }
+
+ const widgetId = query.get('widgetId');
+
+ const selectedWidgetIndex = getSelectedWidgetIndex(
+ selectedDashboard,
+ widgetId,
+ );
+
+ const preWidgets = getPreviousWidgets(selectedDashboard, selectedWidgetIndex);
+
+ const afterWidgets = getNextWidgets(selectedDashboard, selectedWidgetIndex);
+
+ const selectedWidget = (selectedDashboard.data.widgets || [])[
+ selectedWidgetIndex || 0
+ ];
+
+ updateDashboardMutation.mutateAsync(
+ {
+ uuid: selectedDashboard.uuid,
+ data: {
+ ...selectedDashboard.data,
+ widgets: [
+ ...preWidgets,
+ {
+ ...selectedWidget,
+ description,
+ timePreferance: selectedTime.enum,
+ isStacked: stacked,
+ opacity,
+ nullZeroValues: selectedNullZeroValue,
+ title,
+ yAxisUnit,
+ panelTypes: graphType,
+ },
+ ...afterWidgets,
+ ],
+ },
+ },
+ {
+ onSuccess: () => {
+ featureResponse.refetch();
+ history.push(generatePath(ROUTES.DASHBOARD, { dashboardId }));
+ },
+ onError: () => {
+ notifications.error({
+ message: SOMETHING_WENT_WRONG,
+ });
+ },
+ },
+ );
}, [
- featureResponse,
- saveSettingOfPanel,
- selectedDashboard.uuid,
+ selectedDashboard,
+ updateDashboardMutation,
description,
+ selectedTime.enum,
stacked,
- selectedNullZeroValue,
opacity,
- selectedTime.enum,
+ selectedNullZeroValue,
title,
yAxisUnit,
+ graphType,
query,
+ featureResponse,
dashboardId,
- graphType,
notifications,
]);
const onClickDiscardHandler = useCallback(() => {
- dispatch({
- type: FLUSH_DASHBOARD,
- });
history.push(generatePath(ROUTES.DASHBOARD, { dashboardId }));
- }, [dashboardId, dispatch]);
+ }, [dashboardId]);
const setGraphHandler = (type: PANEL_TYPES): void => {
const params = new URLSearchParams(search);
params.set('graphType', type);
- history.push({ search: params.toString() });
setGraphType(type);
};
@@ -165,19 +189,12 @@ function NewWidget({ selectedGraph, saveSettingOfPanel }: Props): JSX.Element {
FeatureKeys.QUERY_BUILDER_PANELS,
);
- const isNewTraceLogsAvailable = useMemo(
- () =>
- isQueryBuilderActive &&
- currentQuery.queryType === EQueryType.QUERY_BUILDER &&
- currentQuery.builder.queryData.find(
- (query) => query.dataSource !== DataSource.METRICS,
- ) !== undefined,
- [
- currentQuery.builder.queryData,
- currentQuery.queryType,
- isQueryBuilderActive,
- ],
- );
+ const isNewTraceLogsAvailable =
+ isQueryBuilderActive &&
+ currentQuery.queryType === EQueryType.QUERY_BUILDER &&
+ currentQuery.builder.queryData.find(
+ (query) => query.dataSource !== DataSource.METRICS,
+ ) !== undefined;
const isSaveDisabled = useMemo(() => {
// new created dashboard
@@ -239,23 +256,21 @@ function NewWidget({ selectedGraph, saveSettingOfPanel }: Props): JSX.Element {
<RightContainerWrapper flex={1}>
<RightContainer
setGraphHandler={setGraphHandler}
- {...{
- title,
- setTitle,
- description,
- setDescription,
- stacked,
- setStacked,
- opacity,
- yAxisUnit,
- setOpacity,
- selectedNullZeroValue,
- setSelectedNullZeroValue,
- selectedGraph: graphType,
- setSelectedTime,
- selectedTime,
- setYAxisUnit,
- }}
+ title={title}
+ setTitle={setTitle}
+ description={description}
+ setDescription={setDescription}
+ stacked={stacked}
+ setStacked={setStacked}
+ opacity={opacity}
+ yAxisUnit={yAxisUnit}
+ setOpacity={setOpacity}
+ selectedNullZeroValue={selectedNullZeroValue}
+ setSelectedNullZeroValue={setSelectedNullZeroValue}
+ selectedGraph={graphType}
+ setSelectedTime={setSelectedTime}
+ selectedTime={selectedTime}
+ setYAxisUnit={setYAxisUnit}
/>
</RightContainerWrapper>
</PanelContainer>
@@ -280,18 +295,4 @@ function NewWidget({ selectedGraph, saveSettingOfPanel }: Props): JSX.Element {
);
}
-interface DispatchProps {
- saveSettingOfPanel: (
- props: SaveDashboardProps,
- ) => (dispatch: Dispatch<AppActions>) => void;
-}
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- saveSettingOfPanel: bindActionCreators(SaveDashboard, dispatch),
-});
-
-type Props = DispatchProps & NewWidgetProps;
-
-export default connect(null, mapDispatchToProps)(NewWidget);
+export default NewWidget;
diff --git a/frontend/src/container/ServiceApplication/types.ts b/frontend/src/container/ServiceApplication/types.ts
index 6b800216be..6ff6b7c87a 100644
--- a/frontend/src/container/ServiceApplication/types.ts
+++ b/frontend/src/container/ServiceApplication/types.ts
@@ -1,7 +1,7 @@
import { ServiceDataProps } from 'api/metrics/getTopLevelOperations';
import { Time } from 'container/TopNav/DateTimeSelection/config';
+import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { UseQueryResult } from 'react-query';
-import { GetQueryResultsProps } from 'store/actions/dashboard/getQueryResults';
import { SuccessResponse } from 'types/api';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import { ServicesList } from 'types/api/metrics/getService';
diff --git a/frontend/src/container/ServiceApplication/utils.ts b/frontend/src/container/ServiceApplication/utils.ts
index d4d1b34bce..efe3a9ab2e 100644
--- a/frontend/src/container/ServiceApplication/utils.ts
+++ b/frontend/src/container/ServiceApplication/utils.ts
@@ -2,7 +2,7 @@ import { PANEL_TYPES } from 'constants/queryBuilder';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
import { updateStepInterval } from 'hooks/queryBuilder/useStepInterval';
import { getDashboardVariables } from 'lib/dashbaordVariables/getDashboardVariables';
-import { GetQueryResultsProps } from 'store/actions/dashboard/getQueryResults';
+import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { ServicesList } from 'types/api/metrics/getService';
import { QueryDataV3 } from 'types/api/widgets/getQuery';
import { EQueryType } from 'types/common/dashboard';
diff --git a/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx b/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx
index 6824b23995..8594ccd90c 100644
--- a/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx
+++ b/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx
@@ -32,7 +32,7 @@ function TimeSeriesView({
{!isLoading && !isError && (
<Graph
animate={false}
- data={chartData}
+ data={chartData.data}
yAxisUnit={yAxisUnit}
name="tracesExplorerGraph"
type="line"
diff --git a/frontend/src/hooks/dashboard/useDeleteDashboard.tsx b/frontend/src/hooks/dashboard/useDeleteDashboard.tsx
new file mode 100644
index 0000000000..35a3c27fce
--- /dev/null
+++ b/frontend/src/hooks/dashboard/useDeleteDashboard.tsx
@@ -0,0 +1,15 @@
+import deleteDashboard from 'api/dashboard/delete';
+import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
+import { useMutation, UseMutationResult } from 'react-query';
+import { PayloadProps } from 'types/api/dashboard/delete';
+
+export const useDeleteDashboard = (
+ id: string,
+): UseMutationResult<PayloadProps, unknown, void, unknown> =>
+ useMutation({
+ mutationKey: REACT_QUERY_KEY.DELETE_DASHBOARD,
+ mutationFn: () =>
+ deleteDashboard({
+ uuid: id,
+ }),
+ });
diff --git a/frontend/src/hooks/dashboard/useUpdateDashboard.tsx b/frontend/src/hooks/dashboard/useUpdateDashboard.tsx
index b4c34974dc..cdab00bfb2 100644
--- a/frontend/src/hooks/dashboard/useUpdateDashboard.tsx
+++ b/frontend/src/hooks/dashboard/useUpdateDashboard.tsx
@@ -1,10 +1,21 @@
import update from 'api/dashboard/update';
+import dayjs from 'dayjs';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import { useMutation, UseMutationResult } from 'react-query';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { Dashboard } from 'types/api/dashboard/getAll';
import { Props } from 'types/api/dashboard/update';
-export const useUpdateDashboard = (): UseUpdateDashboard => useMutation(update);
+export const useUpdateDashboard = (): UseUpdateDashboard => {
+ const { updatedTimeRef } = useDashboard();
+ return useMutation(update, {
+ onSuccess: (data) => {
+ if (data.payload) {
+ updatedTimeRef.current = dayjs(data.payload.updated_at);
+ }
+ },
+ });
+};
type UseUpdateDashboard = UseMutationResult<
SuccessResponse<Dashboard> | ErrorResponse,
diff --git a/frontend/src/hooks/queryBuilder/useGetQueriesRange.ts b/frontend/src/hooks/queryBuilder/useGetQueriesRange.ts
index c9f78d6e80..d7ec04d336 100644
--- a/frontend/src/hooks/queryBuilder/useGetQueriesRange.ts
+++ b/frontend/src/hooks/queryBuilder/useGetQueriesRange.ts
@@ -1,4 +1,8 @@
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
+import {
+ GetMetricQueryRange,
+ GetQueryResultsProps,
+} from 'lib/dashboard/getQueryResults';
import { useMemo } from 'react';
import {
QueryKey,
@@ -6,10 +10,6 @@ import {
UseQueryOptions,
UseQueryResult,
} from 'react-query';
-import {
- GetMetricQueryRange,
- GetQueryResultsProps,
-} from 'store/actions/dashboard/getQueryResults';
import { SuccessResponse } from 'types/api';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
diff --git a/frontend/src/hooks/queryBuilder/useGetQueryRange.ts b/frontend/src/hooks/queryBuilder/useGetQueryRange.ts
index b6e12b517c..9aa76405c2 100644
--- a/frontend/src/hooks/queryBuilder/useGetQueryRange.ts
+++ b/frontend/src/hooks/queryBuilder/useGetQueryRange.ts
@@ -1,10 +1,10 @@
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
-import { useMemo } from 'react';
-import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
import {
GetMetricQueryRange,
GetQueryResultsProps,
-} from 'store/actions/dashboard/getQueryResults';
+} from 'lib/dashboard/getQueryResults';
+import { useMemo } from 'react';
+import { useQuery, UseQueryOptions, UseQueryResult } from 'react-query';
import { SuccessResponse } from 'types/api';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
diff --git a/frontend/src/hooks/queryBuilder/useGetWidgetQueryRange.ts b/frontend/src/hooks/queryBuilder/useGetWidgetQueryRange.ts
index 28bc07566f..f3ecd21101 100644
--- a/frontend/src/hooks/queryBuilder/useGetWidgetQueryRange.ts
+++ b/frontend/src/hooks/queryBuilder/useGetWidgetQueryRange.ts
@@ -1,9 +1,10 @@
import { initialQueriesMap } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { getDashboardVariables } from 'lib/dashbaordVariables/getDashboardVariables';
+import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import { UseQueryOptions, UseQueryResult } from 'react-query';
import { useSelector } from 'react-redux';
-import { GetQueryResultsProps } from 'store/actions/dashboard/getQueryResults';
import { AppState } from 'store/reducers';
import { SuccessResponse } from 'types/api';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
@@ -26,13 +27,15 @@ export const useGetWidgetQueryRange = (
const { stagedQuery } = useQueryBuilder();
+ const { selectedDashboard } = useDashboard();
+
return useGetQueryRange(
{
graphType,
selectedTime,
globalSelectedInterval,
query: stagedQuery || initialQueriesMap.metrics,
- variables: getDashboardVariables(),
+ variables: getDashboardVariables(selectedDashboard?.data.variables),
},
{
enabled: !!stagedQuery,
diff --git a/frontend/src/hooks/useChartMutable.ts b/frontend/src/hooks/useChartMutable.ts
index 157cae13c5..642b294b53 100644
--- a/frontend/src/hooks/useChartMutable.ts
+++ b/frontend/src/hooks/useChartMutable.ts
@@ -1,5 +1,5 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
-import { PanelTypeAndGraphManagerVisibilityProps } from 'container/GridGraphLayout/Graph/FullView/types';
+import { PanelTypeAndGraphManagerVisibilityProps } from 'container/GridCardLayout/GridCard/FullView/types';
import { PanelTypeKeys } from 'types/common/queryBuilder';
export const useChartMutable = ({
diff --git a/frontend/src/hooks/useTabFocus.tsx b/frontend/src/hooks/useTabFocus.tsx
new file mode 100644
index 0000000000..8476d9d116
--- /dev/null
+++ b/frontend/src/hooks/useTabFocus.tsx
@@ -0,0 +1,28 @@
+import { useEffect, useRef, useState } from 'react';
+
+const useTabVisibility = (): boolean => {
+ const [isVisible, setIsVisible] = useState(false);
+ const prevVisibilityRef = useRef<boolean>(isVisible);
+
+ useEffect(() => {
+ const handleVisibilityChange = (): void => {
+ const isTabVisible = document.visibilityState === 'visible';
+ if (isTabVisible && !prevVisibilityRef.current) {
+ setIsVisible(true);
+ } else if (!isTabVisible && prevVisibilityRef.current) {
+ setIsVisible(false);
+ }
+ prevVisibilityRef.current = isTabVisible;
+ };
+
+ document.addEventListener('visibilitychange', handleVisibilityChange);
+
+ return (): void => {
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
+ };
+ }, []);
+
+ return isVisible;
+};
+
+export default useTabVisibility;
diff --git a/frontend/src/lib/dashbaordVariables/getDashboardVariables.ts b/frontend/src/lib/dashbaordVariables/getDashboardVariables.ts
index 1fae298675..346cd61ff6 100644
--- a/frontend/src/lib/dashbaordVariables/getDashboardVariables.ts
+++ b/frontend/src/lib/dashbaordVariables/getDashboardVariables.ts
@@ -1,33 +1,29 @@
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
import store from 'store';
+import { Dashboard } from 'types/api/dashboard/getAll';
-export const getDashboardVariables = (): Record<string, unknown> => {
- try {
- const {
- globalTime,
- dashboards: { dashboards },
- } = store.getState();
- if (dashboards.length > 0) {
- const [selectedDashboard] = dashboards || [];
- const {
- data: { variables = {} },
- } = selectedDashboard;
+export const getDashboardVariables = (
+ variables?: Dashboard['data']['variables'],
+): Record<string, unknown> => {
+ if (!variables) {
+ return {};
+ }
- const { start, end } = getStartEndRangeTime({
- type: 'GLOBAL_TIME',
- interval: globalTime.selectedTime,
- });
+ try {
+ const { globalTime } = store.getState();
+ const { start, end } = getStartEndRangeTime({
+ type: 'GLOBAL_TIME',
+ interval: globalTime.selectedTime,
+ });
- const variablesTuple: Record<string, unknown> = {
- SIGNOZ_START_TIME: parseInt(start, 10) * 1e3,
- SIGNOZ_END_TIME: parseInt(end, 10) * 1e3,
- };
- Object.keys(variables).forEach((key) => {
- variablesTuple[key] = variables[key].selectedValue;
- });
- return variablesTuple;
- }
- return {};
+ const variablesTuple: Record<string, unknown> = {
+ SIGNOZ_START_TIME: parseInt(start, 10) * 1e3,
+ SIGNOZ_END_TIME: parseInt(end, 10) * 1e3,
+ };
+ Object.keys(variables).forEach((key) => {
+ variablesTuple[key] = variables[key].selectedValue;
+ });
+ return variablesTuple;
} catch (e) {
console.error(e);
}
diff --git a/frontend/src/store/actions/dashboard/getQueryResults.ts b/frontend/src/lib/dashboard/getQueryResults.ts
similarity index 99%
rename from frontend/src/store/actions/dashboard/getQueryResults.ts
rename to frontend/src/lib/dashboard/getQueryResults.ts
index 2e6beae483..47f21bdd25 100644
--- a/frontend/src/store/actions/dashboard/getQueryResults.ts
+++ b/frontend/src/lib/dashboard/getQueryResults.ts
@@ -3,15 +3,16 @@
// @ts-nocheck
import { getMetricsQueryRange } from 'api/metrics/getQueryRange';
+import { PANEL_TYPES } from 'constants/queryBuilder';
import { timePreferenceType } from 'container/NewWidget/RightContainer/timeItems';
import { Time } from 'container/TopNav/DateTimeSelection/config';
+import { Pagination } from 'hooks/queryPagination';
import { convertNewDataToOld } from 'lib/newQueryBuilder/convertNewDataToOld';
import { isEmpty } from 'lodash-es';
import { SuccessResponse } from 'types/api';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
-import { Pagination } from 'hooks/queryPagination';
-import { PANEL_TYPES } from 'constants/queryBuilder';
+
import { prepareQueryRangePayload } from './prepareQueryRangePayload';
export async function GetMetricQueryRange(
diff --git a/frontend/src/store/actions/dashboard/prepareQueryRangePayload.ts b/frontend/src/lib/dashboard/prepareQueryRangePayload.ts
similarity index 100%
rename from frontend/src/store/actions/dashboard/prepareQueryRangePayload.ts
rename to frontend/src/lib/dashboard/prepareQueryRangePayload.ts
diff --git a/frontend/src/lib/getChartData.ts b/frontend/src/lib/getChartData.ts
index b45ee3d9fb..8686ac6054 100644
--- a/frontend/src/lib/getChartData.ts
+++ b/frontend/src/lib/getChartData.ts
@@ -5,10 +5,16 @@ import { QueryData } from 'types/api/widgets/getQuery';
import convertIntoEpoc from './covertIntoEpoc';
import { colors } from './getRandomColor';
+const limit = 20;
+
const getChartData = ({
queryData,
createDataset,
-}: GetChartDataProps): ChartData => {
+ isWarningLimit = false,
+}: GetChartDataProps): {
+ data: ChartData;
+ isWarning: boolean;
+} => {
const uniqueTimeLabels = new Set<number>();
queryData.forEach((data) => {
data.queryData.forEach((query) => {
@@ -62,27 +68,34 @@ const getChartData = ({
.map((e) => e.map((e) => e.second))
.reduce((a, b) => [...a, ...b], []);
- return {
- datasets: alldata.map((e, index) => {
- const datasetBaseConfig = {
- index,
- label: allLabels[index],
- borderColor: colors[index % colors.length] || 'red',
- data: e,
- borderWidth: 1.5,
- spanGaps: true,
- animations: false,
- showLine: true,
- pointRadius: 0,
- };
+ const updatedDataSet = alldata.map((e, index) => {
+ const datasetBaseConfig = {
+ index,
+ label: allLabels[index],
+ borderColor: colors[index % colors.length] || 'red',
+ data: e,
+ borderWidth: 1.5,
+ spanGaps: true,
+ animations: false,
+ showLine: true,
+ pointRadius: 0,
+ };
+
+ return createDataset ? createDataset(e, index, allLabels) : datasetBaseConfig;
+ });
- return createDataset
- ? createDataset(e, index, allLabels)
- : datasetBaseConfig;
- }),
- labels: response
- .map((e) => e.map((e) => e.first))
- .reduce((a, b) => [...a, ...b], [])[0],
+ const updatedLabels = response
+ .map((e) => e.map((e) => e.first))
+ .reduce((a, b) => [...a, ...b], [])[0];
+
+ const updatedData = {
+ datasets: isWarningLimit ? updatedDataSet?.slice(0, limit) : updatedDataSet,
+ labels: updatedLabels,
+ };
+
+ return {
+ data: updatedData,
+ isWarning: isWarningLimit && (updatedDataSet?.length || 0) > limit,
};
};
@@ -97,6 +110,7 @@ export interface GetChartDataProps {
index: number,
allLabels: string[],
) => ChartDataset;
+ isWarningLimit?: boolean;
}
export default getChartData;
diff --git a/frontend/src/lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi.ts b/frontend/src/lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi.ts
index f89c8b025e..1dd30b249b 100644
--- a/frontend/src/lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi.ts
+++ b/frontend/src/lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi.ts
@@ -1,4 +1,4 @@
-import { GetQueryResultsProps } from 'store/actions/dashboard/getQueryResults';
+import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import {
MapData,
MapQueryDataToApiResult,
diff --git a/frontend/src/pages/DashboardWidget/index.tsx b/frontend/src/pages/DashboardWidget/index.tsx
index fc8a712b63..9dd439d86c 100644
--- a/frontend/src/pages/DashboardWidget/index.tsx
+++ b/frontend/src/pages/DashboardWidget/index.tsx
@@ -1,30 +1,24 @@
import { Card, Typography } from 'antd';
import Spinner from 'components/Spinner';
+import { SOMETHING_WENT_WRONG } from 'constants/api';
import { PANEL_TYPES } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import NewWidget from 'container/NewWidget';
+import useUrlQuery from 'hooks/useUrlQuery';
import history from 'lib/history';
-import { useEffect, useRef, useState } from 'react';
-import { connect, useSelector } from 'react-redux';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { useEffect, useState } from 'react';
import { generatePath, useLocation, useParams } from 'react-router-dom';
-import { bindActionCreators, Dispatch } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
-import { GetDashboard, GetDashboardProps } from 'store/actions';
-import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
-import DashboardReducer from 'types/reducer/dashboards';
-function DashboardWidget({ getDashboard }: NewDashboardProps): JSX.Element {
+function DashboardWidget(): JSX.Element | null {
const { search } = useLocation();
const { dashboardId } = useParams<DashboardWidgetPageParams>();
const [selectedGraph, setSelectedGraph] = useState<PANEL_TYPES>();
- const { loading, dashboards, error, errorMessage } = useSelector<
- AppState,
- DashboardReducer
- >((state) => state.dashboards);
- const [selectedDashboard] = dashboards;
- const params = new URLSearchParams(search);
+
+ const { selectedDashboard, dashboardResponse } = useDashboard();
+
+ const params = useUrlQuery();
const widgetId = params.get('widgetId');
const { data } = selectedDashboard || {};
@@ -43,37 +37,22 @@ function DashboardWidget({ getDashboard }: NewDashboardProps): JSX.Element {
}
}, [dashboardId, search]);
- const counter = useRef(0);
-
- useEffect(() => {
- if (counter.current === 0 && selectedGraph && widgetId !== null) {
- counter.current = 1;
- getDashboard({
- uuid: dashboardId,
- graphType: selectedGraph,
- widgetId,
- });
- }
- }, [selectedGraph, dashboardId, getDashboard, search, widgetId]);
-
- if (
- selectedGraph === undefined ||
- loading ||
- dashboards.length === 0 ||
- dashboards[0].data.widgets === undefined ||
- selectedWidget === undefined
- ) {
+ if (selectedGraph === undefined || dashboardResponse.isLoading) {
return <Spinner tip="Loading.." />;
}
- if (error) {
+ if (dashboardResponse.isError) {
return (
<Card>
- <Typography>{errorMessage}</Typography>
+ <Typography>{SOMETHING_WENT_WRONG}</Typography>
</Card>
);
}
+ if (selectedWidget === undefined) {
+ return null;
+ }
+
return (
<NewWidget
yAxisUnit={selectedWidget.yAxisUnit}
@@ -86,20 +65,4 @@ export interface DashboardWidgetPageParams {
dashboardId: string;
}
-interface DispatchProps {
- getDashboard: ({
- uuid,
- widgetId,
- graphType,
- }: GetDashboardProps) => (dispatch: Dispatch<AppActions>) => void;
-}
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- getDashboard: bindActionCreators(GetDashboard, dispatch),
-});
-
-type NewDashboardProps = DispatchProps;
-
-export default connect(null, mapDispatchToProps)(DashboardWidget);
+export default DashboardWidget;
diff --git a/frontend/src/pages/NewDashboard/index.tsx b/frontend/src/pages/NewDashboard/index.tsx
index 98ed3d394f..105d21cfdf 100644
--- a/frontend/src/pages/NewDashboard/index.tsx
+++ b/frontend/src/pages/NewDashboard/index.tsx
@@ -1,70 +1,33 @@
import { Typography } from 'antd';
+import { AxiosError } from 'axios';
import NotFound from 'components/NotFound';
import Spinner from 'components/Spinner';
import NewDashboard from 'container/NewDashboard';
-import { useEffect } from 'react';
-import { connect, useSelector } from 'react-redux';
-import { useParams } from 'react-router-dom';
-import { bindActionCreators, Dispatch } from 'redux';
-import { ThunkDispatch } from 'redux-thunk';
-import { GetDashboard, GetDashboardProps } from 'store/actions/dashboard';
-import { AppState } from 'store/reducers';
-import AppActions from 'types/actions';
+import { useDashboard } from 'providers/Dashboard/Dashboard';
import { ErrorType } from 'types/common';
-import DashboardReducer from 'types/reducer/dashboards';
-function NewDashboardPage({ getDashboard }: NewDashboardProps): JSX.Element {
- const { loading, dashboards, error, errorMessage } = useSelector<
- AppState,
- DashboardReducer
- >((state) => state.dashboards);
+function NewDashboardPage(): JSX.Element {
+ const { dashboardResponse } = useDashboard();
- const { dashboardId } = useParams<Params>();
+ const { isFetching, isError, isLoading } = dashboardResponse;
- useEffect(() => {
- getDashboard({
- uuid: dashboardId,
- });
- }, [getDashboard, dashboardId]);
+ const errorMessage = isError
+ ? (dashboardResponse?.error as AxiosError)?.response?.data.errorType
+ : 'Something went wrong';
- if (
- error &&
- !loading &&
- dashboards.length === 0 &&
- errorMessage === ErrorType.NotFound
- ) {
+ if (isError && !isFetching && errorMessage === ErrorType.NotFound) {
return <NotFound />;
}
- if (error && !loading && dashboards.length === 0) {
+ if (isError && errorMessage) {
return <Typography>{errorMessage}</Typography>;
}
- // when user comes from dashboard page. dashboard array is populated with some dashboard as dashboard is populated
- // so to avoid any unmount call dashboard must have length zero
- if (loading || dashboards.length === 0 || dashboards.length !== 1) {
+ if (isLoading) {
return <Spinner tip="Loading.." />;
}
return <NewDashboard />;
}
-interface Params {
- dashboardId: string;
-}
-
-interface DispatchProps {
- getDashboard: (
- props: GetDashboardProps,
- ) => (dispatch: Dispatch<AppActions>) => void;
-}
-
-const mapDispatchToProps = (
- dispatch: ThunkDispatch<unknown, unknown, AppActions>,
-): DispatchProps => ({
- getDashboard: bindActionCreators(GetDashboard, dispatch),
-});
-
-type NewDashboardProps = DispatchProps;
-
-export default connect(null, mapDispatchToProps)(NewDashboardPage);
+export default NewDashboardPage;
diff --git a/frontend/src/providers/Dashboard/Dashboard.tsx b/frontend/src/providers/Dashboard/Dashboard.tsx
new file mode 100644
index 0000000000..9b4da727ae
--- /dev/null
+++ b/frontend/src/providers/Dashboard/Dashboard.tsx
@@ -0,0 +1,231 @@
+import { Modal } from 'antd';
+import get from 'api/dashboard/get';
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
+import ROUTES from 'constants/routes';
+import { getMinMax } from 'container/TopNav/AutoRefresh/config';
+import dayjs, { Dayjs } from 'dayjs';
+import useTabVisibility from 'hooks/useTabFocus';
+import {
+ createContext,
+ PropsWithChildren,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import { Layout } from 'react-grid-layout';
+import { useTranslation } from 'react-i18next';
+import { useQuery, UseQueryResult } from 'react-query';
+import { useDispatch, useSelector } from 'react-redux';
+import { useRouteMatch } from 'react-router-dom';
+import { Dispatch } from 'redux';
+import { AppState } from 'store/reducers';
+import AppActions from 'types/actions';
+import { UPDATE_TIME_INTERVAL } from 'types/actions/globalTime';
+import { Dashboard } from 'types/api/dashboard/getAll';
+import AppReducer from 'types/reducer/app';
+import { GlobalReducer } from 'types/reducer/globalTime';
+
+import { IDashboardContext } from './types';
+
+const DashboardContext = createContext<IDashboardContext>({
+ isDashboardSliderOpen: false,
+ handleToggleDashboardSlider: () => {},
+ dashboardResponse: {} as UseQueryResult<Dashboard, unknown>,
+ selectedDashboard: {} as Dashboard,
+ dashboardId: '',
+ layouts: [],
+ setLayouts: () => {},
+ setSelectedDashboard: () => {},
+ updatedTimeRef: {} as React.MutableRefObject<Dayjs | null>,
+});
+
+interface Props {
+ dashboardId: string;
+}
+
+export function DashboardProvider({
+ children,
+}: PropsWithChildren): JSX.Element {
+ const [isDashboardSliderOpen, setIsDashboardSlider] = useState<boolean>(false);
+ const isDashboardPage = useRouteMatch<Props>({
+ path: ROUTES.DASHBOARD,
+ exact: true,
+ });
+
+ const dispatch = useDispatch<Dispatch<AppActions>>();
+
+ const globalTime = useSelector<AppState, GlobalReducer>(
+ (state) => state.globalTime,
+ );
+
+ const [onModal, Content] = Modal.useModal();
+
+ const isDashboardWidgetPage = useRouteMatch<Props>({
+ path: ROUTES.DASHBOARD_WIDGET,
+ exact: true,
+ });
+
+ const [layouts, setLayouts] = useState<Layout[]>([]);
+
+ const { isLoggedIn } = useSelector<AppState, AppReducer>((state) => state.app);
+
+ const dashboardId =
+ (isDashboardPage
+ ? isDashboardPage.params.dashboardId
+ : isDashboardWidgetPage?.params.dashboardId) || '';
+
+ const [selectedDashboard, setSelectedDashboard] = useState<Dashboard>();
+
+ const updatedTimeRef = useRef<Dayjs | null>(null); // Using ref to store the updated time
+ const modalRef = useRef<any>(null);
+
+ const isVisible = useTabVisibility();
+
+ const { t } = useTranslation(['dashboard']);
+ const dashboardRef = useRef<Dashboard>();
+
+ const dashboardResponse = useQuery(
+ [REACT_QUERY_KEY.DASHBOARD_BY_ID, isDashboardPage?.params],
+ {
+ enabled: (!!isDashboardPage || !!isDashboardWidgetPage) && isLoggedIn,
+ queryFn: () =>
+ get({
+ uuid: dashboardId,
+ }),
+ refetchOnWindowFocus: false,
+ onSuccess: (data) => {
+ const updatedDate = dayjs(data.updated_at);
+
+ // on first render
+ if (updatedTimeRef.current === null) {
+ setSelectedDashboard(data);
+
+ updatedTimeRef.current = updatedDate;
+
+ dashboardRef.current = data;
+
+ setLayouts(
+ data.data.layout?.filter(
+ (layout) => layout.i !== PANEL_TYPES.EMPTY_WIDGET,
+ ) || [],
+ );
+ }
+
+ if (
+ updatedTimeRef.current !== null &&
+ updatedDate.isAfter(updatedTimeRef.current) &&
+ isVisible &&
+ dashboardRef.current?.id === data.id
+ ) {
+ // show modal when state is out of sync
+ const modal = onModal.confirm({
+ centered: true,
+ title: t('dashboard_has_been_updated'),
+ content: t('do_you_want_to_refresh_the_dashboard'),
+ onOk() {
+ setSelectedDashboard(data);
+
+ const { maxTime, minTime } = getMinMax(
+ globalTime.selectedTime,
+ globalTime.minTime,
+ globalTime.maxTime,
+ );
+
+ dispatch({
+ type: UPDATE_TIME_INTERVAL,
+ payload: {
+ maxTime,
+ minTime,
+ selectedTime: globalTime.selectedTime,
+ },
+ });
+
+ dashboardRef.current = data;
+
+ updatedTimeRef.current = dayjs(data.updated_at);
+
+ setLayouts(
+ data.data.layout?.filter(
+ (layout) => layout.i !== PANEL_TYPES.EMPTY_WIDGET,
+ ) || [],
+ );
+ },
+ });
+
+ modalRef.current = modal;
+ } else {
+ // normal flow
+ updatedTimeRef.current = dayjs(data.updated_at);
+
+ dashboardRef.current = data;
+
+ setSelectedDashboard(data);
+
+ setLayouts(
+ data.data.layout?.filter(
+ (layout) => layout.i !== PANEL_TYPES.EMPTY_WIDGET,
+ ) || [],
+ );
+ }
+ },
+ },
+ );
+
+ useEffect(() => {
+ if (isVisible && updatedTimeRef.current) {
+ dashboardResponse.refetch();
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isVisible]);
+
+ useEffect(() => {
+ if (!isVisible && modalRef.current) {
+ modalRef.current.destroy();
+ }
+ }, [isVisible]);
+
+ const handleToggleDashboardSlider = (value: boolean): void => {
+ setIsDashboardSlider(value);
+ };
+
+ const value: IDashboardContext = useMemo(
+ () => ({
+ isDashboardSliderOpen,
+ handleToggleDashboardSlider,
+ dashboardResponse,
+ selectedDashboard,
+ dashboardId,
+ layouts,
+ setLayouts,
+ setSelectedDashboard,
+ updatedTimeRef,
+ }),
+ [
+ isDashboardSliderOpen,
+ dashboardResponse,
+ selectedDashboard,
+ dashboardId,
+ layouts,
+ ],
+ );
+
+ return (
+ <DashboardContext.Provider value={value}>
+ {Content}
+ {children}
+ </DashboardContext.Provider>
+ );
+}
+
+export const useDashboard = (): IDashboardContext => {
+ const context = useContext(DashboardContext);
+
+ if (!context) {
+ throw new Error('Should be used inside the context');
+ }
+
+ return context;
+};
diff --git a/frontend/src/providers/Dashboard/types.ts b/frontend/src/providers/Dashboard/types.ts
new file mode 100644
index 0000000000..9fc15c5f77
--- /dev/null
+++ b/frontend/src/providers/Dashboard/types.ts
@@ -0,0 +1,18 @@
+import dayjs from 'dayjs';
+import { Layout } from 'react-grid-layout';
+import { UseQueryResult } from 'react-query';
+import { Dashboard } from 'types/api/dashboard/getAll';
+
+export interface IDashboardContext {
+ isDashboardSliderOpen: boolean;
+ handleToggleDashboardSlider: (value: boolean) => void;
+ dashboardResponse: UseQueryResult<Dashboard, unknown>;
+ selectedDashboard: Dashboard | undefined;
+ dashboardId: string;
+ layouts: Layout[];
+ setLayouts: React.Dispatch<React.SetStateAction<Layout[]>>;
+ setSelectedDashboard: React.Dispatch<
+ React.SetStateAction<Dashboard | undefined>
+ >;
+ updatedTimeRef: React.MutableRefObject<dayjs.Dayjs | null>;
+}
diff --git a/frontend/src/providers/Dashboard/util.ts b/frontend/src/providers/Dashboard/util.ts
new file mode 100644
index 0000000000..40ec15f75e
--- /dev/null
+++ b/frontend/src/providers/Dashboard/util.ts
@@ -0,0 +1,22 @@
+import { Dashboard, Widgets } from 'types/api/dashboard/getAll';
+
+export const getPreviousWidgets = (
+ selectedDashboard: Dashboard,
+ selectedWidgetIndex: number,
+): Widgets[] =>
+ selectedDashboard.data.widgets?.slice(0, selectedWidgetIndex || 0) || [];
+
+export const getNextWidgets = (
+ selectedDashboard: Dashboard,
+ selectedWidgetIndex: number,
+): Widgets[] =>
+ selectedDashboard.data.widgets?.slice(
+ (selectedWidgetIndex || 0) + 1, // this is never undefined
+ selectedDashboard.data.widgets?.length,
+ ) || [];
+
+export const getSelectedWidgetIndex = (
+ selectedDashboard: Dashboard,
+ widgetId: string | null,
+): number =>
+ selectedDashboard.data.widgets?.findIndex((e) => e.id === widgetId) || 0;
diff --git a/frontend/src/store/actions/dashboard/applySettingsToPanel.ts b/frontend/src/store/actions/dashboard/applySettingsToPanel.ts
deleted file mode 100644
index 0a9a6bdd5f..0000000000
--- a/frontend/src/store/actions/dashboard/applySettingsToPanel.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { Dispatch } from 'redux';
-import AppActions from 'types/actions';
-import { Widgets } from 'types/api/dashboard/getAll';
-
-export const ApplySettingsToPanel = (
- props: ApplySettingsToPanelProps,
-): ((dispatch: Dispatch<AppActions>) => void) => (
- dispatch: Dispatch<AppActions>,
-): void => {
- dispatch({
- type: 'APPLY_SETTINGS_TO_PANEL',
- payload: props,
- });
-};
-
-export interface ApplySettingsToPanelProps {
- title: Widgets['title'];
- description: Widgets['description'];
- opacity: Widgets['opacity'];
- isStacked: Widgets['isStacked'];
- timePreferance: Widgets['timePreferance'];
- nullZeroValues: Widgets['nullZeroValues'];
- widgetId: Widgets['id'];
- yAxisUnit: Widgets['yAxisUnit'];
-}
diff --git a/frontend/src/store/actions/dashboard/deleteDashboard.ts b/frontend/src/store/actions/dashboard/deleteDashboard.ts
deleted file mode 100644
index a8add8002a..0000000000
--- a/frontend/src/store/actions/dashboard/deleteDashboard.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import deleteDashboardApi from 'api/dashboard/delete';
-import { UseQueryResult } from 'react-query';
-import { Dispatch } from 'redux';
-import AppActions from 'types/actions';
-import { Dashboard } from 'types/api/dashboard/getAll';
-
-export const DeleteDashboard = ({
- uuid,
- refetch,
-}: DeleteDashboardProps): ((dispatch: Dispatch<AppActions>) => void) => async (
- dispatch: Dispatch<AppActions>,
-): Promise<void> => {
- try {
- const response = await deleteDashboardApi({
- uuid,
- });
-
- if (response.statusCode === 200) {
- refetch();
-
- dispatch({
- type: 'DELETE_DASHBOARD_SUCCESS',
- payload: {
- uuid,
- },
- });
- } else {
- dispatch({
- type: 'DELETE_DASHBOARD_ERROR',
- payload: {
- errorMessage: response.error || 'Something went wrong',
- },
- });
- }
- } catch (error) {
- dispatch({
- type: 'DELETE_DASHBOARD_ERROR',
- payload: {
- errorMessage:
- error instanceof Error ? error.toString() : 'Something went wrong',
- },
- });
- }
-};
-
-export interface DeleteDashboardProps {
- uuid: Dashboard['uuid'];
- refetch: UseQueryResult['refetch'];
-}
diff --git a/frontend/src/store/actions/dashboard/deleteQuery.ts b/frontend/src/store/actions/dashboard/deleteQuery.ts
deleted file mode 100644
index 0b0131d05f..0000000000
--- a/frontend/src/store/actions/dashboard/deleteQuery.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { Dispatch } from 'redux';
-import AppActions from 'types/actions';
-import { DeleteQueryProps } from 'types/actions/dashboard';
-
-export const DeleteQuery = (
- props: DeleteQueryProps,
-): ((dispatch: Dispatch<AppActions>) => void) => (
- dispatch: Dispatch<AppActions>,
-): void => {
- dispatch({
- type: 'DELETE_QUERY',
- payload: {
- currentIndex: props.currentIndex,
- widgetId: props.widgetId,
- },
- });
-};
diff --git a/frontend/src/store/actions/dashboard/deleteWidget.ts b/frontend/src/store/actions/dashboard/deleteWidget.ts
deleted file mode 100644
index d4a29db3f5..0000000000
--- a/frontend/src/store/actions/dashboard/deleteWidget.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import updateDashboardApi from 'api/dashboard/update';
-import { AxiosError } from 'axios';
-import { getPreLayouts, LayoutProps } from 'container/GridGraphLayout';
-import { Dispatch, SetStateAction } from 'react';
-import store from 'store';
-import AppActions from 'types/actions';
-import { UPDATE_DASHBOARD } from 'types/actions/dashboard';
-import { Dashboard, Widgets } from 'types/api/dashboard/getAll';
-
-export const DeleteWidget = ({
- widgetId,
- setLayout,
-}: DeleteWidgetProps): ((dispatch: Dispatch<AppActions>) => void) => async (
- dispatch: Dispatch<AppActions>,
-): Promise<void> => {
- try {
- const { dashboards } = store.getState();
- const [selectedDashboard] = dashboards.dashboards;
-
- const { widgets = [] } = selectedDashboard.data;
- const updatedWidgets = widgets.filter((e) => e.id !== widgetId);
- const updatedLayout =
- selectedDashboard.data.layout?.filter((e) => e.i !== widgetId) || [];
-
- const updatedSelectedDashboard: Dashboard = {
- ...selectedDashboard,
- data: {
- title: selectedDashboard.data.title,
- description: selectedDashboard.data.description,
- name: selectedDashboard.data.name,
- tags: selectedDashboard.data.tags,
- widgets: updatedWidgets,
- layout: updatedLayout,
- variables: selectedDashboard.data.variables,
- },
- uuid: selectedDashboard.uuid,
- };
-
- const response = await updateDashboardApi(updatedSelectedDashboard);
-
- if (response.statusCode === 200) {
- dispatch({
- type: UPDATE_DASHBOARD,
- payload: updatedSelectedDashboard,
- });
- if (setLayout) {
- setLayout(getPreLayouts(updatedWidgets, updatedLayout));
- }
- } else {
- dispatch({
- type: 'DELETE_WIDGET_ERROR',
- payload: {
- errorMessage: response.error || 'Something went wrong',
- },
- });
- }
- } catch (error) {
- dispatch({
- type: 'DELETE_WIDGET_ERROR',
- payload: {
- errorMessage: (error as AxiosError).toString() || 'Something went wrong',
- },
- });
- }
-};
-
-export interface DeleteWidgetProps {
- widgetId: Widgets['id'];
- setLayout?: Dispatch<SetStateAction<LayoutProps[]>>;
-}
diff --git a/frontend/src/store/actions/dashboard/getDashboard.ts b/frontend/src/store/actions/dashboard/getDashboard.ts
deleted file mode 100644
index 76305bae3b..0000000000
--- a/frontend/src/store/actions/dashboard/getDashboard.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import getDashboard from 'api/dashboard/get';
-import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
-import { Dispatch } from 'redux';
-import AppActions from 'types/actions';
-import { Props } from 'types/api/dashboard/get';
-
-export const GetDashboard = ({
- uuid,
- widgetId,
- graphType,
-}: GetDashboardProps): ((dispatch: Dispatch<AppActions>) => void) => async (
- dispatch: Dispatch<AppActions>,
-): Promise<void> => {
- try {
- dispatch({
- type: 'GET_DASHBOARD_LOADING_START',
- });
-
- const response = await getDashboard({
- uuid,
- });
-
- if (response.statusCode === 200) {
- dispatch({
- payload: response.payload,
- type: 'GET_DASHBOARD_SUCCESS',
- });
-
- if (widgetId !== undefined) {
- dispatch({
- type: 'CREATE_DEFAULT_WIDGET',
- payload: {
- description: '',
- id: widgetId,
- isStacked: false,
- nullZeroValues: 'zero',
- opacity: '0',
- panelTypes: graphType || PANEL_TYPES.TIME_SERIES,
- timePreferance: 'GLOBAL_TIME',
- title: '',
- query: initialQueriesMap.metrics,
- },
- });
- }
- } else {
- dispatch({
- type: 'GET_DASHBOARD_ERROR',
- payload: {
- errorMessage: response.error || 'Something went wrong',
- },
- });
- }
- } catch (error) {
- dispatch({
- type: 'GET_DASHBOARD_ERROR',
- payload: {
- errorMessage:
- error instanceof Error ? error.toString() : 'Something went wrong',
- },
- });
- }
-};
-
-export interface GetDashboardProps {
- uuid: Props['uuid'];
- widgetId?: string;
- graphType?: PANEL_TYPES;
-}
diff --git a/frontend/src/store/actions/dashboard/index.ts b/frontend/src/store/actions/dashboard/index.ts
deleted file mode 100644
index b01947fe3d..0000000000
--- a/frontend/src/store/actions/dashboard/index.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export * from './applySettingsToPanel';
-export * from './deleteDashboard';
-export * from './deleteQuery';
-export * from './getDashboard';
-export * from './toggleEditMode';
-export * from './updateDashboardTitle';
diff --git a/frontend/src/store/actions/dashboard/saveDashboard.ts b/frontend/src/store/actions/dashboard/saveDashboard.ts
deleted file mode 100644
index 614c66b18c..0000000000
--- a/frontend/src/store/actions/dashboard/saveDashboard.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-import { notification } from 'antd';
-import updateDashboardApi from 'api/dashboard/update';
-import { AxiosError } from 'axios';
-import { QueryParams } from 'constants/query';
-import { PANEL_TYPES } from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
-import { updateStepInterval } from 'hooks/queryBuilder/useStepInterval';
-import history from 'lib/history';
-import { Layout } from 'react-grid-layout';
-import { generatePath } from 'react-router-dom';
-import { Dispatch } from 'redux';
-import store from 'store';
-import AppActions from 'types/actions';
-import { Dashboard, Widgets } from 'types/api/dashboard/getAll';
-import { v4 } from 'uuid';
-
-export const SaveDashboard = ({
- uuid,
- description,
- isStacked,
- nullZeroValues,
- opacity,
- timePreferance,
- title,
- widgetId,
- dashboardId,
- yAxisUnit,
- graphType,
-}: SaveDashboardProps): ((dispatch: Dispatch<AppActions>) => void) =>
- // eslint-disable-next-line sonarjs/cognitive-complexity
- async (dispatch: Dispatch<AppActions>): Promise<void> => {
- try {
- const dashboard = store.getState();
-
- const selectedDashboard = dashboard.dashboards.dashboards.find(
- (e) => e.uuid === uuid,
- );
-
- if (selectedDashboard === undefined) {
- throw new Error('Dashboard Not Found');
- }
-
- const { data } = selectedDashboard;
-
- const updatedTitle = title;
- const updatedDescription = description;
- const updatedisStacked = isStacked;
- const updatednullZeroValues = nullZeroValues;
- const updatedopacity = opacity;
- const updatedtimePreferance = timePreferance;
- const updatedYAxisUnit = yAxisUnit;
-
- const selectedWidgetIndex = data.widgets?.findIndex(
- (e) => e.id === widgetId,
- );
-
- const isEmptyWidget = widgetId === 'empty';
-
- const emptyLayoutIndex = data.layout?.findIndex((e) => e.i === 'empty');
-
- const newWidgetId = v4();
-
- const preWidget = data.widgets?.slice(0, selectedWidgetIndex) || [];
-
- const afterWidget =
- data.widgets?.slice(
- (selectedWidgetIndex || 0) + 1, // this is never undefined
- data.widgets?.length,
- ) || [];
-
- const selectedWidget = (selectedDashboard.data.widgets || [])[
- selectedWidgetIndex || 0
- ];
-
- const getAllLayout = (): Layout[] => {
- const allLayout = data.layout || [];
-
- // empty layout is not present
- if (emptyLayoutIndex === -1 || emptyLayoutIndex === undefined) {
- return allLayout;
- }
-
- return [
- ...allLayout.slice(0, emptyLayoutIndex),
- { ...allLayout[emptyLayoutIndex], i: newWidgetId },
- ...allLayout.slice(emptyLayoutIndex + 1, allLayout.length),
- ];
- };
- const allLayout = getAllLayout();
- const params = new URLSearchParams(window.location.search);
- const compositeQuery = params.get(QueryParams.compositeQuery);
- const { maxTime, minTime } = store.getState().globalTime;
- const query = compositeQuery
- ? updateStepInterval(
- JSON.parse(decodeURIComponent(compositeQuery)),
- maxTime,
- minTime,
- )
- : updateStepInterval(selectedWidget.query, maxTime, minTime);
-
- const response = await updateDashboardApi({
- data: {
- ...selectedDashboard.data,
- // this is the data for the dashboard
- title: selectedDashboard.data.title,
- description: selectedDashboard.data.description,
- tags: selectedDashboard.data.tags,
- name: selectedDashboard.data.name,
- layout: allLayout,
- // as we are updated the widget only
- widgets: [
- ...preWidget,
- {
- ...selectedWidget,
- query,
- description: updatedDescription,
- id: isEmptyWidget ? newWidgetId : widgetId,
- isStacked: updatedisStacked,
- nullZeroValues: updatednullZeroValues,
- opacity: updatedopacity,
- title: updatedTitle,
- timePreferance: updatedtimePreferance,
- yAxisUnit: updatedYAxisUnit,
- panelTypes: graphType,
- },
- ...afterWidget,
- ],
- },
- uuid,
- });
-
- if (response.statusCode === 200) {
- dispatch({
- type: 'SAVE_SETTING_TO_PANEL_SUCCESS',
- payload: response.payload,
- });
- history.push(generatePath(ROUTES.DASHBOARD, { dashboardId }));
- } else {
- const error = 'Something went wrong';
-
- notification.error({
- message: response.error || error,
- });
-
- dispatch({
- type: 'SAVE_SETTING_TO_PANEL_ERROR',
- payload: {
- errorMessage: response.error || error,
- },
- });
- }
- } catch (error) {
- dispatch({
- type: 'SAVE_SETTING_TO_PANEL_ERROR',
- payload: {
- errorMessage: (error as AxiosError).toString() || 'Something went wrong',
- },
- });
- }
- };
-
-export interface SaveDashboardProps {
- uuid: Dashboard['uuid'];
- title: Widgets['title'];
- description: Widgets['description'];
- opacity: Widgets['opacity'];
- isStacked: Widgets['isStacked'];
- timePreferance: Widgets['timePreferance'];
- nullZeroValues: Widgets['nullZeroValues'];
- widgetId: Widgets['id'];
- dashboardId: string;
- yAxisUnit: Widgets['yAxisUnit'];
- graphType: PANEL_TYPES;
-}
diff --git a/frontend/src/store/actions/dashboard/toggleAddWidget.ts b/frontend/src/store/actions/dashboard/toggleAddWidget.ts
deleted file mode 100644
index ba2ad08107..0000000000
--- a/frontend/src/store/actions/dashboard/toggleAddWidget.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { Dispatch } from 'redux';
-import AppActions from 'types/actions';
-
-export const ToggleAddWidget = (
- props: ToggleAddWidgetProps,
-): ((dispatch: Dispatch<AppActions>) => void) => (
- dispatch: Dispatch<AppActions>,
-): void => {
- dispatch({
- type: 'IS_ADD_WIDGET',
- payload: {
- isAddWidget: props,
- },
- });
-};
-
-export type ToggleAddWidgetProps = boolean;
diff --git a/frontend/src/store/actions/dashboard/toggleEditMode.ts b/frontend/src/store/actions/dashboard/toggleEditMode.ts
deleted file mode 100644
index f03d6c5ff4..0000000000
--- a/frontend/src/store/actions/dashboard/toggleEditMode.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { Dispatch } from 'redux';
-import AppActions from 'types/actions';
-
-export const ToggleEditMode = (): ((
- dispatch: Dispatch<AppActions>,
-) => void) => (dispatch: Dispatch<AppActions>): void => {
- dispatch({
- type: 'TOGGLE_EDIT_MODE',
- });
-};
diff --git a/frontend/src/store/actions/dashboard/updateDashboardTitle.ts b/frontend/src/store/actions/dashboard/updateDashboardTitle.ts
deleted file mode 100644
index 4400e3ea39..0000000000
--- a/frontend/src/store/actions/dashboard/updateDashboardTitle.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import update from 'api/dashboard/update';
-import { Dispatch } from 'redux';
-import AppActions from 'types/actions';
-import { Dashboard } from 'types/api/dashboard/getAll';
-
-export const UpdateDashboardTitleDescriptionTags = ({
- dashboard, // @TODO need to grab the dashboard from the store
-}: UpdateDashboardTitleDescriptionTagsProps): ((
- dispatch: Dispatch<AppActions>,
-) => void) => async (dispatch: Dispatch<AppActions>): Promise<void> => {
- try {
- const { data } = dashboard;
-
- const response = await update({
- data: {
- ...dashboard.data,
- title: dashboard.data.title,
- },
- uuid: dashboard.uuid,
- });
-
- if (response.statusCode === 200) {
- dispatch({
- type: 'UPDATE_TITLE_DESCRIPTION_TAGS_SUCCESS',
- payload: {
- description: data.description,
- tags: data.tags,
- title: dashboard.data.title,
- },
- });
- dispatch({
- type: 'TOGGLE_EDIT_MODE',
- });
- } else {
- dispatch({
- type: 'UPDATE_TITLE_DESCRIPTION_TAGS_ERROR',
- payload: {
- errorMessage: response.error || 'Something went wrong',
- },
- });
- }
- } catch (error) {
- dispatch({
- type: 'UPDATE_TITLE_DESCRIPTION_TAGS_ERROR',
- payload: {
- errorMessage:
- error instanceof Error ? error.toString() : 'Something went wrong',
- },
- });
- }
-};
-
-export interface UpdateDashboardTitleDescriptionTagsProps {
- dashboard: Dashboard;
-}
diff --git a/frontend/src/store/actions/dashboard/updateQuery.ts b/frontend/src/store/actions/dashboard/updateQuery.ts
deleted file mode 100644
index 5b30c4dfe3..0000000000
--- a/frontend/src/store/actions/dashboard/updateQuery.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { Dispatch } from 'redux';
-import AppActions from 'types/actions';
-
-export const UpdateQuery = (
- props: UpdateQueryProps,
-): ((dispatch: Dispatch<AppActions>) => void) => (
- dispatch: Dispatch<AppActions>,
-): void => {
- dispatch({
- type: 'UPDATE_QUERY',
- payload: {
- widgetId: props.widgetId,
- yAxisUnit: props.yAxisUnit,
- },
- });
-};
-
-export interface UpdateQueryProps {
- widgetId: string;
- yAxisUnit: string | undefined;
-}
diff --git a/frontend/src/store/actions/dashboard/updatedDashboardVariables.ts b/frontend/src/store/actions/dashboard/updatedDashboardVariables.ts
deleted file mode 100644
index 4b1d2091f5..0000000000
--- a/frontend/src/store/actions/dashboard/updatedDashboardVariables.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { NotificationInstance } from 'antd/es/notification/interface';
-import update from 'api/dashboard/update';
-import { Dispatch } from 'redux';
-import store from 'store/index';
-import AppActions from 'types/actions';
-import { UPDATE_DASHBOARD_VARIABLES } from 'types/actions/dashboard';
-import { IDashboardVariable } from 'types/api/dashboard/getAll';
-
-export const UpdateDashboardVariables = (
- variables: Record<string, IDashboardVariable>,
- notify: NotificationInstance,
-): ((dispatch: Dispatch<AppActions>) => void) => async (
- dispatch: Dispatch<AppActions>,
-): Promise<void> => {
- try {
- dispatch({
- type: UPDATE_DASHBOARD_VARIABLES,
- payload: variables,
- });
-
- const reduxStoreState = store.getState();
- const [dashboard] = reduxStoreState.dashboards.dashboards;
-
- const response = await update({
- data: {
- ...dashboard.data,
- },
- uuid: dashboard.uuid,
- });
-
- if (response.statusCode !== 200) {
- notify.error({
- message: response.error,
- });
- }
- } catch (error) {
- console.error(error);
- }
-};
diff --git a/frontend/src/store/actions/index.ts b/frontend/src/store/actions/index.ts
index 7281693e13..3074cdb3a2 100644
--- a/frontend/src/store/actions/index.ts
+++ b/frontend/src/store/actions/index.ts
@@ -1,5 +1,4 @@
export * from './app';
-export * from './dashboard';
export * from './global';
export * from './metrics';
export * from './serviceMap';
diff --git a/frontend/src/store/reducers/dashboard.ts b/frontend/src/store/reducers/dashboard.ts
deleted file mode 100644
index f9140830b3..0000000000
--- a/frontend/src/store/reducers/dashboard.ts
+++ /dev/null
@@ -1,331 +0,0 @@
-import {
- APPLY_SETTINGS_TO_PANEL,
- CREATE_DEFAULT_WIDGET,
- DashboardActions,
- DELETE_DASHBOARD_SUCCESS,
- // DELETE_QUERY,
- DELETE_WIDGET_SUCCESS,
- FLUSH_DASHBOARD,
- GET_ALL_DASHBOARD_ERROR,
- GET_ALL_DASHBOARD_LOADING_START,
- GET_ALL_DASHBOARD_SUCCESS,
- GET_DASHBOARD_ERROR,
- GET_DASHBOARD_LOADING_START,
- GET_DASHBOARD_SUCCESS,
- IS_ADD_WIDGET,
- SAVE_SETTING_TO_PANEL_SUCCESS,
- TOGGLE_EDIT_MODE,
- UPDATE_DASHBOARD,
- UPDATE_DASHBOARD_VARIABLES,
- UPDATE_QUERY,
- UPDATE_TITLE_DESCRIPTION_TAGS_SUCCESS,
-} from 'types/actions/dashboard';
-import InitialValueTypes from 'types/reducer/dashboards';
-
-const InitialValue: InitialValueTypes = {
- dashboards: [],
- loading: false,
- error: false,
- errorMessage: '',
- isEditMode: false,
- isAddWidget: false,
-};
-
-const dashboard = (
- state = InitialValue,
- action: DashboardActions,
- // eslint-disable-next-line sonarjs/cognitive-complexity
-): InitialValueTypes => {
- switch (action.type) {
- case GET_ALL_DASHBOARD_LOADING_START:
- case GET_DASHBOARD_LOADING_START: {
- return {
- ...state,
- loading: true,
- };
- }
-
- case GET_ALL_DASHBOARD_SUCCESS: {
- return {
- ...state,
- loading: false,
- dashboards: action.payload,
- };
- }
-
- case GET_DASHBOARD_SUCCESS: {
- const dashboard = action.payload;
- const { data } = dashboard;
- return {
- ...state,
- loading: false,
- dashboards: [
- {
- ...dashboard,
- data: {
- ...data,
- },
- },
- ],
- };
- }
-
- case GET_ALL_DASHBOARD_ERROR: {
- const { payload } = action;
-
- return {
- ...state,
- loading: false,
- error: true,
- errorMessage: payload.errorMessage,
- };
- }
-
- case GET_DASHBOARD_ERROR: {
- return {
- ...state,
- loading: false,
- errorMessage: action.payload.errorMessage,
- error: true,
- };
- }
-
- case UPDATE_TITLE_DESCRIPTION_TAGS_SUCCESS: {
- const [dashboard] = state.dashboards;
-
- const dashboardData = dashboard.data;
- const { tags, title, description } = action.payload;
-
- return {
- ...state,
- dashboards: [
- {
- created_at: dashboard.created_at,
- id: dashboard.id,
- updated_at: dashboard.updated_at,
- uuid: dashboard.uuid,
- data: {
- ...dashboardData,
- tags,
- title,
- description,
- },
- },
- ],
- };
- }
-
- case TOGGLE_EDIT_MODE: {
- return {
- ...state,
- isEditMode: !state.isEditMode,
- };
- }
-
- case DELETE_DASHBOARD_SUCCESS: {
- return {
- ...state,
- dashboards: state.dashboards.filter((e) => e.uuid !== action.payload.uuid),
- };
- }
-
- // NOTE: this action will will be dispatched in the single dashboard only
- case CREATE_DEFAULT_WIDGET: {
- const [selectedDashboard] = state.dashboards;
- const { data } = selectedDashboard;
- const { widgets } = data;
- const defaultWidget = action.payload;
- const { query } = action.payload;
-
- const isPresent = widgets?.find((e) => e.id === action.payload.id);
-
- if (isPresent !== undefined) {
- return {
- ...state,
- };
- }
-
- return {
- ...state,
- dashboards: [
- {
- ...selectedDashboard,
- data: {
- ...data,
- widgets: [
- ...(widgets || []),
- {
- ...defaultWidget,
- query,
- id: action.payload.id,
- },
- ],
- },
- },
- ],
- };
- }
-
- case APPLY_SETTINGS_TO_PANEL: {
- const { widgetId } = action.payload;
-
- const { dashboards } = state;
- const [selectedDashboard] = dashboards;
- const { data } = selectedDashboard;
- const { widgets } = data;
-
- const selectedWidgetIndex = data.widgets?.findIndex(
- (e) => e.id === widgetId,
- );
-
- const preWidget = data.widgets?.slice(0, selectedWidgetIndex) || [];
- const afterWidget =
- data.widgets?.slice(
- (selectedWidgetIndex || 0) + 1, // this is never undefined
- widgets?.length,
- ) || [];
-
- const selectedWidget = (selectedDashboard.data.widgets || [])[
- selectedWidgetIndex || 0
- ];
-
- return {
- ...state,
- dashboards: [
- {
- ...selectedDashboard,
- data: {
- ...data,
- widgets: [
- ...preWidget,
- {
- ...selectedWidget,
- description: action.payload.description,
- id: action.payload.widgetId,
- isStacked: action.payload.isStacked,
- nullZeroValues: action.payload.nullZeroValues,
- opacity: action.payload.opacity,
- timePreferance: action.payload.timePreferance,
- title: action.payload.title,
- },
- ...afterWidget,
- ],
- },
- },
- ],
- };
- }
-
- case SAVE_SETTING_TO_PANEL_SUCCESS:
- case UPDATE_DASHBOARD: {
- const selectedDashboard = action.payload;
-
- return {
- ...state,
- dashboards: [
- {
- ...selectedDashboard,
- },
- ],
- };
- }
-
- case FLUSH_DASHBOARD: {
- return {
- ...state,
- dashboards: [],
- };
- }
- case DELETE_WIDGET_SUCCESS: {
- const { widgetId, layout } = action.payload;
-
- const { dashboards } = state;
- const [selectedDashboard] = dashboards;
- const { data } = selectedDashboard;
- const { widgets = [] } = data;
-
- return {
- ...state,
- dashboards: [
- {
- ...selectedDashboard,
- data: {
- ...data,
- widgets: widgets.filter((e) => e.id !== widgetId),
- layout,
- },
- },
- ],
- };
- }
-
- case IS_ADD_WIDGET: {
- return {
- ...state,
- isAddWidget: action.payload.isAddWidget,
- };
- }
-
- case UPDATE_QUERY: {
- const { widgetId, yAxisUnit } = action.payload;
- const { dashboards } = state;
- const [selectedDashboard] = dashboards;
- const { data } = selectedDashboard;
- const { widgets = [] } = data;
-
- const selectedWidgetIndex = widgets.findIndex((e) => e.id === widgetId) || 0;
-
- const preWidget = widgets?.slice(0, selectedWidgetIndex) || [];
- const afterWidget =
- widgets?.slice(
- selectedWidgetIndex + 1, // this is never undefined
- widgets.length,
- ) || [];
-
- const selectedWidget = widgets[selectedWidgetIndex];
-
- return {
- ...state,
- dashboards: [
- {
- ...selectedDashboard,
- data: {
- ...data,
- widgets: [
- ...preWidget,
- {
- ...selectedWidget,
- yAxisUnit,
- },
- ...afterWidget,
- ],
- },
- },
- ],
- };
- }
- case UPDATE_DASHBOARD_VARIABLES: {
- const variablesData = action.payload;
- const { dashboards } = state;
- const [selectedDashboard] = dashboards;
- const { data } = selectedDashboard;
-
- return {
- ...state,
- dashboards: [
- {
- ...selectedDashboard,
- data: {
- ...data,
- variables: variablesData,
- },
- },
- ],
- };
- }
- default:
- return state;
- }
-};
-
-export default dashboard;
diff --git a/frontend/src/store/reducers/index.ts b/frontend/src/store/reducers/index.ts
index bfb7a357e1..b685ff6412 100644
--- a/frontend/src/store/reducers/index.ts
+++ b/frontend/src/store/reducers/index.ts
@@ -1,7 +1,6 @@
import { combineReducers } from 'redux';
import appReducer from './app';
-import dashboardReducer from './dashboard';
import globalTimeReducer from './global';
import { LogsReducer } from './logs';
import metricsReducers from './metric';
@@ -14,7 +13,6 @@ const reducers = combineReducers({
usageDate: usageDataReducer,
globalTime: globalTimeReducer,
serviceMap: ServiceMapReducer,
- dashboards: dashboardReducer,
app: appReducer,
metrics: metricsReducers,
logs: LogsReducer,
diff --git a/frontend/src/types/actions/dashboard.ts b/frontend/src/types/actions/dashboard.ts
deleted file mode 100644
index a147eb7516..0000000000
--- a/frontend/src/types/actions/dashboard.ts
+++ /dev/null
@@ -1,189 +0,0 @@
-import { Layout } from 'react-grid-layout';
-import { ApplySettingsToPanelProps } from 'store/actions/dashboard/applySettingsToPanel';
-import {
- Dashboard,
- IDashboardVariable,
- Widgets,
-} from 'types/api/dashboard/getAll';
-import { QueryData } from 'types/api/widgets/getQuery';
-
-export const GET_DASHBOARD = 'GET_DASHBOARD';
-export const UPDATE_DASHBOARD = 'UPDATE_DASHBOARD';
-
-export const GET_ALL_DASHBOARD_LOADING_START =
- 'GET_ALL_DASHBOARD_LOADING_START';
-export const GET_ALL_DASHBOARD_SUCCESS = 'GET_ALL_DASHBOARD_SUCCESS';
-export const GET_ALL_DASHBOARD_ERROR = 'GET_ALL_DASHBOARD_ERROR';
-
-export const GET_DASHBOARD_LOADING_START = 'GET_DASHBOARD_LOADING_START';
-export const GET_DASHBOARD_SUCCESS = 'GET_DASHBOARD_SUCCESS';
-export const GET_DASHBOARD_ERROR = 'GET_DASHBOARD_ERROR';
-export const UPDATE_TITLE_DESCRIPTION_TAGS_SUCCESS =
- 'UPDATE_TITLE_DESCRIPTION_TAGS_SUCCESS';
-export const UPDATE_TITLE_DESCRIPTION_TAGS_ERROR =
- 'UPDATE_TITLE_DESCRIPTION_TAGS_ERROR';
-export const TOGGLE_EDIT_MODE = 'TOGGLE_EDIT_MODE';
-
-export const DELETE_DASHBOARD_SUCCESS = 'DELETE_DASHBOARD_SUCCESS';
-export const DELETE_DASHBOARD_ERROR = 'DELETE_DASHBOARD_ERROR';
-
-export const CREATE_DEFAULT_WIDGET = 'CREATE_DEFAULT_WIDGET';
-
-export const UPDATE_QUERY = 'UPDATE_QUERY';
-
-export const APPLY_SETTINGS_TO_PANEL = 'APPLY_SETTINGS_TO_PANEL';
-
-export const SAVE_SETTING_TO_PANEL_SUCCESS = 'SAVE_SETTING_TO_PANEL_SUCCESS';
-export const SAVE_SETTING_TO_PANEL_ERROR = 'SAVE_SETTING_TO_PANEL_ERROR';
-
-export const DELETE_WIDGET_SUCCESS = 'DELETE_WIDGET_SUCCESS';
-export const DELETE_WIDGET_ERROR = 'DELETE_WIDGET_ERROR';
-
-export const IS_ADD_WIDGET = 'IS_ADD_WIDGET';
-
-export const DELETE_QUERY = 'DELETE_QUERY';
-export const FLUSH_DASHBOARD = 'FLUSH_DASHBOARD';
-export const UPDATE_DASHBOARD_VARIABLES = 'UPDATE_DASHBOARD_VARIABLES';
-
-interface GetDashboard {
- type: typeof GET_DASHBOARD;
- payload: Dashboard;
-}
-interface UpdateDashboard {
- type: typeof UPDATE_DASHBOARD;
- payload: Dashboard;
-}
-
-interface DeleteDashboardSuccess {
- type: typeof DELETE_DASHBOARD_SUCCESS;
- payload: {
- uuid: Dashboard['uuid'];
- };
-}
-
-interface DashboardStart {
- type:
- | typeof GET_ALL_DASHBOARD_LOADING_START
- | typeof GET_DASHBOARD_LOADING_START;
-}
-
-interface GetAllDashboardSuccess {
- type: typeof GET_ALL_DASHBOARD_SUCCESS;
- payload: Dashboard[];
-}
-
-interface GetDashboardSuccess {
- type: typeof GET_DASHBOARD_SUCCESS;
- payload: Dashboard;
-}
-
-interface ApplySettingsToPanel {
- type: typeof APPLY_SETTINGS_TO_PANEL;
- payload: ApplySettingsToPanelProps;
-}
-
-interface CreateDefaultWidget {
- type: typeof CREATE_DEFAULT_WIDGET;
- payload: Widgets;
-}
-
-interface IsAddWidget {
- type: typeof IS_ADD_WIDGET;
- payload: {
- isAddWidget: boolean;
- };
-}
-
-interface DashboardError {
- type:
- | typeof GET_ALL_DASHBOARD_ERROR
- | typeof GET_DASHBOARD_ERROR
- | typeof UPDATE_TITLE_DESCRIPTION_TAGS_ERROR
- | typeof DELETE_DASHBOARD_ERROR
- | typeof SAVE_SETTING_TO_PANEL_ERROR
- | typeof DELETE_WIDGET_ERROR;
- payload: {
- errorMessage: string;
- };
-}
-
-interface UpdateDashboardTitle {
- type: typeof UPDATE_TITLE_DESCRIPTION_TAGS_SUCCESS;
- payload: {
- title: Dashboard['data']['title'];
- description: Dashboard['data']['description'];
- tags: Dashboard['data']['tags'];
- };
-}
-
-interface ToggleEditMode {
- type: typeof TOGGLE_EDIT_MODE;
-}
-
-export interface QuerySuccessPayload {
- widgetId: string;
- data: {
- // legend: string;
- queryData: QueryData[];
- // query: string
- };
-}
-
-interface UpdateQuery {
- type: typeof UPDATE_QUERY;
- payload: {
- widgetId: string;
- yAxisUnit: string | undefined;
- };
-}
-
-interface SaveDashboardSuccess {
- type: typeof SAVE_SETTING_TO_PANEL_SUCCESS;
- payload: Dashboard;
-}
-
-interface WidgetDeleteSuccess {
- type: typeof DELETE_WIDGET_SUCCESS;
- payload: {
- widgetId: Widgets['id'];
- layout: Layout[];
- };
-}
-
-export interface DeleteQueryProps {
- widgetId: string;
- currentIndex: number;
-}
-
-interface DeleteQuery {
- type: typeof DELETE_QUERY;
- payload: DeleteQueryProps;
-}
-
-interface FlushDashboard {
- type: typeof FLUSH_DASHBOARD;
-}
-interface UpdateDashboardVariables {
- type: typeof UPDATE_DASHBOARD_VARIABLES;
- payload: Record<string, IDashboardVariable>;
-}
-
-export type DashboardActions =
- | GetDashboard
- | UpdateDashboard
- | DeleteDashboardSuccess
- | DashboardError
- | GetAllDashboardSuccess
- | DashboardStart
- | GetDashboardSuccess
- | UpdateDashboardTitle
- | ToggleEditMode
- | CreateDefaultWidget
- | ApplySettingsToPanel
- | SaveDashboardSuccess
- | WidgetDeleteSuccess
- | IsAddWidget
- | UpdateQuery
- | DeleteQuery
- | FlushDashboard
- | UpdateDashboardVariables;
diff --git a/frontend/src/types/actions/index.ts b/frontend/src/types/actions/index.ts
index 5d15b0c150..723c6956bb 100644
--- a/frontend/src/types/actions/index.ts
+++ b/frontend/src/types/actions/index.ts
@@ -1,12 +1,10 @@
import { AppAction } from './app';
-import { DashboardActions } from './dashboard';
import { GlobalTimeAction } from './globalTime';
import { LogsActions } from './logs';
import { MetricsActions } from './metrics';
import { TraceActions } from './trace';
type AppActions =
- | DashboardActions
| AppAction
| GlobalTimeAction
| MetricsActions
diff --git a/frontend/src/types/api/dashboard/delete.ts b/frontend/src/types/api/dashboard/delete.ts
index 78d3253d30..9bdc519b47 100644
--- a/frontend/src/types/api/dashboard/delete.ts
+++ b/frontend/src/types/api/dashboard/delete.ts
@@ -3,3 +3,7 @@ import { Dashboard } from './getAll';
export type Props = {
uuid: Dashboard['uuid'];
};
+
+export interface PayloadProps {
+ status: 'success';
+}
diff --git a/frontend/src/types/reducer/dashboards.ts b/frontend/src/types/reducer/dashboards.ts
deleted file mode 100644
index a8d5bb2bae..0000000000
--- a/frontend/src/types/reducer/dashboards.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { PayloadProps } from 'types/api/dashboard/getAll';
-
-export default interface DashboardReducer {
- dashboards: PayloadProps;
- loading: boolean;
- error: boolean;
- errorMessage: string;
- isEditMode: boolean;
- isAddWidget: boolean;
-}
diff --git a/frontend/src/utils/dashboard/selectedDashboard.ts b/frontend/src/utils/dashboard/selectedDashboard.ts
deleted file mode 100644
index c05077f39c..0000000000
--- a/frontend/src/utils/dashboard/selectedDashboard.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { Dashboard, IDashboardVariable } from 'types/api/dashboard/getAll';
-
-export const getSelectedDashboard = (dashboard: Dashboard[]): Dashboard => {
- if (dashboard.length > 0) {
- return dashboard[0];
- }
- return {} as Dashboard;
-};
-
-export const getSelectedDashboardVariable = (
- dashboard: Dashboard[],
-): Record<string, IDashboardVariable> => {
- if (dashboard.length > 0) {
- const { variables } = dashboard[0].data;
- return variables;
- }
- return {};
-};