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.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
Feat: import export dashboard (#980)
palash-signozb335d440cffc
diff --git a/frontend/public/locales/en-GB/common.json b/frontend/public/locales/en-GB/common.jsonindex c17e7e73dd..c2ee199592 100644--- a/frontend/public/locales/en-GB/common.json+++ b/frontend/public/locales/en-GB/common.json@@ -1,3 +1,8 @@{- "something_went_wrong": "Something went wrong"+ "something_went_wrong": "Something went wrong",+ "success": "Success",+ "cancel": "Cancel",+ "share": "Share",+ "save": "Save",+ "edit": "Edit"}diff --git a/frontend/public/locales/en-GB/dashboard.json b/frontend/public/locales/en-GB/dashboard.jsonnew file mode 100644index 0000000000..7f21149511--- /dev/null+++ b/frontend/public/locales/en-GB/dashboard.json@@ -0,0 +1,16 @@+{+ "create_dashboard": "Create Dashboard",+ "import_json": "Import JSON",+ "copy_to_clipboard": "Copy To ClipBoard",+ "download_json": "Download JSON",+ "view_json": "View JSON",+ "export_dashboard": "Export this dashboard.",+ "upload_json_file": "Upload JSON file",+ "paste_json_below": "Paste JSON below",+ "error_upload_json": "Invalid JSON",+ "load_json": "Load JSON",+ "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"+}diff --git a/frontend/public/locales/en/common.json b/frontend/public/locales/en/common.jsonindex c17e7e73dd..c2ee199592 100644--- a/frontend/public/locales/en/common.json+++ b/frontend/public/locales/en/common.json@@ -1,3 +1,8 @@{- "something_went_wrong": "Something went wrong"+ "something_went_wrong": "Something went wrong",+ "success": "Success",+ "cancel": "Cancel",+ "share": "Share",+ "save": "Save",+ "edit": "Edit"}diff --git a/frontend/public/locales/en/dashboard.json b/frontend/public/locales/en/dashboard.jsonnew file mode 100644index 0000000000..7f21149511--- /dev/null+++ b/frontend/public/locales/en/dashboard.json@@ -0,0 +1,16 @@+{+ "create_dashboard": "Create Dashboard",+ "import_json": "Import JSON",+ "copy_to_clipboard": "Copy To ClipBoard",+ "download_json": "Download JSON",+ "view_json": "View JSON",+ "export_dashboard": "Export this dashboard.",+ "upload_json_file": "Upload JSON file",+ "paste_json_below": "Paste JSON below",+ "error_upload_json": "Invalid JSON",+ "load_json": "Load JSON",+ "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"+}diff --git a/frontend/src/api/dashboard/update.ts b/frontend/src/api/dashboard/update.tsindex b22689c0ed..37341524f8 100644--- a/frontend/src/api/dashboard/update.ts+++ b/frontend/src/api/dashboard/update.ts@@ -9,7 +9,7 @@ const update = async (): Promise<SuccessResponse<PayloadProps> | ErrorResponse> => {try {const response = await axios.put(`/dashboards/${props.uuid}`, {- ...props,+ ...props.data,});return {diff --git a/frontend/src/components/Editor/index.tsx b/frontend/src/components/Editor/index.tsxindex 1dc78d2f32..9e7593e1ba 100644--- a/frontend/src/components/Editor/index.tsx+++ b/frontend/src/components/Editor/index.tsx@@ -1,18 +1,21 @@import MEditor from '@monaco-editor/react';import React from 'react';-function Editor({ value, readOnly = false }: EditorProps): JSX.Element {+function Editor({+ value,+ language = 'yaml',+ onChange,+}: EditorProps): JSX.Element {return (<MEditortheme="vs-dark"- defaultLanguage="yaml"- value={value.current}- options={{ fontSize: 16, automaticLayout: true, readOnly }}+ language={language}+ value={value}+ options={{ fontSize: 16, automaticLayout: true }}height="40vh"onChange={(newValue): void => {- if (value.current && newValue) {- // eslint-disable-next-line no-param-reassign- value.current = newValue;+ if (newValue) {+ onChange(newValue);}}}/>@@ -20,12 +23,13 @@ function Editor({ value, readOnly = false }: EditorProps): JSX.Element {}interface EditorProps {- value: React.MutableRefObject<string>;- readOnly?: boolean;+ value: string;+ language?: string;+ onChange: (value: string) => void;}Editor.defaultProps = {- readOnly: false,+ language: undefined,};export default Editor;diff --git a/frontend/src/container/EditRules/index.tsx b/frontend/src/container/EditRules/index.tsxindex 342fd5c494..e228af0a10 100644--- a/frontend/src/container/EditRules/index.tsx+++ b/frontend/src/container/EditRules/index.tsx@@ -5,14 +5,14 @@ import Editor from 'components/Editor';import ROUTES from 'constants/routes';import { State } from 'hooks/useFetch';import history from 'lib/history';-import React, { useCallback, useRef, useState } from 'react';+import React, { useCallback, useState } from 'react';import { PayloadProps } from 'types/api/alerts/get';import { PayloadProps as PutPayloadProps } from 'types/api/alerts/put';import { ButtonContainer } from './styles';function EditRules({ initialData, ruleId }: EditRulesProps): JSX.Element {- const value = useRef<string>(initialData);+ const [value, setEditorValue] = useState<string>(initialData);const [notifications, Element] = notification.useNotification();const [editButtonState, setEditButtonState] = useState<State<PutPayloadProps>>({@@ -31,7 +31,7 @@ function EditRules({ initialData, ruleId }: EditRulesProps): JSX.Element {loading: true,}));const response = await put({- data: value.current,+ data: value,id: parseInt(ruleId, 10),});@@ -72,13 +72,13 @@ function EditRules({ initialData, ruleId }: EditRulesProps): JSX.Element {'Oops! Some issue occured in editing the alert please try again or contact [email protected]',});}- }, [ruleId, notifications]);+ }, [value, ruleId, notifications]);return (<>{Element}- <Editor value={value} />+ <Editor onChange={(value): void => setEditorValue(value)} value={value} /><ButtonContainer><Buttondiff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx b/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsxindex ba8a66a82d..ef04a4e3da 100644--- a/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx+++ b/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx@@ -116,16 +116,11 @@ function FullView({}));} else {const chartDataSet = getChartData({- queryData: {- data: response.map((e) => ({- query: e.query,- legend: e.legend,- queryData: e.queryData.payload?.result || [],- })),- error: false,- errorMessage: '',- loading: false,- },+ queryData: response.map((e) => ({+ query: e.query,+ legend: e.legend,+ queryData: e.queryData.payload?.result || [],+ })),});setState((state) => ({diff --git a/frontend/src/container/GridGraphLayout/Graph/index.tsx b/frontend/src/container/GridGraphLayout/Graph/index.tsxindex eb1ed0e2d6..fa87b67638 100644--- a/frontend/src/container/GridGraphLayout/Graph/index.tsx+++ b/frontend/src/container/GridGraphLayout/Graph/index.tsx@@ -89,16 +89,11 @@ function GridCardGraph({}));} else {const chartDataSet = getChartData({- queryData: {- data: response.map((e) => ({- query: e.query,- legend: e.legend,- queryData: e.queryData.payload?.result || [],- })),- error: false,- errorMessage: '',- loading: false,- },+ queryData: response.map((e) => ({+ query: e.query,+ legend: e.legend,+ queryData: e.queryData.payload?.result || [],+ })),});setState((state) => ({diff --git a/frontend/src/container/GridGraphLayout/index.tsx b/frontend/src/container/GridGraphLayout/index.tsxindex e5676c8f7b..38ff0e6d1f 100644--- a/frontend/src/container/GridGraphLayout/index.tsx+++ b/frontend/src/container/GridGraphLayout/index.tsx@@ -1,6 +1,4 @@-/* eslint-disable react/jsx-no-useless-fragment *//* eslint-disable react/no-unstable-nested-components */-/* eslint-disable react/display-name */import { SaveFilled } from '@ant-design/icons';import { notification } from 'antd';import updateDashboardApi from 'api/dashboard/update';@@ -85,7 +83,7 @@ function GridGraph(): JSX.Element {/>);}- return <></>;+ return <div />;},}));}, [widgets, data.layout]);@@ -150,6 +148,7 @@ function GridGraph(): JSX.Element {w: e.i === '__dropping-elem__' ? 6 : e.w,h: e.i === '__dropping-elem__' ? 2 : e.h,}))+ // removing add widgets layout config.filter((e) => e.maxW === undefined),});} catch (error) {@@ -172,13 +171,15 @@ function GridGraph(): JSX.Element {}));const response = await updateDashboardApi({- title: data.title,+ data: {+ title: data.title,+ description: data.description,+ name: data.name,+ tags: data.tags,+ widgets: data.widgets,+ layout: saveLayoutState.payload.filter((e) => e.maxW === undefined),+ },uuid: selectedDashboard.uuid,- description: data.description,- name: data.name,- tags: data.tags,- widgets: data.widgets,- layout: saveLayoutState.payload.filter((e) => e.maxW === undefined),});if (response.statusCode === 200) {setSaveLayoutState((state) => ({diff --git a/frontend/src/container/GridGraphLayout/utils.ts b/frontend/src/container/GridGraphLayout/utils.tsindex a3d5f9ee1f..2bfcb4e61f 100644--- a/frontend/src/container/GridGraphLayout/utils.ts+++ b/frontend/src/container/GridGraphLayout/utils.ts@@ -13,37 +13,39 @@ export const updateDashboard = async ({selectedDashboard,}: UpdateDashboardProps): Promise<void> => {const response = await updateDashboardApi({- title: data.title,- uuid: selectedDashboard.uuid,- description: data.description,- name: data.name,- tags: data.tags,- widgets: [- ...(data.widgets || []),- {- description: '',- id: generateWidgetId,- isStacked: false,- nullZeroValues: '',- opacity: '',- panelTypes: graphType,- query: [- {- query: '',- legend: '',+ data: {+ title: data.title,+ description: data.description,+ name: data.name,+ tags: data.tags,+ widgets: [+ ...(data.widgets || []),+ {+ description: '',+ id: generateWidgetId,+ isStacked: false,+ nullZeroValues: '',+ opacity: '',+ panelTypes: graphType,+ query: [+ {+ query: '',+ legend: '',+ },+ ],+ queryData: {+ data: [],+ error: false,+ errorMessage: '',+ loading: false,},- ],- queryData: {- data: [],- error: false,- errorMessage: '',- loading: false,+ timePreferance: 'GLOBAL_TIME',+ title: '',},- timePreferance: 'GLOBAL_TIME',- title: '',- },- ],- layout,+ ],+ layout,+ },+ uuid: selectedDashboard.uuid,});if (response.statusCode === 200) {diff --git a/frontend/src/container/ListOfDashboard/ImportJSON/index.tsx b/frontend/src/container/ListOfDashboard/ImportJSON/index.tsxnew file mode 100644index 0000000000..24b2d8b753--- /dev/null+++ b/frontend/src/container/ListOfDashboard/ImportJSON/index.tsx@@ -0,0 +1,182 @@+import { red } from '@ant-design/colors';+import { ExclamationCircleTwoTone } from '@ant-design/icons';+import {+ Button,+ Modal,+ notification,+ Space,+ Typography,+ Upload,+ UploadProps,+} from 'antd';+import createDashboard from 'api/dashboard/create';+import Editor from 'components/Editor';+import ROUTES from 'constants/routes';+import history from 'lib/history';+import React, { useState } from 'react';+import { useTranslation } from 'react-i18next';+import { generatePath } from 'react-router-dom';+import { DashboardData } from 'types/api/dashboard/getAll';++import { EditorContainer, FooterContainer } from './styles';++function ImportJSON({+ isImportJSONModalVisible,+ onModalHandler,+}: ImportJSONProps): JSX.Element {+ const [jsonData, setJsonData] = useState<Record<string, unknown>>();+ const { t } = useTranslation(['dashboard', 'common']);+ const [isUploadJSONError, setIsUploadJSONError] = useState<boolean>(false);+ const [isCreateDashboardError, setIsCreateDashboardError] = useState<boolean>(+ false,+ );+ const [dashboardCreating, setDashboardCreating] = useState<boolean>(false);++ const [editorValue, setEditorValue] = useState<string>('');++ const onChangeHandler: UploadProps['onChange'] = (info) => {+ const { fileList } = info;+ const reader = new FileReader();++ const lastFile = fileList[fileList.length - 1];++ if (lastFile.originFileObj) {+ reader.onload = async (event): Promise<void> => {+ if (event.target) {+ const target = event.target.result;+ try {+ if (target) {+ const targetFile = target.toString();+ const parsedValue = JSON.parse(targetFile);+ setJsonData(parsedValue);+ setEditorValue(JSON.stringify(parsedValue, null, 2));+ setIsUploadJSONError(false);+ }+ } catch (error) {+ setIsUploadJSONError(true);+ }+ }+ };+ reader.readAsText(lastFile.originFileObj);+ }+ };++ const onClickLoadJsonHandler = async (): Promise<void> => {+ try {+ setDashboardCreating(true);+ const dashboardData = JSON.parse(editorValue) as DashboardData;++ // removing the queryData+ const parsedWidgets: DashboardData = {+ ...dashboardData,+ widgets: dashboardData.widgets?.map((e) => ({+ ...e,+ queryData: {+ ...e.queryData,+ data: e.queryData.data.map((queryData) => ({+ ...queryData,+ queryData: [],+ })),+ },+ })),+ };++ const response = await createDashboard({+ ...parsedWidgets,+ });++ if (response.statusCode === 200) {+ setTimeout(() => {+ history.push(+ generatePath(ROUTES.DASHBOARD, {+ dashboardId: response.payload.uuid,+ }),+ );+ }, 10);+ } else {+ setIsCreateDashboardError(true);+ notification.error({+ message:+ response.error ||+ t('something_went_wrong', {+ ns: 'common',+ }),+ });+ }+ setDashboardCreating(false);+ } catch {+ setDashboardCreating(false);++ setIsCreateDashboardError(true);+ }+ };++ const getErrorNode = (error: string): JSX.Element => (+ <Space>+ <ExclamationCircleTwoTone twoToneColor={[red[7], '#1f1f1f']} />+ <Typography style={{ color: '#D89614' }}>{error}</Typography>+ </Space>+ );++ return (+ <Modal+ visible={isImportJSONModalVisible}+ centered+ maskClosable+ destroyOnClose+ width="70vw"+ onCancel={onModalHandler}+ title={+ <>+ <Typography.Title level={4}>{t('import_json')}</Typography.Title>+ <Typography>{t('import_dashboard_by_pasting')}</Typography>+ </>+ }+ footer={+ <FooterContainer>+ <Button+ disabled={editorValue.length === 0}+ onClick={onClickLoadJsonHandler}+ loading={dashboardCreating}+ >+ {t('load_json')}+ </Button>+ {isCreateDashboardError && getErrorNode(t('error_loading_json'))}+ </FooterContainer>+ }+ >+ <div>+ <Space direction="horizontal">+ <Upload+ accept=".json"+ showUploadList={false}+ multiple={false}+ onChange={onChangeHandler}+ beforeUpload={(): boolean => false}+ action="none"+ data={jsonData}+ >+ <Button type="primary">{t('upload_json_file')}</Button>+ </Upload>+ {isUploadJSONError && <>{getErrorNode(t('error_upload_json'))}</>}+ </Space>++ <EditorContainer>+ <Typography.Paragraph>{t('paste_json_below')}</Typography.Paragraph>+ <Editor+ onChange={(newValue): void => setEditorValue(newValue)}+ value={editorValue}+ language="json"+ />+ </EditorContainer>+ </div>+ </Modal>+ );+}++interface ImportJSONProps {+ isImportJSONModalVisible: boolean;+ onModalHandler: VoidFunction;+}++export default ImportJSON;diff --git a/frontend/src/container/ListOfDashboard/ImportJSON/styles.ts b/frontend/src/container/ListOfDashboard/ImportJSON/styles.tsnew file mode 100644index 0000000000..7dd936baef--- /dev/null+++ b/frontend/src/container/ListOfDashboard/ImportJSON/styles.ts@@ -0,0 +1,10 @@+import { Space } from 'antd';+import styled from 'styled-components';++export const EditorContainer = styled.div`+ margin-top: 2rem;+`;++export const FooterContainer = styled(Space)`+ display: flex;+`;diff --git a/frontend/src/container/ListOfDashboard/index.tsx b/frontend/src/container/ListOfDashboard/index.tsxindex 49051a2ce4..98e29887bb 100644--- a/frontend/src/container/ListOfDashboard/index.tsx+++ b/frontend/src/container/ListOfDashboard/index.tsx@@ -1,20 +1,28 @@-/* eslint-disable react/no-unstable-nested-components */import { PlusOutlined } from '@ant-design/icons';-import { Card, Row, Table, TableColumnProps, Typography } from 'antd';+import {+ Card,+ Dropdown,+ Menu,+ Row,+ Table,+ TableColumnProps,+ Typography,+} from 'antd';import createDashboard from 'api/dashboard/create';import { AxiosError } from 'axios';import TextToolTip from 'components/TextToolTip';import ROUTES from 'constants/routes';import SearchFilter from 'container/ListOfDashboard/SearchFilter';import history from 'lib/history';-import React, { useCallback, useEffect, useState } from 'react';+import React, { useCallback, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';import { useSelector } from 'react-redux';import { generatePath } from 'react-router-dom';import { AppState } from 'store/reducers';import { Dashboard } from 'types/api/dashboard/getAll';import DashboardReducer from 'types/reducer/dashboards';-import { v4 } from 'uuid';+import ImportJSON from './ImportJSON';import { ButtonContainer, NewDashboardButton, TableContainer } from './styles';import Createdby from './TableComponents/CreatedBy';import DateComponent from './TableComponents/Date';@@ -27,6 +35,12 @@ function ListOfAllDashboard(): JSX.Element {(state) => state.dashboards,);+ const { t } = useTranslation('dashboard');+ const [+ isImportJSONModalVisible,+ setIsImportJSONModalVisible,+ ] = useState<boolean>(false);+const [filteredDashboards, setFilteredDashboards] = useState<Dashboard[]>();useEffect(() => {@@ -95,24 +109,20 @@ function ListOfAllDashboard(): JSX.Element {const onNewDashboardHandler = useCallback(async () => {try {- const newDashboardId = v4();setNewDashboardState({...newDashboardState,loading: true,});const response = await createDashboard({- uuid: newDashboardId,- title: 'Sample Title',+ title: t('new_dashboard_title', {+ ns: 'dashboard',+ }),});if (response.statusCode === 200) {- setNewDashboardState({- ...newDashboardState,- loading: false,- });history.push(generatePath(ROUTES.DASHBOARD, {- dashboardId: newDashboardId,+ dashboardId: response.payload.uuid,}),);} else {@@ -130,9 +140,9 @@ function ListOfAllDashboard(): JSX.Element {errorMessage: (error as AxiosError).toString() || 'Something went Wrong',});}- }, [newDashboardState]);+ }, [newDashboardState, t]);- const getText = (): string => {+ const getText = useCallback(() => {if (!newDashboardState.error && !newDashboardState.loading) {return 'New Dashboard';}@@ -142,10 +152,36 @@ function ListOfAllDashboard(): JSX.Element {}return newDashboardState.errorMessage;+ }, [+ newDashboardState.error,+ newDashboardState.errorMessage,+ newDashboardState.loading,+ ]);++ const onModalHandler = (): void => {+ setIsImportJSONModalVisible((state) => !state);};- return (- <Card>+ const menu = useMemo(+ () => (+ <Menu>+ <Menu.Item+ onClick={onNewDashboardHandler}+ disabled={loading}+ key={t('create_dashboard').toString()}+ >+ {t('create_dashboard')}+ </Menu.Item>+ <Menu.Item onClick={onModalHandler} key={t('import_json').toString()}>+ {t('import_json')}+ </Menu.Item>+ </Menu>+ ),+ [loading, onNewDashboardHandler, t],+ );++ const GetHeader = useMemo(+ () => (<Row justify="space-between"><Typography>Dashboard List</Typography>@@ -156,18 +192,26 @@ function ListOfAllDashboard(): JSX.Element {url: 'https://signoz.io/docs/userguide/dashboards',}}/>-- <NewDashboardButton- onClick={onNewDashboardHandler}- icon={<PlusOutlined />}- type="primary"- loading={newDashboardState.loading}- danger={newDashboardState.error}- >- {getText()}- </NewDashboardButton>+ <Dropdown trigger={['click']} overlay={menu}>+ <NewDashboardButton+ icon={<PlusOutlined />}+ type="primary"+ loading={newDashboardState.loading}+ danger={newDashboardState.error}+ >+ {getText()}+ </NewDashboardButton>+ </Dropdown></ButtonContainer></Row>+ ),+ [getText, menu, newDashboardState.error, newDashboardState.loading],+ );++ return (+ <Card>+ {GetHeader}+{!loading && (<SearchFiltersearchData={dashboards}@@ -176,6 +220,10 @@ function ListOfAllDashboard(): JSX.Element {)}<TableContainer>+ <ImportJSON+ isImportJSONModalVisible={isImportJSONModalVisible}+ onModalHandler={onModalHandler}+ /><Tablepagination={{pageSize: 9,diff --git a/frontend/src/container/NewDashboard/ComponentsSlider/index.tsx b/frontend/src/container/NewDashboard/ComponentsSlider/index.tsxindex bbe352b29a..d80897f700 100644--- a/frontend/src/container/NewDashboard/ComponentsSlider/index.tsx+++ b/frontend/src/container/NewDashboard/ComponentsSlider/index.tsx@@ -6,7 +6,6 @@ import { useSelector } from 'react-redux';import { AppState } from 'store/reducers';import AppReducer from 'types/reducer/app';import DashboardReducer from 'types/reducer/dashboards';-import { v4 } from 'uuid';import menuItems, { ITEMS } from './menuItems';import { Card, Container, Text } from './styles';@@ -29,8 +28,6 @@ function DashboardGraphSlider(): JSX.Element {const onClickHandler = useCallback(async (name: ITEMS) => {try {- const generateWidgetId = v4();-const getX = (): number => {if (data.layout && data.layout?.length > 0) {const lastIndexX = data.layout[(data.layout?.length || 0) - 1];@@ -41,7 +38,7 @@ function DashboardGraphSlider(): JSX.Element {await updateDashboard({data,- generateWidgetId,+ generateWidgetId: selectedDashboard.uuid,graphType: name,layout: [...(data.layout || []),diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/ShareModal.tsx b/frontend/src/container/NewDashboard/DescriptionOfDashboard/ShareModal.tsxnew file mode 100644index 0000000000..68272d2158--- /dev/null+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/ShareModal.tsx@@ -0,0 +1,99 @@+import { Button, Modal, notification, Typography } from 'antd';+import Editor from 'components/Editor';+import React, { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { DashboardData } from 'types/api/dashboard/getAll';++import { downloadObjectAsJson } from './util';++function ShareModal({+ isJSONModalVisible,+ onToggleHandler,+ selectedData,+}: ShareModalProps): JSX.Element {+ const [jsonValue, setJSONValue] = useState<string>(+ JSON.stringify(selectedData, null, 2),+ );+ const [isViewJSON, setIsViewJSON] = useState<boolean>(false);+ const { t } = useTranslation(['dashboard', 'common']);++ const onClickCopyClipBoardHandler = useCallback(async () => {+ try {+ await navigator.clipboard.writeText(jsonValue);+ notification.success({+ message: t('success', {+ ns: 'common',+ }),+ });+ } catch (error) {+ notification.error({+ message: t('something_went_wrong', {+ ns: 'common',+ }),+ });+ }+ }, [jsonValue, t]);++ const GetFooterComponent = useMemo(() => {+ if (!isViewJSON) {+ return (+ <>+ <Button+ onClick={(): void => {+ setIsViewJSON(true);+ }}+ >+ {t('view_json')}+ </Button>++ <Button+ type="primary"+ onClick={(): void => {+ downloadObjectAsJson(selectedData, selectedData.title);+ }}+ >+ {t('download_json')}+ </Button>+ </>+ );+ }+ return (+ <Button onClick={onClickCopyClipBoardHandler} type="primary">+ {t('copy_to_clipboard')}+ </Button>+ );+ }, [isViewJSON, onClickCopyClipBoardHandler, selectedData, t]);++ return (+ <Modal+ visible={isJSONModalVisible}+ onCancel={(): void => {+ onToggleHandler();+ setIsViewJSON(false);+ }}+ width="70vw"+ centered+ title={t('share', {+ ns: 'common',+ })}+ okText={t('download_json')}+ cancelText={t('cancel')}+ destroyOnClose+ footer={GetFooterComponent}+ >+ {!isViewJSON ? (+ <Typography>{t('export_dashboard')}</Typography>+ ) : (+ <Editor onChange={(value): void => setJSONValue(value)} value={jsonValue} />+ )}+ </Modal>+ );+}++interface ShareModalProps {+ isJSONModalVisible: boolean;+ onToggleHandler: VoidFunction;+ selectedData: DashboardData;+}++export default ShareModal;diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsx b/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsxindex 7ee3132d37..7d3227b731 100644--- a/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsx+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsx@@ -1,8 +1,13 @@-import { EditOutlined, SaveOutlined } from '@ant-design/icons';-import { Card, Col, Row, Tag, Typography } from 'antd';+import {+ EditOutlined,+ SaveOutlined,+ ShareAltOutlined,+} from '@ant-design/icons';+import { Card, Col, Row, Space, Tag, Typography } from 'antd';import AddTags from 'container/NewDashboard/DescriptionOfDashboard/AddTags';import NameOfTheDashboard from 'container/NewDashboard/DescriptionOfDashboard/NameOfTheDashboard';import React, { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';import { connect, useSelector } from 'react-redux';import { bindActionCreators, Dispatch } from 'redux';import { ThunkDispatch } from 'redux-thunk';@@ -16,6 +21,7 @@ import AppActions from 'types/actions';import DashboardReducer from 'types/reducer/dashboards';import Description from './Description';+import ShareModal from './ShareModal';import { Button, Container } from './styles';function DescriptionOfDashboard({@@ -34,9 +40,12 @@ function DescriptionOfDashboard({const [updatedTitle, setUpdatedTitle] = useState<string>(title);const [updatedTags, setUpdatedTags] = useState<string[]>(tags || []);- const [updatedDescription, setUpdtatedDescription] = useState(+ const [updatedDescription, setUpdatedDescription] = useState(description || '',);+ const [isJSONModalVisible, isIsJSONModalVisible] = useState<boolean>(false);++ const { t } = useTranslation('common');const onClickEditHandler = useCallback(() => {if (isEditMode) {@@ -66,6 +75,10 @@ function DescriptionOfDashboard({updateDashboardTitleDescriptionTags,]);+ const onToggleHandler = (): void => {+ isIsJSONModalVisible((state) => !state);+ };+return (<Card><Row align="top" justify="space-between">@@ -87,17 +100,31 @@ function DescriptionOfDashboard({<AddTags tags={updatedTags} setTags={setUpdatedTags} /><Descriptiondescription={updatedDescription}- setDescription={setUpdtatedDescription}+ setDescription={setUpdatedDescription}/></Col>)}++ <ShareModal+ {...{+ isJSONModalVisible,+ onToggleHandler,+ selectedData,+ }}+ />+<Col>- <Button- icon={!isEditMode ? <EditOutlined /> : <SaveOutlined />}- onClick={onClickEditHandler}- >- {isEditMode ? 'Save' : 'Edit'}- </Button>+ <Space direction="vertical">+ <Button onClick={onToggleHandler} icon={<ShareAltOutlined />}>+ {t('share')}+ </Button>+ <Button+ icon={!isEditMode ? <EditOutlined /> : <SaveOutlined />}+ onClick={onClickEditHandler}+ >+ {isEditMode ? t('save') : t('edit')}+ </Button>+ </Space></Col></Row></Card>diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/util.ts b/frontend/src/container/NewDashboard/DescriptionOfDashboard/util.tsnew file mode 100644index 0000000000..c86698436d--- /dev/null+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/util.ts@@ -0,0 +1,14 @@+export function downloadObjectAsJson(+ exportObj: unknown,+ exportName: string,+): void {+ const dataStr = `data:text/json;charset=utf-8,${encodeURIComponent(+ JSON.stringify(exportObj),+ )}`;+ const downloadAnchorNode = document.createElement('a');+ downloadAnchorNode.setAttribute('href', dataStr);+ downloadAnchorNode.setAttribute('download', `${exportName}.json`);+ document.body.appendChild(downloadAnchorNode); // required for firefox+ downloadAnchorNode.click();+ downloadAnchorNode.remove();+}diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsxindex 2a6fd02a00..37bf188bb3 100644--- a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx@@ -43,7 +43,7 @@ function WidgetGraph({}const chartDataSet = getChartData({- queryData,+ queryData: queryData.data,});return (diff --git a/frontend/src/lib/getChartData.ts b/frontend/src/lib/getChartData.tsindex 4a57b07826..bdc73eb707 100644--- a/frontend/src/lib/getChartData.ts+++ b/frontend/src/lib/getChartData.ts@@ -6,7 +6,7 @@ import convertIntoEpoc from './covertIntoEpoc';import { colors } from './getRandomColor';const getChartData = ({ queryData }: GetChartDataProps): ChartData => {- const response = queryData.data.map(({ query, queryData, legend }) => {+ const response = queryData.map(({ query, queryData, legend }) => {return queryData.map((e) => {const { values = [], metric } = e || {};const labelNames = getLabelName(@@ -59,7 +59,7 @@ const getChartData = ({ queryData }: GetChartDataProps): ChartData => {};interface GetChartDataProps {- queryData: Widgets['queryData'];+ queryData: Widgets['queryData']['data'];}export default getChartData;diff --git a/frontend/src/pages/CreateAlert/index.tsx b/frontend/src/pages/CreateAlert/index.tsxindex a78622dbad..edfe543b1f 100644--- a/frontend/src/pages/CreateAlert/index.tsx+++ b/frontend/src/pages/CreateAlert/index.tsx@@ -5,13 +5,13 @@ import Editor from 'components/Editor';import ROUTES from 'constants/routes';import { State } from 'hooks/useFetch';import history from 'lib/history';-import React, { useCallback, useRef, useState } from 'react';+import React, { useCallback, useState } from 'react';import { PayloadProps as CreateAlertPayloadProps } from 'types/api/alerts/create';import { ButtonContainer, Title } from './styles';function CreateAlert(): JSX.Element {- const value = useRef<string>(+ const [value, setEditorValue] = useState<string>(`\n alert: High RPS\n expr: sum(rate(signoz_latency_count{span_kind="SPAN_KIND_SERVER"}[2m])) by (service_name) > 100\n for: 0m\n labels:\n severity: warning\n annotations:\n summary: High RPS of Applications\n description: "RPS is > 100\n\t\t\t VALUE = {{ $value }}\n\t\t\t LABELS = {{ $labels }}"\n `,);@@ -36,7 +36,7 @@ function CreateAlert(): JSX.Element {loading: true,}));- if (value.current.length === 0) {+ if (value.length === 0) {setNewAlertState((state) => ({...state,loading: false,@@ -49,7 +49,7 @@ function CreateAlert(): JSX.Element {}const response = await createAlertsApi({- query: value.current,+ query: value,});if (response.statusCode === 200) {@@ -83,14 +83,14 @@ function CreateAlert(): JSX.Element {message: defaultError,});}- }, [notifications]);+ }, [notifications, value]);return (<>{Element}<Title>Create New Alert</Title>- <Editor value={value} />+ <Editor onChange={(value): void => setEditorValue(value)} value={value} /><ButtonContainer><Buttondiff --git a/frontend/src/store/actions/dashboard/deleteWidget.ts b/frontend/src/store/actions/dashboard/deleteWidget.tsindex d86ba2b086..6e2a34cf93 100644--- a/frontend/src/store/actions/dashboard/deleteWidget.ts+++ b/frontend/src/store/actions/dashboard/deleteWidget.ts@@ -17,12 +17,14 @@ export const DeleteWidget = ({const updatedWidgets = widgets.filter((e) => e.id !== widgetId);const response = await updateDashboardApi({- title: selectedDashboard.data.title,+ data: {+ title: selectedDashboard.data.title,+ description: selectedDashboard.data.description,+ name: selectedDashboard.data.name,+ tags: selectedDashboard.data.tags,+ widgets: updatedWidgets,+ },uuid: selectedDashboard.uuid,- description: selectedDashboard.data.description,- name: selectedDashboard.data.name,- tags: selectedDashboard.data.tags,- widgets: updatedWidgets,});if (response.statusCode === 200) {diff --git a/frontend/src/store/actions/dashboard/saveDashboard.ts b/frontend/src/store/actions/dashboard/saveDashboard.tsindex e14e40b737..32ca92ab8b 100644--- a/frontend/src/store/actions/dashboard/saveDashboard.ts+++ b/frontend/src/store/actions/dashboard/saveDashboard.ts@@ -57,38 +57,40 @@ export const SaveDashboard = ({];const response = await updateDashboardApi({- ...selectedDashboard.data,- uuid,- // this is the data for the dashboard- title: selectedDashboard.data.title,- description: selectedDashboard.data.description,- tags: selectedDashboard.data.tags,- name: selectedDashboard.data.name,- // as we are updated the widget only- widgets: [- ...preWidget,- {- ...selectedWidget,- description: updatedDescription,- id: widgetId,- isStacked: updatedisStacked,- nullZeroValues: updatednullZeroValues,- opacity: updatedopacity,- title: updatedTitle,- timePreferance: updatedtimePreferance,- yAxisUnit: updatedYAxisUnit,- queryData: {- ...selectedWidget.queryData,- data: [- ...selectedWidget.queryData.data.map((e) => ({- ...e,- queryData: [],- })),- ],+ 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,+ // as we are updated the widget only+ widgets: [+ ...preWidget,+ {+ ...selectedWidget,+ description: updatedDescription,+ id: widgetId,+ isStacked: updatedisStacked,+ nullZeroValues: updatednullZeroValues,+ opacity: updatedopacity,+ title: updatedTitle,+ timePreferance: updatedtimePreferance,+ yAxisUnit: updatedYAxisUnit,+ queryData: {+ ...selectedWidget.queryData,+ data: [+ ...selectedWidget.queryData.data.map((e) => ({+ ...e,+ queryData: [],+ })),+ ],+ },},- },- ...afterWidget,- ],+ ...afterWidget,+ ],+ },+ uuid,});if (response.statusCode === 200) {diff --git a/frontend/src/store/actions/dashboard/updateDashboardTitle.ts b/frontend/src/store/actions/dashboard/updateDashboardTitle.tsindex dc1b24fb96..277ddf7629 100644--- a/frontend/src/store/actions/dashboard/updateDashboardTitle.ts+++ b/frontend/src/store/actions/dashboard/updateDashboardTitle.ts@@ -13,8 +13,10 @@ export const UpdateDashboardTitleDescriptionTags = ({const { data } = dashboard;const response = await update({- ...dashboard.data,- title: dashboard.data.title,+ data: {+ ...dashboard.data,+ title: dashboard.data.title,+ },uuid: dashboard.uuid,});diff --git a/frontend/src/types/api/dashboard/create.ts b/frontend/src/types/api/dashboard/create.tsindex bd0996a0d6..3c859edc6c 100644--- a/frontend/src/types/api/dashboard/create.ts+++ b/frontend/src/types/api/dashboard/create.ts@@ -1,8 +1,9 @@-import { Dashboard } from './getAll';+import { Dashboard, DashboardData } from './getAll';-export type Props = {- uuid: Dashboard['uuid'];- title: Dashboard['data']['title'];-};+export type Props =+ | {+ title: Dashboard['data']['title'];+ }+ | DashboardData;export type PayloadProps = Dashboard;diff --git a/frontend/src/types/api/dashboard/update.ts b/frontend/src/types/api/dashboard/update.tsindex c58e3b5cd4..3839a84c88 100644--- a/frontend/src/types/api/dashboard/update.ts+++ b/frontend/src/types/api/dashboard/update.ts@@ -1,8 +1,8 @@import { Dashboard, DashboardData } from './getAll';export type Props = {- title: Dashboard['data']['title'];uuid: Dashboard['uuid'];-} & DashboardData;+ data: DashboardData;+};export type PayloadProps = Dashboard;