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: Metrics (#281)
Palash7b70cfb0c497
diff --git a/.gitignore b/.gitignoreindex e7fecd9a68..10736de861 100644--- a/.gitignore+++ b/.gitignore@@ -1,5 +1,6 @@node_modulesyarn.lock+package.jsondeploy/docker/environment_tiny/common_testfrontend/node_modulesdiff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.jsindex 1ebe27f73c..b27d5be241 100644--- a/frontend/.eslintrc.js+++ b/frontend/.eslintrc.js@@ -9,6 +9,7 @@ module.exports = {'plugin:react/recommended','plugin:@typescript-eslint/recommended','plugin:@typescript-eslint/eslint-recommended',+ 'plugin:prettier/recommended',],parser: '@typescript-eslint/parser',parserOptions: {@@ -18,7 +19,18 @@ module.exports = {ecmaVersion: 12,sourceType: 'module',},- plugins: ['react', '@typescript-eslint', 'simple-import-sort'],+ plugins: [+ 'react',+ '@typescript-eslint',+ 'simple-import-sort',+ 'react-hooks',+ 'prettier',+ ],+ settings: {+ react: {+ version: 'latest',+ },+ },rules: {'react/jsx-filename-extension': ['error',@@ -30,12 +42,21 @@ module.exports = {'@typescript-eslint/explicit-function-return-type': 'error','@typescript-eslint/no-var-requires': 0,'linebreak-style': ['error', 'unix'],- indent: ['error', 'tab'],- quotes: ['error', 'single'],- semi: ['error', 'always'],// simple sort error'simple-import-sort/imports': 'error','simple-import-sort/exports': 'error',++ // hooks+ 'react-hooks/rules-of-hooks': 'error',+ 'react-hooks/exhaustive-deps': 'warn',++ 'prettier/prettier': [+ 'error',+ {},+ {+ usePrettierrc: true,+ },+ ],},};diff --git a/frontend/.prettierrc.json b/frontend/.prettierrc.jsonindex fd2d5e75d1..a147736ad6 100644--- a/frontend/.prettierrc.json+++ b/frontend/.prettierrc.json@@ -3,5 +3,6 @@"useTabs": true,"tabWidth": 1,"singleQuote": true,- "jsxSingleQuote": false+ "jsxSingleQuote": false,+ "semi": true}diff --git a/frontend/cypress/CustomFunctions/Login.ts b/frontend/cypress/CustomFunctions/Login.tsindex 0f2f4a47e1..7b99516b44 100644--- a/frontend/cypress/CustomFunctions/Login.ts+++ b/frontend/cypress/CustomFunctions/Login.ts@@ -1,38 +1,38 @@-import ROUTES from "constants/routes";+import ROUTES from 'constants/routes';const Login = ({ email, name }: LoginProps): void => {- const emailInput = cy.findByPlaceholderText("[email protected]");+ const emailInput = cy.findByPlaceholderText('[email protected]');emailInput.then((emailInput) => {const element = emailInput[0];// element is presentexpect(element).not.undefined;- expect(element.nodeName).to.be.equal("INPUT");+ expect(element.nodeName).to.be.equal('INPUT');});emailInput.type(email).then((inputElements) => {const inputElement = inputElements[0];- const inputValue = inputElement.getAttribute("value");+ const inputValue = inputElement.getAttribute('value');expect(inputValue).to.be.equals(email);});- const firstNameInput = cy.findByPlaceholderText("Mike");+ const firstNameInput = cy.findByPlaceholderText('Mike');firstNameInput.then((firstNameInput) => {const element = firstNameInput[0];// element is presentexpect(element).not.undefined;- expect(element.nodeName).to.be.equal("INPUT");+ expect(element.nodeName).to.be.equal('INPUT');});firstNameInput.type(name).then((inputElements) => {const inputElement = inputElements[0];- const inputValue = inputElement.getAttribute("value");+ const inputValue = inputElement.getAttribute('value');expect(inputValue).to.be.equals(name);});- const gettingStartedButton = cy.get("button");+ const gettingStartedButton = cy.get('button');gettingStartedButton.click();- cy.location("pathname").then((e) => {+ cy.location('pathname').then((e) => {expect(e).to.be.equal(ROUTES.APPLICATION);});};diff --git a/frontend/cypress/integration/appLayout/index.spec.ts b/frontend/cypress/integration/appLayout/index.spec.tsindex 1dd2e5e6b3..38a063953a 100644--- a/frontend/cypress/integration/appLayout/index.spec.ts+++ b/frontend/cypress/integration/appLayout/index.spec.ts@@ -1,20 +1,20 @@/// <reference types="cypress" />-import ROUTES from "constants/routes";+import ROUTES from 'constants/routes';-describe("App Layout", () => {+describe('App Layout', () => {beforeEach(() => {- cy.visit(Cypress.env("baseUrl"));+ cy.visit(Cypress.env('baseUrl'));});- it("Check the user is in Logged Out State", async () => {- cy.location("pathname").then((e) => {+ it('Check the user is in Logged Out State', async () => {+ cy.location('pathname').then((e) => {expect(e).to.be.equal(ROUTES.SIGN_UP);});});- it("Logged In State", () => {- const testEmail = "[email protected]";- const firstName = "Test";+ it('Logged In State', () => {+ const testEmail = '[email protected]';+ const firstName = 'Test';cy.login({email: testEmail,diff --git a/frontend/cypress/integration/metrics/index.spec.ts b/frontend/cypress/integration/metrics/index.spec.tsindex 2621556541..3169f5eb2d 100644--- a/frontend/cypress/integration/metrics/index.spec.ts+++ b/frontend/cypress/integration/metrics/index.spec.ts@@ -1,16 +1,17 @@/// <reference types="cypress" />-import defaultApps from "../../fixtures/defaultApp.json";-import convertToNanoSecondsToSecond from "lib/convertToNanoSecondsToSecond";+import convertToNanoSecondsToSecond from 'lib/convertToNanoSecondsToSecond';-describe("Metrics", () => {+import defaultApps from '../../fixtures/defaultApp.json';++describe('Metrics', () => {beforeEach(() => {- cy.visit(Cypress.env("baseUrl"));+ cy.visit(Cypress.env('baseUrl'));- const testEmail = "[email protected]";- const firstName = "Test";+ const testEmail = '[email protected]';+ const firstName = 'Test';cy- .intercept("GET", "/api/v1//services?start*", { fixture: "defaultApp.json" })- .as("defaultApps");+ .intercept('GET', '/api/v1//services?start*', { fixture: 'defaultApp.json' })+ .as('defaultApps');cy.login({email: testEmail,@@ -18,10 +19,10 @@ describe("Metrics", () => {});});- it("Default Apps", () => {- cy.wait("@defaultApps");+ it('Default Apps', () => {+ cy.wait('@defaultApps');- cy.get("tbody").then((elements) => {+ cy.get('tbody').then((elements) => {const trElements = elements.children();expect(trElements.length).to.be.equal(defaultApps.length);diff --git a/frontend/cypress/support/commands.ts b/frontend/cypress/support/commands.tsindex ab52b22cf1..9fb840e8d9 100644--- a/frontend/cypress/support/commands.ts+++ b/frontend/cypress/support/commands.ts@@ -1,4 +1,5 @@import '@testing-library/cypress/add-commands';+import Login, { LoginProps } from '../CustomFunctions/Login';Cypress.Commands.add('login', Login);diff --git a/frontend/package.json b/frontend/package.jsonindex 9ae091b47d..c2da7b39f6 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -26,10 +26,8 @@"@testing-library/jest-dom": "^5.11.4","@testing-library/react": "^11.1.0","@testing-library/user-event": "^12.1.10",- "@types/chart.js": "^2.9.28","@types/d3": "^6.2.0","@types/jest": "^26.0.15",- "@types/node": "^14.14.7","@types/react": "^17.0.0","@types/react-dom": "^16.9.9","@types/react-redux": "^7.1.11",@@ -37,7 +35,7 @@"@types/redux": "^3.6.0","@types/styled-components": "^5.1.4","@types/vis": "^4.21.21",- "antd": "^4.8.0",+ "antd": "^4.16.13","axios": "^0.21.0","babel-eslint": "^10.1.0","babel-jest": "^26.6.0",@@ -48,7 +46,8 @@"bfj": "^7.0.2","camelcase": "^6.1.0","case-sensitive-paths-webpack-plugin": "2.3.0",- "chart.js": "^2.9.4",+ "chart.js": "^3.4.0",+ "chartjs-adapter-date-fns": "^2.0.0","css-loader": "4.3.0","d3": "^6.2.0","d3-flame-graph": "^3.1.1",@@ -64,6 +63,7 @@"eslint-webpack-plugin": "^2.1.0","file-loader": "6.1.1","fs-extra": "^9.0.1",+ "history": "4.10.1","html-webpack-plugin": "5.1.0","identity-obj-proxy": "3.0.0","jest": "26.6.0",@@ -78,13 +78,13 @@"prop-types": "^15.6.2","react": "17.0.0","react-app-polyfill": "^2.0.0",- "react-chartjs-2": "^2.11.1","react-chips": "^0.8.0","react-css-theme-switcher": "^0.1.6","react-dev-utils": "^11.0.0","react-dom": "17.0.0","react-force-graph": "^1.41.0","react-graph-vis": "^1.0.5",+ "react-grid-layout": "^1.2.5","react-modal": "^3.12.1","react-redux": "^7.2.2","react-refresh": "^0.8.3",@@ -103,6 +103,7 @@"tsconfig-paths-webpack-plugin": "^3.5.1","typescript": "^4.0.5","url-loader": "4.1.1",+ "uuid": "^8.3.2","web-vitals": "^0.2.4","webpack": "^5.23.0","webpack-dev-server": "^3.11.2",@@ -129,7 +130,11 @@"@babel/preset-react": "^7.12.13","@babel/preset-typescript": "^7.12.17","@testing-library/cypress": "^8.0.0",+ "@types/d3-tip": "^3.5.5","@types/lodash-es": "^4.17.4",+ "@types/node": "^14.17.12",+ "@types/react-grid-layout": "^1.1.2",+ "@types/uuid": "^8.3.1","@typescript-eslint/eslint-plugin": "^4.28.2","@typescript-eslint/parser": "^4.28.2","autoprefixer": "^9.0.0",@@ -138,9 +143,11 @@"copy-webpack-plugin": "^7.0.0","cypress": "^8.3.0","eslint": "^7.30.0",+ "eslint-config-prettier": "^8.3.0","eslint-config-standard": "^16.0.3","eslint-plugin-import": "^2.23.4","eslint-plugin-node": "^11.1.0",+ "eslint-plugin-prettier": "^4.0.0","eslint-plugin-promise": "^5.1.0","eslint-plugin-react": "^7.24.0","eslint-plugin-simple-import-sort": "^7.0.0",diff --git a/frontend/src/AppRoutes/index.tsx b/frontend/src/AppRoutes/index.tsxindex b38409b676..a99c68b9d1 100644--- a/frontend/src/AppRoutes/index.tsx+++ b/frontend/src/AppRoutes/index.tsx@@ -2,28 +2,31 @@ import NotFound from 'components/NotFound';import Spinner from 'components/Spinner';import { IS_LOGGED_IN } from 'constants/auth';import ROUTES from 'constants/routes';+import history from 'lib/history';import AppLayout from 'modules/AppLayout';import { RouteProvider } from 'modules/RouteProvider';import React, { Suspense } from 'react';-import { BrowserRouter, Redirect,Route, Switch } from 'react-router-dom';+import { Redirect, Route, Router, Switch } from 'react-router-dom';import routes from './routes';-const App = () => (- <BrowserRouter basename="/">+const App = (): JSX.Element => (+ <Router history={history}><RouteProvider><AppLayout><Suspense fallback={<Spinner size="large" tip="Loading..." />}><Switch>- {routes.map(({ path, component, exact }) => {- return <Route exact={exact} path={path} component={component} />;+ {routes.map(({ path, component, exact }, index) => {+ return (+ <Route key={index} exact={exact} path={path} component={component} />+ );})}{/* This logic should be moved to app layout */}<Routepath="/"exact- render={() => {+ render={(): JSX.Element => {return localStorage.getItem(IS_LOGGED_IN) === 'yes' ? (<Redirect to={ROUTES.APPLICATION} />) : (@@ -31,12 +34,12 @@ const App = () => ();}}/>- <Route path="*" component={NotFound} />+ <Route path="*" exact component={NotFound} /></Switch></Suspense></AppLayout></RouteProvider>- </BrowserRouter>+ </Router>);export default App;diff --git a/frontend/src/pages.ts b/frontend/src/AppRoutes/pageComponents.tssimilarity index 75%rename from frontend/src/pages.tsrename to frontend/src/AppRoutes/pageComponents.tsindex a0d18b811a..b9e2b21886 100644--- a/frontend/src/pages.ts+++ b/frontend/src/AppRoutes/pageComponents.ts@@ -1,4 +1,4 @@-import Loadable from './components/Loadable';+import Loadable from 'components/Loadable';export const ServiceMetricsPage = Loadable(() =>@@ -59,3 +59,16 @@ export const InstrumentationPage = Loadable(/* webpackChunkName: "InstrumentationPage" */ 'modules/add-instrumentation/instrumentationPage'),);++export const DashboardPage = Loadable(+ () => import(/* webpackChunkName: "DashboardPage" */ 'pages/Dashboard'),+);++export const NewDashboardPage = Loadable(+ () => import(/* webpackChunkName: "New DashboardPage" */ 'pages/NewDashboard'),+);++export const DashboardWidget = Loadable(+ () =>+ import(/* webpackChunkName: "New DashboardPage" */ 'pages/DashboardWidget'),+);diff --git a/frontend/src/AppRoutes/routes.ts b/frontend/src/AppRoutes/routes.tsindex d247e9f6c3..f2dc54544d 100644--- a/frontend/src/AppRoutes/routes.ts+++ b/frontend/src/AppRoutes/routes.ts@@ -1,6 +1,11 @@import ROUTES from 'constants/routes';+import DashboardWidget from 'pages/DashboardWidget';+import { RouteProps } from 'react-router-dom';+import {+ DashboardPage,InstrumentationPage,+ NewDashboardPage,ServiceMapPage,ServiceMetricsPage,ServicesTablePage,@@ -9,8 +14,7 @@ import {TraceDetailPage,TraceGraphPage,UsageExplorerPage,-} from 'pages';-import { RouteProps } from 'react-router-dom';+} from './pageComponents';const routes: AppRoutes[] = [{@@ -58,6 +62,21 @@ const routes: AppRoutes[] = [exact: true,component: TraceDetailPage,},+ {+ path: ROUTES.ALL_DASHBOARD,+ exact: true,+ component: DashboardPage,+ },+ {+ path: ROUTES.DASHBOARD,+ exact: true,+ component: NewDashboardPage,+ },+ {+ path: ROUTES.DASHBOARD_WIDGET,+ exact: true,+ component: DashboardWidget,+ },];interface AppRoutes {diff --git a/frontend/src/api/ErrorResponseHandler.ts b/frontend/src/api/ErrorResponseHandler.tsnew file mode 100644index 0000000000..277510146a--- /dev/null+++ b/frontend/src/api/ErrorResponseHandler.ts@@ -0,0 +1,57 @@+import { AxiosError } from 'axios';+import { ErrorResponse } from 'types/api';+import { ErrorStatusCode } from 'types/common';++export const ErrorResponseHandler = (error: AxiosError): ErrorResponse => {+ if (error.response) {+ // client received an error response (5xx, 4xx)+ // making the error status code as standard Error Status Code+ const statusCode = error.response.status as ErrorStatusCode;++ if (statusCode >= 400 && statusCode < 500) {+ const { data } = error.response;++ if (statusCode === 404) {+ return {+ statusCode,+ payload: null,+ error: 'Not Found',+ message: null,+ };+ }++ return {+ statusCode,+ payload: null,+ error: data.error,+ message: null,+ };+ }++ return {+ statusCode,+ payload: null,+ error: 'Something went wrong',+ message: null,+ };+ }+ if (error.request) {+ // client never received a response, or request never left+ console.error('client never received a response, or request never left');++ return {+ statusCode: 500,+ payload: null,+ error: 'Something went wrong',+ message: null,+ };+ }+ // anything else+ console.error('any');+ return {+ statusCode: 500,+ payload: null,+ error: error.toString(),+ message: null,+ };+};diff --git a/frontend/src/api/dashboard/create.ts b/frontend/src/api/dashboard/create.tsnew file mode 100644index 0000000000..ab2ace2144--- /dev/null+++ b/frontend/src/api/dashboard/create.ts@@ -0,0 +1,26 @@+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/create';++const create = async (+ props: Props,+): Promise<SuccessResponse<PayloadProps> | ErrorResponse> => {+ try {+ const response = await axios.post('/dashboards', {+ ...props,+ });++ return {+ statusCode: 200,+ error: null,+ message: response.data.status,+ payload: response.data.data,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};++export default create;diff --git a/frontend/src/api/dashboard/delete.ts b/frontend/src/api/dashboard/delete.tsnew file mode 100644index 0000000000..2f7c8f16b9--- /dev/null+++ b/frontend/src/api/dashboard/delete.ts@@ -0,0 +1,24 @@+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';++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);+ }+};++export default deleteDashboard;diff --git a/frontend/src/api/dashboard/get.ts b/frontend/src/api/dashboard/get.tsnew file mode 100644index 0000000000..6c9c953e7d--- /dev/null+++ b/frontend/src/api/dashboard/get.ts@@ -0,0 +1,24 @@+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';++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);+ }+};++export default get;diff --git a/frontend/src/api/dashboard/getAll.ts b/frontend/src/api/dashboard/getAll.tsnew file mode 100644index 0000000000..abd3e8fc93--- /dev/null+++ b/frontend/src/api/dashboard/getAll.ts@@ -0,0 +1,24 @@+import axios from 'api';+import { ErrorResponseHandler } from 'api/ErrorResponseHandler';+import { AxiosError } from 'axios';+import { ErrorResponse, SuccessResponse } from 'types/api';+import { PayloadProps } from 'types/api/dashboard/getAll';++const getAll = async (): Promise<+ SuccessResponse<PayloadProps> | ErrorResponse+> => {+ try {+ const response = await axios.get('/dashboards');++ return {+ statusCode: 200,+ error: null,+ message: response.data.message,+ payload: response.data.data,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};++export default getAll;diff --git a/frontend/src/api/dashboard/update.ts b/frontend/src/api/dashboard/update.tsnew file mode 100644index 0000000000..b22689c0ed--- /dev/null+++ b/frontend/src/api/dashboard/update.ts@@ -0,0 +1,26 @@+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/update';++const update = async (+ props: Props,+): Promise<SuccessResponse<PayloadProps> | ErrorResponse> => {+ try {+ const response = await axios.put(`/dashboards/${props.uuid}`, {+ ...props,+ });++ return {+ statusCode: 200,+ error: null,+ message: response.data.status,+ payload: response.data.data,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};++export default update;diff --git a/frontend/src/api/index.ts b/frontend/src/api/index.tsindex 4cd108b169..b1592ba7dc 100644--- a/frontend/src/api/index.ts+++ b/frontend/src/api/index.ts@@ -1,10 +1,10 @@-import axios, { AxiosRequestConfig } from 'axios';+import axios from 'axios';import { ENVIRONMENT } from 'constants/env';import apiV1 from './apiV1';export default axios.create({- baseURL: `${ENVIRONMENT.baseURL}`,+ baseURL: `${ENVIRONMENT.baseURL}${apiV1}`,});export { apiV1 };diff --git a/frontend/src/api/widgets/getQuery.ts b/frontend/src/api/widgets/getQuery.tsnew file mode 100644index 0000000000..a706db3b77--- /dev/null+++ b/frontend/src/api/widgets/getQuery.ts@@ -0,0 +1,26 @@+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/widgets/getQuery';++const getQuery = async (+ props: Props,+): Promise<SuccessResponse<PayloadProps> | ErrorResponse> => {+ try {+ const response = await axios.get(+ `/query_range?query=${props.query}&start=${props.start}&end=${props.end}&step=${props.step}`,+ );++ return {+ statusCode: 200,+ error: null,+ message: response.data.status,+ payload: response.data.data,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};++export default getQuery;diff --git a/frontend/src/assets/Dashboard/TimeSeries.tsx b/frontend/src/assets/Dashboard/TimeSeries.tsxnew file mode 100644index 0000000000..de50a3e512--- /dev/null+++ b/frontend/src/assets/Dashboard/TimeSeries.tsx@@ -0,0 +1,35 @@+import React from 'react';++const TimeSeries = (): JSX.Element => (+ <svg+ width="81"+ height="46"+ viewBox="0 0 81 46"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ xmlnsXlink="http://www.w3.org/1999/xlink"+ >+ <rect width="81" height="46" fill="url(#pattern0)" />+ <defs>+ <pattern+ id="pattern0"+ patternContentUnits="objectBoundingBox"+ width="1"+ height="1"+ >+ <use+ xlinkHref="#image0"+ transform="translate(0 -0.0365149) scale(0.015625 0.0275136)"+ />+ </pattern>+ <image+ id="image0"+ width="64"+ height="39"+ xlinkHref="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAAnCAYAAAC/mE48AAAMbmlDQ1BJQ0MgUHJvZmlsZQAASImVVwdYU8kWnluSkJDQAghICb0J0gkgJYQWQHoRbIQkkFBiTAgqdnRRwbUiIljRVRHFtgJix64sir0vFlSUdVEXGypvQgK67ivfO9839/45c+Y/5c7k3gOA5geuRJKHagGQLy6QJoQHM8akpTNInYAETIA2cAPeXJ5MwoqLiwZQBu9/l3c3AKK4X3VScP1z/r+KDl8g4wGAjIM4ky/j5UN8HAB8LU8iLQCAqNBbTimQKPAciHWlMECIyxU4W4m3K3CmEh8esElKYEN8GQA1KpcrzQZA4x7UMwp52ZBH4zPELmK+SAyA5giIA3hCLh9iRewj8vMnKXAlxHbQXgIxjAcwM7/jzP4bf+YQP5ebPYSVeQ2IWohIJsnjTvs/S/O/JT9PPujDBg6qUBqRoMgf1vBW7qQoBaZC3C3OjIlV1BriDyK+su4AoBShPCJZaY8a82RsWD+gD7ELnxsSBbExxGHivJholT4zSxTGgRjuFnSqqICTBLEBxAsFstBElc1G6aQElS+0IUvKZqn057jSAb8KXw/kucksFf8boYCj4sc0ioRJqRBTILYqFKXEQKwBsbMsNzFKZTOqSMiOGbSRyhMU8VtBnCAQhwcr+bHCLGlYgsq+NF82mC+2USjixKjwvgJhUoSyPtgpHncgfpgLdlkgZiUP8ghkY6IHc+ELQkKVuWPPBeLkRBXPB0lBcIJyLU6R5MWp7HELQV64Qm8BsYesMFG1Fk8pgJtTyY9nSQrikpRx4kU53Mg4ZTz4MhAN2CAEMIAcjkwwCeQAUVt3Yzf8pZwJA1wgBdlAAJxUmsEVqQMzYnhNBEXgD4gEQDa0LnhgVgAKof7LkFZ5dQJZA7OFAytywVOI80EUyIO/5QOrxEPeUsATqBH9wzsXDh6MNw8Oxfy/1w9qv2lYUBOt0sgHPTI0By2JocQQYgQxjGiPG+EBuB8eDa9BcLjhTNxnMI9v9oSnhHbCI8J1Qgfh9kRRsfSHKEeDDsgfpqpF5ve1wG0gpycejPtDdsiM6+NGwAn3gH5YeCD07Am1bFXciqowfuD+WwbfPQ2VHdmFjJKHkYPIdj+u1HDQ8BxiUdT6+/ooY80cqjd7aOZH/+zvqs+H96gfLbGF2H7sLHYCO48dxhoBAzuGNWGt2BEFHtpdTwZ216C3hIF4ciGP6B/+uCqfikrKXOpculw+K+cKBFMLFAePPUkyTSrKFhYwWPDtIGBwxDznEQw3FzdXABTvGuXf19v4gXcIot/6TTfvdwD8j/X39x/6pos8BsBeb3j8D37T2TEB0FYH4NxBnlxaqNThigsB/ktowpNmCEyBJbCD+bgBL+AHgkAoiASxIAmkgQmwykK4z6VgCpgB5oISUAaWgVWgCmwAm8F2sAvsA43gMDgBzoCL4DK4Du7C3dMJXoIe8A70IQhCQmgIHTFEzBBrxBFxQ5hIABKKRCMJSBqSgWQjYkSOzEDmIWXICqQK2YTUInuRg8gJ5DzSjtxGHiJdyBvkE4qhVFQXNUFt0JEoE2WhUWgSOh7NRiejReh8dAlaidagO9EG9AR6Eb2OdqAv0V4MYOqYPmaOOWFMjI3FYulYFibFZmGlWAVWg9VjzfA5X8U6sG7sI07E6TgDd4I7OAJPxnn4ZHwWvhivwrfjDfgp/Cr+EO/BvxJoBGOCI8GXwCGMIWQTphBKCBWErYQDhNPwLHUS3hGJRH2iLdEbnsU0Yg5xOnExcR1xN/E4sZ34mNhLIpEMSY4kf1IsiUsqIJWQ1pB2ko6RrpA6SR/U1NXM1NzUwtTS1cRqxWoVajvUjqpdUXum1kfWIluTfcmxZD55GnkpeQu5mXyJ3Enuo2hTbCn+lCRKDmUupZJSTzlNuUd5q66ubqHuox6vLlKfo16pvkf9nPpD9Y9UHaoDlU0dR5VTl1C3UY9Tb1Pf0mg0G1oQLZ1WQFtCq6WdpD2gfdCgazhrcDT4GrM1qjUaNK5ovNIka1prsjQnaBZpVmju17yk2a1F1rLRYmtxtWZpVWsd1Lqp1atN13bVjtXO116svUP7vPZzHZKOjU6oDl9nvs5mnZM6j+kY3ZLOpvPo8+hb6KfpnbpEXVtdjm6ObpnuLt023R49HT0PvRS9qXrVekf0OvQxfRt9jn6e/lL9ffo39D8NMxnGGiYYtmhY/bArw94bDDcIMhAYlBrsNrhu8MmQYRhqmGu43LDR8L4RbuRgFG80xWi90Wmj7uG6w/2G84aXDt83/I4xauxgnGA83Xizcatxr4mpSbiJxGSNyUmTblN90yDTHNNy06OmXWZ0swAzkVm52TGzFww9BouRx6hknGL0mBubR5jLzTeZt5n3WdhaJFsUW+y2uG9JsWRaZlmWW7ZY9liZWY22mmFVZ3XHmmzNtBZar7Y+a/3extYm1WaBTaPNc1sDW45tkW2d7T07ml2g3WS7Grtr9kR7pn2u/Tr7yw6og6eD0KHa4ZIj6ujlKHJc59g+gjDCZ4R4RM2Im05UJ5ZToVOd00Nnfedo52LnRudXI61Gpo9cPvLsyK8uni55Lltc7rrquEa6Frs2u75xc3DjuVW7XXOnuYe5z3Zvcn/t4egh8FjvccuT7jnac4Fni+cXL28vqVe9V5e3lXeG91rvm0xdZhxzMfOcD8En2Ge2z2Gfj75evgW++3z/9HPyy/Xb4fd8lO0owagtox77W/hz/Tf5dwQwAjICNgZ0BJoHcgNrAh8FWQbxg7YGPWPZs3JYO1mvgl2CpcEHgt+zfdkz2cdDsJDwkNKQtlCd0OTQqtAHYRZh2WF1YT3hnuHTw49HECKiIpZH3OSYcHicWk5PpHfkzMhTUdSoxKiqqEfRDtHS6ObR6OjI0StH34uxjhHHNMaCWE7sytj7cbZxk+MOxRPj4+Kr458muCbMSDibSE+cmLgj8V1ScNLSpLvJdsny5JYUzZRxKbUp71NDUlekdowZOWbmmItpRmmitKZ0UnpK+tb03rGhY1eN7RznOa5k3I3xtuOnjj8/wWhC3oQjEzUncifuzyBkpGbsyPjMjeXWcHszOZlrM3t4bN5q3kt+EL+c3yXwF6wQPMvyz1qR9TzbP3tldpcwUFgh7BaxRVWi1zkRORty3ufG5m7L7c9Lzdudr5afkX9QrCPOFZ+aZDpp6qR2iaOkRNIx2Xfyqsk90ijpVhkiGy9rKtCFH/Wtcjv5T/KHhQGF1YUfpqRM2T9Ve6p4aus0h2mLpj0rCiv6ZTo+nTe9ZYb5jLkzHs5kzdw0C5mVOatltuXs+bM754TP2T6XMjd37m/FLsUriv+alzqveb7J/DnzH/8U/lNdiUaJtOTmAr8FGxbiC0UL2xa5L1qz6Gspv/RCmUtZRdnnxbzFF352/bny5/4lWUvalnotXb+MuEy87MbywOXbV2ivKFrxeOXolQ3ljPLS8r9WTVx1vsKjYsNqymr56o7K6MqmNVZrlq35XCWsul4dXL17rfHaRWvfr+Ovu7I+aH39BpMNZRs+bRRtvLUpfFNDjU1NxWbi5sLNT7ekbDn7C/OX2q1GW8u2ftkm3taxPWH7qVrv2todxjuW1qF18rquneN2Xt4Vsqup3ql+02793WV7wB75nhd7M/be2Be1r2U/c3/9r9a/rj1AP1DagDRMa+hpFDZ2NKU1tR+MPNjS7Nd84JDzoW2HzQ9XH9E7svQo5ej8o/3Hio71Hpcc7z6RfeJxy8SWuyfHnLx2Kv5U2+mo0+fOhJ05eZZ19tg5/3OHz/ueP3iBeaHxotfFhlbP1gO/ef52oM2rreGS96Wmyz6Xm9tHtR+9EnjlxNWQq2euca5dvB5zvf1G8o1bN8fd7LjFv/X8dt7t13cK7/TdnXOPcK/0vtb9igfGD2p+t/99d4dXx5GHIQ9bHyU+uvuY9/jlE9mTz53zn9KeVjwze1b73O354a6wrssvxr7ofCl52ddd8of2H2tf2b369c+gP1t7xvR0vpa+7n+z+K3h221/efzV0hvX++Bd/ru+96UfDD9s/8j8ePZT6qdnfVM+kz5XfrH/0vw16uu9/vz+fglXyh34FMDgQLOyAHizDQBaGgB02LdRxip7wQFBlP3rAAL/CSv7xQHxAqAefr/Hd8Ovm5sA7NkC2y/Irwl71TgaAEk+AHV3HxoqkWW5uym5qLBPITzo738LezbSSgC+LOvv76vp7/+yGQYLe8fjYmUPqhAi7Bk2cr5k5meCfyPK/vS7HH+8A0UEHuDH+78AhB+RBatyf5wAAABWZVhJZk1NACoAAAAIAAGHaQAEAAAAAQAAABoAAAAAAAOShgAHAAAAEgAAAESgAgAEAAAAAQAAAECgAwAEAAAAAQAAACcAAAAAQVNDSUkAAABTY3JlZW5zaG906UURvQAAAdRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDYuMC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6ZXhpZj0iaHR0cDovL25zLmFkb2JlLmNvbS9leGlmLzEuMC8iPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+Mzk8L2V4aWY6UGl4ZWxZRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFhEaW1lbnNpb24+NjQ8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpVc2VyQ29tbWVudD5TY3JlZW5zaG90PC9leGlmOlVzZXJDb21tZW50PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4Kd1qoIQAADORJREFUaAXlWltw1tUR31zJBQIkgVwgTUgQUCwQaosDOkJs0QEJgy2jVZ/q1Ie2j23f67Mz1bHtjA86daTlwRGxhBFjgQgyyiSYcKnUoeQKuZCQACF38v37292z///5fwnYjlgeeobvXHb37G93z57L94WUAIVmKUxM8ekgBCAYjWeluIHKejOsK21AAWbZPFVpAj5AvD9DAoRvAz/VYNlMv6Qkx8VzXuRSInl1znPReNJ6ztsU9kSKEeDcPcJPNVzPTCW55fUTJDKXM8GcSHaFx+CJcCQTGzoyZ8a9xk+P+8FmRq4dPFinzrDBkhHMk4HareJgamFeQAkMOK5wjzMgASryTAKAlWcJCWqqOi/aJNiQ8DA0IxzAXcLfvm27Gur2L6tNZwoblCJGCJIKiaOptH3bNsREDREnwGUpLhE1TlGuV8tEVHZoeCzuRvgyclynU0AiJGbG0ZSnk/y+U8MNyLqYjubZIQGwVWXVcmCxHinoCJpCGrBxfapOUU0SGRayCdLaQAMXZzOPNSThM9mbG2ng2aZeqV+L7zmtsjo/VQYxEFB4LDTmOvF4w/hSlCy7WROFqeF8lWEV/iGnbjLPUf8X+HYwi3lqL+NjJ5oLYo+wUUnR9XQSYqSLiwmgVfJtmE5Ory8nw3DhLaBnAouJFVI5OZnL/buEb5hJ+DieFNBtc4G1SuxhE+RwQgcEo5nM17Usrwjeavs+3gHfdH+b+LoFGClmFMbitHPX9g9kTOyOgWCm+5g8z4z6bjYa14sUsy1c7jI+o8+GH24BBZVaKzjNN0NooC8AoiiLM6PJnE4Q8LMuYhL1X7lKv3v5ZXrzrTch5inxunpjKHdqaooaGhroSv8VVaPqvej52tGfBd9XHRoGG5EBLi4swV1f0oBC/SqrjilzYnwi5FrHdDrNMScTiQS9v/892vHUU3Tt2hB1d/fpNKgbHhmO44PDOg7W1VF7ezt9+OEhkfXxdXK8vhO+SHoHIj9HtFgnZPKetWig9bosOjoySl2XLtGly5epu6cbGcsPIC4GryOtTTnRJ8eOUd68PFpfvZ5qamqovv4QDd8cpta2Vuq+3E1tbRfp1q1bood1nTx5kvr6++iF51+gifFxOnP6rFuyWO44eUa7M766AXukg1vAOjxVixnLrX1VABiGvHqDQ1eptbUV6TgAR+ZSZeUyMaizo4umwdc1U03RM1pD2d3dTaeaTtGOHbWib9X9D9C1oWt0uqWZiotLaOXKlTR/4ULq7OxCEKax6h10/Phx+umzz1FaRjrt3LmTPqr/kMbGxgQgCgF749s9C75jSwNxzaIUeAhKLGYaImjgTjigvt5eugjHJyYmqbS0lCoqymn+/AVyThSXlNJcBKOttR38CT2/2CQ7PIGWmJ6m9/ftoyeffILS4UwPZw4+NY/XUAtWNTs7S6zOX5BPCxfMp/Pnv6R3332Xdu/eTXl5eeJeUVERrVtXTYcO6VYwp6fdLRVeVjD7MnS/8sor1NHRId6Gic0o8FkCga4ssQ2YF+4vEVEOhyEjM4Oqli2jkuJiyspSY1meC0sVFBRQcdEirF4nTU1OyCrdGL5BAwP91NPbQ/vgfO68eZSZkUmXkQlZ2dlUVVlJa9asQSbNo+bmZtHF+PPy5tGx45/S6tUP0tKypW4ZdDG2bN4sGcJbJpGYpsHBQWpvbaPJqUk9N6Glr6+X9u7dS0//+GkqL/9O6K1oQKWaBC7McR2BpS6jNmlHK8gvoNS0NARIJXgCR/yrr74KRefCkbKyMurs6qIrfVdoZHgEUqkw8ip1gbZ7909oxcoVVIlA5ufnwzDVtXXrVjp69CjdYicw44MP/kZLkFUbNvyAurCCnD3mRVpGBm3d+iPav+99YF+gyclJKsL26WzvlCBc6e+nPXv2UG1tLQJc5eapy4KGSlHBQpHvAtrlWneVCdo+ifj+5IAOHz5Mn544QRsffpi2PvGEiHF2VGJlU1P1/GAD/7LnHarF/s3NyQlVsUmSlgArRlbxnBMnPqOMOZl0FQF78WcvSsB5AgdvyZKldBOH5fVr1ygbGCVLSkHvpFX3rxKHikqK6Ny5f9CRvx+mbdu30YoVK0Is80tXVd03fDvldBXZKH+aBM7uAo2isNG9+K9WAJ6l3/7m10hppPh7++SQZH5qdLfIfl2+4j5aXpW8GlDigW2pqaGGTxroUz70nnmW0pBtzC4oyKfCRYvp4sULNDY6RkUlxTh/ltGunbvo9OkWvCn0Gp2emqajR47Q2nXr5GAWO71Kn0GsUf2QpZZhkMBh7ZVwmAjq6uo8RtQdGRkJcMAE7R0dQsS1Fezd+9fgnT3vBJOTUyoIPdgewWuvvRbgTMAt6cihftOnhOnEdNDe3hZcHbjqGHFBbAObELbNLS3BG2+8EVy/fj149dXfB41NjcHNmyPBhQsXAgQrlGPwugPqSyKuNkAG2DK4FXZDixNHzHHCeO7fv5+qq6upvAwHDAqv1jNYtby58+jtt/9MY7ivx8bH6MCBA7Rr1y5cYZkCw3r4R5IzZ89gv/Jdz0UBU3EelJdXUD5WnEuEqfgpbksJ01Xr1qylDJwJr7/+B5wXD9ND33uIcnNzqLikBO+TS+F1yScbHzeG7+t3P4iwYZwUIirqU3AAeCcC7utBWrAwnxqbmmjk5ihtqdnizIBa/OP5tbU76fCRw/TWm29RYWE+rV27hsqWljk5NHgnnMJpz84cQ7rzDbB48WI5TGfD19i4FVHztRZPoA+s559/jqbxZsjm88XR5+bmylV9GUFYXnVf5LxYovpMq/4g4ka6TyJ7vTuBTn3xBe76PGrAaf3SSz9XdAHEZNOG9nHc6yOjo/IN8vGaHzpeQFPYo01NjTjAsmld9VoawgOopaWFenp6cN2tpvR0/nXOFKkNN24MyzXaPzBAOXgncIbwm4BPT1kq4GdmzkHlbJbpystBQJaULg3xQyPFZhcpTJMA6HQlhiwoC+z1AOKjjzxKr//pj7SsosIZi1kMKBOiuUys3bEDQRiR3wJZNz+OPvv8JN4JRbRy1Som0UK8+B7b/Bid//KfyIZPaP36apqTnUP9uMYG8crsHxzA2yOTFhcsokpgDg8PU9OpU5SDG6C8vJyKS0sABQNmwWezEvI0TwgW22S+8M3mB1q3AMSECGWs00pKgrWjgNaAN3wZrqJNGzfR53CmCqc6X13Mkyppbm52LjNwdd2U93xV5XKqWKZnhuVqKt4Iq1c/gHu8iJpbziCVb+HEL6TCxYto1QP3U9YcrK4zqBBbpRKYfb191NbRTl+eP08VFRV4QWbLXh8fw+ML5874+Cg+k3iMTcpja8uWzWJHCn6cZVx1XqImZugWYBF+1fjeMw1jFu0A4NkzZ+mXv/oFjMqigsJCpG8zHjt9VIJnMR86c7Ba5hhP5cAMDQ0h7Zvowe8+KG99XS3HlEYNKcQr8tFHNuGJnMHUWHGmhjQOFn84sB34rsCZMQdZkTs3B8HLF6ezs3KwNeK6JAN0+aFLVg0NtHt3RdR1V0Vd3UGlJV0dJoj9GzS3NAf1H9UHjY2NAd72wS13XfX29gb1H9cHAwMDJh610IcUjcbJvWRW8jiUn8mYSVHhuoPelQ4hw/fOAASGA4LgWCKk2FdcF7BwGVynuKhYXnHT0wnqxfubvx6fO3eOSpcuod6eXtrw/Q2UNx+HliwjV9zVJORayE6XY8bww6y8Db4KqwLVZdqdUgPgVr4pRfec4WsATJCd9+ZG734TYEX4mJBr09JSceKWyoefvvzjxaaNGyUdRZ3IqbDXDZ/CoU4wVcrB2EqEArPjM4anXSClMmWilwcafAPhHaABMMFwalIkeYY5niwrdGPiRsKjR9/hTNNiXGuZKn3TZa2TZ64z1VH+c/zQzqgjPcabDR8vQaQFc1zRrlpkdgnN2RCXw2wRMklww6512BktmvTWd8Q74EcS6EGJZ2bY/6b48hTWTHOuS6N9Ve4cAEkdcXLOOnPOjJ3Z+hJeCKDGNN0OX3XdLXy2YyY+AmDFGSqNExQLIwfMYJ4xM2uUK9qsKy0fPFFRbaCgE2lmvhtJ4xlqdEioHpX77/Fjs0P8MABxM8EHQsxADOLjyC2le1x7QUrr7WaboqkVusTuz4bP9LB8Q3yxbhb8dAmrKI8cYDn5cgISvhLj72dYEfQDVLw2LKkyTFMTueFoypAF8AqVP4s7AjvI5KiwJtCYD4ZqFmHRIbKocGHfJXzFEXxnCFuEhTYXmOWsEankcTJvFnGZp3JhzZFzgJFacMMrLqTOotDH9Ptuziwk80FZqL8GX7ZAFAO2lKfyhwvG0uVK96VxmMu6I1nrq7dhzR2e5Mc5yfl7ia8ZIP5FTtoWnrFy7ONtigUmFhONwowZMVnm3kP8/5//HxBmteayrk1A/wZIeQM45whS1wAAAABJRU5ErkJggg=="+ />+ </defs>+ </svg>+);++export default TimeSeries;diff --git a/frontend/src/assets/Dashboard/Value.tsx b/frontend/src/assets/Dashboard/Value.tsxnew file mode 100644index 0000000000..61bf672fa5--- /dev/null+++ b/frontend/src/assets/Dashboard/Value.tsx@@ -0,0 +1,18 @@+import React from 'react';++const Value = (): JSX.Element => (+ <svg+ width="78"+ height="32"+ viewBox="0 0 78 32"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ d="M15.0215 17.875C14.2285 18.8184 13.2783 19.5771 12.1709 20.1514C11.0771 20.7256 9.87402 21.0127 8.56152 21.0127C6.83887 21.0127 5.33496 20.5889 4.0498 19.7412C2.77832 18.8936 1.79395 17.7041 1.09668 16.1729C0.399414 14.6279 0.0507812 12.9258 0.0507812 11.0664C0.0507812 9.07031 0.426758 7.27246 1.17871 5.67285C1.94434 4.07324 3.02441 2.84961 4.41895 2.00195C5.81348 1.1543 7.44043 0.730469 9.2998 0.730469C12.2529 0.730469 14.5771 1.83789 16.2725 4.05273C17.9814 6.25391 18.8359 9.26172 18.8359 13.0762V14.1836C18.8359 19.9941 17.6875 24.2393 15.3906 26.9189C13.0938 29.585 9.62793 30.9521 4.99316 31.0205H4.25488V27.8213H5.05469C8.18555 27.7666 10.5918 26.9531 12.2734 25.3809C13.9551 23.7949 14.8711 21.293 15.0215 17.875ZM9.17676 17.875C10.4482 17.875 11.6172 17.4854 12.6836 16.7061C13.7637 15.9268 14.5498 14.9629 15.042 13.8145V12.2969C15.042 9.80859 14.502 7.78516 13.4219 6.22656C12.3418 4.66797 10.9746 3.88867 9.32031 3.88867C7.65234 3.88867 6.3125 4.53125 5.30078 5.81641C4.28906 7.08789 3.7832 8.76953 3.7832 10.8613C3.7832 12.8984 4.26855 14.5801 5.23926 15.9062C6.22363 17.2188 7.53613 17.875 9.17676 17.875ZM24.5371 29.0107C24.5371 28.3545 24.7285 27.8076 25.1113 27.3701C25.5078 26.9326 26.0957 26.7139 26.875 26.7139C27.6543 26.7139 28.2422 26.9326 28.6387 27.3701C29.0488 27.8076 29.2539 28.3545 29.2539 29.0107C29.2539 29.6396 29.0488 30.166 28.6387 30.5898C28.2422 31.0137 27.6543 31.2256 26.875 31.2256C26.0957 31.2256 25.5078 31.0137 25.1113 30.5898C24.7285 30.166 24.5371 29.6396 24.5371 29.0107ZM51.1562 20.9717H55.2988V24.0684H51.1562V31H47.3418V24.0684H33.7451V21.833L47.1162 1.14062H51.1562V20.9717ZM38.0518 20.9717H47.3418V6.3291L46.8906 7.14941L38.0518 20.9717ZM73.6123 1.12012V4.33984H72.915C69.9619 4.39453 67.6104 5.26953 65.8604 6.96484C64.1104 8.66016 63.0986 11.0459 62.8252 14.1221C64.3975 12.3174 66.5439 11.415 69.2646 11.415C71.8623 11.415 73.9336 12.3311 75.4785 14.1631C77.0371 15.9951 77.8164 18.3604 77.8164 21.2588C77.8164 24.335 76.9756 26.7959 75.2939 28.6416C73.626 30.4873 71.3838 31.4102 68.5674 31.4102C65.71 31.4102 63.3926 30.3164 61.6152 28.1289C59.8379 25.9277 58.9492 23.0977 58.9492 19.6387V18.1826C58.9492 12.6865 60.1182 8.48926 62.4561 5.59082C64.8076 2.67871 68.3008 1.18848 72.9355 1.12012H73.6123ZM68.6289 14.5732C67.3301 14.5732 66.1338 14.9629 65.04 15.7422C63.9463 16.5215 63.1875 17.499 62.7637 18.6748V20.0693C62.7637 22.5303 63.3174 24.5127 64.4248 26.0166C65.5322 27.5205 66.9131 28.2725 68.5674 28.2725C70.2764 28.2725 71.6162 27.6436 72.5869 26.3857C73.5713 25.1279 74.0635 23.4805 74.0635 21.4434C74.0635 19.3926 73.5645 17.7383 72.5664 16.4805C71.582 15.209 70.2695 14.5732 68.6289 14.5732Z"+ fill="white"+ />+ </svg>+);++export default Value;diff --git a/frontend/src/assets/index.css b/frontend/src/assets/index.cssindex a7f60fc45f..7e078e2a59 100644--- a/frontend/src/assets/index.css+++ b/frontend/src/assets/index.css@@ -1,4 +1,4 @@-@import "~antd/dist/antd.dark.css";+@import '~antd/dist/antd.dark.css';.ant-space-item {margin-right: 0 !important;@@ -10,3 +10,11 @@#chart {width: 100%;}++.ant-tabs-tab {+ margin: 0 0 0 32px !important;+}++.ant-tabs-nav-list > .ant-tabs-tab:first-child {+ margin: 0 !important;+}diff --git a/frontend/src/components/Graph/Legend/index.tsx b/frontend/src/components/Graph/Legend/index.tsxnew file mode 100644index 0000000000..41255241db--- /dev/null+++ b/frontend/src/components/Graph/Legend/index.tsx@@ -0,0 +1,24 @@+import { Typography } from 'antd';+import React from 'react';++import { ColorContainer, Container } from './styles';++const Legend = ({ text, color }: LegendProps): JSX.Element => {+ if (text.length === 0) {+ return <></>;+ }++ return (+ <Container>+ <ColorContainer color={color}></ColorContainer>+ <Typography>{text}</Typography>+ </Container>+ );+};++interface LegendProps {+ text: string;+ color: string;+}++export default Legend;diff --git a/frontend/src/components/Graph/Legend/styles.ts b/frontend/src/components/Graph/Legend/styles.tsnew file mode 100644index 0000000000..ac627bf0ea--- /dev/null+++ b/frontend/src/components/Graph/Legend/styles.ts@@ -0,0 +1,20 @@+import styled from 'styled-components';++export const Container = styled.div`+ margin-left: 2rem;+ margin-right: 2rem;+ display: flex;+ cursor: pointer;+`;++interface Props {+ color: string;+}++export const ColorContainer = styled.div<Props>`+ background-color: ${({ color }): string => color};+ border-radius: 50%;+ width: 20px;+ height: 20px;+ margin-right: 0.5rem;+`;diff --git a/frontend/src/components/Graph/index.tsx b/frontend/src/components/Graph/index.tsxnew file mode 100644index 0000000000..bb14085d62--- /dev/null+++ b/frontend/src/components/Graph/index.tsx@@ -0,0 +1,235 @@+import {+ BarController,+ BarElement,+ CategoryScale,+ Chart,+ ChartOptions,+ ChartType,+ Decimation,+ Filler,+ Legend,+ // LegendItem,+ LinearScale,+ LineController,+ LineElement,+ PointElement,+ ScaleOptions,+ SubTitle,+ TimeScale,+ TimeSeriesScale,+ Title,+ Tooltip,+} from 'chart.js';+import chartjsAdapter from 'chartjs-adapter-date-fns';+// import { colors } from 'lib/getRandomColor';+// import stringToHTML from 'lib/stringToHTML';+import React, { useCallback, useEffect, useRef } from 'react';+import { useThemeSwitcher } from 'react-css-theme-switcher';++// import Legends from './Legend';+// import { LegendsContainer } from './styles';++const Graph = ({+ data,+ type,+ title,+ isStacked,+ label,+ xAxisType,+ onClickHandler,+}: GraphProps): JSX.Element => {+ const chartRef = useRef<HTMLCanvasElement>(null);+ const { currentTheme } = useThemeSwitcher();++ // const [tooltipVisible, setTooltipVisible] = useState<boolean>(false);+ const lineChartRef = useRef<Chart>();++ const getGridColor = useCallback(() => {+ if (currentTheme === undefined) {+ return 'rgba(231,233,237,0.1)';+ }++ if (currentTheme === 'dark') {+ return 'rgba(231,233,237,0.1)';+ }++ return 'rgba(231,233,237,0.8)';+ }, [currentTheme]);++ const buildChart = useCallback(() => {+ if (lineChartRef.current !== undefined) {+ lineChartRef.current.destroy();+ }++ if (chartRef.current !== null) {+ Chart.register(+ LineElement,+ PointElement,+ LineController,+ CategoryScale,+ LinearScale,+ TimeScale,+ TimeSeriesScale,+ Decimation,+ Filler,+ Legend,+ Title,+ Tooltip,+ SubTitle,+ BarController,+ BarElement,+ );++ const options: ChartOptions = {+ responsive: true,+ maintainAspectRatio: false,+ interaction: {+ mode: 'index',+ intersect: false,+ },+ plugins: {+ title: {+ display: title === undefined ? false : true,+ text: title,+ },+ legend: {+ // just making sure that label is present+ display: !(+ data.datasets.find((e) => e.label !== undefined) === undefined+ ),+ labels: {+ usePointStyle: true,+ pointStyle: 'circle',+ },+ position: 'bottom',+ // labels: {+ // generateLabels: (chart: Chart): LegendItem[] => {+ // return (data.datasets || []).map((e, index) => {+ // return {+ // text: e.label || '',+ // datasetIndex: index,+ // };+ // });+ // },+ // pointStyle: 'circle',+ // usePointStyle: true,+ // },+ },+ },+ layout: {+ padding: 0,+ },+ scales: {+ x: {+ animate: false,+ grid: {+ display: true,+ color: getGridColor(),+ },+ labels: label,+ adapters: {+ date: chartjsAdapter,+ },+ type: xAxisType,+ },+ y: {+ display: true,+ grid: {+ display: true,+ color: getGridColor(),+ },+ },+ stacked: {+ display: isStacked === undefined ? false : 'auto',+ },+ },+ elements: {+ line: {+ tension: 0,+ cubicInterpolationMode: 'monotone',+ },+ },+ onClick: onClickHandler,+ };++ lineChartRef.current = new Chart(chartRef.current, {+ type: type,+ data: data,+ options,+ // plugins: [+ // {+ // id: 'htmlLegendPlugin',+ // afterUpdate: (chart: Chart): void => {+ // if (+ // chart &&+ // chart.options &&+ // chart.options.plugins &&+ // chart.options.plugins.legend &&+ // chart.options.plugins.legend.labels &&+ // chart.options.plugins.legend.labels.generateLabels+ // ) {+ // const labels = chart.options.plugins?.legend?.labels?.generateLabels(+ // chart,+ // );++ // const id = 'htmlLegend';++ // const response = document.getElementById(id);++ // if (labels && response && response?.childNodes.length === 0) {+ // const labelComponent = labels.map((e, index) => {+ // return {+ // element: Legends({+ // text: e.text,+ // color: colors[index] || 'white',+ // }),+ // dataIndex: e.datasetIndex,+ // };+ // });++ // labelComponent.map((e) => {+ // const el = stringToHTML(e.element);++ // if (el) {+ // el.addEventListener('click', () => {+ // chart.setDatasetVisibility(+ // e.dataIndex,+ // !chart.isDatasetVisible(e.dataIndex),+ // );+ // chart.update();+ // });+ // response.append(el);+ // }+ // });+ // }+ // }+ // },+ // },+ // ],+ });+ }+ }, [chartRef, data, type, title, isStacked, label, xAxisType, getGridColor]);++ useEffect(() => {+ buildChart();+ }, [buildChart]);++ return (+ <>+ <canvas ref={chartRef} />+ {/* <LegendsContainer id="htmlLegend" /> */}+ </>+ );+};++interface GraphProps {+ type: ChartType;+ data: Chart['data'];+ title?: string;+ isStacked?: boolean;+ label?: string[];+ xAxisType?: ScaleOptions['type'];+ onClickHandler?: ChartOptions['onClick'];+}++export default Graph;diff --git a/frontend/src/components/Graph/styles.ts b/frontend/src/components/Graph/styles.tsnew file mode 100644index 0000000000..204a78a57f--- /dev/null+++ b/frontend/src/components/Graph/styles.ts@@ -0,0 +1,8 @@+import styled from 'styled-components';++export const LegendsContainer = styled.div`+ display: flex;+ overflow-y: scroll;+ margin-right: 1rem;+ margin-bottom: 1rem;+`;diff --git a/frontend/src/components/Input/index.tsx b/frontend/src/components/Input/index.tsxnew file mode 100644index 0000000000..939d59455f--- /dev/null+++ b/frontend/src/components/Input/index.tsx@@ -0,0 +1,48 @@+import { Form, Input, InputProps } from 'antd';+import React from 'react';++const InputComponent = ({+ value,+ type = 'text',+ onChangeHandler,+ placeholder,+ ref,+ size = 'small',+ onBlurHandler,+ onPressEnterHandler,+ label,+ labelOnTop,+ addonBefore,+ ...props+}: InputComponentProps): JSX.Element => (+ <Form.Item labelCol={{ span: labelOnTop ? 24 : 4 }} label={label}>+ <Input+ placeholder={placeholder}+ type={type}+ onChange={onChangeHandler}+ value={value}+ ref={ref}+ size={size}+ addonBefore={addonBefore}+ onBlur={onBlurHandler}+ onPressEnter={onPressEnterHandler}+ {...props}+ />+ </Form.Item>+);++interface InputComponentProps extends InputProps {+ value: InputProps['value'];+ type?: InputProps['type'];+ onChangeHandler?: React.ChangeEventHandler<HTMLInputElement>;+ placeholder?: InputProps['placeholder'];+ ref?: React.LegacyRef<Input>;+ size?: InputProps['size'];+ onBlurHandler?: React.FocusEventHandler<HTMLInputElement>;+ onPressEnterHandler?: React.KeyboardEventHandler<HTMLInputElement>;+ label?: string;+ labelOnTop?: boolean;+ addonBefore?: React.ReactNode;+}++export default InputComponent;diff --git a/frontend/src/components/Loadable/index.tsx b/frontend/src/components/Loadable/index.tsxindex 5614b45110..f1b6774b16 100644--- a/frontend/src/components/Loadable/index.tsx+++ b/frontend/src/components/Loadable/index.tsx@@ -1,4 +1,4 @@-import { ComponentType,lazy } from 'react';+import { ComponentType, lazy } from 'react';function Loadable(importPath: {(): LoadableProps;diff --git a/frontend/src/components/Modal.tsx b/frontend/src/components/Modal.tsxindex e026a6f06f..8d7df61d78 100644--- a/frontend/src/components/Modal.tsx+++ b/frontend/src/components/Modal.tsx@@ -1,21 +1,13 @@-import { Modal } from 'antd';+import { Modal, ModalProps as Props } from 'antd';import React, { ReactElement } from 'react';-export const CustomModal = ({+const CustomModal = ({title,children,isModalVisible,- setIsModalVisible,footer,closable = true,-}: {- isModalVisible: boolean;- closable?: boolean;- setIsModalVisible: Function;- footer?: any;- title: string;- children: ReactElement;-}) => {+}: ModalProps): JSX.Element => {return (<><Modal@@ -29,3 +21,13 @@ export const CustomModal = ({</>);};++interface ModalProps {+ isModalVisible: boolean;+ closable?: boolean;+ footer?: Props['footer'];+ title: string;+ children: ReactElement;+}++export default CustomModal;diff --git a/frontend/src/components/NotFound/index.tsx b/frontend/src/components/NotFound/index.tsxindex b66af95fb7..1618484b24 100644--- a/frontend/src/components/NotFound/index.tsx+++ b/frontend/src/components/NotFound/index.tsx@@ -2,7 +2,7 @@ import NotFoundImage from 'assets/NotFound';import ROUTES from 'constants/routes';import React from 'react';-import { Button, Container,Text, TextContainer } from './styles';+import { Button, Container, Text, TextContainer } from './styles';const NotFound = (): JSX.Element => {return (diff --git a/frontend/src/components/SideNav/index.tsx b/frontend/src/components/SideNav/index.tsxindex 0d91094496..d2159259d2 100644--- a/frontend/src/components/SideNav/index.tsx+++ b/frontend/src/components/SideNav/index.tsx@@ -1,13 +1,15 @@-import React, { useState, useCallback } from "react";-import { Layout, Menu, Switch as ToggleButton } from "antd";-import { NavLink } from "react-router-dom";-import { useThemeSwitcher } from "react-css-theme-switcher";-import { useLocation } from "react-router-dom";-import ROUTES from "constants/routes";--import { ThemeSwitcherWrapper, Logo } from "./styles";+import { Layout, Menu, Switch as ToggleButton, Typography } from 'antd';+import ROUTES from 'constants/routes';+import React, { useCallback, useState } from 'react';+import { useThemeSwitcher } from 'react-css-theme-switcher';+import { NavLink } from 'react-router-dom';+import { useLocation } from 'react-router-dom';++import { Logo, ThemeSwitcherWrapper } from './styles';const { Sider } = Layout;-import menus from "./menuItems";+import history from 'lib/history';++import menus from './menuItems';const SideNav = (): JSX.Element => {const { switcher, currentTheme, themes } = useThemeSwitcher();@@ -15,14 +17,21 @@ const SideNav = (): JSX.Element => {const [collapsed, setCollapsed] = useState<boolean>(false);const { pathname } = useLocation();- const toggleTheme = useCallback((isChecked: boolean) => {- switcher({ theme: isChecked ? themes.dark : themes.light });- }, []);+ const toggleTheme = useCallback(+ (isChecked: boolean) => {+ switcher({ theme: isChecked ? themes.dark : themes.light });+ },+ [switcher, themes],+ );const onCollapse = useCallback(() => {setCollapsed((collapsed) => !collapsed);}, []);+ const onClickHandler = useCallback((to: string) => {+ history.push(to);+ }, []);+return (<Sider collapsible collapsed={collapsed} onCollapse={onCollapse} width={160}><ThemeSwitcherWrapper>@@ -32,7 +41,7 @@ const SideNav = (): JSX.Element => {/></ThemeSwitcherWrapper><NavLink to="/">- <Logo src={"/signoz.svg"} alt="SigNoz" collapsed={collapsed} />+ <Logo src={'/signoz.svg'} alt="SigNoz" collapsed={collapsed} /></NavLink><Menu@@ -43,9 +52,9 @@ const SideNav = (): JSX.Element => {>{menus.map(({ to, Icon, name }) => (<Menu.Item key={to} icon={<Icon />}>- <NavLink to={to} style={{ fontSize: 12, textDecoration: "none" }}>- {name}- </NavLink>+ <div onClick={(): void => onClickHandler(to)}>+ <Typography>{name}</Typography>+ </div></Menu.Item>))}</Menu>diff --git a/frontend/src/components/SideNav/menuItems.ts b/frontend/src/components/SideNav/menuItems.tsindex f857412389..acbf400d0c 100644--- a/frontend/src/components/SideNav/menuItems.ts+++ b/frontend/src/components/SideNav/menuItems.ts@@ -1,43 +1,49 @@import {- BarChartOutlined,AlignLeftOutlined,+ ApiOutlined,+ BarChartOutlined,+ DashboardFilled,DeploymentUnitOutlined,LineChartOutlined,SettingOutlined,- ApiOutlined,-} from "@ant-design/icons";-import ROUTES from "constants/routes";+} from '@ant-design/icons';+import ROUTES from 'constants/routes';const menus: SidebarMenu[] = [{Icon: BarChartOutlined,to: ROUTES.APPLICATION,- name: "Metrics",+ name: 'Metrics',},{Icon: AlignLeftOutlined,to: ROUTES.TRACES,- name: "Traces",+ name: 'Traces',},{to: ROUTES.SERVICE_MAP,- name: "Service Map",+ name: 'Service Map',Icon: DeploymentUnitOutlined,},{Icon: LineChartOutlined,to: ROUTES.USAGE_EXPLORER,- name: "Usage Explorer",+ name: 'Usage Explorer',},{Icon: SettingOutlined,to: ROUTES.SETTINGS,- name: "Settings",+ name: 'Settings',},{Icon: ApiOutlined,to: ROUTES.INSTRUMENTATION,- name: "Add instrumentation",+ name: 'Add instrumentation',+ },+ {+ Icon: DashboardFilled,+ to: ROUTES.ALL_DASHBOARD,+ name: 'Dashboard',},];diff --git a/frontend/src/components/SideNav/styles.ts b/frontend/src/components/SideNav/styles.tsindex 886559a2ad..0885303d63 100644--- a/frontend/src/components/SideNav/styles.ts+++ b/frontend/src/components/SideNav/styles.ts@@ -1,4 +1,4 @@-import styled from "styled-components";+import styled from 'styled-components';export const ThemeSwitcherWrapper = styled.div`display: flex;@@ -10,7 +10,7 @@ export const ThemeSwitcherWrapper = styled.div`export const Logo = styled.img<LogoProps>`width: 100px;margin: 5%;- display: ${({ collapsed }) => (!collapsed ? "block" : "none")};+ display: ${({ collapsed }): string => (!collapsed ? 'block' : 'none')};`;interface LogoProps {diff --git a/frontend/src/components/TimePreferenceDropDown/index.tsx b/frontend/src/components/TimePreferenceDropDown/index.tsxnew file mode 100644index 0000000000..02b75c1e2b--- /dev/null+++ b/frontend/src/components/TimePreferenceDropDown/index.tsx@@ -0,0 +1,52 @@+import { Button, Dropdown, Menu, Typography } from 'antd';+import timeItems, {+ timePreferance,+ timePreferenceType,+} from 'container/NewWidget/RightContainer/timeItems';+import React, { useCallback } from 'react';++import { TextContainer } from './styles';++const TimePreference = ({+ setSelectedTime,+ selectedTime,+}: TimePreferenceDropDownProps): JSX.Element => {+ const timeMenuItemOnChangeHandler = useCallback(+ (event: TimeMenuItemOnChangeHandlerEvent) => {+ const selectedTime = timeItems.find((e) => e.enum === event.key);+ if (selectedTime !== undefined) {+ setSelectedTime(selectedTime);+ }+ },+ [setSelectedTime],+ );++ return (+ <TextContainer noButtonMargin>+ <Dropdown+ overlay={+ <Menu>+ {timeItems.map((item) => (+ <Menu.Item onClick={timeMenuItemOnChangeHandler} key={item.enum}>+ <Typography>{item.name}</Typography>+ </Menu.Item>+ ))}+ </Menu>+ }+ >+ <Button>{selectedTime.name}</Button>+ </Dropdown>+ </TextContainer>+ );+};++interface TimeMenuItemOnChangeHandlerEvent {+ key: timePreferenceType | string;+}++interface TimePreferenceDropDownProps {+ setSelectedTime: React.Dispatch<React.SetStateAction<timePreferance>>;+ selectedTime: timePreferance;+}++export default TimePreference;diff --git a/frontend/src/components/TimePreferenceDropDown/styles.ts b/frontend/src/components/TimePreferenceDropDown/styles.tsnew file mode 100644index 0000000000..e2eeac983c--- /dev/null+++ b/frontend/src/components/TimePreferenceDropDown/styles.ts@@ -0,0 +1,14 @@+import styled from 'styled-components';++interface TextContainerProps {+ noButtonMargin?: boolean;+}++export const TextContainer = styled.div<TextContainerProps>`+ display: flex;++ > button {+ margin-left: ${({ noButtonMargin }): string => {+ return noButtonMargin ? '0' : '0.5rem';+ }}+`;diff --git a/frontend/src/components/ValueGraph/index.tsx b/frontend/src/components/ValueGraph/index.tsxnew file mode 100644index 0000000000..c25fd60e15--- /dev/null+++ b/frontend/src/components/ValueGraph/index.tsx@@ -0,0 +1,13 @@+import React from 'react';++import { Value } from './styles';++const ValueGraph = ({ value }: ValueGraphProps): JSX.Element => (+ <Value>{value}</Value>+);++interface ValueGraphProps {+ value: string;+}++export default ValueGraph;diff --git a/frontend/src/components/ValueGraph/styles.ts b/frontend/src/components/ValueGraph/styles.tsnew file mode 100644index 0000000000..af9f9c7ad0--- /dev/null+++ b/frontend/src/components/ValueGraph/styles.ts@@ -0,0 +1,6 @@+import { Typography } from 'antd';+import styled from 'styled-components';++export const Value = styled(Typography)`+ font-size: 3rem;+`;diff --git a/frontend/src/constants/query.ts b/frontend/src/constants/query.tsindex 5752c7f343..9e327ed6d4 100644--- a/frontend/src/constants/query.ts+++ b/frontend/src/constants/query.ts@@ -5,5 +5,5 @@ export enum METRICS_PAGE_QUERY_PARAM {service = 'service',error = 'error',operation = 'operation',- kind = 'kind'+ kind = 'kind',}diff --git a/frontend/src/constants/routes.ts b/frontend/src/constants/routes.tsindex 4714170b50..40ab99fe66 100644--- a/frontend/src/constants/routes.ts+++ b/frontend/src/constants/routes.ts@@ -8,6 +8,9 @@ const ROUTES = {INSTRUMENTATION: '/add-instrumentation',USAGE_EXPLORER: '/usage-explorer',APPLICATION: '/application',+ ALL_DASHBOARD: '/dashboard',+ DASHBOARD: '/dashboard/:dashboardId',+ DASHBOARD_WIDGET: '/dashboard/:dashboardId/:widgetId',};export default ROUTES;diff --git a/frontend/src/container/GridGraphComponent/index.tsx b/frontend/src/container/GridGraphComponent/index.tsxnew file mode 100644index 0000000000..4831bf7794--- /dev/null+++ b/frontend/src/container/GridGraphComponent/index.tsx@@ -0,0 +1,71 @@+import { Typography } from 'antd';+import { ChartData } from 'chart.js';+import Graph from 'components/Graph';+import ValueGraph from 'components/ValueGraph';+import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';+import history from 'lib/history';+import React from 'react';++import { TitleContainer, ValueContainer } from './styles';++const GridGraphComponent = ({+ GRAPH_TYPES,+ data,+ title,+ opacity,+ isStacked,+}: GridGraphComponentProps): JSX.Element | null => {+ const location = history.location.pathname;++ const isDashboardPage = location.split('/').length === 3;++ if (GRAPH_TYPES === 'TIME_SERIES') {+ return (+ <Graph+ {...{+ data,+ title,+ type: 'line',+ isStacked,+ opacity,+ xAxisType: 'time',+ }}+ />+ );+ }++ if (GRAPH_TYPES === 'VALUE') {+ const value = (((data.datasets[0] || []).data || [])[0] || 0) as number;++ if (data.datasets.length === 0) {+ return (+ <ValueContainer isDashboardPage={isDashboardPage}>+ <Typography>No Data</Typography>+ </ValueContainer>+ );+ }++ return (+ <>+ <TitleContainer isDashboardPage={isDashboardPage}>+ <Typography>{title}</Typography>+ </TitleContainer>+ <ValueContainer isDashboardPage={isDashboardPage}>+ <ValueGraph value={value.toString()} />+ </ValueContainer>+ </>+ );+ }++ return null;+};++export interface GridGraphComponentProps {+ GRAPH_TYPES: GRAPH_TYPES;+ data: ChartData;+ title?: string;+ opacity?: string;+ isStacked?: boolean;+}++export default GridGraphComponent;diff --git a/frontend/src/container/GridGraphComponent/styles.ts b/frontend/src/container/GridGraphComponent/styles.tsnew file mode 100644index 0000000000..a4450f2797--- /dev/null+++ b/frontend/src/container/GridGraphComponent/styles.ts@@ -0,0 +1,19 @@+import styled from 'styled-components';++interface Props {+ isDashboardPage: boolean;+}+export const ValueContainer = styled.div<Props>`+ height: ${({ isDashboardPage }): string =>+ isDashboardPage ? '100%' : '55vh'};+ display: flex;+ justify-content: center;+ align-items: center;+ flex-direction: column;+`;++export const TitleContainer = styled.div<Props>`+ text-align: center;+ padding-top: ${({ isDashboardPage }): string =>+ !isDashboardPage ? '1rem' : '0rem'};+`;diff --git a/frontend/src/container/GridGraphLayout/AddWidget/index.tsx b/frontend/src/container/GridGraphLayout/AddWidget/index.tsxnew file mode 100644index 0000000000..39f8c32448--- /dev/null+++ b/frontend/src/container/GridGraphLayout/AddWidget/index.tsx@@ -0,0 +1,55 @@+import { PlusOutlined } from '@ant-design/icons';+import { Typography } from 'antd';+import React, { useCallback } from 'react';+import { connect, useSelector } from 'react-redux';+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 { Button, Container } from './styles';++const AddWidget = ({ toggleAddWidget }: Props): JSX.Element => {+ const { isAddWidget } = useSelector<AppState, DashboardReducer>(+ (state) => state.dashboards,+ );++ const onToggleHandler = useCallback(() => {+ toggleAddWidget(true);+ }, [toggleAddWidget]);++ return (+ <Container>+ {!isAddWidget ? (+ <>+ <Button onClick={onToggleHandler} icon={<PlusOutlined />}>+ Add Widgets+ </Button>+ </>+ ) : (+ <Typography>Click a widget icon to add it here</Typography>+ )}+ </Container>+ );+};++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)(AddWidget);diff --git a/frontend/src/container/GridGraphLayout/AddWidget/styles.ts b/frontend/src/container/GridGraphLayout/AddWidget/styles.tsnew file mode 100644index 0000000000..9a7d6b58f3--- /dev/null+++ b/frontend/src/container/GridGraphLayout/AddWidget/styles.ts@@ -0,0 +1,18 @@+import { Button as ButtonComponent } from 'antd';+import styled from 'styled-components';++export const Button = styled(ButtonComponent)`+ &&& {+ display: flex;+ justify-content: center;+ align-items: center;+ border: none;+ }+`;++export const Container = styled.div`+ display: flex;+ justify-content: center;+ align-items: center;+ height: 100%;+`;diff --git a/frontend/src/container/GridGraphLayout/Graph/Bar/index.tsx b/frontend/src/container/GridGraphLayout/Graph/Bar/index.tsxnew file mode 100644index 0000000000..3c3cce7064--- /dev/null+++ b/frontend/src/container/GridGraphLayout/Graph/Bar/index.tsx@@ -0,0 +1,40 @@+import {+ DeleteOutlined,+ EditFilled,+ FullscreenOutlined,+} from '@ant-design/icons';+import React, { useCallback } from 'react';+import { useHistory, useLocation } from 'react-router';+import { Widgets } from 'types/api/dashboard/getAll';++import { Container } from './styles';++const Bar = ({+ widget,+ onViewFullScreenHandler,+ onDeleteHandler,+}: BarProps): JSX.Element => {+ const { push } = useHistory();+ const { pathname } = useLocation();++ const onEditHandler = useCallback(() => {+ const widgetId = widget.id;+ push(`${pathname}/new?widgetId=${widgetId}&graphType=${widget.panelTypes}`);+ }, [push, pathname, widget]);++ return (+ <Container>+ <FullscreenOutlined onClick={onViewFullScreenHandler} />+ <EditFilled onClick={onEditHandler} />+ <DeleteOutlined onClick={onDeleteHandler} />+ </Container>+ );+};++interface BarProps {+ widget: Widgets;+ onViewFullScreenHandler: () => void;+ onDeleteHandler: () => void;+}++export default Bar;diff --git a/frontend/src/container/GridGraphLayout/Graph/Bar/styles.ts b/frontend/src/container/GridGraphLayout/Graph/Bar/styles.tsnew file mode 100644index 0000000000..ca8073a672--- /dev/null+++ b/frontend/src/container/GridGraphLayout/Graph/Bar/styles.ts@@ -0,0 +1,15 @@+import styled from 'styled-components';++export const Container = styled.div`+ height: 15%;+ align-items: center;+ justify-content: flex-end;+ display: flex;+ gap: 1rem;+ padding-right: 1rem;+ padding-left: 1rem;+ padding-top: 0.5rem;+ position: absolute;+ top: 0;+ right: 0;+`;diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx b/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsxnew file mode 100644index 0000000000..5f9310d312--- /dev/null+++ b/frontend/src/container/GridGraphLayout/Graph/FullView/index.tsx@@ -0,0 +1,181 @@+import { Button, Typography } from 'antd';+import getQueryResult from 'api/widgets/getQuery';+import { AxiosError } from 'axios';+import { ChartData } from 'chart.js';+import Spinner from 'components/Spinner';+import TimePreference from 'components/TimePreferenceDropDown';+import GridGraphComponent from 'container/GridGraphComponent';+import {+ timeItems,+ timePreferance,+} from 'container/NewWidget/RightContainer/timeItems';+import getChartData from 'lib/getChartData';+import GetMaxMinTime from 'lib/getMaxMinTime';+import getStartAndEndTime from 'lib/getStartAndEndTime';+import React, { useCallback, useEffect, useState } from 'react';+import { useSelector } from 'react-redux';+import { GlobalTime } from 'store/actions';+import { AppState } from 'store/reducers';+import { Widgets } from 'types/api/dashboard/getAll';++import { GraphContainer, NotFoundContainer, TimeContainer } from './styles';++const FullView = ({ widget }: FullViewProps): JSX.Element => {+ const { minTime, maxTime } = useSelector<AppState, GlobalTime>(+ (state) => state.globalTime,+ );++ const [state, setState] = useState<FullViewState>({+ error: false,+ errorMessage: '',+ loading: true,+ payload: undefined,+ });++ const getSelectedTime = useCallback(+ () =>+ timeItems.find((e) => e.enum === (widget?.timePreferance || 'GLOBAL_TIME')),+ [widget],+ );++ const [selectedTime, setSelectedTime] = useState<timePreferance>({+ name: getSelectedTime()?.name || '',+ enum: widget?.timePreferance || 'GLOBAL_TIME',+ });++ const onFetchDataHandler = useCallback(async () => {+ try {+ const maxMinTime = GetMaxMinTime({+ graphType: widget.panelTypes,+ maxTime,+ minTime,+ });++ const { end, start } = getStartAndEndTime({+ type: selectedTime.enum,+ maxTime: maxMinTime.maxTime,+ minTime: maxMinTime.minTime,+ });++ const response = await Promise.all(+ widget.query+ .filter((e) => e.query.length !== 0)+ .map(async (query) => {+ const result = await getQueryResult({+ end,+ query: query.query,+ start: start,+ step: '30',+ });+ return {+ query: query.query,+ queryData: result,+ legend: query.legend,+ };+ }),+ );++ const isError = response.find((e) => e.queryData.statusCode !== 200);++ if (isError !== undefined) {+ setState((state) => ({+ ...state,+ error: true,+ errorMessage: isError.queryData.error || 'Something went wrong',+ loading: false,+ }));+ } 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,+ },+ });++ setState((state) => ({+ ...state,+ loading: false,+ payload: chartDataSet,+ }));+ }+ } catch (error) {+ setState((state) => ({+ ...state,+ error: true,+ errorMessage: (error as AxiosError).toString(),+ loading: false,+ }));+ }+ }, [widget, maxTime, minTime, selectedTime.enum]);++ useEffect(() => {+ onFetchDataHandler();+ }, [onFetchDataHandler]);++ if (state.loading || state.payload === undefined) {+ return <Spinner height="80vh" size="large" tip="Loading..." />;+ }++ if (state.loading === false && state.payload.datasets.length === 0) {+ return (+ <>+ <TimePreference+ {...{+ selectedTime,+ setSelectedTime,+ }}+ />+ <NotFoundContainer>+ <Typography>No Data</Typography>+ </NotFoundContainer>+ </>+ );+ }++ return (+ <>+ <TimeContainer>+ <TimePreference+ {...{+ selectedTime,+ setSelectedTime,+ }}+ />+ <Button onClick={onFetchDataHandler} type="primary">+ Refresh+ </Button>+ </TimeContainer>++ <GraphContainer>+ <GridGraphComponent+ {...{+ GRAPH_TYPES: widget.panelTypes,+ data: state.payload,+ isStacked: widget.isStacked,+ opacity: widget.opacity,+ title: widget.title,+ }}+ />+ </GraphContainer>+ </>+ );+};++interface FullViewState {+ loading: boolean;+ error: boolean;+ errorMessage: string;+ payload: ChartData | undefined;+}++interface FullViewProps {+ widget: Widgets;+}++export default FullView;diff --git a/frontend/src/container/GridGraphLayout/Graph/FullView/styles.ts b/frontend/src/container/GridGraphLayout/Graph/FullView/styles.tsnew file mode 100644index 0000000000..10d21cd4da--- /dev/null+++ b/frontend/src/container/GridGraphLayout/Graph/FullView/styles.ts@@ -0,0 +1,21 @@+import styled from 'styled-components';++export const GraphContainer = styled.div`+ min-height: 70vh;+ align-items: center;+ justify-content: center;+ display: flex;+ flex-direction: column;+`;++export const NotFoundContainer = styled.div`+ display: flex;+ justify-content: center;+ align-items: center;+ min-height: 55vh;+`;++export const TimeContainer = styled.div`+ display: flex;+ justify-content: flex-end;+`;diff --git a/frontend/src/container/GridGraphLayout/Graph/index.tsx b/frontend/src/container/GridGraphLayout/Graph/index.tsxnew file mode 100644index 0000000000..05adbd4654--- /dev/null+++ b/frontend/src/container/GridGraphLayout/Graph/index.tsx@@ -0,0 +1,209 @@+import { Typography } from 'antd';+import getQueryResult from 'api/widgets/getQuery';+import { AxiosError } from 'axios';+import { ChartData } from 'chart.js';+import Spinner from 'components/Spinner';+import GridGraphComponent from 'container/GridGraphComponent';+import getChartData from 'lib/getChartData';+import GetMaxMinTime from 'lib/getMaxMinTime';+import GetStartAndEndTime from 'lib/getStartAndEndTime';+import React, { useCallback, useEffect, useState } from 'react';+import { useSelector } from 'react-redux';+import { connect } from 'react-redux';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { GlobalTime } from 'store/actions';+import {+ DeleteWidget,+ DeleteWidgetProps,+} from 'store/actions/dashboard/deleteWidget';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import { Widgets } from 'types/api/dashboard/getAll';++import Bar from './Bar';+import FullView from './FullView';+import { Modal } from './styles';++const GridCardGraph = ({+ widget,+ deleteWidget,+ isDeleted,+}: GridCardGraphProps): JSX.Element => {+ const [state, setState] = useState<GridCardGraphState>({+ loading: true,+ errorMessage: '',+ error: false,+ payload: undefined,+ });+ const [modal, setModal] = useState(false);+ const { minTime, maxTime } = useSelector<AppState, GlobalTime>(+ (state) => state.globalTime,+ );+ const [deleteModal, setDeletModal] = useState(false);++ useEffect(() => {+ (async (): Promise<void> => {+ try {+ const getMaxMinTime = GetMaxMinTime({+ graphType: widget.panelTypes,+ maxTime,+ minTime,+ });++ const { start, end } = GetStartAndEndTime({+ type: widget.timePreferance,+ maxTime: getMaxMinTime.maxTime,+ minTime: getMaxMinTime.minTime,+ });++ const response = await Promise.all(+ widget.query+ .filter((e) => e.query.length !== 0)+ .map(async (query) => {+ const result = await getQueryResult({+ end,+ query: query.query,+ start: start,+ step: '30',+ });++ return {+ query: query.query,+ queryData: result,+ legend: query.legend,+ };+ }),+ );++ const isError = response.find((e) => e.queryData.statusCode !== 200);++ if (isError !== undefined) {+ setState((state) => ({+ ...state,+ error: true,+ errorMessage: isError.queryData.error || 'Something went wrong',+ loading: false,+ }));+ } 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,+ },+ });++ setState((state) => ({+ ...state,+ loading: false,+ payload: chartDataSet,+ }));+ }+ } catch (error) {+ setState((state) => ({+ ...state,+ error: true,+ errorMessage: (error as AxiosError).toString(),+ loading: false,+ }));+ }+ })();+ }, [widget, maxTime, minTime]);++ const onToggleModal = useCallback(+ (func: React.Dispatch<React.SetStateAction<boolean>>) => {+ func((value) => !value);+ },+ [],+ );++ const onDeleteHandler = useCallback(() => {+ deleteWidget({ widgetId: widget.id });+ onToggleModal(setDeletModal);+ isDeleted.current = true;+ }, [deleteWidget, widget, onToggleModal, isDeleted]);++ if (state.error) {+ return <div>{state.errorMessage}</div>;+ }++ if (state.loading === true || state.payload === undefined) {+ return <Spinner height="20vh" tip="Loading..." />;+ }++ return (+ <>+ <Bar+ onViewFullScreenHandler={(): void => onToggleModal(setModal)}+ widget={widget}+ onDeleteHandler={(): void => onToggleModal(setDeletModal)}+ />++ <Modal+ destroyOnClose+ onCancel={(): void => onToggleModal(setDeletModal)}+ visible={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+ visible={modal}+ onCancel={(): void => onToggleModal(setModal)}+ width="85%"+ destroyOnClose+ >+ <FullView widget={widget} />+ </Modal>++ <GridGraphComponent+ {...{+ GRAPH_TYPES: widget.panelTypes,+ data: state.payload,+ isStacked: widget.isStacked,+ opacity: widget.opacity,+ title: widget.title,+ }}+ />+ </>+ );+};++interface GridCardGraphState {+ loading: boolean;+ error: boolean;+ errorMessage: string;+ payload: ChartData | undefined;+}++interface DispatchProps {+ deleteWidget: ({+ widgetId,+ }: DeleteWidgetProps) => (dispatch: Dispatch<AppActions>) => void;+}++interface GridCardGraphProps extends DispatchProps {+ widget: Widgets;+ isDeleted: React.MutableRefObject<boolean>;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ deleteWidget: bindActionCreators(DeleteWidget, dispatch),+});++export default connect(null, mapDispatchToProps)(GridCardGraph);diff --git a/frontend/src/container/GridGraphLayout/Graph/styles.ts b/frontend/src/container/GridGraphLayout/Graph/styles.tsnew file mode 100644index 0000000000..156b7553d7--- /dev/null+++ b/frontend/src/container/GridGraphLayout/Graph/styles.ts@@ -0,0 +1,13 @@+import { Modal as ModalComponent } from 'antd';+import styled from 'styled-components';++interface Props {+ height?: string;+}++export const Modal = styled(ModalComponent)<Props>`+ .ant-modal-content,+ .ant-modal-body {+ min-height: ${({ height = '80vh' }): string => height};+ }+`;diff --git a/frontend/src/container/GridGraphLayout/index.tsx b/frontend/src/container/GridGraphLayout/index.tsxnew file mode 100644index 0000000000..1d069bf835--- /dev/null+++ b/frontend/src/container/GridGraphLayout/index.tsx@@ -0,0 +1,130 @@+import Spinner from 'components/Spinner';+import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';+import React, { memo, useCallback, useEffect, useRef, useState } from 'react';+import { Layout } from 'react-grid-layout';+import { useSelector } from 'react-redux';+import { useHistory, useLocation } from 'react-router-dom';+import { AppState } from 'store/reducers';+import DashboardReducer from 'types/reducer/dashboards';+import { v4 } from 'uuid';++import AddWidget from './AddWidget';+import Graph from './Graph';+import { Card, CardContainer, ReactGridLayout } from './styles';++const GridGraph = (): JSX.Element => {+ const { push } = useHistory();+ const { pathname } = useLocation();++ const { dashboards, loading } = useSelector<AppState, DashboardReducer>(+ (state) => state.dashboards,+ );++ const [selectedDashboard] = dashboards;+ const { data } = selectedDashboard;+ const { widgets } = data;++ const [layouts, setLayout] = useState<LayoutProps[]>([]);++ const AddWidgetWrapper = useCallback(() => <AddWidget />, []);++ const isMounted = useRef(true);+ const isDeleted = useRef(false);++ useEffect(() => {+ if (+ loading === false &&+ (isMounted.current === true || isDeleted.current === true)+ ) {+ const getPreLayouts = (): LayoutProps[] => {+ if (widgets === undefined) {+ return [];+ }++ return widgets.map((e, index) => {+ return {+ h: 2,+ w: 6,+ y: Infinity,+ i: (index + 1).toString(),+ x: (index % 2) * 6,+ // eslint-disable-next-line react/display-name+ Component: (): JSX.Element => (+ <Graph isDeleted={isDeleted} widget={widgets[index]} />+ ),+ };+ });+ };++ const preLayouts = getPreLayouts();++ setLayout(() => [+ ...preLayouts,+ {+ i: (preLayouts.length + 1).toString(),+ x: (preLayouts.length % 2) * 6,+ y: Infinity,+ w: 6,+ h: 2,+ Component: AddWidgetWrapper,+ },+ ]);+ }++ return (): void => {+ isMounted.current = false;+ };+ }, [widgets, layouts.length, AddWidgetWrapper, loading]);++ const onDropHandler = useCallback(+ (allLayouts: Layout[], currectLayout: Layout, event: DragEvent) => {+ event.preventDefault();+ if (event.dataTransfer) {+ const graphType = event.dataTransfer.getData('text') as GRAPH_TYPES;+ const generateWidgetId = v4();+ push(`${pathname}/new?graphType=${graphType}&widgetId=${generateWidgetId}`);+ }+ },+ [pathname, push],+ );++ if (layouts.length === 0) {+ return <Spinner height="40vh" size="large" tip="Loading..." />;+ }++ return (+ <ReactGridLayout+ isResizable+ isDraggable+ cols={12}+ rowHeight={100}+ autoSize+ width={100}+ isDroppable+ useCSSTransforms+ onDrop={onDropHandler}+ >+ {layouts.map(({ Component, ...rest }, index) => {+ const widget = (widgets || [])[index] || {};++ const type = widget.panelTypes;++ const isQueryType = type === 'VALUE';++ return (+ <CardContainer key={rest.i} data-grid={rest}>+ <Card isQueryType={isQueryType}>+ <Component />+ </Card>+ </CardContainer>+ );+ })}+ </ReactGridLayout>+ );+};++interface LayoutProps extends Layout {+ Component: () => JSX.Element;+}++export default memo(GridGraph);diff --git a/frontend/src/container/GridGraphLayout/styles.ts b/frontend/src/container/GridGraphLayout/styles.tsnew file mode 100644index 0000000000..eac707db79--- /dev/null+++ b/frontend/src/container/GridGraphLayout/styles.ts@@ -0,0 +1,42 @@+import { Card as CardComponent } from 'antd';+import RGL, { WidthProvider } from 'react-grid-layout';+import styled from 'styled-components';++const ReactGridLayoutComponent = WidthProvider(RGL);++interface Props {+ isQueryType: boolean;+}+export const Card = styled(CardComponent)<Props>`+ &&& {+ height: 100%;+ }++ .ant-card-body {+ height: 100%;+ padding: 0;+ }+`;++export const CardContainer = styled.div`+ .react-resizable-handle {+ position: absolute;+ width: 20px;+ height: 20px;+ bottom: 0;+ right: 0;+ background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/Pg08IS0tIEdlbmVyYXRvcjogQWRvYmUgRmlyZXdvcmtzIENTNiwgRXhwb3J0IFNWRyBFeHRlbnNpb24gYnkgQWFyb24gQmVhbGwgKGh0dHA6Ly9maXJld29ya3MuYWJlYWxsLmNvbSkgLiBWZXJzaW9uOiAwLjYuMSAgLS0+DTwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DTxzdmcgaWQ9IlVudGl0bGVkLVBhZ2UlMjAxIiB2aWV3Qm94PSIwIDAgNiA2IiBzdHlsZT0iYmFja2dyb3VuZC1jb2xvcjojZmZmZmZmMDAiIHZlcnNpb249IjEuMSINCXhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbDpzcGFjZT0icHJlc2VydmUiDQl4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjZweCIgaGVpZ2h0PSI2cHgiDT4NCTxnIG9wYWNpdHk9IjAuMzAyIj4NCQk8cGF0aCBkPSJNIDYgNiBMIDAgNiBMIDAgNC4yIEwgNCA0LjIgTCA0LjIgNC4yIEwgNC4yIDAgTCA2IDAgTCA2IDYgTCA2IDYgWiIgZmlsbD0iIzAwMDAwMCIvPg0JPC9nPg08L3N2Zz4=');+ background-position: bottom right;+ padding: 0 3px 3px 0;+ background-repeat: no-repeat;+ background-origin: content-box;+ box-sizing: border-box;+ cursor: se-resize;+ }+`;++export const ReactGridLayout = styled(ReactGridLayoutComponent)`+ border: 1px solid #434343;+ margin-top: 1rem;+ position: relative;+`;diff --git a/frontend/src/container/ListOfDashboard/TableComponents/CreatedBy.tsx b/frontend/src/container/ListOfDashboard/TableComponents/CreatedBy.tsxnew file mode 100644index 0000000000..9416261f39--- /dev/null+++ b/frontend/src/container/ListOfDashboard/TableComponents/CreatedBy.tsx@@ -0,0 +1,17 @@+import { Typography } from 'antd';+import convertDateToAmAndPm from 'lib/convertDateToAmAndPm';+import React from 'react';++import { Data } from '..';++const Created = (createdBy: Data['createdBy']): JSX.Element => {+ const time = new Date(createdBy);++ return (+ <Typography>{`${time.toLocaleDateString()} ${convertDateToAmAndPm(+ time,+ )}`}</Typography>+ );+};++export default Created;diff --git a/frontend/src/container/ListOfDashboard/TableComponents/Date.tsx b/frontend/src/container/ListOfDashboard/TableComponents/Date.tsxnew file mode 100644index 0000000000..ef0bce03c9--- /dev/null+++ b/frontend/src/container/ListOfDashboard/TableComponents/Date.tsx@@ -0,0 +1,14 @@+import { Typography } from 'antd';+import React from 'react';++import { Data } from '..';++const DateComponent = (+ lastUpdatedTime: Data['lastUpdatedTime'],+): JSX.Element => {+ const date = new Date(lastUpdatedTime).toDateString();++ return <Typography>{date}</Typography>;+};++export default DateComponent;diff --git a/frontend/src/container/ListOfDashboard/TableComponents/DeleteButton.tsx b/frontend/src/container/ListOfDashboard/TableComponents/DeleteButton.tsxnew file mode 100644index 0000000000..726ccf0253--- /dev/null+++ b/frontend/src/container/ListOfDashboard/TableComponents/DeleteButton.tsx@@ -0,0 +1,56 @@+import { Button } from 'antd';+import React, { useCallback } from 'react';+import { connect } from 'react-redux';+import { bindActionCreators } from 'redux';+import { Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { DeleteDashboard, DeleteDashboardProps } from 'store/actions';+import AppActions from 'types/actions';++import { Data } from '../index';++const DeleteButton = ({+ deleteDashboard,+ id,+}: DeleteButtonProps): JSX.Element => {+ const onClickHandler = useCallback(() => {+ deleteDashboard({+ uuid: id,+ });+ }, [id, deleteDashboard]);++ return (+ <Button onClick={onClickHandler} type="link">+ Delete+ </Button>+ );+};++interface DispatchProps {+ deleteDashboard: ({+ uuid,+ }: DeleteDashboardProps) => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ deleteDashboard: bindActionCreators(DeleteDashboard, dispatch),+});++type DeleteButtonProps = Data & DispatchProps;++const WrapperDeleteButton = connect(null, mapDispatchToProps)(DeleteButton);++// This is to avoid the type collision+const Wrapper = (props: Data): JSX.Element => {+ return (+ <WrapperDeleteButton+ {...{+ ...props,+ }}+ />+ );+};++export default Wrapper;diff --git a/frontend/src/container/ListOfDashboard/TableComponents/Name.tsx b/frontend/src/container/ListOfDashboard/TableComponents/Name.tsxnew file mode 100644index 0000000000..80787ff18e--- /dev/null+++ b/frontend/src/container/ListOfDashboard/TableComponents/Name.tsx@@ -0,0 +1,23 @@+import { Button } from 'antd';+import ROUTES from 'constants/routes';+import updateUrl from 'lib/updateUrl';+import React, { useCallback } from 'react';+import { useHistory } from 'react-router-dom';++import { Data } from '..';++const Name = (name: Data['name'], data: Data): JSX.Element => {+ const { push } = useHistory();++ const onClickHandler = useCallback(() => {+ push(updateUrl(ROUTES.DASHBOARD, ':dashboardId', data.id));+ }, []);++ return (+ <Button onClick={onClickHandler} type="link">+ {name}+ </Button>+ );+};++export default Name;diff --git a/frontend/src/container/ListOfDashboard/TableComponents/Tags.tsx b/frontend/src/container/ListOfDashboard/TableComponents/Tags.tsxnew file mode 100644index 0000000000..7831409a7c--- /dev/null+++ b/frontend/src/container/ListOfDashboard/TableComponents/Tags.tsx@@ -0,0 +1,16 @@+import { Tag } from 'antd';+import React from 'react';++import { Data } from '../index';++const Tags = (props: Data['tags']): JSX.Element => {+ return (+ <>+ {props.map((e) => (+ <Tag key={e}>{e}</Tag>+ ))}+ </>+ );+};++export default Tags;diff --git a/frontend/src/container/ListOfDashboard/index.tsx b/frontend/src/container/ListOfDashboard/index.tsxnew file mode 100644index 0000000000..2961566e5c--- /dev/null+++ b/frontend/src/container/ListOfDashboard/index.tsx@@ -0,0 +1,171 @@+import { PlusOutlined } from '@ant-design/icons';+import { Row, Table, TableColumnProps, Typography } from 'antd';+import createDashboard from 'api/dashboard/create';+import { AxiosError } from 'axios';+import ROUTES from 'constants/routes';+import updateUrl from 'lib/updateUrl';+import React, { useCallback, useState } from 'react';+import { useSelector } from 'react-redux';+import { useHistory } from 'react-router-dom';+import { AppState } from 'store/reducers';+import DashboardReducer from 'types/reducer/dashboards';+import { v4 } from 'uuid';++import { NewDashboardButton, TableContainer } from './styles';+import Createdby from './TableComponents/CreatedBy';+import DateComponent from './TableComponents/Date';+import DeleteButton from './TableComponents/DeleteButton';+import Name from './TableComponents/Name';+import Tags from './TableComponents/Tags';++const ListOfAllDashboard = (): JSX.Element => {+ const { dashboards } = useSelector<AppState, DashboardReducer>(+ (state) => state.dashboards,+ );++ const [newDashboardState, setNewDashboardState] = useState({+ loading: false,+ error: false,+ errorMessage: '',+ });++ const { push } = useHistory();++ const columns: TableColumnProps<Data>[] = [+ {+ title: 'Name',+ dataIndex: 'name',+ render: Name,+ },+ {+ title: 'Description',+ dataIndex: 'description',+ },+ {+ title: 'Tags (can be multiple)',+ dataIndex: 'tags',+ render: Tags,+ },+ {+ title: 'Created By',+ dataIndex: 'createdBy',+ render: Createdby,+ },+ {+ title: 'Last Updated Time',+ dataIndex: 'lastUpdatedTime',+ sorter: (a: Data, b: Data): number => {+ return parseInt(a.lastUpdatedTime, 10) - parseInt(b.lastUpdatedTime, 10);+ },+ render: DateComponent,+ },+ {+ title: 'Action',+ dataIndex: '',+ key: 'x',+ render: DeleteButton,+ },+ ];++ const data: Data[] = dashboards.map((e) => ({+ createdBy: e.created_at,+ description: e.data.description || '',+ id: e.uuid,+ lastUpdatedTime: e.updated_at,+ name: e.data.title,+ tags: e.data.tags || [],+ key: e.uuid,+ }));++ const onNewDashboardHandler = useCallback(async () => {+ try {+ const newDashboardId = v4();+ setNewDashboardState({+ ...newDashboardState,+ loading: true,+ });+ const response = await createDashboard({+ uuid: newDashboardId,+ title: 'Sample Title',+ });++ if (response.statusCode === 200) {+ setNewDashboardState({+ ...newDashboardState,+ loading: false,+ });+ push(updateUrl(ROUTES.DASHBOARD, ':dashboardId', newDashboardId));+ } else {+ setNewDashboardState({+ ...newDashboardState,+ loading: false,+ error: true,+ errorMessage: response.error || 'Something went wrong',+ });+ }+ } catch (error) {+ setNewDashboardState({+ ...newDashboardState,+ error: true,+ errorMessage: (error as AxiosError).toString() || 'Something went Wrong',+ });+ }+ }, [newDashboardState, push]);++ const getText = (): string => {+ if (!newDashboardState.error && !newDashboardState.loading) {+ return 'New Dashboard';+ }++ if (newDashboardState.loading) {+ return 'Loading';+ }++ return newDashboardState.errorMessage;+ };++ return (+ <TableContainer>+ <Table+ pagination={{+ pageSize: 9,+ defaultPageSize: 9,+ }}+ showHeader+ bordered+ sticky+ title={(): JSX.Element => {+ return (+ <Row justify="space-between">+ <Typography>Dashboard List</Typography>+ <NewDashboardButton+ onClick={onNewDashboardHandler}+ icon={<PlusOutlined />}+ type="primary"+ loading={newDashboardState.loading}+ danger={newDashboardState.error}+ >+ {getText()}+ </NewDashboardButton>+ </Row>+ );+ }}+ columns={columns}+ dataSource={data}+ showSorterTooltip+ />+ </TableContainer>+ );+};++export interface Data {+ key: React.Key;+ name: string;+ description: string;+ tags: string[];+ createdBy: string;+ lastUpdatedTime: string;+ id: string;+}++export default ListOfAllDashboard;diff --git a/frontend/src/container/ListOfDashboard/styles.ts b/frontend/src/container/ListOfDashboard/styles.tsnew file mode 100644index 0000000000..7ba5d0975f--- /dev/null+++ b/frontend/src/container/ListOfDashboard/styles.ts@@ -0,0 +1,16 @@+import { Button, Row } from 'antd';+import styled from 'styled-components';++export const NewDashboardButton = styled(Button)`+ &&& {+ display: flex;+ justify-content: center;+ align-items: center;+ }+`;++export const TableContainer = styled(Row)`+ &&& {+ margin-top: 1rem;+ }+`;diff --git a/frontend/src/container/NewDashboard/ComponentsSlider/index.tsx b/frontend/src/container/NewDashboard/ComponentsSlider/index.tsxnew file mode 100644index 0000000000..078851260e--- /dev/null+++ b/frontend/src/container/NewDashboard/ComponentsSlider/index.tsx@@ -0,0 +1,46 @@+import React, { useCallback } from 'react';+import { useHistory, useLocation } from 'react-router';+import { v4 } from 'uuid';++import menuItems, { ITEMS } from './menuItems';+import { Card, Container, Text } from './styles';++const DashboardGraphSlider = (): JSX.Element => {+ const onDragStartHandler: React.DragEventHandler<HTMLDivElement> = useCallback(+ (event: React.DragEvent<HTMLDivElement>) => {+ event.dataTransfer.setData('text/plain', event.currentTarget.id);+ },+ [],+ );+ const { push } = useHistory();+ const { pathname } = useLocation();++ const onClickHandler = useCallback(+ (name: ITEMS) => {+ const generateWidgetId = v4();+ push(`${pathname}/new?graphType=${name}&widgetId=${generateWidgetId}`);+ },+ [push, pathname],+ );++ return (+ <Container>+ {menuItems.map(({ name, Icon, display }) => (+ <Card+ onClick={(): void => onClickHandler(name)}+ id={name}+ onDragStart={onDragStartHandler}+ key={name}+ draggable+ >+ <Icon />+ <Text>{display}</Text>+ </Card>+ ))}+ </Container>+ );+};++export type GRAPH_TYPES = ITEMS;++export default DashboardGraphSlider;diff --git a/frontend/src/container/NewDashboard/ComponentsSlider/menuItems.ts b/frontend/src/container/NewDashboard/ComponentsSlider/menuItems.tsnew file mode 100644index 0000000000..ced78bb14d--- /dev/null+++ b/frontend/src/container/NewDashboard/ComponentsSlider/menuItems.ts@@ -0,0 +1,25 @@+import TimeSeries from 'assets/Dashboard/TimeSeries';+import ValueIcon from 'assets/Dashboard/Value';++const Items: ItemsProps[] = [+ {+ name: 'TIME_SERIES',+ Icon: TimeSeries,+ display: 'Time Series',+ },+ {+ name: 'VALUE',+ Icon: ValueIcon,+ display: 'Value',+ },+];++export type ITEMS = 'TIME_SERIES' | 'VALUE';++interface ItemsProps {+ name: ITEMS;+ Icon: () => JSX.Element;+ display: string;+}++export default Items;diff --git a/frontend/src/container/NewDashboard/ComponentsSlider/styles.ts b/frontend/src/container/NewDashboard/ComponentsSlider/styles.tsnew file mode 100644index 0000000000..ad59f774a8--- /dev/null+++ b/frontend/src/container/NewDashboard/ComponentsSlider/styles.ts@@ -0,0 +1,25 @@+import { Card as CardComponent, Typography } from 'antd';+import styled from 'styled-components';++export const Container = styled.div`+ display: flex;+ gap: 0.6rem;+`;++export const Card = styled(CardComponent)`+ min-height: 10vh;+ overflow-y: auto;+ cursor: pointer;++ .ant-card-body {+ height: 100%;+ display: flex;+ flex-direction: column;+ justify-content: space-between;+ }+`;++export const Text = styled(Typography)`+ text-align: center;+ margin-top: 1rem;+`;diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/AddTags/index.tsx b/frontend/src/container/NewDashboard/DescriptionOfDashboard/AddTags/index.tsxnew file mode 100644index 0000000000..b16d15e7be--- /dev/null+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/AddTags/index.tsx@@ -0,0 +1,120 @@+import { PlusOutlined } from '@ant-design/icons';+import { Col, Tooltip, Typography } from 'antd';+import Input from 'components/Input';+import React, { useState } from 'react';++import { InputContainer, NewTagContainer, TagsContainer } from './styles';++const AddTags = ({ tags, setTags }: AddTagsProps): JSX.Element => {+ const [inputValue, setInputValue] = useState<string>('');+ const [inputVisible, setInputVisible] = useState<boolean>(false);+ const [editInputIndex, setEditInputIndex] = useState(-1);+ const [editInputValue, setEditInputValue] = useState('');++ const handleInputConfirm = (): void => {+ if (inputValue) {+ setTags([...tags, inputValue]);+ }+ setInputVisible(false);+ setInputValue('');+ };++ const handleEditInputConfirm = (): void => {+ const newTags = [...tags];+ newTags[editInputIndex] = editInputValue;+ setTags(newTags);+ setEditInputIndex(-1);+ setInputValue('');+ };++ const handleClose = (removedTag: string): void => {+ const newTags = tags.filter((tag) => tag !== removedTag);+ setTags(newTags);+ };++ const showInput = (): void => {+ setInputVisible(true);+ };++ const onChangeHandler = (+ value: string,+ func: React.Dispatch<React.SetStateAction<string>>,+ ): void => {+ func(value);+ };++ return (+ <TagsContainer>+ {tags.map((tag, index) => {+ if (editInputIndex === index) {+ return (+ <Col lg={4}>+ <Input+ key={tag}+ size="small"+ value={editInputValue}+ onChangeHandler={(event): void =>+ onChangeHandler(event.target.value, setEditInputValue)+ }+ onBlurHandler={handleEditInputConfirm}+ onPressEnterHandler={handleEditInputConfirm}+ />+ </Col>+ );+ }++ const isLongTag = tag.length > 20;++ const tagElem = (+ <NewTagContainer closable key={tag} onClose={(): void => handleClose(tag)}>+ <span+ onDoubleClick={(e): void => {+ setEditInputIndex(index);+ setEditInputValue(tag);+ e.preventDefault();+ }}+ >+ {isLongTag ? `${tag.slice(0, 20)}...` : tag}+ </span>+ </NewTagContainer>+ );++ return isLongTag ? (+ <Tooltip title={tag} key={tag}>+ {tagElem}+ </Tooltip>+ ) : (+ tagElem+ );+ })}++ {inputVisible && (+ <InputContainer lg={4}>+ <Input+ type="text"+ size="small"+ value={inputValue}+ onChangeHandler={(event): void =>+ onChangeHandler(event.target.value, setInputValue)+ }+ onBlurHandler={handleInputConfirm}+ onPressEnterHandler={handleInputConfirm}+ />+ </InputContainer>+ )}++ {!inputVisible && (+ <NewTagContainer icon={<PlusOutlined />} onClick={showInput}>+ <Typography>New Tag</Typography>+ </NewTagContainer>+ )}+ </TagsContainer>+ );+};++interface AddTagsProps {+ tags: string[];+ setTags: React.Dispatch<React.SetStateAction<string[]>>;+}++export default AddTags;diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/AddTags/styles.ts b/frontend/src/container/NewDashboard/DescriptionOfDashboard/AddTags/styles.tsnew file mode 100644index 0000000000..f2daefe65e--- /dev/null+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/AddTags/styles.ts@@ -0,0 +1,26 @@+import { Col, Tag } from 'antd';+import styled from 'styled-components';++export const TagsContainer = styled.div`+ display: flex;+ align-items: center;+`;++export const NewTagContainer = styled(Tag)`+ &&& {+ display: flex;+ justify-content: space-between;+ align-items: center;+ height: 100%;++ svg {+ margin-right: 0.2rem;+ }+ }+`;++export const InputContainer = styled(Col)`+ > div {+ margin: 0;+ }+`;diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/Description/index.tsx b/frontend/src/container/NewDashboard/DescriptionOfDashboard/Description/index.tsxnew file mode 100644index 0000000000..b368de2403--- /dev/null+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/Description/index.tsx@@ -0,0 +1,34 @@+import { Input } from 'antd';+import React, { useCallback } from 'react';++import { Container } from './styles';+const { TextArea } = Input;++const Description = ({+ description,+ setDescription,+}: DescriptionProps): JSX.Element => {+ const onChangeHandler = useCallback(+ (e: React.ChangeEvent<HTMLTextAreaElement>) => {+ setDescription(e.target.value);+ },+ [setDescription],+ );++ return (+ <Container>+ <TextArea+ placeholder={'Description of the dashboard'}+ onChange={onChangeHandler}+ value={description}+ ></TextArea>+ </Container>+ );+};++interface DescriptionProps {+ description: string;+ setDescription: React.Dispatch<React.SetStateAction<string>>;+}++export default Description;diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/Description/styles.ts b/frontend/src/container/NewDashboard/DescriptionOfDashboard/Description/styles.tsnew file mode 100644index 0000000000..67fb0b6692--- /dev/null+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/Description/styles.ts@@ -0,0 +1,5 @@+import styled from 'styled-components';++export const Container = styled.div`+ margin-top: 1rem;+`;diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/NameOfTheDashboard/index.tsx b/frontend/src/container/NewDashboard/DescriptionOfDashboard/NameOfTheDashboard/index.tsxnew file mode 100644index 0000000000..528028bffb--- /dev/null+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/NameOfTheDashboard/index.tsx@@ -0,0 +1,30 @@+import Input from 'components/Input';+import React, { useCallback } from 'react';++const NameOfTheDashboard = ({+ setName,+ name,+}: NameOfTheDashboardProps): JSX.Element => {+ const onChangeHandler = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ setName(e.target.value);+ },+ [setName],+ );++ return (+ <Input+ size="middle"+ placeholder="Title"+ value={name}+ onChangeHandler={onChangeHandler}+ />+ );+};++interface NameOfTheDashboardProps {+ name: string;+ setName: React.Dispatch<React.SetStateAction<string>>;+}++export default NameOfTheDashboard;diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsx b/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsxnew file mode 100644index 0000000000..7d8d670ebc--- /dev/null+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/index.tsx@@ -0,0 +1,122 @@+import { EditOutlined, SaveOutlined } from '@ant-design/icons';+import { Card, Col, Row, 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 { connect, useSelector } from 'react-redux';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import {+ ToggleEditMode,+ UpdateDashboardTitleDescriptionTags,+ UpdateDashboardTitleDescriptionTagsProps,+} from 'store/actions';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import DashboardReducer from 'types/reducer/dashboards';++import Description from './Description';+import { Button, Container } from './styles';++const DescriptionOfDashboard = ({+ updateDashboardTitleDescriptionTags,+ toggleEditMode,+}: DescriptionOfDashboardProps): JSX.Element => {+ const { dashboards, isEditMode } = useSelector<AppState, DashboardReducer>(+ (state) => state.dashboards,+ );++ const [selectedDashboard] = dashboards;+ const selectedData = selectedDashboard.data;+ const title = selectedData.title;+ const tags = selectedData.tags;+ const description = selectedData.description;++ const [updatedTitle, setUpdatedTitle] = useState<string>(title);+ const [updatedTags, setUpdatedTags] = useState<string[]>(tags || []);+ const [updatedDescription, setUpdtatedDescription] = useState(+ description || '',+ );++ const onClickEditHandler = useCallback(() => {+ if (isEditMode) {+ const dashboard = selectedDashboard;+ // @TODO need to update this function to take title,description,tags only+ updateDashboardTitleDescriptionTags({+ dashboard: {+ ...dashboard,+ data: {+ ...dashboard.data,+ description: updatedDescription,+ tags: updatedTags,+ title: updatedTitle,+ },+ },+ });+ } else {+ toggleEditMode();+ }+ }, [isEditMode, updatedTitle, updatedTags, updatedDescription]);++ return (+ <>+ <Card>+ <Row align="top" justify="space-between">+ {!isEditMode ? (+ <>+ <Col>+ <Typography>{title}</Typography>+ <Container>+ {tags?.map((e) => (+ <Tag key={e}>{e}</Tag>+ ))}+ </Container>+ <Container>+ <Typography>{description}</Typography>+ </Container>+ </Col>+ </>+ ) : (+ <Col lg={8}>+ <NameOfTheDashboard name={updatedTitle} setName={setUpdatedTitle} />+ <AddTags tags={updatedTags} setTags={setUpdatedTags} />+ <Description+ description={updatedDescription}+ setDescription={setUpdtatedDescription}+ />+ </Col>+ )}+ <Col>+ <Button+ icon={!isEditMode ? <EditOutlined /> : <SaveOutlined />}+ onClick={onClickEditHandler}+ >+ {isEditMode ? 'Save' : 'Edit'}+ </Button>+ </Col>+ </Row>+ </Card>+ </>+ );+};++interface DispatchProps {+ updateDashboardTitleDescriptionTags: (+ props: UpdateDashboardTitleDescriptionTagsProps,+ ) => (dispatch: Dispatch<AppActions>) => void;+ toggleEditMode: () => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ updateDashboardTitleDescriptionTags: bindActionCreators(+ UpdateDashboardTitleDescriptionTags,+ dispatch,+ ),+ toggleEditMode: bindActionCreators(ToggleEditMode, dispatch),+});++type DescriptionOfDashboardProps = DispatchProps;++export default connect(null, mapDispatchToProps)(DescriptionOfDashboard);diff --git a/frontend/src/container/NewDashboard/DescriptionOfDashboard/styles.ts b/frontend/src/container/NewDashboard/DescriptionOfDashboard/styles.tsnew file mode 100644index 0000000000..74794e163c--- /dev/null+++ b/frontend/src/container/NewDashboard/DescriptionOfDashboard/styles.ts@@ -0,0 +1,13 @@+import { Button as ButtonComponent } from 'antd';+import styled from 'styled-components';++export const Container = styled.div`+ margin-top: 0.5rem;+`;++export const Button = styled(ButtonComponent)`+ &&& {+ display: flex;+ align-items: center;+ }+`;diff --git a/frontend/src/container/NewDashboard/GridGraphs/index.tsx b/frontend/src/container/NewDashboard/GridGraphs/index.tsxnew file mode 100644index 0000000000..bc689e0948--- /dev/null+++ b/frontend/src/container/NewDashboard/GridGraphs/index.tsx@@ -0,0 +1,26 @@+import GridGraphLayout from 'container/GridGraphLayout';+import ComponentsSlider from 'container/NewDashboard/ComponentsSlider';+import React, { useCallback, useState } from 'react';+import { useSelector } from 'react-redux';+import { AppState } from 'store/reducers';+import DashboardReducer from 'types/reducer/dashboards';++import { GridComponentSliderContainer } from './styles';++const GridGraphs = (): JSX.Element => {+ const { isAddWidget } = useSelector<AppState, DashboardReducer>(+ (state) => state.dashboards,+ );++ return (+ <>+ <GridComponentSliderContainer>+ {isAddWidget && <ComponentsSlider />}++ <GridGraphLayout />+ </GridComponentSliderContainer>+ </>+ );+};++export default GridGraphs;diff --git a/frontend/src/container/NewDashboard/GridGraphs/styles.ts b/frontend/src/container/NewDashboard/GridGraphs/styles.tsnew file mode 100644index 0000000000..1bc68c27b0--- /dev/null+++ b/frontend/src/container/NewDashboard/GridGraphs/styles.ts@@ -0,0 +1,28 @@+import { Card as CardComponent, Row } from 'antd';+import styled from 'styled-components';++export const CardContainer = styled(Row)`+ &&& {+ margin-top: 1rem;+ }+`;++export const Card = styled(CardComponent)`+ &&& {+ cursor: pointer;+ }+ .ant-card-body {+ display: flex;+ width: 100%;+ justify-content: center;+ align-items: center;++ > span {+ margin-right: 0.5rem;+ }+ }+`;++export const GridComponentSliderContainer = styled.div`+ margin-top: 1rem;+`;diff --git a/frontend/src/container/NewDashboard/index.tsx b/frontend/src/container/NewDashboard/index.tsxnew file mode 100644index 0000000000..edf2936414--- /dev/null+++ b/frontend/src/container/NewDashboard/index.tsx@@ -0,0 +1,15 @@+import React from 'react';++import Description from './DescriptionOfDashboard';+import GridGraphs from './GridGraphs';++const NewDashboard = (): JSX.Element => {+ return (+ <div>+ <Description />+ <GridGraphs />+ </div>+ );+};++export default NewDashboard;diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/Query.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/Query.tsxnew file mode 100644index 0000000000..02729ab7c3--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/Query.tsx@@ -0,0 +1,95 @@+import { Divider } from 'antd';+import Input from 'components/Input';+import { timePreferance } from 'container/NewWidget/RightContainer/timeItems';+import React, { useCallback, useState } from 'react';+import { connect } from 'react-redux';+import { useLocation } from 'react-router';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import {+ UpdateQuery,+ UpdateQueryProps,+} from 'store/actions/dashboard/updateQuery';+import AppActions from 'types/actions';++import { Container, InputContainer } from './styles';++const Query = ({+ currentIndex,+ preLegend,+ preQuery,+ updateQuery,+}: QueryProps): JSX.Element => {+ const [promqlQuery, setPromqlQuery] = useState(preQuery);+ const [legendFormat, setLegendFormat] = useState(preLegend);+ const { search } = useLocation();++ const query = new URLSearchParams(search);+ const widgetId = query.get('widgetId') || '';++ const onChangeHandler = useCallback(+ (setFunc: React.Dispatch<React.SetStateAction<string>>, value: string) => {+ setFunc(value);+ },+ [],+ );++ const onBlurHandler = (): void => {+ updateQuery({+ currentIndex,+ legend: legendFormat,+ query: promqlQuery,+ widgetId,+ });+ };++ return (+ <Container>+ <InputContainer>+ <Input+ onChangeHandler={(event): void =>+ onChangeHandler(setPromqlQuery, event.target.value)+ }+ size="middle"+ value={promqlQuery}+ addonBefore={'PromQL Query'}+ onBlur={(): void => onBlurHandler()}+ />+ </InputContainer>++ <InputContainer>+ <Input+ onChangeHandler={(event): void =>+ onChangeHandler(setLegendFormat, event.target.value)+ }+ size="middle"+ value={legendFormat}+ addonBefore={'Legend Format'}+ onBlur={(): void => onBlurHandler()}+ />+ </InputContainer>+ <Divider />+ </Container>+ );+};++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 {+ selectedTime: timePreferance;+ currentIndex: number;+ preQuery: string;+ preLegend: string;+}++export default connect(null, mapDispatchToProps)(Query);diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx b/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsxnew file mode 100644index 0000000000..3ca10d230e--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/index.tsx@@ -0,0 +1,89 @@+import { PlusOutlined } from '@ant-design/icons';+import Spinner from 'components/Spinner';+import { timePreferance } from 'container/NewWidget/RightContainer/timeItems';+import React, { useCallback, useMemo } from 'react';+import { connect, useSelector } from 'react-redux';+import { useLocation } from 'react-router';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { CreateQuery, CreateQueryProps } from 'store/actions';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import { Widgets } from 'types/api/dashboard/getAll';+import DashboardReducer from 'types/reducer/dashboards';++import Query from './Query';+import { QueryButton } from './styles';++const QuerySection = ({+ selectedTime,+ createQuery,+}: QueryProps): JSX.Element => {+ const { dashboards } = useSelector<AppState, DashboardReducer>(+ (state) => state.dashboards,+ );+ const [selectedDashboards] = dashboards;+ const { search } = useLocation();+ const widgets = selectedDashboards.data.widgets;++ const urlQuery = useMemo(() => {+ return new URLSearchParams(search);+ }, [search]);++ const getWidget = useCallback(() => {+ const widgetId = urlQuery.get('widgetId');+ return widgets?.find((e) => e.id === widgetId);+ }, [widgets, urlQuery]);++ const selectedWidget = getWidget() as Widgets;++ const { query = [] } = selectedWidget || {};++ const queryOnClickHandler = useCallback(() => {+ const widgetId = urlQuery.get('widgetId');++ createQuery({+ widgetId: String(widgetId),+ });+ }, [createQuery, urlQuery]);++ if (query.length === 0) {+ return <Spinner size="small" height="30vh" tip="Loading..." />;+ }++ return (+ <div>+ {query.map((e, index) => (+ <Query+ currentIndex={index}+ selectedTime={selectedTime}+ key={e.query + index}+ preQuery={e.query}+ preLegend={e.legend || ''}+ />+ ))}++ <QueryButton onClick={queryOnClickHandler} icon={<PlusOutlined />}>+ Query+ </QueryButton>+ </div>+ );+};++interface DispatchProps {+ createQuery: ({+ widgetId,+ }: CreateQueryProps) => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ createQuery: bindActionCreators(CreateQuery, dispatch),+});++interface QueryProps extends DispatchProps {+ selectedTime: timePreferance;+}++export default connect(null, mapDispatchToProps)(QuerySection);diff --git a/frontend/src/container/NewWidget/LeftContainer/QuerySection/styles.ts b/frontend/src/container/NewWidget/LeftContainer/QuerySection/styles.tsnew file mode 100644index 0000000000..6e63558615--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/QuerySection/styles.ts@@ -0,0 +1,17 @@+import { Button } from 'antd';+import styled from 'styled-components';++export const InputContainer = styled.div`+ width: 50%;+`;++export const Container = styled.div`+ margin-top: 1rem;+`;++export const QueryButton = styled(Button)`+ &&& {+ display: flex;+ align-items: center;+ }+`;diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsxnew file mode 100644index 0000000000..dad79914b3--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/WidgetGraph.tsx@@ -0,0 +1,59 @@+import { Card, Typography } from 'antd';+import GridGraphComponent from 'container/GridGraphComponent';+import { NewWidgetProps } from 'container/NewWidget';+import getChartData from 'lib/getChartData';+import React from 'react';+import { useSelector } from 'react-redux';+import { useLocation } from 'react-router';+import { AppState } from 'store/reducers';+import DashboardReducer from 'types/reducer/dashboards';++import { NotFoundContainer } from './styles';++const WidgetGraph = ({ selectedGraph }: WidgetGraphProps): JSX.Element => {+ const { dashboards } = useSelector<AppState, DashboardReducer>(+ (state) => state.dashboards,+ );++ const [selectedDashboard] = dashboards;+ const { data } = selectedDashboard;+ const { widgets = [] } = data;+ const { search } = useLocation();++ const params = new URLSearchParams(search);+ const widgetId = params.get('widgetId');++ const selectedWidget = widgets.find((e) => e.id === widgetId);++ if (selectedWidget === undefined) {+ return <Card>Invalid widget</Card>;+ }++ const { queryData, title, opacity, isStacked } = selectedWidget;++ if (queryData.data.length === 0) {+ return (+ <NotFoundContainer>+ <Typography>No Data</Typography>+ </NotFoundContainer>+ );+ }++ const chartDataSet = getChartData({+ queryData,+ });++ return (+ <GridGraphComponent+ title={title}+ isStacked={isStacked}+ opacity={opacity}+ data={chartDataSet}+ GRAPH_TYPES={selectedGraph}+ />+ );+};++type WidgetGraphProps = NewWidgetProps;++export default WidgetGraph;diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsx b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsxnew file mode 100644index 0000000000..d844862875--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/index.tsx@@ -0,0 +1,57 @@+import { InfoCircleOutlined } from '@ant-design/icons';+import { Typography } from 'antd';+import { Card } from 'container/GridGraphLayout/styles';+import React, { 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 { NewWidgetProps } from '../../index';+import { AlertIconContainer, Container, NotFoundContainer } from './styles';+import WidgetGraphComponent from './WidgetGraph';++const WidgetGraph = ({ selectedGraph }: WidgetGraphProps): JSX.Element => {+ const { dashboards, isQueryFired } = useSelector<AppState, DashboardReducer>(+ (state) => state.dashboards,+ );+ const [selectedDashboard] = dashboards;+ const { search } = useLocation();++ const { data } = selectedDashboard;++ const { widgets = [] } = data;++ const params = new URLSearchParams(search);+ const widgetId = params.get('widgetId');++ const selectedWidget = widgets.find((e) => e.id === widgetId);++ if (selectedWidget === undefined) {+ return <Card isQueryType={false}>Invalid widget</Card>;+ }++ const { queryData } = selectedWidget;++ return (+ <Container>+ {queryData.error && (+ <AlertIconContainer color="red" title={queryData.errorMessage}>+ <InfoCircleOutlined />+ </AlertIconContainer>+ )}++ {!isQueryFired && (+ <NotFoundContainer>+ <Typography>No Data</Typography>+ </NotFoundContainer>+ )}++ {isQueryFired && <WidgetGraphComponent selectedGraph={selectedGraph} />}+ </Container>+ );+};++type WidgetGraphProps = NewWidgetProps;++export default memo(WidgetGraph);diff --git a/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/styles.ts b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/styles.tsnew file mode 100644index 0000000000..b376f0d247--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/WidgetGraph/styles.ts@@ -0,0 +1,27 @@+import { Card, Tooltip } from 'antd';+import styled from 'styled-components';++export const Container = styled(Card)`+ &&& {+ position: relative;+ }++ .ant-card-body {+ padding: 0;+ height: 55vh;+ /* padding-bottom: 2rem; */+ }+`;++export const AlertIconContainer = styled(Tooltip)`+ position: absolute;+ top: 10px;+ left: 10px;+`;++export const NotFoundContainer = styled.div`+ display: flex;+ justify-content: center;+ align-items: center;+ min-height: 55vh;+`;diff --git a/frontend/src/container/NewWidget/LeftContainer/index.tsx b/frontend/src/container/NewWidget/LeftContainer/index.tsxnew file mode 100644index 0000000000..58b2c8f3ab--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/index.tsx@@ -0,0 +1,28 @@+import React, { memo } from 'react';++import { NewWidgetProps } from '../index';+import { timePreferance } from '../RightContainer/timeItems';+import QuerySection from './QuerySection';+import { QueryContainer } from './styles';+import WidgetGraph from './WidgetGraph';++const LeftContainer = ({+ selectedGraph,+ selectedTime,+}: LeftContainerProps): JSX.Element => {+ return (+ <>+ <WidgetGraph selectedGraph={selectedGraph} />++ <QueryContainer>+ <QuerySection selectedTime={selectedTime} />+ </QueryContainer>+ </>+ );+};++interface LeftContainerProps extends NewWidgetProps {+ selectedTime: timePreferance;+}++export default memo(LeftContainer);diff --git a/frontend/src/container/NewWidget/LeftContainer/styles.ts b/frontend/src/container/NewWidget/LeftContainer/styles.tsnew file mode 100644index 0000000000..4d1988a4e1--- /dev/null+++ b/frontend/src/container/NewWidget/LeftContainer/styles.ts@@ -0,0 +1,9 @@+import { Card } from 'antd';+import styled from 'styled-components';++export const QueryContainer = styled(Card)`+ &&& {+ margin-top: 1rem;+ min-height: 23.5%;+ }+`;diff --git a/frontend/src/container/NewWidget/RightContainer/index.tsx b/frontend/src/container/NewWidget/RightContainer/index.tsxnew file mode 100644index 0000000000..651725459e--- /dev/null+++ b/frontend/src/container/NewWidget/RightContainer/index.tsx@@ -0,0 +1,157 @@+import { Button, Input, Slider, Switch, Typography } from 'antd';+import InputComponent from 'components/Input';+import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';+import GraphTypes from 'container/NewDashboard/ComponentsSlider/menuItems';+import React, { useCallback } from 'react';++import { timePreferance } from './timeItems';++const { TextArea } = Input;+import TimePreference from 'components/TimePreferenceDropDown';++import { Container, NullButtonContainer, TextContainer, Title } from './styles';++const RightContainer = ({+ description,+ opacity,+ selectedNullZeroValue,+ setDescription,+ setOpacity,+ setSelectedNullZeroValue,+ setStacked,+ setTitle,+ stacked,+ title,+ selectedGraph,+ setSelectedTime,+ selectedTime,+}: RightContainerProps): JSX.Element => {+ const onChangeHandler = useCallback(+ (setFunc: React.Dispatch<React.SetStateAction<string>>, value: string) => {+ setFunc(value);+ },+ [],+ );++ const nullValueButtons = [+ {+ check: 'zero',+ name: 'Zero',+ },+ {+ check: 'interpolate',+ name: 'Interpolate',+ },+ {+ check: 'blank',+ name: 'Blank',+ },+ ];++ const selectedGraphType =+ GraphTypes.find((e) => e.name === selectedGraph)?.display || '';++ return (+ <Container>+ <InputComponent+ labelOnTop+ label="Panel Type"+ size="middle"+ value={selectedGraphType}+ disabled+ />++ <Title>Panel Attributes</Title>++ <InputComponent+ label="Panel Title"+ size="middle"+ placeholder="Title"+ labelOnTop+ onChangeHandler={(event): void =>+ onChangeHandler(setTitle, event.target.value)+ }+ value={title}+ />++ <Title light={'true'}>Description</Title>++ <TextArea+ placeholder="Write something describing the panel"+ bordered+ allowClear+ value={description}+ onChange={(event): void =>+ onChangeHandler(setDescription, event.target.value)+ }+ />++ <TextContainer>+ <Typography>Stacked Graphs :</Typography>+ <Switch+ checked={stacked}+ onChange={(): void => {+ setStacked((value) => !value);+ }}+ />+ </TextContainer>++ <Title light={'true'}>Fill Opacity: </Title>++ <Slider+ value={parseInt(opacity, 10)}+ marks={{+ 0: '0',+ 33: '33',+ 66: '66',+ 100: '100',+ }}+ onChange={(number): void => onChangeHandler(setOpacity, number.toString())}+ step={1}+ />++ <Title light={'true'}>Null/Zero values: </Title>++ <NullButtonContainer>+ {nullValueButtons.map((button) => (+ <Button+ type={button.check === selectedNullZeroValue ? 'primary' : 'default'}+ key={button.name}+ onClick={(): void =>+ onChangeHandler(setSelectedNullZeroValue, button.check)+ }+ >+ {button.name}+ </Button>+ ))}+ </NullButtonContainer>++ <Title light={'true'}>Panel Time Preference</Title>++ <TimePreference+ {...{+ selectedTime,+ setSelectedTime,+ }}+ />+ </Container>+ );+};++interface RightContainerProps {+ title: string;+ setTitle: React.Dispatch<React.SetStateAction<string>>;+ description: string;+ setDescription: React.Dispatch<React.SetStateAction<string>>;+ stacked: boolean;+ setStacked: React.Dispatch<React.SetStateAction<boolean>>;+ opacity: string;+ setOpacity: React.Dispatch<React.SetStateAction<string>>;+ selectedNullZeroValue: string;+ setSelectedNullZeroValue: React.Dispatch<React.SetStateAction<string>>;+ selectedGraph: GRAPH_TYPES;+ setSelectedTime: React.Dispatch<React.SetStateAction<timePreferance>>;+ selectedTime: timePreferance;+}++export default RightContainer;diff --git a/frontend/src/container/NewWidget/RightContainer/styles.ts b/frontend/src/container/NewWidget/RightContainer/styles.tsnew file mode 100644index 0000000000..c30a38eeb3--- /dev/null+++ b/frontend/src/container/NewWidget/RightContainer/styles.ts@@ -0,0 +1,40 @@+import { Card, Typography } from 'antd';+import styled from 'styled-components';++export const Container = styled(Card)`+ height: 100%;+ .ant-card-body {+ height: 100%;+ }+`;++interface TitleProps {+ light?: string;+}++export const Title = styled(Typography)<TitleProps>`+ &&& {+ margin-top: 0.5rem;+ margin-bottom: 1rem;+ font-weight: ${({ light }): string => (light === 'true' ? 'none' : 'bold')};+ }+`;++interface TextContainerProps {+ noButtonMargin?: boolean;+}++export const TextContainer = styled.div<TextContainerProps>`+ display: flex;+ margin-top: 1rem;+ margin-bottom: 1rem;++ > button {+ margin-left: ${({ noButtonMargin }): string => {+ return noButtonMargin ? '0' : '0.5rem';+ }}+`;++export const NullButtonContainer = styled.div`+ margin-bottom: 1rem;+`;diff --git a/frontend/src/container/NewWidget/RightContainer/timeItems.ts b/frontend/src/container/NewWidget/RightContainer/timeItems.tsnew file mode 100644index 0000000000..6ceb175d71--- /dev/null+++ b/frontend/src/container/NewWidget/RightContainer/timeItems.ts@@ -0,0 +1,60 @@+export const timeItems: timePreferance[] = [+ {+ name: 'Global Time',+ enum: 'GLOBAL_TIME',+ },+ {+ name: 'Last 5 min',+ enum: 'LAST_5_MIN',+ },+ {+ name: 'Last 15 min',+ enum: 'LAST_15_MIN',+ },+ {+ name: 'Last 30 min',+ enum: 'LAST_30_MIN',+ },+ {+ name: 'Last 1 hr',+ enum: 'LAST_1_HR',+ },+ {+ name: 'Last 6 hr',+ enum: 'LAST_6_HR',+ },+ {+ name: 'Last 1 day',+ enum: 'LAST_1_DAY',+ },+ {+ name: 'Last 1 week',+ enum: 'LAST_1_WEEK',+ },+];++export interface timePreferance {+ name: string;+ enum: timePreferenceType;+}++export type timePreferenceType =+ | GLOBAL_TIME+ | LAST_5_MIN+ | LAST_15_MIN+ | LAST_30_MIN+ | LAST_1_HR+ | LAST_6_HR+ | LAST_1_DAY+ | LAST_1_WEEK;++type GLOBAL_TIME = 'GLOBAL_TIME';+type LAST_5_MIN = 'LAST_5_MIN';+type LAST_15_MIN = 'LAST_15_MIN';+type LAST_30_MIN = 'LAST_30_MIN';+type LAST_1_HR = 'LAST_1_HR';+type LAST_6_HR = 'LAST_6_HR';+type LAST_1_DAY = 'LAST_1_DAY';+type LAST_1_WEEK = 'LAST_1_WEEK';++export default timeItems;diff --git a/frontend/src/container/NewWidget/index.tsx b/frontend/src/container/NewWidget/index.tsxnew file mode 100644index 0000000000..5bfb59641a--- /dev/null+++ b/frontend/src/container/NewWidget/index.tsx@@ -0,0 +1,237 @@+import { Button } from 'antd';+import ROUTES from 'constants/routes';+import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';+import updateUrl from 'lib/updateUrl';+import { DashboardWidgetPageParams } from 'pages/DashboardWidget';+import React, { useCallback, useEffect, useMemo, useState } from 'react';+import { connect, useSelector } from 'react-redux';+import { useHistory, useLocation, useParams } from 'react-router';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import {+ ApplySettingsToPanel,+ ApplySettingsToPanelProps,+ GlobalTime,+} from 'store/actions';+import {+ GetQueryResults,+ GetQueryResultsProps,+} from 'store/actions/dashboard/getQueryResults';+import {+ SaveDashboard,+ SaveDashboardProps,+} from 'store/actions/dashboard/saveDashboard';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import DashboardReducer from 'types/reducer/dashboards';++import LeftContainer from './LeftContainer';+import RightContainer from './RightContainer';+import timeItems, { timePreferance } from './RightContainer/timeItems';+import {+ ButtonContainer,+ Container,+ LeftContainerWrapper,+ PanelContainer,+ RightContainerWrapper,+} from './styles';++const NewWidget = ({+ selectedGraph,+ applySettingsToPanel,+ saveSettingOfPanel,+ getQueryResults,+}: Props): JSX.Element => {+ const { dashboards } = useSelector<AppState, DashboardReducer>(+ (state) => state.dashboards,+ );+ const { maxTime, minTime } = useSelector<AppState, GlobalTime>(+ (state) => state.globalTime,+ );++ const [selectedDashboard] = dashboards;++ const widgets = selectedDashboard.data.widgets;++ const { push } = useHistory();+ const { search } = useLocation();++ const query = useMemo(() => {+ return new URLSearchParams(search);+ }, [search]);++ const { dashboardId } = useParams<DashboardWidgetPageParams>();++ const getWidget = useCallback(() => {+ const widgetId = query.get('widgetId');+ return widgets?.find((e) => e.id === widgetId);+ }, [query, widgets]);++ const selectedWidget = getWidget();++ const [title, setTitle] = useState<string>(selectedWidget?.title || '');+ const [description, setDescription] = useState<string>(+ selectedWidget?.description || '',+ );++ const [stacked, setStacked] = useState<boolean>(+ selectedWidget?.isStacked || false,+ );+ const [opacity, setOpacity] = useState<string>(selectedWidget?.opacity || '1');+ const [selectedNullZeroValue, setSelectedNullZeroValue] = useState<string>(+ selectedWidget?.nullZeroValues || 'zero',+ );++ const getSelectedTime = useCallback(+ () =>+ timeItems.find(+ (e) => e.enum === (selectedWidget?.timePreferance || 'GLOBAL_TIME'),+ ),+ [selectedWidget],+ );++ const [selectedTime, setSelectedTime] = useState<timePreferance>({+ name: getSelectedTime()?.name || '',+ enum: selectedWidget?.timePreferance || 'GLOBAL_TIME',+ });++ const onClickSaveHandler = useCallback(() => {+ // update the global state+ saveSettingOfPanel({+ uuid: selectedDashboard.uuid,+ description,+ isStacked: stacked,+ nullZeroValues: selectedNullZeroValue,+ opacity,+ timePreferance: selectedTime.enum,+ title,+ widgetId: query.get('widgetId') || '',+ dashboardId: dashboardId,+ });+ }, [+ opacity,+ description,+ query,+ selectedTime,+ stacked,+ title,+ selectedNullZeroValue,+ saveSettingOfPanel,+ selectedDashboard,+ dashboardId,+ ]);++ const onClickApplyHandler = useCallback(() => {+ applySettingsToPanel({+ description,+ isStacked: stacked,+ nullZeroValues: selectedNullZeroValue,+ opacity,+ timePreferance: selectedTime.enum,+ title,+ widgetId: selectedWidget?.id || '',+ });+ }, [+ applySettingsToPanel,+ description,+ opacity,+ selectedTime,+ selectedWidget?.id,+ selectedNullZeroValue,+ stacked,+ title,+ ]);++ const onClickDiscardHandler = useCallback(() => {+ push(updateUrl(ROUTES.DASHBOARD, ':dashboardId', dashboardId));+ }, [dashboardId, push]);++ const getQueryResult = useCallback(() => {+ if (selectedWidget?.id.length !== 0) {+ getQueryResults({+ maxTime,+ minTime,+ query: selectedWidget?.query || [],+ selectedTime: selectedTime.enum,+ widgetId: selectedWidget?.id || '',+ graphType: selectedGraph,+ });+ }+ }, [+ selectedWidget?.query,+ selectedTime.enum,+ maxTime,+ minTime,+ selectedWidget?.id,+ selectedGraph,+ getQueryResults,+ ]);++ useEffect(() => {+ getQueryResult();+ }, [getQueryResult]);++ return (+ <Container>+ <ButtonContainer>+ <Button onClick={onClickSaveHandler}>Save</Button>+ <Button onClick={onClickApplyHandler}>Apply</Button>+ <Button onClick={onClickDiscardHandler}>Discard</Button>+ </ButtonContainer>++ <PanelContainer>+ <LeftContainerWrapper flex={5}>+ <LeftContainer selectedTime={selectedTime} selectedGraph={selectedGraph} />+ </LeftContainerWrapper>++ <RightContainerWrapper flex={1}>+ <RightContainer+ {...{+ title,+ setTitle,+ description,+ setDescription,+ stacked,+ setStacked,+ opacity,+ setOpacity,+ selectedNullZeroValue,+ setSelectedNullZeroValue,+ selectedGraph,+ setSelectedTime,+ selectedTime,+ }}+ />+ </RightContainerWrapper>+ </PanelContainer>+ </Container>+ );+};++export interface NewWidgetProps {+ selectedGraph: GRAPH_TYPES;+}++interface DispatchProps {+ applySettingsToPanel: (+ props: ApplySettingsToPanelProps,+ ) => (dispatch: Dispatch<AppActions>) => void;+ saveSettingOfPanel: (+ props: SaveDashboardProps,+ ) => (dispatch: Dispatch<AppActions>) => void;+ getQueryResults: (+ props: GetQueryResultsProps,+ ) => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ applySettingsToPanel: bindActionCreators(ApplySettingsToPanel, dispatch),+ saveSettingOfPanel: bindActionCreators(SaveDashboard, dispatch),+ getQueryResults: bindActionCreators(GetQueryResults, dispatch),+});++type Props = DispatchProps & NewWidgetProps;++export default connect(null, mapDispatchToProps)(NewWidget);diff --git a/frontend/src/container/NewWidget/styles.ts b/frontend/src/container/NewWidget/styles.tsnew file mode 100644index 0000000000..c5974baf45--- /dev/null+++ b/frontend/src/container/NewWidget/styles.ts@@ -0,0 +1,33 @@+import { Col } from 'antd';+import styled from 'styled-components';++export const Container = styled.div`+ min-height: 78vh;+ display: flex;+ margin-top: 1rem;+ flex-direction: column;+`;++export const RightContainerWrapper = styled(Col)`+ &&& {+ min-width: 200px;+ }+`;++export const LeftContainerWrapper = styled(Col)`+ &&& {+ margin-right: 1rem;+ max-width: 70%;+ }+`;++export const ButtonContainer = styled.div`+ display: flex;+ gap: 1rem;+ margin-bottom: 1rem;+ justify-content: flex-end;+`;++export const PanelContainer = styled.div`+ display: flex;+`;diff --git a/frontend/src/hooks/useFetch.ts b/frontend/src/hooks/useFetch.tsnew file mode 100644index 0000000000..df83c76127--- /dev/null+++ b/frontend/src/hooks/useFetch.ts@@ -0,0 +1,85 @@+import { useEffect, useRef, useState } from 'react';+import { ErrorResponse, SuccessResponse } from 'types/api';++function useFetch<PayloadProps, FunctionParams>(+ functions: {+ (props: FunctionParams): Promise<+ SuccessResponse<PayloadProps> | ErrorResponse+ >;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (arg0: any): Promise<SuccessResponse<PayloadProps> | ErrorResponse>;+ },+ param?: FunctionParams,+): State<PayloadProps | undefined> {+ const [state, setStates] = useState<State<PayloadProps | undefined>>({+ loading: true,+ success: null,+ errorMessage: '',+ error: null,+ payload: undefined,+ });++ const loadingRef = useRef(0);++ useEffect(() => {+ let abortController = new window.AbortController();+ const { signal } = abortController;++ try {+ (async (): Promise<void> => {+ if (state.loading) {+ const response = await functions(param);++ if (!signal.aborted && loadingRef.current === 0) {+ loadingRef.current = 1;++ if (response.statusCode === 200) {+ setStates({+ loading: false,+ error: false,+ success: true,+ payload: response.payload,+ errorMessage: '',+ });+ } else {+ setStates({+ loading: false,+ error: true,+ success: false,+ payload: undefined,+ errorMessage: response.error as string,+ });+ }+ }+ }+ })();+ } catch (error) {+ if (!signal.aborted) {+ setStates({+ payload: undefined,+ loading: false,+ success: false,+ error: true,+ errorMessage: error,+ });+ }+ }+ return (): void => {+ abortController.abort();+ abortController = new window.AbortController();+ };+ }, [functions, param, state.loading]);+ return {+ ...state,+ };+}++export interface State<T> {+ loading: boolean | null;+ error: boolean | null;+ success: boolean | null;+ payload: T;+ errorMessage: string;+}++export default useFetch;diff --git a/frontend/src/hooks/useMountedState.ts b/frontend/src/hooks/useMountedState.tsnew file mode 100644index 0000000000..712943dd30--- /dev/null+++ b/frontend/src/hooks/useMountedState.ts@@ -0,0 +1,18 @@+import { useCallback, useEffect, useRef } from 'react';++function useMountedState(): () => boolean {+ const mountedRef = useRef<boolean>(false);+ const get = useCallback(() => mountedRef.current, []);++ useEffect(() => {+ mountedRef.current = true;++ return (): void => {+ mountedRef.current = false;+ };+ }, []);++ return get;+}++export default useMountedState;diff --git a/frontend/src/lib/convertDateToAmAndPm.ts b/frontend/src/lib/convertDateToAmAndPm.tsnew file mode 100644index 0000000000..ccc13bab22--- /dev/null+++ b/frontend/src/lib/convertDateToAmAndPm.ts@@ -0,0 +1,9 @@+const convertDateToAmAndPm = (date: Date): string => {+ return date.toLocaleString('en-US', {+ hour: 'numeric',+ minute: 'numeric',+ hour12: true,+ });+};++export default convertDateToAmAndPm;diff --git a/frontend/src/lib/convertToNanoSecondsToSecond.ts b/frontend/src/lib/convertToNanoSecondsToSecond.tsindex 4436290478..6284b771f0 100644--- a/frontend/src/lib/convertToNanoSecondsToSecond.ts+++ b/frontend/src/lib/convertToNanoSecondsToSecond.ts@@ -1,4 +1,4 @@-const convertToNanoSecondsToSecond = (number: number) => {+const convertToNanoSecondsToSecond = (number: number): string => {return parseFloat((number / 1000000).toString()).toFixed(2);};diff --git a/frontend/src/lib/covertIntoEpoc.ts b/frontend/src/lib/covertIntoEpoc.tsnew file mode 100644index 0000000000..60385c7e76--- /dev/null+++ b/frontend/src/lib/covertIntoEpoc.ts@@ -0,0 +1,5 @@+const convertIntoEpoc = (number: number): string => {+ return number.toString().split('.').join('').toString();+};++export default convertIntoEpoc;diff --git a/frontend/src/lib/getChartData.ts b/frontend/src/lib/getChartData.tsnew file mode 100644index 0000000000..71d40d57b2--- /dev/null+++ b/frontend/src/lib/getChartData.ts@@ -0,0 +1,71 @@+import { ChartData } from 'chart.js';+import getLabelName from 'lib/getLabelName';+import { Widgets } from 'types/api/dashboard/getAll';++import convertIntoEpoc from './covertIntoEpoc';+import { colors } from './getRandomColor';++const getChartData = ({ queryData }: GetChartDataProps): ChartData => {+ const response = queryData.data.map(({ query, queryData, legend }) => {+ return queryData.map((e, index) => {+ const { values = [], metric } = e || {};+ const labelNames = getLabelName(+ metric,+ query, //query+ legend || '', // legends+ );++ const dataValue = values?.map((e) => {+ const [first = 0, second = ''] = e || [];+ return {+ first: new Date(parseInt(convertIntoEpoc(first), 10)),+ second: Number(parseFloat(second).toFixed(2)),+ };+ });++ const color = colors[index] || 'red';+ return {+ label: labelNames,+ first: dataValue.map((e) => e.first),+ borderColor: color,+ second: dataValue.map((e) => e.second),+ };+ });+ });++ const allLabels = response+ .map((e) => e.map((e) => e.label))+ .reduce((a, b) => [...a, ...b], []);++ const allColor = response+ .map((e) => e.map((e) => e.borderColor))+ .reduce((a, b) => [...a, ...b], []);++ const alldata = response+ .map((e) => e.map((e) => e.second))+ .reduce((a, b) => [...a, ...b], []);++ return {+ datasets: alldata.map((e, index) => {+ return {+ data: e,+ label: allLabels[index],+ borderWidth: 1.5,+ spanGaps: true,+ animations: false,+ borderColor: allColor[index],+ showLine: true,+ pointRadius: 0,+ };+ }),+ labels: response+ .map((e) => e.map((e) => e.first))+ .reduce((a, b) => [...a, ...b], [])[0],+ };+};++interface GetChartDataProps {+ queryData: Widgets['queryData'];+}++export default getChartData;diff --git a/frontend/src/lib/getLabelName.ts b/frontend/src/lib/getLabelName.tsnew file mode 100644index 0000000000..5f55bcacb9--- /dev/null+++ b/frontend/src/lib/getLabelName.ts@@ -0,0 +1,52 @@+import { QueryData } from 'types/api/widgets/getQuery';++const getLabelName = (+ metric: QueryData['metric'],+ query: string,+ legends: string,+): string => {+ if (metric === undefined) {+ return '';+ }++ const keysArray = Object.keys(metric);++ if (legends.length !== 0) {+ const variables = legends+ .split('{{')+ .filter((e) => e)+ .map((e) => e.split('}}')[0]);++ const results = variables.map((variable) => metric[variable]);++ let endResult = legends;++ variables.forEach((e, index) => {+ endResult = endResult.replace(`{{${e}}}`, results[index]);+ });++ return endResult;+ }++ const index = keysArray.findIndex((e) => e === '__name__');++ const preArray = keysArray.slice(0, index);+ const postArray = keysArray.slice(index + 1, keysArray.length);++ if (index === undefined && preArray.length === 0 && postArray.length) {+ return query;+ }++ const post = postArray.map((e) => `${e}="${metric[e]}"`).join(',');+ const pre = preArray.map((e) => `${e}="${metric[e]}"`).join(',');++ const result = `${metric[keysArray[index]]}`;++ if (post.length === 0 && pre.length === 0) {+ return result;+ }++ return `${result}{${pre}${post}}`;+};++export default getLabelName;diff --git a/frontend/src/lib/getMaxMinTime.ts b/frontend/src/lib/getMaxMinTime.tsnew file mode 100644index 0000000000..5d3a2cfa7b--- /dev/null+++ b/frontend/src/lib/getMaxMinTime.ts@@ -0,0 +1,27 @@+import { GlobalTime } from 'store/actions';+import { Widgets } from 'types/api/dashboard/getAll';++const GetMaxMinTime = ({+ graphType,+ minTime,+ maxTime,+}: GetMaxMinProps): GlobalTime => {+ if (graphType === 'VALUE') {+ return {+ maxTime: maxTime,+ minTime: maxTime,+ };+ }+ return {+ maxTime: maxTime,+ minTime: minTime,+ };+};++interface GetMaxMinProps {+ graphType: Widgets['panelTypes'];+ maxTime: GlobalTime['maxTime'];+ minTime: GlobalTime['minTime'];+}++export default GetMaxMinTime;diff --git a/frontend/src/lib/getRandomColor.ts b/frontend/src/lib/getRandomColor.tsnew file mode 100644index 0000000000..49361caae8--- /dev/null+++ b/frontend/src/lib/getRandomColor.ts@@ -0,0 +1,21 @@+export const colors = [+ '#F2994A',+ '#56CCF2',+ '#F2C94C',+ '#219653',+ '#2F80ED',+ '#EB5757',+ '#BB6BD9',+ '#BDBDBD',+];++export function getRandomNumber(min: number, max: number): number {+ return Math.random() * (max - min) + min;+}++const getRandomColor = (): string => {+ const index = parseInt(getRandomNumber(0, colors.length - 1).toString(), 10);+ return colors[index];+};++export default getRandomColor;diff --git a/frontend/src/lib/getStartAndEndTime/getMicroSeconds.ts b/frontend/src/lib/getStartAndEndTime/getMicroSeconds.tsnew file mode 100644index 0000000000..584ab40dae--- /dev/null+++ b/frontend/src/lib/getStartAndEndTime/getMicroSeconds.ts@@ -0,0 +1,9 @@+const getMicroSeconds = ({ time }: getMicroSecondsProps): string => {+ return (time / 1000).toString();+};++interface getMicroSecondsProps {+ time: number;+}++export default getMicroSeconds;diff --git a/frontend/src/lib/getStartAndEndTime/getMinAgo.ts b/frontend/src/lib/getStartAndEndTime/getMinAgo.tsnew file mode 100644index 0000000000..a302d7649e--- /dev/null+++ b/frontend/src/lib/getStartAndEndTime/getMinAgo.ts@@ -0,0 +1,13 @@+const getMinAgo = ({ minutes }: getMinAgoProps): Date => {+ const currentDate = new Date();++ const agoDate = new Date(currentDate.getTime() - minutes * 60000);++ return agoDate;+};++interface getMinAgoProps {+ minutes: number;+}++export default getMinAgo;diff --git a/frontend/src/lib/getStartAndEndTime/index.ts b/frontend/src/lib/getStartAndEndTime/index.tsnew file mode 100644index 0000000000..cfebd73e2e--- /dev/null+++ b/frontend/src/lib/getStartAndEndTime/index.ts@@ -0,0 +1,101 @@+import { timePreferenceType } from 'container/NewWidget/RightContainer/timeItems';++import getMicroSeconds from './getMicroSeconds';+import getMinAgo from './getMinAgo';++const GetStartAndEndTime = ({+ type,+ minTime,+ maxTime,+}: GetStartAndEndTimeProps): Payload => {+ const end = new Date().getTime();+ const endString = getMicroSeconds({ time: end });++ if (type === 'LAST_5_MIN') {+ const agodate = getMinAgo({ minutes: 5 }).getTime();+ const agoString = getMicroSeconds({ time: agodate });++ return {+ start: agoString,+ end: endString,+ };+ }++ if (type === 'LAST_30_MIN') {+ const agodate = getMinAgo({ minutes: 30 }).getTime();+ const agoString = getMicroSeconds({ time: agodate });++ return {+ start: agoString,+ end: endString,+ };+ }++ if (type === 'LAST_1_HR') {+ const agodate = getMinAgo({ minutes: 60 }).getTime();+ const agoString = getMicroSeconds({ time: agodate });++ return {+ start: agoString,+ end: endString,+ };+ }++ if (type === 'LAST_15_MIN') {+ const agodate = getMinAgo({ minutes: 15 }).getTime();+ const agoString = getMicroSeconds({ time: agodate });++ return {+ start: agoString,+ end: endString,+ };+ }++ if (type === 'LAST_6_HR') {+ const agoDate = getMinAgo({ minutes: 6 * 60 }).getTime();+ const agoString = getMicroSeconds({ time: agoDate });++ return {+ start: agoString,+ end: endString,+ };+ }++ if (type === 'LAST_1_DAY') {+ const agoDate = getMinAgo({ minutes: 24 * 60 }).getTime();+ const agoString = getMicroSeconds({ time: agoDate });++ return {+ start: agoString,+ end: endString,+ };+ }++ if (type === 'LAST_1_WEEK') {+ const agoDate = getMinAgo({ minutes: 24 * 60 * 7 }).getTime();+ const agoString = getMicroSeconds({ time: agoDate });++ return {+ start: agoString,+ end: endString,+ };+ }++ return {+ start: getMicroSeconds({ time: minTime / 1000000 }),+ end: getMicroSeconds({ time: maxTime / 1000000 }),+ };+};++interface GetStartAndEndTimeProps {+ type: timePreferenceType;+ minTime: number;+ maxTime: number;+}++interface Payload {+ start: string;+ end: string;+}++export default GetStartAndEndTime;diff --git a/frontend/src/utils/history.ts b/frontend/src/lib/history.tssimilarity index 98%rename from frontend/src/utils/history.tsrename to frontend/src/lib/history.tsindex 13e940c1d9..9937105a69 100644--- a/frontend/src/utils/history.ts+++ b/frontend/src/lib/history.ts@@ -1,2 +1,3 @@import { createBrowserHistory } from 'history';+export default createBrowserHistory();diff --git a/frontend/src/lib/stringToHTML.ts b/frontend/src/lib/stringToHTML.tsnew file mode 100644index 0000000000..b5fb77afbf--- /dev/null+++ b/frontend/src/lib/stringToHTML.ts@@ -0,0 +1,9 @@+import { renderToString } from 'react-dom/server';++const stringToHTML = function (str: JSX.Element): HTMLElement {+ const parser = new DOMParser();+ const doc = parser.parseFromString(renderToString(str), 'text/html');+ return doc.body.firstChild as HTMLElement;+};++export default stringToHTML;diff --git a/frontend/src/lib/updateUrl.ts b/frontend/src/lib/updateUrl.tsnew file mode 100644index 0000000000..f826704c82--- /dev/null+++ b/frontend/src/lib/updateUrl.ts@@ -0,0 +1,9 @@+const updateUrl = (+ routes: string,+ variables: string,+ value: string,+): string => {+ return routes.replace(variables, value);+};++export default updateUrl;diff --git a/frontend/src/modules/AppLayout.tsx b/frontend/src/modules/AppLayout.tsxindex 118d5270b1..425eb4b939 100644--- a/frontend/src/modules/AppLayout.tsx+++ b/frontend/src/modules/AppLayout.tsx@@ -1,8 +1,8 @@import { Layout } from 'antd';+import SideNav from 'components/SideNav';import React, { ReactNode, useEffect } from 'react';import { useLocation } from 'react-router-dom';-import SideNav from 'components/SideNav';import TopNav from './Nav/TopNav';import { useRoute } from './RouteProvider';@@ -19,7 +19,7 @@ const BaseLayout: React.FC<BaseLayoutProps> = ({ children }) => {useEffect(() => {dispatch({ type: 'ROUTE_IS_LOADED', payload: location.pathname });- }, [location]);+ }, [location, dispatch]);return (<Layout style={{ minHeight: '100vh' }}>diff --git a/frontend/src/modules/Auth/Signup.tsx b/frontend/src/modules/Auth/Signup.tsxindex 7df8c72328..4cdc946e57 100644--- a/frontend/src/modules/Auth/Signup.tsx+++ b/frontend/src/modules/Auth/Signup.tsx@@ -1,5 +1,5 @@-import { Button, Input,Row, Space } from 'antd';-import api, { apiV1 } from 'api';+import { Button, Input, Row, Space } from 'antd';+import api from 'api';import { IS_LOGGED_IN } from 'constants/auth';import ROUTES from 'constants/routes';import React, { useState } from 'react';@@ -8,7 +8,7 @@ import { RouteComponentProps } from 'react-router-dom';type SignUpProps = RouteComponentProps<any>;-const Signup = (props: SignUpProps) => {+const Signup = (props: SignUpProps): JSX.Element => {const [state, setState] = useState({ submitted: false });const [formState, setFormState] = useState({firstName: { value: '' },@@ -45,9 +45,9 @@ const Signup = (props: SignUpProps) => {const texttolog = JSON.stringify(payload);- api.post(apiV1 + '/user?email=' + texttolog).then((res) => {- console.log(res);- console.log(res.data);+ api.post('/user?email=' + texttolog).then((res) => {+ // console.log(res);+ // console.log(res.data);});localStorage.setItem(IS_LOGGED_IN, 'yes');diff --git a/frontend/src/modules/Metrics/ErrorRateChart.tsx b/frontend/src/modules/Metrics/ErrorRateChart.tsxindex 9c989ee113..72b2b54b3a 100644--- a/frontend/src/modules/Metrics/ErrorRateChart.tsx+++ b/frontend/src/modules/Metrics/ErrorRateChart.tsx@@ -1,22 +1,21 @@-import { ChartOptions } from 'chart.js';-import ROUTES from 'constants/routes';-import React from 'react';-import { Line as ChartJSLine } from 'react-chartjs-2';-import { withRouter } from 'react-router';-import { RouteComponentProps } from 'react-router-dom';+import { ActiveElement, Chart, ChartEvent } from 'chart.js';+import Graph from 'components/Graph';+import React, { useMemo, useState } from 'react';import { metricItem } from 'store/actions/MetricsActions';import styled from 'styled-components';+import { GraphContainer } from './styles';+const ChartPopUpUnique = styled.div<{ycoordinate: number;xcoordinate: number;}>`background-color: white;border: 1px solid rgba(219, 112, 147, 0.5);- zindex: 10;+ z-index: 10;position: absolute;- top: ${(props) => props.ycoordinate}px;- left: ${(props) => props.xcoordinate}px;+ top: ${(props): number => props.ycoordinate}px;+ left: ${(props): number => props.xcoordinate}px;font-size: 12px;border-radius: 2px;`;@@ -31,202 +30,89 @@ const PopUpElements = styled.p`}`;-// PNOTE - Check if this should be the case-const theme = 'dark';--interface ErrorRateChartProps extends RouteComponentProps<any> {+interface ErrorRateChartProps {data: metricItem[];- onTracePopupClick: Function;+ onTracePopupClick: (props: number) => void;}-interface ErrorRateChart {- chartRef: any;-}--class ErrorRateChart extends React.Component<ErrorRateChartProps> {- constructor(props: ErrorRateChartProps) {- super(props);- this.chartRef = React.createRef();- }-- state = {- // data: props.data,+const ErrorRateChart = ({+ data,+ onTracePopupClick,+}: ErrorRateChartProps): JSX.Element => {+ const [state, setState] = useState({xcoordinate: 0,ycoordinate: 0,showpopUp: false,firstpoint_ts: 0,- // graphInfo:{}- };-- onClickhandler = async (e: any, event: any) => {- let firstPoint;- if (this.chartRef) {- firstPoint = this.chartRef.current.chartInstance.getElementAtEvent(e)[0];- }+ });- if (firstPoint) {- // PNOTE - TODO - Is await needed in this expression?- this.setState({- xcoordinate: e.offsetX + 20,- ycoordinate: e.offsetY,- showpopUp: true,- firstpoint_ts: this.props.data[firstPoint._index].timestamp,- // graphInfo:{...event}- });- }- };-- gotoTracesHandler = () => {- this.props.onTracePopupClick(this.state.firstpoint_ts);- };-- gotoAlertsHandler = () => {- this.props.history.push(ROUTES.SERVICE_MAP);- // PNOTE - Keeping service map for now, will replace with alerts when alert page is made+ const gotoTracesHandler = (): void => {+ onTracePopupClick(state.firstpoint_ts);};- options_charts: ChartOptions = {- onClick: this.onClickhandler,-- maintainAspectRatio: true,- responsive: true,-- title: {- display: true,- text: '',- fontSize: 20,- position: 'top',- padding: 2,- fontFamily: 'Arial',- fontStyle: 'regular',- fontColor: theme === 'dark' ? 'rgb(200, 200, 200)' : 'rgb(20, 20, 20)',- },-- legend: {- display: true,- position: 'bottom',- align: 'center',-- labels: {- fontColor: theme === 'dark' ? 'rgb(200, 200, 200)' : 'rgb(20, 20, 20)',- fontSize: 10,- boxWidth: 10,- usePointStyle: true,- },- },-- tooltips: {- mode: 'label',- bodyFontSize: 12,- titleFontSize: 12,-- callbacks: {- label: function (tooltipItem, data) {- if (typeof tooltipItem.yLabel === 'number') {- return (- data.datasets![tooltipItem.datasetIndex!].label +- ' : ' +- tooltipItem.yLabel.toFixed(2)- );- } else {- return '';- }- },- },- },-- scales: {- yAxes: [+ const data_chartJS: Chart['data'] = useMemo(() => {+ return {+ labels: data.map((s) => new Date(s.timestamp / 1000000)),+ datasets: [{- stacked: false,- ticks: {- beginAtZero: false,- fontSize: 10,- autoSkip: true,- maxTicksLimit: 6,- },-- // scaleLabel: {- // display: true,- // labelString: 'latency in ms',- // fontSize: 6,- // padding: 4,- // },- gridLines: {- // You can change the color, the dash effect, the main axe color, etc.- borderDash: [1, 4],- color: '#D3D3D3',- lineWidth: 0.25,- },+ label: 'Error Percentage (%)',+ data: data.map((s: { errorRate: any }) => s.errorRate),+ pointRadius: 0.5,+ borderColor: 'rgba(227, 74, 51,1)', // Can also add transparency in border color+ borderWidth: 2,},],- xAxes: [- {- type: 'time',- // time: {- // unit: 'second'- // },- distribution: 'linear',- ticks: {- beginAtZero: false,- fontSize: 10,- autoSkip: true,- maxTicksLimit: 10,- },- // gridLines: false, --> not a valid option- },- ],- },+ };+ }, [data]);++ const onClickhandler = (+ event: ChartEvent,+ elements: ActiveElement[],+ chart: Chart,+ ): void => {+ {+ if (event.native) {+ const points = chart.getElementsAtEventForMode(+ event.native,+ 'nearest',+ { intersect: true },+ true,+ );+ if (points.length) {+ const firstPoint = points[0];+ setState({+ xcoordinate: firstPoint.element.x,+ ycoordinate: firstPoint.element.y,+ showpopUp: true,+ firstpoint_ts: data[firstPoint.index].timestamp,+ });+ }+ }+ }};- GraphTracePopUp = () => {- if (this.state.showpopUp) {- return (+ return (+ <div>+ {state.showpopUp && (<ChartPopUpUnique- xcoordinate={this.state.xcoordinate}- ycoordinate={this.state.ycoordinate}+ xcoordinate={state.xcoordinate}+ ycoordinate={state.ycoordinate}>- <PopUpElements onClick={this.gotoTracesHandler}>View Traces</PopUpElements>- {/* <PopUpElements onClick={this.gotoAlertsHandler}>Set Alerts</PopUpElements> */}+ <PopUpElements onClick={gotoTracesHandler}>View Traces</PopUpElements></ChartPopUpUnique>- );- } else return null;- };-- render() {- const ndata = this.props.data;-- const data_chartJS = (canvas: any) => {- const ctx = canvas.getContext('2d');- const gradient = ctx.createLinearGradient(0, 0, 0, 100);- gradient.addColorStop(0, 'rgba(250,174,50,1)');- gradient.addColorStop(1, 'rgba(250,174,50,1)');- return {- labels: ndata.map((s) => new Date(s.timestamp / 1000000)), // converting from nano second to mili second- datasets: [- {- label: 'Error Percentage (%)',- data: ndata.map((s) => s.errorRate),- pointRadius: 0.5,- borderColor: 'rgba(227, 74, 51,1)', // Can also add transparency in border color- borderWidth: 2,- },- ],- };- };-- return (- <div>- {this.GraphTracePopUp()}- <div style={{ textAlign: 'center' }}>Error Percentage (%)</div>- <ChartJSLine- ref={this.chartRef}+ )}+ <div style={{ textAlign: 'center' }}>Error Percentage (%)</div>++ <GraphContainer>+ <Graph+ onClickHandler={onClickhandler}+ xAxisType="timeseries"+ type="line"data={data_chartJS}- options={this.options_charts}/>- </div>- );- }-}+ </GraphContainer>+ </div>+ );+};-export default withRouter(ErrorRateChart);+export default ErrorRateChart;diff --git a/frontend/src/modules/Metrics/ExternalApi/ExternalApiGraph.tsx b/frontend/src/modules/Metrics/ExternalApi/ExternalApiGraph.tsxindex d8f354464d..8412ca6595 100644--- a/frontend/src/modules/Metrics/ExternalApi/ExternalApiGraph.tsx+++ b/frontend/src/modules/Metrics/ExternalApi/ExternalApiGraph.tsx@@ -1,13 +1,12 @@-import { filter,uniqBy } from 'lodash';+import Graph from 'components/Graph';+import { filter, uniqBy } from 'lodash';import React from 'react';-import { Line as ChartJSLine } from 'react-chartjs-2';import { withRouter } from 'react-router';import { RouteComponentProps } from 'react-router-dom';import { externalMetricsItem } from 'store/actions/MetricsActions';-import { borderColors,getOptions } from './graphConfig';--const theme = 'dark';+import { GraphContainer } from '../styles';+import { borderColors } from './graphConfig';interface ExternalApiGraphProps extends RouteComponentProps<any> {data: externalMetricsItem[];@@ -80,11 +79,8 @@ class ExternalApiGraph extends React.Component<ExternalApiGraphProps> {};});};- const data_chartJS = (canvas: any) => {- const ctx = canvas.getContext('2d');- const gradient = ctx.createLinearGradient(0, 0, 0, 100);- gradient.addColorStop(0, 'rgba(250,174,50,1)');- gradient.addColorStop(1, 'rgba(250,174,50,1)');++ const data_chartJS = () => {const uniqTimestamp = uniqBy(data, 'timestamp');return {@@ -96,16 +92,12 @@ class ExternalApiGraph extends React.Component<ExternalApiGraphProps> {};return (- <div>- <div>- <div style={{ textAlign: 'center' }}>{title}</div>- <ChartJSLine- ref={this.chartRef}- data={data_chartJS}- options={getOptions(theme)}- />- </div>- </div>+ <>+ <div style={{ textAlign: 'center' }}>{title}</div>+ <GraphContainer>+ <Graph data={data_chartJS()} xAxisType="timeseries" type="line" />+ </GraphContainer>+ </>);}}diff --git a/frontend/src/modules/Metrics/GenericVisualization.tsx b/frontend/src/modules/Metrics/GenericVisualization.tsxdeleted file mode 100644index 0b88807299..0000000000--- a/frontend/src/modules/Metrics/GenericVisualization.tsx+++ /dev/null@@ -1,83 +0,0 @@-import React from 'react';-import { Bar, Line as ChartJSLine } from 'react-chartjs-2';-import { customMetricsItem } from 'store/actions/MetricsActions';-import styled from 'styled-components';--const GenVisualizationWrapper = styled.div`- height: 160px;-`;--interface GenericVisualizationsProps {- chartType: string;- data: customMetricsItem[];-}--const GenericVisualizations = (props: GenericVisualizationsProps) => {- const data = {- labels:- props.data !== undefined &&- props.data !== null &&- props.data.map((s) => new Date(s.timestamp / 1000000)),- datasets: [- {- data:- props.data !== undefined &&- props.data !== null &&- props.data.map((s) => s.value),- borderColor: 'rgba(250,174,50,1)', // for line chart- backgroundColor: props.chartType === 'bar' ? 'rgba(250,174,50,1)' : '', // for bar chart, don't assign backgroundcolor if its not a bar chart, may be relevant for area graph though- },- ],- };-- const options = {- responsive: true,- maintainAspectRatio: false,- legend: {- display: false,- },- scales: {- yAxes: [- {- gridLines: {- drawBorder: false,- },- ticks: {- display: false,- },- },- ],- xAxes: [- {- type: 'time',- // distribution: 'linear',- //'linear': data are spread according to their time (distances can vary)- // From https://www.chartjs.org/docs/latest/axes/cartesian/time.html- ticks: {- beginAtZero: false,- fontSize: 10,- autoSkip: true,- maxTicksLimit: 10,- },- // gridLines: false, --> not a valid option- },- ],- },- };-- if (props.chartType === 'line') {- return (- <GenVisualizationWrapper>- <ChartJSLine data={data} options={options} />- </GenVisualizationWrapper>- );- } else if (props.chartType === 'bar') {- return (- <GenVisualizationWrapper>- <Bar data={data} options={options} />- </GenVisualizationWrapper>- );- } else return null;-};--export default GenericVisualizations;diff --git a/frontend/src/modules/Metrics/LatencyLineChart.tsx b/frontend/src/modules/Metrics/LatencyLineChart.tsxdeleted file mode 100644index 4b6da0fd8d..0000000000--- a/frontend/src/modules/Metrics/LatencyLineChart.tsx+++ /dev/null@@ -1,234 +0,0 @@-import { ChartOptions } from 'chart.js';-import React from 'react';-import { Line as ChartJSLine } from 'react-chartjs-2';-import { withRouter } from 'react-router';-import { RouteComponentProps } from 'react-router-dom';-import { metricItem } from 'store/actions/MetricsActions';-import styled from 'styled-components';--const ChartPopUpUnique = styled.div<{- ycoordinate: number;- xcoordinate: number;-}>`- background-color: white;- border: 1px solid rgba(219, 112, 147, 0.5);- zindex: 10;- position: absolute;- top: ${(props) => props.ycoordinate}px;- left: ${(props) => props.xcoordinate}px;- font-size: 12px;- border-radius: 2px;-`;--const PopUpElements = styled.p`- color: black;- margin-bottom: 0px;- padding-left: 4px;- padding-right: 4px;- &:hover {- cursor: pointer;- }-`;--const theme = 'dark';--interface LatencyLineChartProps extends RouteComponentProps<any> {- data: metricItem[];- popupClickHandler: Function;-}--class LatencyLineChart extends React.Component<LatencyLineChartProps> {- private chartRef: React.RefObject<HTMLElement>;- constructor(props: LatencyLineChartProps) {- super(props);- this.chartRef = React.createRef();- }-- state = {- xcoordinate: 0,- ycoordinate: 0,- showpopUp: false,- firstpoint_ts: 0,- };-- onClickhandler = async (e: any, event: any) => {- let firstPoint;- if (this.chartRef) {- firstPoint = this.chartRef.current.chartInstance.getElementAtEvent(e)[0];- }-- if (firstPoint) {- this.setState({- xcoordinate: e.offsetX + 20,- ycoordinate: e.offsetY,- showpopUp: true,- firstpoint_ts: this.props.data[firstPoint._index].timestamp,- });- } else {- // if clicked outside of the graph line, then firstpoint is undefined -> close popup.- // Only works for clicking in the same chart - as click handler only detects clicks in that chart- this.setState({- showpopUp: false,- });- }- };-- options_charts: ChartOptions = {- onClick: this.onClickhandler,-- maintainAspectRatio: true,- responsive: true,-- title: {- display: true,- text: '',- fontSize: 20,- position: 'top',- padding: 8,- fontFamily: 'Arial',- fontStyle: 'regular',- fontColor: theme === 'dark' ? 'rgb(200, 200, 200)' : 'rgb(20, 20, 20)',- },-- legend: {- display: true,- position: 'bottom',- align: 'center',-- labels: {- fontColor: theme === 'dark' ? 'rgb(200, 200, 200)' : 'rgb(20, 20, 20)',- fontSize: 10,- boxWidth: 10,- usePointStyle: true,- },- },-- tooltips: {- mode: 'label',- bodyFontSize: 12,- titleFontSize: 12,-- callbacks: {- label: function (tooltipItem, data) {- if (typeof tooltipItem.yLabel === 'number') {- return (- data.datasets![tooltipItem.datasetIndex!].label +- ' : ' +- tooltipItem.yLabel.toFixed(2)- );- } else {- return '';- }- },- },- },-- scales: {- yAxes: [- {- stacked: false,- ticks: {- beginAtZero: false,- fontSize: 10,- autoSkip: true,- maxTicksLimit: 6,- },-- gridLines: {- // You can change the color, the dash effect, the main axe color, etc.- borderDash: [1, 4],- color: '#D3D3D3',- lineWidth: 0.25,- },- },- ],- xAxes: [- {- type: 'time',- distribution: 'linear',- //'linear': data are spread according to their time (distances can vary)- // From https://www.chartjs.org/docs/latest/axes/cartesian/time.html- ticks: {- beginAtZero: false,- fontSize: 10,- autoSkip: true,- maxTicksLimit: 10,- },- // gridLines: false, --> not a valid option- },- ],- },- };-- GraphTracePopUp = () => {- if (this.state.showpopUp) {- return (- <ChartPopUpUnique- xcoordinate={this.state.xcoordinate}- ycoordinate={this.state.ycoordinate}- >- <PopUpElements- onClick={() => {- this.props.popupClickHandler(this.state.firstpoint_ts);- }}- >- View Traces- </PopUpElements>- </ChartPopUpUnique>- );- } else return null;- };-- render() {- const ndata = this.props.data;-- const data_chartJS = (canvas: any) => {- const ctx = canvas.getContext('2d');- const gradient = ctx.createLinearGradient(0, 0, 0, 100);- gradient.addColorStop(0, 'rgba(250,174,50,1)');- gradient.addColorStop(1, 'rgba(250,174,50,1)');- return {- labels: ndata.map((s) => new Date(s.timestamp / 1000000)),- datasets: [- {- label: 'p99 Latency',- data: ndata.map((s) => s.p99 / 1000000), //converting latency from nano sec to ms- pointRadius: 0.5,- borderColor: 'rgba(250,174,50,1)', // Can also add transparency in border color- borderWidth: 2,- },- {- label: 'p95 Latency',- data: ndata.map((s) => s.p95 / 1000000), //converting latency from nano sec to ms- pointRadius: 0.5,- borderColor: 'rgba(227, 74, 51, 1.0)',- borderWidth: 2,- },- {- label: 'p50 Latency',- data: ndata.map((s) => s.p50 / 1000000), //converting latency from nano sec to ms- pointRadius: 0.5,- borderColor: 'rgba(57, 255, 20, 1.0)',- borderWidth: 2,- },- ],- };- };-- return (- <div>- {this.GraphTracePopUp()}- <div>- <div style={{ textAlign: 'center' }}>Application latency in ms</div>- <ChartJSLine- ref={this.chartRef}- data={data_chartJS}- options={this.options_charts}- />- </div>- </div>- );- }-}--export default withRouter(LatencyLineChart);diff --git a/frontend/src/modules/Metrics/LatencyLineChart/LatencyLine.tsx b/frontend/src/modules/Metrics/LatencyLineChart/LatencyLine.tsxnew file mode 100644index 0000000000..1fa4e6e4ae--- /dev/null+++ b/frontend/src/modules/Metrics/LatencyLineChart/LatencyLine.tsx@@ -0,0 +1,28 @@+import { ChartData, ChartOptions } from 'chart.js';+import Graph from 'components/Graph';+import React from 'react';++import { GraphContainer } from '../styles';++const LatencyChart = ({+ data,+ onClickhandler,+}: LatencyChartProps): JSX.Element => {+ return (+ <GraphContainer>+ <Graph+ onClickHandler={onClickhandler}+ xAxisType="timeseries"+ type="line"+ data={data}+ />+ </GraphContainer>+ );+};++interface LatencyChartProps {+ data: ChartData;+ onClickhandler: ChartOptions['onClick'];+}++export default LatencyChart;diff --git a/frontend/src/modules/Metrics/LatencyLineChart/index.tsx b/frontend/src/modules/Metrics/LatencyLineChart/index.tsxnew file mode 100644index 0000000000..05026d548b--- /dev/null+++ b/frontend/src/modules/Metrics/LatencyLineChart/index.tsx@@ -0,0 +1,142 @@+import {+ ActiveElement,+ Chart,+ ChartData,+ ChartEvent,+ ChartOptions,+} from 'chart.js';+import React, { useMemo, useState } from 'react';+import { metricItem } from 'store/actions/MetricsActions';+import styled from 'styled-components';++import { GraphTitle } from '../styles';+import LatencyLine from './LatencyLine';++const ChartPopUpUnique = styled.div<{+ ycoordinate: number;+ xcoordinate: number;+ showPopUp: boolean;+}>`+ background-color: white;+ border: 1px solid rgba(219, 112, 147, 0.5);+ z-index: 10;+ position: absolute;+ top: ${(props): number => props.ycoordinate}px;+ left: ${(props): number => props.xcoordinate}px;+ font-size: 12px;+ border-radius: 2px;+ display: ${({ showPopUp }): string => (showPopUp ? 'block' : 'none')};+`;++const PopUpElements = styled.p`+ color: black;+ margin-bottom: 0px;+ padding-left: 4px;+ padding-right: 4px;+ &:hover {+ cursor: pointer;+ }+`;++interface LatencyLineChartProps {+ data: metricItem[];+ popupClickHandler: (props: any) => void;+}++const LatencyLineChart = ({+ data,+ popupClickHandler,+}: LatencyLineChartProps): JSX.Element => {+ const [state, setState] = useState({+ xcoordinate: 0,+ ycoordinate: 0,+ showpopUp: false,+ firstpoint_ts: 0,+ });++ const onClickhandler: ChartOptions['onClick'] = async (+ event: ChartEvent,+ elements: ActiveElement[],+ chart: Chart,+ ): Promise<void> => {+ if (event.native) {+ const points = chart.getElementsAtEventForMode(+ event.native,+ 'nearest',+ { intersect: true },+ true,+ );++ if (points.length) {+ const firstPoint = points[0];++ setState({+ xcoordinate: firstPoint.element.x,+ ycoordinate: firstPoint.element.y,+ showpopUp: true,+ firstpoint_ts: data[firstPoint.index].timestamp,+ });+ } else {+ if (state.showpopUp) {+ setState((state) => ({+ ...state,+ showpopUp: false,+ }));+ }+ }+ }+ };++ const chartData: ChartData<'line'> = useMemo(() => {+ return {+ labels: data.map((s) => new Date(s.timestamp / 1000000)),+ datasets: [+ {+ label: 'p99 Latency',+ data: data.map((s) => s.p99 / 1000000), //converting latency from nano sec to ms+ pointRadius: 0.5,+ borderColor: 'rgba(250,174,50,1)', // Can also add transparency in border color+ borderWidth: 2,+ },+ {+ label: 'p95 Latency',+ data: data.map((s) => s.p95 / 1000000), //converting latency from nano sec to ms+ pointRadius: 0.5,+ borderColor: 'rgba(227, 74, 51, 1.0)',+ borderWidth: 2,+ },+ {+ label: 'p50 Latency',+ data: data.map((s) => s.p50 / 1000000), //converting latency from nano sec to ms+ pointRadius: 0.5,+ borderColor: 'rgba(57, 255, 20, 1.0)',+ borderWidth: 2,+ },+ ],+ };+ }, [data]);++ return (+ <>+ <ChartPopUpUnique+ xcoordinate={state.xcoordinate}+ ycoordinate={state.ycoordinate}+ showPopUp={state.showpopUp}+ >+ <PopUpElements+ onClick={(): void => {+ popupClickHandler(state.firstpoint_ts);+ }}+ >+ View Traces+ </PopUpElements>+ </ChartPopUpUnique>++ <GraphTitle>Application latency in ms</GraphTitle>++ <LatencyLine data={chartData} onClickhandler={onClickhandler} />+ </>+ );+};++export default LatencyLineChart;diff --git a/frontend/src/modules/Metrics/RequestRateChart.tsx b/frontend/src/modules/Metrics/RequestRateChart.tsxindex 3583331c93..27a5927377 100644--- a/frontend/src/modules/Metrics/RequestRateChart.tsx+++ b/frontend/src/modules/Metrics/RequestRateChart.tsx@@ -1,22 +1,23 @@-import { ChartOptions } from 'chart.js';+import { ActiveElement, Chart, ChartEvent } from 'chart.js';+import Graph from 'components/Graph';import ROUTES from 'constants/routes';-import React from 'react';-import { Line as ChartJSLine } from 'react-chartjs-2';-import { withRouter } from 'react-router';-import { RouteComponentProps } from 'react-router-dom';+import history from 'lib/history';+import React, { useMemo, useState } from 'react';import { metricItem } from 'store/actions/MetricsActions';import styled from 'styled-components';+import { GraphContainer } from './styles';+const ChartPopUpUnique = styled.div<{ycoordinate: number;xcoordinate: number;}>`background-color: white;border: 1px solid rgba(219, 112, 147, 0.5);- zindex: 10;+ z-index: 10;position: absolute;- top: ${(props) => props.ycoordinate}px;- left: ${(props) => props.xcoordinate}px;+ top: ${(props): number => props.ycoordinate}px;+ left: ${(props): number => props.xcoordinate}px;font-size: 12px;border-radius: 2px;`;@@ -31,191 +32,96 @@ const PopUpElements = styled.p`}`;-const theme = 'dark';--interface RequestRateChartProps extends RouteComponentProps<any> {+interface RequestRateChartProps {data: metricItem[];}-interface RequestRateChart {- chartRef: any;-}--class RequestRateChart extends React.Component<RequestRateChartProps> {- constructor(props: RequestRateChartProps) {- super(props);- this.chartRef = React.createRef();- }-- state = {+const RequestRateChart = ({ data }: RequestRateChartProps): JSX.Element => {+ const [state, setState] = useState({xcoordinate: 0,ycoordinate: 0,showpopUp: false,- // graphInfo:{}+ });+ const gotoTracesHandler = (): void => {+ history.push(ROUTES.TRACES);};- onClickhandler = async (e: any, event: any) => {- let firstPoint;- if (this.chartRef) {- firstPoint = this.chartRef.current.chartInstance.getElementAtEvent(e)[0];- }+ const onClickHandler = async (+ event: ChartEvent,+ elements: ActiveElement[],+ charts: Chart,+ ): Promise<void> => {+ if (event.native) {+ const points = charts.getElementsAtEventForMode(+ event.native,+ 'nearest',+ { intersect: true },+ true,+ );- if (firstPoint) {- // PNOTE - TODO - Is await needed in this expression?- await this.setState({- xcoordinate: e.offsetX + 20,- ycoordinate: e.offsetY,- showpopUp: true,- // graphInfo:{...event}- });+ if (points.length) {+ const firstPoint = points[0];++ setState({+ xcoordinate: firstPoint.element.x,+ ycoordinate: firstPoint.element.y,+ showpopUp: true,+ });+ } else {+ if (state.showpopUp) {+ setState((state) => ({+ ...state,+ showpopUp: false,+ }));+ }+ }}};- gotoTracesHandler = () => {- this.props.history.push(ROUTES.TRACES);- };-- gotoAlertsHandler = () => {- this.props.history.push(ROUTES.SERVICE_MAP);- // PNOTE - Keeping service map for now, will replace with alerts when alert page is made- };-- options_charts: ChartOptions = {- onClick: this.onClickhandler,-- maintainAspectRatio: true,- responsive: true,-- title: {- display: true,- text: '',- fontSize: 20,- position: 'top',- padding: 2,- fontFamily: 'Arial',- fontStyle: 'regular',- fontColor: theme === 'dark' ? 'rgb(200, 200, 200)' : 'rgb(20, 20, 20)',- },-- legend: {- display: true,- position: 'bottom',- align: 'center',-- labels: {- fontColor: theme === 'dark' ? 'rgb(200, 200, 200)' : 'rgb(20, 20, 20)',- fontSize: 10,- boxWidth: 10,- usePointStyle: true,- },- },-- tooltips: {- mode: 'label',- bodyFontSize: 12,- titleFontSize: 12,-- callbacks: {- label: function (tooltipItem, data) {- if (typeof tooltipItem.yLabel === 'number') {- return (- data.datasets![tooltipItem.datasetIndex!].label +- ' : ' +- tooltipItem.yLabel.toFixed(2)- );- } else {- return '';- }- },- },- },-- scales: {- yAxes: [- {- stacked: false,- ticks: {- beginAtZero: false,- fontSize: 10,- autoSkip: true,- maxTicksLimit: 6,- },-- gridLines: {- // You can change the color, the dash effect, the main axe color, etc.- borderDash: [1, 4],- color: '#D3D3D3',- lineWidth: 0.25,- },- },- ],- xAxes: [- {- type: 'time',- // time: {- // unit: 'second'- // },- distribution: 'linear',- ticks: {- beginAtZero: false,- fontSize: 10,- autoSkip: true,- maxTicksLimit: 10,- },- // gridLines: false, --> not a valid option- },- ],- },- };-- GraphTracePopUp = () => {- if (this.state.showpopUp) {+ const GraphTracePopUp = (): JSX.Element | null => {+ if (state.showpopUp) {return (<ChartPopUpUnique- xcoordinate={this.state.xcoordinate}- ycoordinate={this.state.ycoordinate}+ xcoordinate={state.xcoordinate}+ ycoordinate={state.ycoordinate}>- <PopUpElements onClick={this.gotoTracesHandler}>View Traces</PopUpElements>- {/* <PopUpElements onClick={this.gotoAlertsHandler}>Set Alerts</PopUpElements> */}+ <PopUpElements onClick={gotoTracesHandler}>View Traces</PopUpElements></ChartPopUpUnique>);} else return null;};- render() {- const ndata = this.props.data;-- const data_chartJS = (canvas: any) => {- const ctx = canvas.getContext('2d');- const gradient = ctx.createLinearGradient(0, 0, 0, 100);- gradient.addColorStop(0, 'rgba(250,174,50,1)');- gradient.addColorStop(1, 'rgba(250,174,50,1)');- return {- labels: ndata.map((s) => new Date(s.timestamp / 1000000)),- datasets: [- {- label: 'Request per sec',- data: ndata.map((s) => s.callRate),- pointRadius: 0.5,- borderColor: 'rgba(250,174,50,1)', // Can also add transparency in border color- borderWidth: 2,- },- ],- };+ const data_chartJS: Chart['data'] = useMemo(() => {+ return {+ labels: data.map((s) => new Date(s.timestamp / 1000000)),+ datasets: [+ {+ label: 'Request per sec',+ data: data.map((s) => s.callRate),+ pointRadius: 0.5,+ borderColor: 'rgba(250,174,50,1)', // Can also add transparency in border color+ borderWidth: 2,+ },+ ],};+ }, [data]);- return (+ return (+ <><div>- {this.GraphTracePopUp()}+ {GraphTracePopUp()}<div style={{ textAlign: 'center' }}>Request per sec</div>- <ChartJSLine- ref={this.chartRef}- data={data_chartJS}- options={this.options_charts}- />+ <GraphContainer>+ <Graph+ onClickHandler={onClickHandler}+ xAxisType="timeseries"+ type="line"+ data={data_chartJS}+ />+ </GraphContainer></div>- );- }-}+ </>+ );+};-export default withRouter(RequestRateChart);+export default RequestRateChart;diff --git a/frontend/src/modules/Metrics/ServiceMetrics.tsx b/frontend/src/modules/Metrics/ServiceMetrics/index.tsxsimilarity index 63%rename from frontend/src/modules/Metrics/ServiceMetrics.tsxrename to frontend/src/modules/Metrics/ServiceMetrics/index.tsxindex 14111834d7..8827e736c8 100644--- a/frontend/src/modules/Metrics/ServiceMetrics.tsx+++ b/frontend/src/modules/Metrics/ServiceMetrics/index.tsx@@ -1,16 +1,18 @@-import { Card, Col,Row, Tabs } from 'antd';+import { Col, Tabs } from 'antd';+import Spinner from 'components/Spinner';import { METRICS_PAGE_QUERY_PARAM } from 'constants/query';import ROUTES from 'constants/routes';-import React, { useEffect, useState } from 'react';+import history from 'lib/history';+import React, { useEffect } from 'react';import { connect } from 'react-redux';-import { withRouter } from 'react-router';-import { RouteComponentProps,useParams } from 'react-router-dom';+import { useParams } from 'react-router-dom';import { GlobalTime, updateTimeInterval } from 'store/actions';import {dbOverviewMetricsItem,externalErrCodeMetricsItem,externalMetricsAvgDurationItem,externalMetricsItem,+ getInitialMerticDataProps,metricItem,topEndpointListItem,} from 'store/actions/MetricsActions';@@ -19,51 +21,38 @@ import {getExternalAvgDurationMetrics,getExternalErrCodeMetrics,getExternalMetrics,+ getInitialMerticData,getServicesMetrics,getTopEndpoints,} from 'store/actions/MetricsActions';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';-import ErrorRateChart from './ErrorRateChart';-import ExternalApiGraph from './ExternalApi';-import LatencyLineChart from './LatencyLineChart';-import RequestRateChart from './RequestRateChart';-import TopEndpointsTable from './TopEndpointsTable';+import ErrorRateChart from '../ErrorRateChart';+import ExternalApiGraph from '../ExternalApi';+import LatencyLineChart from '../LatencyLineChart';+import RequestRateChart from '../RequestRateChart';+import TopEndpointsTable from '../TopEndpointsTable';+import { Card, Row } from './styles';const { TabPane } = Tabs;-interface ServicesMetricsProps extends RouteComponentProps<any> {- serviceMetrics: metricItem[];- dbOverviewMetrics: dbOverviewMetricsItem[];- getServicesMetrics: Function;- getExternalMetrics: Function;- getExternalErrCodeMetrics: Function;- getExternalAvgDurationMetrics: Function;- getDbOverViewMetrics: Function;- externalMetrics: externalMetricsItem[];- topEndpointsList: topEndpointListItem[];- externalAvgDurationMetrics: externalMetricsAvgDurationItem[];- externalErrCodeMetrics: externalErrCodeMetricsItem[];- getTopEndpoints: Function;- globalTime: GlobalTime;- updateTimeInterval: Function;-}--const _ServiceMetrics = (props: ServicesMetricsProps) => {+const _ServiceMetrics = (props: ServicesMetricsProps): JSX.Element => {const { servicename } = useParams<{ servicename?: string }>();+ const { globalTime, getInitialMerticData } = props;+useEffect(() => {- props.getServicesMetrics(servicename, props.globalTime);- props.getTopEndpoints(servicename, props.globalTime);- props.getExternalMetrics(servicename, props.globalTime);- props.getExternalErrCodeMetrics(servicename, props.globalTime);- props.getExternalAvgDurationMetrics(servicename, props.globalTime);- props.getDbOverViewMetrics(servicename, props.globalTime);- }, [props.globalTime, servicename]);-- const onTracePopupClick = (timestamp: number) => {+ if (servicename !== undefined) {+ getInitialMerticData({+ globalTime: globalTime,+ serviceName: servicename,+ });+ }+ }, [getInitialMerticData, servicename, globalTime]);++ const onTracePopupClick = (timestamp: number): void => {const currentTime = timestamp / 1000000;const tPlusOne = timestamp / 1000000 + 1 * 60 * 1000;- props.updateTimeInterval('custom', [currentTime, tPlusOne]); // updateTimeInterval takes second range in ms -- give -5 min to selected time,+ updateTimeInterval('custom', [currentTime, tPlusOne]); // updateTimeInterval takes second range in ms -- give -5 min to selected time,const urlParams = new URLSearchParams();urlParams.set(METRICS_PAGE_QUERY_PARAM.startTime, currentTime.toString());@@ -72,14 +61,14 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {urlParams.set(METRICS_PAGE_QUERY_PARAM.service, servicename);}- props.history.push(`${ROUTES.TRACES}?${urlParams.toString()}`);+ history.push(`${ROUTES.TRACES}?${urlParams.toString()}`);};- const onErrTracePopupClick = (timestamp: number) => {+ const onErrTracePopupClick = (timestamp: number): void => {const currentTime = timestamp / 1000000;const tPlusOne = timestamp / 1000000 + 1 * 60 * 1000;- props.updateTimeInterval('custom', [currentTime, tPlusOne]); // updateTimeInterval takes second range in ms -- give -5 min to selected time,+ updateTimeInterval('custom', [currentTime, tPlusOne]); // updateTimeInterval takes second range in ms -- give -5 min to selected time,const urlParams = new URLSearchParams();urlParams.set(METRICS_PAGE_QUERY_PARAM.startTime, currentTime.toString());@@ -89,15 +78,19 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {}urlParams.set(METRICS_PAGE_QUERY_PARAM.error, 'true');- props.history.push(`${ROUTES.TRACES}?${urlParams.toString()}`);+ history.push(`${ROUTES.TRACES}?${urlParams.toString()}`);};+ if (props.loading) {+ return <Spinner tip="Loading..." height="100vh" size="large" />;+ }+return (<Tabs defaultActiveKey="1"><TabPane tab="Application Metrics" key="1">- <Row gutter={32} style={{ margin: 20 }}>+ <Row gutter={24}><Col span={12}>- <Card bodyStyle={{ padding: 10 }}>+ <Card><LatencyLineChartdata={props.serviceMetrics}popupClickHandler={onTracePopupClick}@@ -106,15 +99,15 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {</Col><Col span={12}>- <Card bodyStyle={{ padding: 10 }}>+ <Card><RequestRateChart data={props.serviceMetrics} /></Card></Col></Row>- <Row gutter={32} style={{ margin: 20 }}>+ <Row gutter={24}><Col span={12}>- <Card bodyStyle={{ padding: 10 }}>+ <Card><ErrorRateChartonTracePopupClick={onErrTracePopupClick}data={props.serviceMetrics}@@ -123,7 +116,7 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {</Col><Col span={12}>- <Card bodyStyle={{ padding: 10 }}>+ <Card><TopEndpointsTable data={props.topEndpointsList} /></Card></Col>@@ -131,9 +124,9 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {</TabPane><TabPane tab="External Calls" key="2">- <Row gutter={32} style={{ margin: 20 }}>+ <Row gutter={24}><Col span={12}>- <Card bodyStyle={{ padding: 10 }}>+ <Card><ExternalApiGraphtitle="External Call Error Percentage (%)"keyIdentifier="externalHttpUrl"@@ -144,7 +137,7 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {</Col><Col span={12}>- <Card bodyStyle={{ padding: 10 }}>+ <Card><ExternalApiGraphlabel="Average Duration"title="External Call duration"@@ -156,9 +149,9 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {</Col></Row>- <Row gutter={32} style={{ margin: 20 }}>+ <Row gutter={24}><Col span={12}>- <Card bodyStyle={{ padding: 10 }}>+ <Card><ExternalApiGraphtitle="External Call RPS(by Address)"keyIdentifier="externalHttpUrl"@@ -169,7 +162,7 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {</Col><Col span={12}>- <Card bodyStyle={{ padding: 10 }}>+ <Card><ExternalApiGraphtitle="External Call duration(by Address)"keyIdentifier="externalHttpUrl"@@ -183,9 +176,9 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {</TabPane><TabPane tab="Database Calls" key="3">- <Row gutter={32} style={{ margin: 20 }}>+ <Row gutter={24}><Col span={12}>- <Card bodyStyle={{ padding: 10 }}>+ <Card><ExternalApiGraphtitle="Database Calls RPS"keyIdentifier="dbSystem"@@ -196,7 +189,7 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {</Col><Col span={12}>- <Card bodyStyle={{ padding: 10 }}>+ <Card><ExternalApiGraphlabel="Average Duration"title="Database Calls Avg Duration (in ms)"@@ -212,8 +205,27 @@ const _ServiceMetrics = (props: ServicesMetricsProps) => {);};+interface ServicesMetricsProps {+ serviceMetrics: metricItem[];+ dbOverviewMetrics: dbOverviewMetricsItem[];+ getServicesMetrics: () => void;+ getExternalMetrics: () => void;+ getExternalErrCodeMetrics: () => void;+ getExternalAvgDurationMetrics: () => void;+ getDbOverViewMetrics: () => void;+ externalMetrics: externalMetricsItem[];+ topEndpointsList: topEndpointListItem[];+ externalAvgDurationMetrics: externalMetricsAvgDurationItem[];+ externalErrCodeMetrics: externalErrCodeMetricsItem[];+ getTopEndpoints: () => void;+ globalTime: GlobalTime;+ updateTimeInterval: () => void;+ getInitialMerticData: (props: getInitialMerticDataProps) => void;+ loading: boolean;+}+const mapStateToProps = (- state: StoreState,+ state: AppState,): {serviceMetrics: metricItem[];topEndpointsList: topEndpointListItem[];@@ -222,6 +234,7 @@ const mapStateToProps = (externalMetrics: externalMetricsItem[];dbOverviewMetrics: dbOverviewMetricsItem[];globalTime: GlobalTime;+ loading: boolean;} => {return {externalErrCodeMetrics: state.metricsData.externalErrCodeMetricsItem,@@ -231,17 +244,17 @@ const mapStateToProps = (globalTime: state.globalTime,dbOverviewMetrics: state.metricsData.dbOverviewMetricsItem,externalAvgDurationMetrics: state.metricsData.externalMetricsAvgDurationItem,+ loading: state.metricsData.loading,};};-export const ServiceMetrics = withRouter(- connect(mapStateToProps, {- getServicesMetrics: getServicesMetrics,- getExternalMetrics: getExternalMetrics,- getExternalErrCodeMetrics: getExternalErrCodeMetrics,- getExternalAvgDurationMetrics: getExternalAvgDurationMetrics,- getTopEndpoints: getTopEndpoints,- updateTimeInterval: updateTimeInterval,- getDbOverViewMetrics: getDbOverViewMetrics,- })(_ServiceMetrics),-);+export const ServiceMetrics = connect(mapStateToProps, {+ getServicesMetrics: getServicesMetrics,+ getExternalMetrics: getExternalMetrics,+ getExternalErrCodeMetrics: getExternalErrCodeMetrics,+ getExternalAvgDurationMetrics: getExternalAvgDurationMetrics,+ getTopEndpoints: getTopEndpoints,+ updateTimeInterval: updateTimeInterval,+ getDbOverViewMetrics: getDbOverViewMetrics,+ getInitialMerticData: getInitialMerticData,+})(_ServiceMetrics);diff --git a/frontend/src/modules/Metrics/ServiceMetrics/styles.ts b/frontend/src/modules/Metrics/ServiceMetrics/styles.tsnew file mode 100644index 0000000000..98efc4662d--- /dev/null+++ b/frontend/src/modules/Metrics/ServiceMetrics/styles.ts@@ -0,0 +1,18 @@+import { Card as CardComponent, Row as RowComponent } from 'antd';+import styled from 'styled-components';++export const Card = styled(CardComponent)`+ &&& {+ padding: 10px;+ }++ .ant-card-body {+ padding: 0;+ }+`;++export const Row = styled(RowComponent)`+ &&& {+ padding: 1rem;+ }+`;diff --git a/frontend/src/modules/Metrics/ServicesTable.tsx b/frontend/src/modules/Metrics/ServiceTable/index.tsxsimilarity index 55%rename from frontend/src/modules/Metrics/ServicesTable.tsxrename to frontend/src/modules/Metrics/ServiceTable/index.tsxindex 802d8a170c..643166e34a 100644--- a/frontend/src/modules/Metrics/ServicesTable.tsx+++ b/frontend/src/modules/Metrics/ServiceTable/index.tsx@@ -1,89 +1,19 @@import { Button, Space, Table } from 'antd';-import { CustomModal } from 'components/Modal';+import { ColumnsType } from 'antd/lib/table';+import Modal from 'components/Modal';import Spinner from 'components/Spinner';import { SKIP_ONBOARDING } from 'constants/onboarding';import ROUTES from 'constants/routes';-import React, { useEffect, useState } from 'react';+import React, { useCallback, useEffect, useState } from 'react';import { connect } from 'react-redux';import { NavLink } from 'react-router-dom';import { getServicesList, GlobalTime } from 'store/actions';import { servicesListItem } from 'store/actions/MetricsActions';-import { StoreState } from 'store/reducers';-import styled from 'styled-components';+import { AppState } from 'store/reducers';-interface ServicesTableProps {- servicesList: servicesListItem[];- getServicesList: Function;- globalTime: GlobalTime;-}+import { Wrapper } from './styles';-const Wrapper = styled.div`- padding-top: 40px;- padding-bottom: 40px;- padding-left: 40px;- padding-right: 40px;- .ant-table table {- font-size: 12px;- }- .ant-table tfoot > tr > td,- .ant-table tfoot > tr > th,- .ant-table-tbody > tr > td,- .ant-table-thead > tr > th {- padding: 10px;- }-`;--const TableLoadingWrapper = styled.div`- display: flex;- justify-content: center;- margin-top: 80px;-`;--const LoadingText = styled.div`- margin-left: 16px;-`;--const columns = [- {- title: 'Application',- dataIndex: 'serviceName',- key: 'serviceName',- render: (text: string) => (- <NavLink- style={{ textTransform: 'capitalize' }}- to={ROUTES.APPLICATION + '/' + text}- >- <strong>{text}</strong>- </NavLink>- ),- },- {- title: 'P99 latency (in ms)',- dataIndex: 'p99',- key: 'p99',- sorter: (a: any, b: any) => a.p99 - b.p99,- // sortDirections: ['descend', 'ascend'],- render: (value: number) => (value / 1000000).toFixed(2),- },- {- title: 'Error Rate (in %)',- dataIndex: 'errorRate',- key: 'errorRate',- sorter: (a: any, b: any) => a.errorRate - b.errorRate,- // sortDirections: ['descend', 'ascend'],- render: (value: number) => value.toFixed(2),- },- {- title: 'Requests Per Second',- dataIndex: 'callRate',- key: 'callRate',- sorter: (a: any, b: any) => a.callRate - b.callRate,- // sortDirections: ['descend', 'ascend'],- render: (value: number) => value.toFixed(2),- },-];--const _ServicesTable = (props: ServicesTableProps) => {+const _ServicesTable = (props: ServicesTableProps): JSX.Element => {const [initialDataFetch, setDataFetched] = useState(false);const [errorObject, setErrorObject] = useState({message: '',@@ -96,14 +26,15 @@ const _ServicesTable = (props: ServicesTableProps) => {localStorage.getItem(SKIP_ONBOARDING) === 'true',);- const onContinueClick = () => {+ const onContinueClick = (): void => {localStorage.setItem(SKIP_ONBOARDING, 'true');setSkipOnboarding(true);};- function getApiServiceData() {- props- .getServicesList(props.globalTime)+ const { globalTime, getServicesList } = props;++ const getApiServiceData = useCallback(() => {+ getServicesList(globalTime).then(() => {setDataFetched(true);setErrorObject({ message: '', isError: false });@@ -112,15 +43,16 @@ const _ServicesTable = (props: ServicesTableProps) => {setErrorObject({ message: e, isError: true });setDataFetched(true);});- }+ }, [globalTime, getServicesList]);++ useEffect(() => {+ getApiServiceData();+ }, [globalTime, getApiServiceData]);- useEffect(getApiServiceData, [props.globalTime]);useEffect(() => {if (props.servicesList.length > 1) {localStorage.removeItem(SKIP_ONBOARDING);}-- refetchFromBackend && setTimeout(getApiServiceData, 50000);}, [props.servicesList, errorObject]);if (!initialDataFetch) {@@ -129,11 +61,10 @@ const _ServicesTable = (props: ServicesTableProps) => {if (refetchFromBackend && !skipOnboarding) {return (- <CustomModal+ <Modaltitle={'Setup instrumentation'}isModalVisible={true}closable={false}- setIsModalVisible={() => {}}footer={[<Button key="submit" type="primary" onClick={onContinueClick}>Continue without instrumentation@@ -149,9 +80,6 @@ const _ServicesTable = (props: ServicesTableProps) => {allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"allowFullScreen></iframe>- <div style={{ margin: '20px 0' }}>- <Spinner />- </div><div>No instrumentation data.<br />@@ -165,10 +93,48 @@ const _ServicesTable = (props: ServicesTableProps) => {</a></div></div>- </CustomModal>+ </Modal>);}+ const columns: ColumnsType<DataProps> = [+ {+ title: 'Application',+ dataIndex: 'serviceName',+ key: 'serviceName',+ // eslint-disable-next-line react/display-name+ render: (text: string): JSX.Element => (+ <NavLink+ style={{ textTransform: 'capitalize' }}+ to={ROUTES.APPLICATION + '/' + text}+ >+ <strong>{text}</strong>+ </NavLink>+ ),+ },+ {+ title: 'P99 latency (in ms)',+ dataIndex: 'p99',+ key: 'p99',+ sorter: (a: DataProps, b: DataProps): number => a.p99 - b.p99,+ render: (value: number): string => (value / 1000000).toFixed(2),+ },+ {+ title: 'Error Rate (in %)',+ dataIndex: 'errorRate',+ key: 'errorRate',+ sorter: (a: DataProps, b: DataProps): number => a.errorRate - b.errorRate,+ render: (value: number): string => value.toFixed(2),+ },+ {+ title: 'Requests Per Second',+ dataIndex: 'callRate',+ key: 'callRate',+ sorter: (a: DataProps, b: DataProps): number => a.callRate - b.callRate,+ render: (value: number): string => value.toFixed(2),+ },+ ];+return (<Wrapper><Table@@ -179,27 +145,35 @@ const _ServicesTable = (props: ServicesTableProps) => {{props.servicesList[0] !== undefined &&props.servicesList[0].numCalls === 0 && (- <Space- style={{ width: '100%', margin: '40px 0', justifyContent: 'center' }}- >- No applications present. Please add instrumentation (follow this- <a- href={'https://signoz.io/docs/instrumentation/overview'}- target={'_blank'}- style={{ marginLeft: 3 }}- rel="noreferrer"+ <Space+ style={{ width: '100%', margin: '40px 0', justifyContent: 'center' }}>+ No applications present. Please add instrumentation (follow this+ <a+ href={'https://signoz.io/docs/instrumentation/overview'}+ target={'_blank'}+ style={{ marginLeft: 3 }}+ rel="noreferrer"+ >guide- </a>+ </a>)- </Space>- )}+ </Space>+ )}</Wrapper>);};+type DataProps = servicesListItem;++interface ServicesTableProps {+ servicesList: servicesListItem[];+ getServicesList: (props: GlobalTime) => Promise<void>;+ globalTime: GlobalTime;+}+const mapStateToProps = (- state: StoreState,+ state: AppState,): { servicesList: servicesListItem[]; globalTime: GlobalTime } => {return {servicesList: state.metricsData.serviceList,diff --git a/frontend/src/modules/Metrics/ServiceTable/styles.ts b/frontend/src/modules/Metrics/ServiceTable/styles.tsnew file mode 100644index 0000000000..704bec81dd--- /dev/null+++ b/frontend/src/modules/Metrics/ServiceTable/styles.ts@@ -0,0 +1,5 @@+import styled from 'styled-components';++export const Wrapper = styled.div`+ padding: 40px;+`;diff --git a/frontend/src/modules/Metrics/ServicesTableDef.tsx b/frontend/src/modules/Metrics/ServicesTableDef.tsxindex d2244a8a3c..7d5c2d568d 100644--- a/frontend/src/modules/Metrics/ServicesTableDef.tsx+++ b/frontend/src/modules/Metrics/ServicesTableDef.tsx@@ -1 +1 @@-export { ServicesTable as default } from './ServicesTable';+export { ServicesTable as default } from './ServiceTable';diff --git a/frontend/src/modules/Metrics/TopEndpointsTable.tsx b/frontend/src/modules/Metrics/TopEndpointsTable.tsxindex e01535bea2..3633e1b350 100644--- a/frontend/src/modules/Metrics/TopEndpointsTable.tsx+++ b/frontend/src/modules/Metrics/TopEndpointsTable.tsx@@ -7,7 +7,7 @@ import { connect } from 'react-redux';import { useHistory, useParams } from 'react-router-dom';import { GlobalTime } from 'store/actions';import { topEndpointListItem } from 'store/actions/MetricsActions';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';import styled from 'styled-components';const Wrapper = styled.div`@@ -118,7 +118,7 @@ const _TopEndpointsTable = (props: TopEndpointsTableProps) => {};const mapStateToProps = (- state: StoreState,+ state: AppState,): {globalTime: GlobalTime;} => {diff --git a/frontend/src/modules/Metrics/styles.ts b/frontend/src/modules/Metrics/styles.tsnew file mode 100644index 0000000000..7f46ae4811--- /dev/null+++ b/frontend/src/modules/Metrics/styles.ts@@ -0,0 +1,12 @@+import { Typography } from 'antd';+import styled from 'styled-components';++export const GraphContainer = styled.div`+ min-height: 27vh;+`;++export const GraphTitle = styled(Typography)`+ &&& {+ text-align: center;+ }+`;diff --git a/frontend/src/modules/Nav/TopNav/CustomDateTimeModal.tsx b/frontend/src/modules/Nav/TopNav/CustomDateTimeModal.tsxindex b8ded8379d..f1ce19078a 100644--- a/frontend/src/modules/Nav/TopNav/CustomDateTimeModal.tsx+++ b/frontend/src/modules/Nav/TopNav/CustomDateTimeModal.tsx@@ -1,4 +1,4 @@-import { DatePicker,Modal } from 'antd';+import { DatePicker, Modal } from 'antd';import { Moment } from 'moment';import moment from 'moment';import React, { useState } from 'react';@@ -18,17 +18,15 @@ const CustomDateTimeModal: React.FC<CustomDateTimeModalProps> = ({onCreate,onCancel,}) => {- // RangeValue<Moment> == [Moment|null,Moment|null]|null-const [customDateTimeRange,setCustomDateTimeRange,] = useState<DateTimeRangeType>();- function handleRangePickerOk(date_time: DateTimeRangeType) {+ function handleRangePickerOk(date_time: DateTimeRangeType): void {setCustomDateTimeRange(date_time);}- function disabledDate(current: Moment) {+ function disabledDate(current: Moment): boolean {if (current > moment()) {return true;} else {@@ -44,7 +42,7 @@ const CustomDateTimeModal: React.FC<CustomDateTimeModalProps> = ({cancelText="Cancel"onCancel={onCancel}style={{ position: 'absolute', top: 60, right: 40 }}- onOk={() => onCreate(customDateTimeRange ? customDateTimeRange : null)}+ onOk={(): void => onCreate(customDateTimeRange ? customDateTimeRange : null)}><RangePickerdisabledDate={disabledDate}diff --git a/frontend/src/modules/Nav/TopNav/DateTimeSelector.tsx b/frontend/src/modules/Nav/TopNav/DateTimeSelector.tsxindex a7b94b65b9..784a97cf6a 100644--- a/frontend/src/modules/Nav/TopNav/DateTimeSelector.tsx+++ b/frontend/src/modules/Nav/TopNav/DateTimeSelector.tsx@@ -1,17 +1,17 @@-import { Button, Form,Select as DefaultSelect, Space } from 'antd';+import { Button, Form, Select as DefaultSelect, Space } from 'antd';import FormItem from 'antd/lib/form/FormItem';import { LOCAL_STORAGE } from 'constants/localStorage';import { METRICS_PAGE_QUERY_PARAM } from 'constants/query';import ROUTES from 'constants/routes';+import history from 'lib/history';import { cloneDeep } from 'lodash';import moment from 'moment';-import React, { useEffect, useState } from 'react';+import React, { useCallback, useEffect, useMemo, useState } from 'react';import { connect } from 'react-redux';-import { withRouter } from 'react-router';-import { RouteComponentProps, useLocation } from 'react-router-dom';+import { useLocation } from 'react-router-dom';import { GlobalTime, updateTimeInterval } from 'store/actions';import { DateTimeRangeType } from 'store/actions';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';import styled from 'styled-components';import {@@ -27,37 +27,58 @@ const DateTimeWrapper = styled.div`margin-top: 20px;justify-content: flex-end !important;`;-const Select = styled(DefaultSelect)``;-interface DateTimeSelectorProps extends RouteComponentProps<any> {+interface DateTimeSelectorProps {currentpath?: string;- updateTimeInterval: Function;+ updateTimeInterval: (+ interval: string,+ datetimeRange?: [number, number],+ ) => void;globalTime: GlobalTime;}/*This components is mounted all the time. Use event listener to track changes.*/-const _DateTimeSelector = (props: DateTimeSelectorProps) => {+const _DateTimeSelector = (props: DateTimeSelectorProps): JSX.Element => {const location = useLocation();const LocalStorageRouteKey: string = getLocalStorageRouteKey(location.pathname,);- const timeDurationInLocalStorage =- JSON.parse(localStorage.getItem(LOCAL_STORAGE.METRICS_TIME_IN_DURATION)) ||- {};+ const { globalTime, updateTimeInterval } = props;++ const timeDurationInLocalStorage = useMemo(() => {+ return (+ JSON.parse(localStorage.getItem(LOCAL_STORAGE.METRICS_TIME_IN_DURATION)) ||+ {}+ );+ }, []);+const options =location.pathname === ROUTES.SERVICE_MAP ? ServiceMapOptions : Options;let defaultTime = DefaultOptionsBasedOnRoute[LocalStorageRouteKey]? DefaultOptionsBasedOnRoute[LocalStorageRouteKey]: DefaultOptionsBasedOnRoute.default;+if (timeDurationInLocalStorage[LocalStorageRouteKey]) {defaultTime = timeDurationInLocalStorage[LocalStorageRouteKey];}++ const getDefaultTime = useCallback(() => {+ if (DefaultOptionsBasedOnRoute[LocalStorageRouteKey]) {+ return DefaultOptionsBasedOnRoute[LocalStorageRouteKey];+ }+ if (timeDurationInLocalStorage[LocalStorageRouteKey]) {+ return timeDurationInLocalStorage[LocalStorageRouteKey];+ }+ return DefaultOptionsBasedOnRoute.default;+ }, [LocalStorageRouteKey, timeDurationInLocalStorage]);+const [currentLocalStorageRouteKey, setCurrentLocalStorageRouteKey] = useState(LocalStorageRouteKey,);+const [customDTPickerVisible, setCustomDTPickerVisible] = useState(false);- const [timeInterval, setTimeInterval] = useState(defaultTime);+ const [timeInterval, setTimeInterval] = useState(getDefaultTime());const [startTime, setStartTime] = useState<moment.Moment | null>(null);const [endTime, setEndTime] = useState<moment.Moment | null>(null);const [refreshButtonHidden, setRefreshButtonHidden] = useState(false);@@ -65,7 +86,45 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {const [refreshButtonClick, setRefreshButtonClick] = useState(0);const [form_dtselector] = Form.useForm();- const updateTimeOnQueryParamChange = () => {+ const setToLocalStorage = useCallback(+ (val: string) => {+ let timeDurationInLocalStorageObj = cloneDeep(timeDurationInLocalStorage);+ if (timeDurationInLocalStorageObj) {+ timeDurationInLocalStorageObj[LocalStorageRouteKey] = val;+ } else {+ timeDurationInLocalStorageObj = {+ [LocalStorageRouteKey]: val,+ };+ }+ window.localStorage.setItem(+ LOCAL_STORAGE.METRICS_TIME_IN_DURATION,+ JSON.stringify(timeDurationInLocalStorageObj),+ );+ },+ [LocalStorageRouteKey, timeDurationInLocalStorage],+ );++ const setMetricsTimeInterval = useCallback(+ (value: string) => {+ updateTimeInterval(value);+ setTimeInterval(value);+ setEndTime(null);+ setStartTime(null);+ setToLocalStorage(value);+ },+ [setToLocalStorage, updateTimeInterval],+ );++ const setCustomTime = useCallback(+ (startTime: moment.Moment, endTime: moment.Moment) => {+ updateTimeInterval('custom', [startTime.valueOf(), endTime.valueOf()]);+ setEndTime(endTime);+ setStartTime(startTime);+ },+ [updateTimeInterval],+ );++ const updateTimeOnQueryParamChange = useCallback(() => {const urlParams = new URLSearchParams(location.search);const intervalInQueryParam = urlParams.get(METRICS_PAGE_QUERY_PARAM.interval);const startTimeString = urlParams.get(METRICS_PAGE_QUERY_PARAM.startTime);@@ -80,7 +139,7 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {) {const startTime = moment(Number(startTimeString));const endTime = moment(Number(endTimeString));- setCustomTime(startTime, endTime, true);+ setCustomTime(startTime, endTime);} else if (currentLocalStorageRouteKey !== LocalStorageRouteKey) {setMetricsTimeInterval(defaultTime);setCurrentLocalStorageRouteKey(LocalStorageRouteKey);@@ -89,68 +148,72 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {else if (intervalInQueryParam) {setMetricsTimeInterval(intervalInQueryParam);}- };-- const setToLocalStorage = (val: string) => {- let timeDurationInLocalStorageObj = cloneDeep(timeDurationInLocalStorage);- if (timeDurationInLocalStorageObj) {- timeDurationInLocalStorageObj[LocalStorageRouteKey] = val;- } else {- timeDurationInLocalStorageObj = {- [LocalStorageRouteKey]: val,- };- }- window.localStorage.setItem(- LOCAL_STORAGE.METRICS_TIME_IN_DURATION,- JSON.stringify(timeDurationInLocalStorageObj),- );- };+ }, [+ LocalStorageRouteKey,+ currentLocalStorageRouteKey,+ setCustomTime,+ defaultTime,+ setMetricsTimeInterval,+ location,+ ]);useEffect(() => {setMetricsTimeInterval(defaultTime);- }, []);+ }, [defaultTime, setMetricsTimeInterval]);// On URL ChangeuseEffect(() => {updateTimeOnQueryParamChange();- }, [location]);-- const setMetricsTimeInterval = (value: string) => {- props.updateTimeInterval(value);- setTimeInterval(value);- setEndTime(null);- setStartTime(null);- setToLocalStorage(value);- };- const setCustomTime = (- startTime: moment.Moment,- endTime: moment.Moment,- triggeredByURLChange = false,- ) => {- props.updateTimeInterval('custom', [startTime.valueOf(), endTime.valueOf()]);- setEndTime(endTime);- setStartTime(startTime);- };+ }, [location, updateTimeOnQueryParamChange]);++ const updateUrlForTimeInterval = (value: string): void => {+ const preSearch = new URLSearchParams(location.search);++ const widgetId = preSearch.get('widgetId');+ const graphType = preSearch.get('graphType');++ let result = '';++ if (widgetId !== null) {+ result = result + `&widgetId=${widgetId}`;+ }++ if (graphType !== null) {+ result = result + `&graphType=${graphType}`;+ }- const updateUrlForTimeInterval = (value: string) => {- props.history.push({- search: `?${METRICS_PAGE_QUERY_PARAM.interval}=${value}`,+ history.push({+ search: `?${METRICS_PAGE_QUERY_PARAM.interval}=${value}${result}`,}); //pass time in URL query param for all choices except custom in datetime picker};const updateUrlForCustomTime = (startTime: moment.Moment,endTime: moment.Moment,- triggeredByURLChange = false,- ) => {- props.history.push(+ ): void => {+ const preSearch = new URLSearchParams(location.search);++ const widgetId = preSearch.get('widgetId');+ const graphType = preSearch.get('graphType');++ let result = '';++ if (widgetId !== null) {+ result = result + `&widgetId=${widgetId}`;+ }++ if (graphType !== null) {+ result = result + `&graphType=${graphType}`;+ }++ history.push(`?${METRICS_PAGE_QUERY_PARAM.startTime}=${startTime.valueOf()}&${METRICS_PAGE_QUERY_PARAM.endTime- }=${endTime.valueOf()}`,+ }=${endTime.valueOf()}${result}`,);};- const handleOnSelect = (value: string) => {+ const handleOnSelect = (value: string): void => {if (value === 'custom') {setCustomDTPickerVisible(true);} else {@@ -160,7 +223,7 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {};//function called on clicking apply in customDateTimeModal- const handleCustomDate = (dateTimeRange: DateTimeRangeType) => {+ const handleCustomDate = (dateTimeRange: DateTimeRangeType): void => {// pass values in ms [minTime, maxTime]if (dateTimeRange !== null &&@@ -184,9 +247,9 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {setCustomDTPickerVisible(false);};- const timeSinceLastRefresh = () => {+ const timeSinceLastRefresh = useCallback(() => {const currentTime = moment();- const lastRefresh = moment(props.globalTime.maxTime / 1000000);+ const lastRefresh = moment(globalTime.maxTime / 1000000);const duration = moment.duration(currentTime.diff(lastRefresh));const secondsDiff = Math.floor(duration.asSeconds());@@ -199,9 +262,9 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {return `Last refresh - ${minutedDiff} mins ago`;}return `Last refresh - ${secondsDiff} sec ago`;- };+ }, [globalTime]);- const handleRefresh = () => {+ const handleRefresh = (): void => {setRefreshButtonClick(refreshButtonClick + 1);setMetricsTimeInterval(timeInterval);};@@ -211,18 +274,18 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {const interval = setInterval(() => {setRefreshText(timeSinceLastRefresh());}, 2000);- return () => {+ return (): void => {clearInterval(interval);};- }, [props.location, refreshButtonClick]);+ }, [refreshButtonClick, timeSinceLastRefresh]);- if (props.location.pathname.startsWith(ROUTES.USAGE_EXPLORER)) {- return null;+ if (history.location.pathname.startsWith(ROUTES.USAGE_EXPLORER)) {+ return <></>;} else {const inputLabeLToShow =startTime && endTime? `${startTime.format('YYYY/MM/DD HH:mm')} - ${endTime.format(- 'YYYY/MM/DD HH:mm',+ 'YYYY/MM/DD HH:mm',)}`: timeInterval;@@ -236,11 +299,13 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {initialValues={{ interval: '15min' }}style={{ marginTop: 10, marginBottom: 10 }}>- <Select onSelect={handleOnSelect} value={inputLabeLToShow}>+ <DefaultSelect onSelect={handleOnSelect} value={inputLabeLToShow}>{options.map(({ value, label }) => (- <Option value={value}>{label}</Option>+ <Option key={value + label} value={value}>+ {label}+ </Option>))}- </Select>+ </DefaultSelect><FormItem hidden={refreshButtonHidden} name="refresh_button"><Button type="primary" onClick={handleRefresh}>@@ -264,7 +329,7 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {<CustomDateTimeModalvisible={customDTPickerVisible}onCreate={handleCustomDate}- onCancel={() => {+ onCancel={(): void => {setCustomDTPickerVisible(false);}}/>@@ -273,14 +338,12 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {);}};-const mapStateToProps = (state: StoreState): { globalTime: GlobalTime } => {+const mapStateToProps = (state: AppState): { globalTime: GlobalTime } => {return { globalTime: state.globalTime };};-export const DateTimeSelector = withRouter(- connect(mapStateToProps, {- updateTimeInterval: updateTimeInterval,- })(_DateTimeSelector),-);+export const DateTimeSelector = connect(mapStateToProps, {+ updateTimeInterval: updateTimeInterval,+})(_DateTimeSelector);export default DateTimeSelector;diff --git a/frontend/src/modules/Nav/TopNav/ShowBreadcrumbs.tsx b/frontend/src/modules/Nav/TopNav/ShowBreadcrumbs.tsxindex 64f4e7351b..f3f0e931c3 100644--- a/frontend/src/modules/Nav/TopNav/ShowBreadcrumbs.tsx+++ b/frontend/src/modules/Nav/TopNav/ShowBreadcrumbs.tsx@@ -18,9 +18,11 @@ const breadcrumbNameMap: any = {[ROUTES.INSTRUMENTATION]: 'Add instrumentation',[ROUTES.SETTINGS]: 'Settings',};+import history from 'lib/history';-const ShowBreadcrumbs = withRouter((props) => {- const { location } = props;+const ShowBreadcrumbs = (): JSX.Element => {+ // const { location } = props;+ const location = history.location;const pathSnippets = location.pathname.split('/').filter((i) => i);const extraBreadcrumbItems = pathSnippets.map((_, index) => {const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;@@ -48,6 +50,6 @@ const ShowBreadcrumbs = withRouter((props) => {<Breadcrumb>{breadcrumbItems}</Breadcrumb></BreadCrumbWrapper>);-});+};export default ShowBreadcrumbs;diff --git a/frontend/src/modules/Nav/TopNav/index.tsx b/frontend/src/modules/Nav/TopNav/index.tsxindex 12d2381201..e9f2ba6c33 100644--- a/frontend/src/modules/Nav/TopNav/index.tsx+++ b/frontend/src/modules/Nav/TopNav/index.tsx@@ -1,14 +1,12 @@-import { Col,Row } from 'antd';+import { Col, Row } from 'antd';import ROUTES from 'constants/routes';+import history from 'lib/history';import React from 'react';-import { useHistory } from 'react-router-dom';import DateTimeSelector from './DateTimeSelector';import ShowBreadcrumbs from './ShowBreadcrumbs';-const TopNav = () => {- const history = useHistory();-+const TopNav = (): JSX.Element | null => {if (history.location.pathname === ROUTES.SIGN_UP) {return null;}diff --git a/frontend/src/modules/RouteProvider.tsx b/frontend/src/modules/RouteProvider.tsxindex d1a9582394..eff5595614 100644--- a/frontend/src/modules/RouteProvider.tsx+++ b/frontend/src/modules/RouteProvider.tsx@@ -1,5 +1,5 @@import ROUTES from 'constants/routes';-import React, { createContext, Dispatch,ReactNode, useContext } from 'react';+import React, { createContext, Dispatch, ReactNode, useContext } from 'react';type State = {[key: string]: {diff --git a/frontend/src/modules/Servicemap/ServiceMap.tsx b/frontend/src/modules/Servicemap/ServiceMap.tsxindex bb3f35d613..f4f4f2adca 100644--- a/frontend/src/modules/Servicemap/ServiceMap.tsx+++ b/frontend/src/modules/Servicemap/ServiceMap.tsx@@ -10,7 +10,7 @@ import {GlobalTime,serviceMapStore,} from 'store/actions';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';import styled from 'styled-components';import SelectService from './SelectService';@@ -139,7 +139,7 @@ const ServiceMap = (props: ServiceMapProps) => {};const mapStateToProps = (- state: StoreState,+ state: AppState,): {serviceMap: serviceMapStore;globalTime: GlobalTime;diff --git a/frontend/src/modules/Servicemap/utils.ts b/frontend/src/modules/Servicemap/utils.tsindex aca99877f0..b6219fa0b9 100644--- a/frontend/src/modules/Servicemap/utils.ts+++ b/frontend/src/modules/Servicemap/utils.ts@@ -1,5 +1,5 @@-import { cloneDeep, find,maxBy, uniq, uniqBy } from 'lodash';-import { serviceMapStore } from 'Src/store/actions';+import { cloneDeep, find, maxBy, uniq, uniqBy } from 'lodash';+import { serviceMapStore } from 'store/actions';import { graphDataType } from './ServiceMap';diff --git a/frontend/src/modules/Settings/settingsPage.tsx b/frontend/src/modules/Settings/settingsPage.tsxindex 5b68aeb2a2..a2abe789fd 100644--- a/frontend/src/modules/Settings/settingsPage.tsx+++ b/frontend/src/modules/Settings/settingsPage.tsx@@ -2,7 +2,7 @@ import { Form, Input, Space } from 'antd';import { Alert } from 'antd';import React, { useEffect, useState } from 'react';import { connect } from 'react-redux';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';interface SettingsPageProps {}@@ -48,7 +48,7 @@ const SettingsPage = (props: SettingsPageProps) => {);};-const mapStateToProps = (state: StoreState): {} => {+const mapStateToProps = (state: AppState): {} => {return {};};diff --git a/frontend/src/modules/Traces/FilterStateDisplay.tsx b/frontend/src/modules/Traces/FilterStateDisplay.tsxindex e4504ed703..37b747a11b 100644--- a/frontend/src/modules/Traces/FilterStateDisplay.tsx+++ b/frontend/src/modules/Traces/FilterStateDisplay.tsx@@ -2,7 +2,7 @@ import { Card, Tag as AntTag } from 'antd';import React from 'react';import { connect } from 'react-redux';import { TagItem, TraceFilters, updateTraceFilters } from 'store/actions';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';import styled from 'styled-components';const Tag = styled(AntTag)`@@ -14,28 +14,34 @@ const Tag = styled(AntTag)`interface FilterStateDisplayProps {traceFilters: TraceFilters;- updateTraceFilters: Function;+ updateTraceFilters: (props: TraceFilters) => void;}-const _FilterStateDisplay = (props: FilterStateDisplayProps) => {- function handleCloseTag(value: string) {- if (value === 'service')- props.updateTraceFilters({ ...props.traceFilters, service: '' });- if (value === 'operation')- props.updateTraceFilters({ ...props.traceFilters, operation: '' });- if (value === 'maxLatency')- props.updateTraceFilters({- ...props.traceFilters,- latency: { max: '', min: props.traceFilters.latency?.min },+const _FilterStateDisplay = (props: FilterStateDisplayProps): JSX.Element => {+ const { traceFilters, updateTraceFilters } = props;++ function handleCloseTag(value: string): void {+ if (value === 'service') {+ updateTraceFilters({ ...traceFilters, service: '' });+ }+ if (value === 'operation') {+ updateTraceFilters({ ...traceFilters, operation: '' });+ }+ if (value === 'maxLatency') {+ updateTraceFilters({+ ...traceFilters,+ latency: { max: '', min: traceFilters.latency?.min || '' },});- if (value === 'minLatency')- props.updateTraceFilters({- ...props.traceFilters,- latency: { min: '', max: props.traceFilters.latency?.max },+ }+ if (value === 'minLatency') {+ updateTraceFilters({+ ...traceFilters,+ latency: { min: '', max: traceFilters.latency?.max || '' },});+ }}- function handleCloseTagElement(item: TagItem) {+ function handleCloseTagElement(item: TagItem): void {props.updateTraceFilters({...props.traceFilters,tags: props.traceFilters.tags?.filter((elem) => elem !== item),@@ -48,73 +54,73 @@ const _FilterStateDisplay = (props: FilterStateDisplayProps) => {>{props.traceFilters.service === '' ||props.traceFilters.operation === undefined ? null : (- <Tag- style={{ fontSize: 14, padding: 8 }}- closable- onClose={(e) => {- handleCloseTag('service');- }}- >+ <Tag+ style={{ fontSize: 14, padding: 8 }}+ closable+ onClose={(): void => {+ handleCloseTag('service');+ }}+ >service:{props.traceFilters.service}- </Tag>- )}+ </Tag>+ )}{props.traceFilters.operation === '' ||props.traceFilters.operation === undefined ? null : (- <Tag- style={{ fontSize: 14, padding: 8 }}- closable- onClose={(e) => {- handleCloseTag('operation');- }}- >+ <Tag+ style={{ fontSize: 14, padding: 8 }}+ closable+ onClose={(): void => {+ handleCloseTag('operation');+ }}+ >operation:{props.traceFilters.operation}- </Tag>- )}+ </Tag>+ )}{props.traceFilters.latency === undefined ||props.traceFilters.latency?.min === '' ? null : (- <Tag- style={{ fontSize: 14, padding: 8 }}- closable- onClose={(e) => {- handleCloseTag('minLatency');- }}- >+ <Tag+ style={{ fontSize: 14, padding: 8 }}+ closable+ onClose={(): void => {+ handleCloseTag('minLatency');+ }}+ >minLatency:- {(parseInt(props.traceFilters.latency!.min) / 1000000).toString()}ms- </Tag>- )}+ {(parseInt(traceFilters?.latency?.min || '0') / 1000000).toString()}ms+ </Tag>+ )}{props.traceFilters.latency === undefined ||props.traceFilters.latency?.max === '' ? null : (- <Tag- style={{ fontSize: 14, padding: 8 }}- closable- onClose={(e) => {- handleCloseTag('maxLatency');- }}- >+ <Tag+ style={{ fontSize: 14, padding: 8 }}+ closable+ onClose={(): void => {+ handleCloseTag('maxLatency');+ }}+ >maxLatency:- {(parseInt(props.traceFilters.latency!.max) / 1000000).toString()}ms- </Tag>- )}+ {(parseInt(traceFilters?.latency?.max || '0') / 1000000).toString()}ms+ </Tag>+ )}{props.traceFilters.tags === undefined? null: props.traceFilters.tags.map((item) => (- <Tag- style={{ fontSize: 14, padding: 8 }}- closable- key={`${item.key}-${item.operator}-${item.value}`}- onClose={(e) => {- handleCloseTagElement(item);- }}- >- {item.key} {item.operator} {item.value}- </Tag>+ <Tag+ style={{ fontSize: 14, padding: 8 }}+ closable+ key={`${item.key}-${item.operator}-${item.value}`}+ onClose={(): void => {+ handleCloseTagElement(item);+ }}+ >+ {item.key} {item.operator} {item.value}+ </Tag>))}</Card>);};-const mapStateToProps = (state: StoreState): { traceFilters: TraceFilters } => {+const mapStateToProps = (state: AppState): { traceFilters: TraceFilters } => {return { traceFilters: state.traceFilters };};diff --git a/frontend/src/modules/Traces/LatencyModalForm.tsx b/frontend/src/modules/Traces/LatencyModalForm.tsxindex daafc3d013..66fa3b9291 100644--- a/frontend/src/modules/Traces/LatencyModalForm.tsx+++ b/frontend/src/modules/Traces/LatencyModalForm.tsx@@ -58,7 +58,7 @@ const LatencyModalForm: React.FC<LatencyModalFormProps> = ({onCreate(values); // giving error for values}).catch((info) => {- console.log('Validate Failed:', info);+ // console.log('Validate Failed:', info);});}}>diff --git a/frontend/src/modules/Traces/TraceCustomVisualizations.tsx b/frontend/src/modules/Traces/TraceCustomVisualizations.tsxindex 5c6695b1f2..58c14b4598 100644--- a/frontend/src/modules/Traces/TraceCustomVisualizations.tsx+++ b/frontend/src/modules/Traces/TraceCustomVisualizations.tsx@@ -1,13 +1,20 @@-import { Card, Form,Select, Space } from 'antd';-import GenericVisualizations from 'modules/Metrics/GenericVisualization';+import { Form, Select, Space } from 'antd';+import Graph from 'components/Graph';import { useRoute } from 'modules/RouteProvider';-import React, { useEffect,useState } from 'react';+import React, { useEffect, useState } from 'react';import { connect } from 'react-redux';import { GlobalTime, TraceFilters } from 'store/actions';import { getFilteredTraceMetrics } from 'store/actions/MetricsActions';import { customMetricsItem } from 'store/actions/MetricsActions';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';const { Option } = Select;+import { colors } from 'lib/getRandomColor';++import {+ Card,+ CustomGraphContainer,+ CustomVisualizationsTitle,+} from './styles';const entity = [{@@ -69,36 +76,43 @@ const aggregation_options = [interface TraceCustomVisualizationsProps {filteredTraceMetrics: customMetricsItem[];globalTime: GlobalTime;- getFilteredTraceMetrics: Function;+ getFilteredTraceMetrics: (value: string, time: GlobalTime) => void;traceFilters: TraceFilters;}-const _TraceCustomVisualizations = (props: TraceCustomVisualizationsProps) => {+const _TraceCustomVisualizations = (+ props: TraceCustomVisualizationsProps,+): JSX.Element => {const [selectedEntity, setSelectedEntity] = useState('calls');const [selectedAggOption, setSelectedAggOption] = useState('count');const { state } = useRoute();const [form] = Form.useForm();const selectedStep = '60';+ const {+ filteredTraceMetrics,+ getFilteredTraceMetrics,+ globalTime,+ traceFilters,+ } = props;// Step should be multiples of 60, 60 -> 1 min-useEffect(() => {let request_string ='service=' +- props.traceFilters.service ++ traceFilters.service +'&operation=' +- props.traceFilters.operation ++ traceFilters.operation +'&maxDuration=' +- props.traceFilters.latency?.max ++ traceFilters.latency?.max +'&minDuration=' +- props.traceFilters.latency?.min ++ traceFilters.latency?.min +'&kind=' +- props.traceFilters.kind;- if (props.traceFilters.tags)+ traceFilters.kind;+ if (traceFilters.tags)request_string =request_string +'&tags=' +- encodeURIComponent(JSON.stringify(props.traceFilters.tags));+ encodeURIComponent(JSON.stringify(traceFilters.tags));if (selectedEntity)request_string =request_string + '&dimension=' + selectedEntity.toLowerCase();@@ -107,8 +121,8 @@ const _TraceCustomVisualizations = (props: TraceCustomVisualizationsProps) => {request_string + '&aggregation_option=' + selectedAggOption.toLowerCase();if (selectedStep) request_string = request_string + '&step=' + selectedStep;const plusMinus15 = {- minTime: props.globalTime.minTime - 15 * 60 * 1000000000,- maxTime: props.globalTime.maxTime + 15 * 60 * 1000000000,+ minTime: globalTime.minTime - 15 * 60 * 1000000000,+ maxTime: globalTime.maxTime + 15 * 60 * 1000000000,};/*@@ -116,14 +130,21 @@ const _TraceCustomVisualizations = (props: TraceCustomVisualizationsProps) => {Check this issue: https://github.com/SigNoz/signoz/issues/110*/if (state.TRACES.isLoaded) {- props.getFilteredTraceMetrics(request_string, plusMinus15);+ getFilteredTraceMetrics(request_string, plusMinus15);}- }, [selectedEntity, selectedAggOption, props.traceFilters, props.globalTime]);+ }, [+ selectedEntity,+ selectedAggOption,+ traceFilters,+ globalTime,+ getFilteredTraceMetrics,+ state.TRACES.isLoaded,+ ]);//Custom metrics API called if time, tracefilters, selected entity or agg option changes// PNOTE - Can also use 'coordinate' option in antd Select for implementing this - https://ant.design/components/select/- const handleFormValuesChange = (changedValues: any) => {+ const handleFormValuesChange = (changedValues: any): void => {const formFieldName = Object.keys(changedValues)[0];if (formFieldName === 'entity') {const temp_entity = aggregation_options.filter(@@ -150,7 +171,7 @@ const _TraceCustomVisualizations = (props: TraceCustomVisualizationsProps) => {return (<Card>- <div>Custom Visualizations</div>+ <CustomVisualizationsTitle>Custom Visualizations</CustomVisualizationsTitle><Formform={form}onValuesChange={handleFormValuesChange}@@ -211,14 +232,27 @@ const _TraceCustomVisualizations = (props: TraceCustomVisualizationsProps) => {</Space></Form>- <GenericVisualizations chartType="line" data={props.filteredTraceMetrics} />- {/* This component should take bar or line as an input */}+ <CustomGraphContainer>+ <Graph+ type="line"+ data={{+ labels: filteredTraceMetrics.map((s) => new Date(s.timestamp / 1000000)),+ datasets: [+ {+ data: filteredTraceMetrics.map((e) => e.value),+ borderColor: colors[0],+ },+ ],+ }}+ xAxisType="timeseries"+ />+ </CustomGraphContainer></Card>);};const mapStateToProps = (- state: StoreState,+ state: AppState,): {filteredTraceMetrics: customMetricsItem[];globalTime: GlobalTime;diff --git a/frontend/src/modules/Traces/TraceDetail.tsx b/frontend/src/modules/Traces/TraceDetail.tsxindex ed279899ef..ede374bae8 100644--- a/frontend/src/modules/Traces/TraceDetail.tsx+++ b/frontend/src/modules/Traces/TraceDetail.tsx@@ -4,13 +4,13 @@ import { TraceCustomVisualizations } from './TraceCustomVisualizations';import { TraceFilter } from './TraceFilter';import { TraceList } from './TraceList';-const TraceDetail = () => {+const TraceDetail = (): JSX.Element => {return (- <div>+ <><TraceFilter /><TraceCustomVisualizations /><TraceList />- </div>+ </>);};diff --git a/frontend/src/modules/Traces/TraceFilter.tsx b/frontend/src/modules/Traces/TraceFilter.tsxindex 9314177508..75ddf6bbf4 100644--- a/frontend/src/modules/Traces/TraceFilter.tsx+++ b/frontend/src/modules/Traces/TraceFilter.tsx@@ -1,10 +1,17 @@-import { AutoComplete,Button, Form, Input, Select } from 'antd';+import { AutoComplete, Button, Form, Input, Select, Typography } from 'antd';import FormItem from 'antd/lib/form/FormItem';import { Store } from 'antd/lib/form/interface';-import api, { apiV1 } from 'api';+import api from 'api';import { METRICS_PAGE_QUERY_PARAM } from 'constants/query';+import useMountedState from 'hooks/useMountedState';import { useRoute } from 'modules/RouteProvider';-import React, { useEffect, useState } from 'react';+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';import { connect } from 'react-redux';import { useLocation } from 'react-router-dom';import {@@ -13,7 +20,7 @@ import {TraceFilters,updateTraceFilters,} from 'store/actions';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';import styled from 'styled-components';import { FilterStateDisplay } from './FilterStateDisplay';@@ -30,8 +37,8 @@ const InfoWrapper = styled.div`interface TraceFilterProps {traceFilters: TraceFilters;globalTime: GlobalTime;- updateTraceFilters: Function;- fetchTraces: Function;+ updateTraceFilters: (props: TraceFilters) => void;+ fetchTraces: (globalTime: GlobalTime, filter_params: string) => void;}interface TagKeyOptionItem {@@ -44,13 +51,48 @@ interface ISpanKind {value: string;}-const _TraceFilter = (props: TraceFilterProps) => {+const _TraceFilter = (props: TraceFilterProps): JSX.Element => {const [serviceList, setServiceList] = useState<string[]>([]);const [operationList, setOperationsList] = useState<string[]>([]);const [tagKeyOptions, setTagKeyOptions] = useState<TagKeyOptionItem[]>([]);const location = useLocation();- const urlParams = new URLSearchParams(location.search.split('?')[1]);+ const urlParams = useMemo(() => {+ return new URLSearchParams(location.search.split('?')[1]);+ }, [location.search]);+ const isMount = useMountedState();++ const isMounted = isMount();+const { state } = useRoute();+ const { updateTraceFilters, traceFilters, globalTime, fetchTraces } = props;+ const [modalVisible, setModalVisible] = useState(false);++ const [latencyFilterValues, setLatencyFilterValues] = useState<{+ min: string;+ max: string;+ }>({+ min: '100',+ max: '500',+ });++ const [form] = Form.useForm();++ const [form_basefilter] = Form.useForm();++ const handleChangeOperation = useCallback(+ (value: string) => {+ updateTraceFilters({ ...traceFilters, operation: value });+ },+ [traceFilters, updateTraceFilters],+ );++ const handleChangeService = useCallback(+ (value: string) => {+ populateData(value);+ updateTraceFilters({ ...traceFilters, service: value });+ },+ [traceFilters, updateTraceFilters],+ );const spanKindList: ISpanKind[] = [{@@ -63,6 +105,30 @@ const _TraceFilter = (props: TraceFilterProps) => {},];+ const handleApplyFilterForm = useCallback(+ (values: any): void => {+ // setTagKeyValueApplied((tagKeyValueApplied) => [+ // ...tagKeyValueApplied,+ // 'service eq' + values.service,+ // 'operation eq ' + values.operation,+ // 'maxduration eq ' ++ // (parseInt(latencyFilterValues.max) / 1000000).toString(),+ // 'minduration eq ' ++ // (parseInt(latencyFilterValues.min) / 1000000).toString(),+ // ]);+ updateTraceFilters({+ service: values.service,+ operation: values.operation,+ latency: {+ max: '',+ min: '',+ },+ kind: values.kind,+ });+ },+ [updateTraceFilters],+ );+useEffect(() => {handleApplyFilterForm({service: '',@@ -71,180 +137,196 @@ const _TraceFilter = (props: TraceFilterProps) => {latency: { min: '', max: '' },kind: '',});- }, []);+ }, [handleApplyFilterForm]);++ const onTagFormSubmit = useCallback(+ (values) => {+ if (traceFilters.tags) {+ // If there are existing tag filters present+ updateTraceFilters({+ service: traceFilters.service,+ operation: traceFilters.operation,+ latency: traceFilters.latency,+ tags: [+ ...traceFilters.tags,+ {+ key: values.tag_key,+ value: values.tag_value,+ operator: values.operator,+ },+ ],+ kind: traceFilters.kind,+ });+ } else {+ updateTraceFilters({+ service: traceFilters.service,+ operation: traceFilters.operation,+ latency: traceFilters.latency,+ tags: [+ {+ key: values.tag_key,+ value: values.tag_value,+ operator: values.operator,+ },+ ],+ kind: traceFilters.kind,+ });+ }++ form.resetFields();+ },+ [form, traceFilters, updateTraceFilters],+ );++ const counter = useRef(0);useEffect(() => {- api- .get<string[]>(`${apiV1}/services/list`)- .then((response) => {- setServiceList(response.data);- })- .then(() => {- /*- Todo- revisit this flow post refactoring store- */- const operationName = urlParams.get(METRICS_PAGE_QUERY_PARAM.operation);- const serviceName = urlParams.get(METRICS_PAGE_QUERY_PARAM.service);- const errorTag = urlParams.get(METRICS_PAGE_QUERY_PARAM.error);- if (operationName && serviceName) {- props.updateTraceFilters({- ...props.traceFilters,- operation: operationName,- service: serviceName,- kind: '',- });- populateData(serviceName);- } else if (serviceName && errorTag) {- props.updateTraceFilters({- ...props.traceFilters,- service: serviceName,- tags: [- {- key: METRICS_PAGE_QUERY_PARAM.error,- value: errorTag,- operator: 'equals',- },- ],- kind: '',- });- } else {- if (operationName) {- handleChangeOperation(operationName);- }- if (serviceName) {- handleChangeService(serviceName);- }- if (errorTag) {- onTagFormSubmit({- tag_key: METRICS_PAGE_QUERY_PARAM.error,- tag_value: errorTag,- operator: 'equals',+ if (isMounted && counter.current === 0) {+ counter.current = 1;+ api+ .get<string[]>(`/services/list`)+ .then((response) => {+ setServiceList(response.data);+ })+ .then(() => {+ const operationName = urlParams.get(METRICS_PAGE_QUERY_PARAM.operation);+ const serviceName = urlParams.get(METRICS_PAGE_QUERY_PARAM.service);+ const errorTag = urlParams.get(METRICS_PAGE_QUERY_PARAM.error);+ if (operationName && serviceName) {+ updateTraceFilters({+ ...traceFilters,+ operation: operationName,+ service: serviceName,+ kind: '',+ });+ populateData(serviceName);+ } else if (serviceName && errorTag) {+ updateTraceFilters({+ ...traceFilters,+ service: serviceName,+ tags: [+ {+ key: METRICS_PAGE_QUERY_PARAM.error,+ value: errorTag,+ operator: 'equals',+ },+ ],+ kind: '',});+ } else {+ if (operationName) {+ handleChangeOperation(operationName);+ }+ if (serviceName) {+ handleChangeService(serviceName);+ }+ if (errorTag) {+ onTagFormSubmit({+ tag_key: METRICS_PAGE_QUERY_PARAM.error,+ tag_value: errorTag,+ operator: 'equals',+ });+ }}- }- });- }, []);+ });+ }+ }, [+ handleChangeOperation,+ onTagFormSubmit,+ handleChangeService,+ traceFilters,+ urlParams,+ updateTraceFilters,+ isMounted,+ ]);useEffect(() => {let request_string ='service=' +- props.traceFilters.service ++ traceFilters.service +'&operation=' +- props.traceFilters.operation ++ traceFilters.operation +'&maxDuration=' +- props.traceFilters.latency?.max ++ traceFilters.latency?.max +'&minDuration=' +- props.traceFilters.latency?.min ++ traceFilters.latency?.min +'&kind=' +- props.traceFilters.kind;- if (props.traceFilters.tags)+ traceFilters.kind;+ if (traceFilters.tags)request_string =request_string +'&tags=' +- encodeURIComponent(JSON.stringify(props.traceFilters.tags));+ encodeURIComponent(JSON.stringify(traceFilters.tags));/*Call the apis only when the route is loaded.Check this issue: https://github.com/SigNoz/signoz/issues/110*/if (state.TRACES.isLoaded) {- props.fetchTraces(props.globalTime, request_string);+ fetchTraces(globalTime, request_string);}- }, [props.traceFilters, props.globalTime]);+ }, [globalTime, traceFilters, fetchTraces, state]);useEffect(() => {let latencyButtonText = 'Latency';- if (- props.traceFilters.latency?.min === '' &&- props.traceFilters.latency?.max !== ''- )+ if (traceFilters.latency?.min === '' && traceFilters.latency?.max !== '')latencyButtonText ='Latency<' +- (parseInt(props.traceFilters.latency?.max) / 1000000).toString() ++ (parseInt(traceFilters.latency?.max) / 1000000).toString() +'ms';- else if (- props.traceFilters.latency?.min !== '' &&- props.traceFilters.latency?.max === ''- )+ else if (traceFilters.latency?.min !== '' && traceFilters.latency?.max === '')latencyButtonText ='Latency>' +- (parseInt(props.traceFilters.latency?.min) / 1000000).toString() ++ (parseInt(traceFilters.latency?.min) / 1000000).toString() +'ms';else if (- props.traceFilters.latency !== undefined &&- props.traceFilters.latency?.min !== '' &&- props.traceFilters.latency?.max !== ''+ traceFilters.latency !== undefined &&+ traceFilters.latency?.min !== '' &&+ traceFilters.latency?.max !== '')latencyButtonText =- (parseInt(props.traceFilters.latency.min) / 1000000).toString() ++ (parseInt(traceFilters.latency.min) / 1000000).toString() +'ms <Latency<' +- (parseInt(props.traceFilters.latency.max) / 1000000).toString() ++ (parseInt(traceFilters.latency.max) / 1000000).toString() +'ms';form_basefilter.setFieldsValue({ latency: latencyButtonText });- }, [props.traceFilters.latency]);+ }, [traceFilters.latency, form_basefilter]);useEffect(() => {- form_basefilter.setFieldsValue({ service: props.traceFilters.service });- }, [props.traceFilters.service]);+ form_basefilter.setFieldsValue({ service: traceFilters.service });+ }, [traceFilters.service, form_basefilter]);useEffect(() => {- form_basefilter.setFieldsValue({ operation: props.traceFilters.operation });- }, [props.traceFilters.operation]);+ form_basefilter.setFieldsValue({ operation: traceFilters.operation });+ }, [traceFilters.operation, form_basefilter]);useEffect(() => {- form_basefilter.setFieldsValue({ kind: props.traceFilters.kind });- }, [props.traceFilters.kind]);-- const [modalVisible, setModalVisible] = useState(false);- const [loading] = useState(false);-- const [tagKeyValueApplied, setTagKeyValueApplied] = useState(['']);- const [latencyFilterValues, setLatencyFilterValues] = useState<{- min: string;- max: string;- }>({- min: '100',- max: '500',- });-- const [form] = Form.useForm();-- const [form_basefilter] = Form.useForm();+ form_basefilter.setFieldsValue({ kind: traceFilters.kind });+ }, [traceFilters.kind, form_basefilter]);- function handleChangeOperation(value: string) {- props.updateTraceFilters({ ...props.traceFilters, operation: value });- }-- function populateData(value: string) {+ function populateData(value: string): void {const service_request = '/service/' + value + '/operations';- api.get<string[]>(apiV1 + service_request).then((response) => {+ api.get<string[]>(service_request).then((response) => {// form_basefilter.resetFields(['operation',])setOperationsList(response.data);});const tagkeyoptions_request = '/tags?service=' + value;- api- .get<TagKeyOptionItem[]>(apiV1 + tagkeyoptions_request)- .then((response) => {- setTagKeyOptions(response.data);- });- }- function handleChangeService(value: string) {- populateData(value);- props.updateTraceFilters({ ...props.traceFilters, service: value });+ api.get<TagKeyOptionItem[]>(tagkeyoptions_request).then((response) => {+ setTagKeyOptions(response.data);+ });}- const onLatencyButtonClick = () => {+ const onLatencyButtonClick = (): void => {setModalVisible(true);};- const onLatencyModalApply = (values: Store) => {+ const onLatencyModalApply = (values: Store): void => {setModalVisible(false);const { min, max } = values;- props.updateTraceFilters({- ...props.traceFilters,+ updateTraceFilters({+ ...traceFilters,latency: {min: min ? (parseInt(min) * 1000000).toString() : '',max: max ? (parseInt(max) * 1000000).toString() : '',@@ -254,57 +336,9 @@ const _TraceFilter = (props: TraceFilterProps) => {setLatencyFilterValues({ min, max });};- const onTagFormSubmit = (values: any) => {- const request_tags =- 'service=frontend&tags=' +- encodeURIComponent(- JSON.stringify([- {- key: values.tag_key,- value: values.tag_value,- operator: values.operator,- },- ]),- );-- if (props.traceFilters.tags) {- // If there are existing tag filters present- props.updateTraceFilters({- service: props.traceFilters.service,- operation: props.traceFilters.operation,- latency: props.traceFilters.latency,- tags: [- ...props.traceFilters.tags,- {- key: values.tag_key,- value: values.tag_value,- operator: values.operator,- },- ],- kind: props.traceFilters.kind,- });- } else {- props.updateTraceFilters({- service: props.traceFilters.service,- operation: props.traceFilters.operation,- latency: props.traceFilters.latency,- tags: [- {- key: values.tag_key,- value: values.tag_value,- operator: values.operator,- },- ],- kind: props.traceFilters.kind,- });- }-- form.resetFields();- };-// For autocomplete//Setting value when autocomplete field is changed- const onChangeTagKey = (data: string) => {+ const onChangeTagKey = (data: string): void => {form.setFieldsValue({ tag_key: data });};@@ -318,55 +352,9 @@ const _TraceFilter = (props: TraceFilterProps) => {);}- // PNOTE - Remove any- const handleApplyFilterForm = (values: any) => {- let request_params = '';- if (- typeof values.service !== undefined &&- typeof values.operation !== undefined- ) {- request_params =- 'service=' + values.service + '&operation=' + values.operation;- } else if (- typeof values.service === undefined &&- typeof values.operation !== undefined- ) {- request_params = 'operation=' + values.operation;- } else if (- typeof values.service !== undefined &&- typeof values.operation === undefined- ) {- request_params = 'service=' + values.service;- }-- request_params =- request_params +- '&minDuration=' +- latencyFilterValues.min +- '&maxDuration=' +- latencyFilterValues.max;-- setTagKeyValueApplied((tagKeyValueApplied) => [- ...tagKeyValueApplied,- 'service eq' + values.service,- 'operation eq ' + values.operation,- 'maxduration eq ' + (parseInt(latencyFilterValues.max) / 1000000).toString(),- 'minduration eq ' + (parseInt(latencyFilterValues.min) / 1000000).toString(),- ]);- props.updateTraceFilters({- service: values.service,- operation: values.operation,- latency: {- max: '',- min: '',- },- kind: values.kind,- });- };-useEffect(() => {- return () => {- props.updateTraceFilters({+ return (): void => {+ updateTraceFilters({service: '',operation: '',tags: [],@@ -374,17 +362,15 @@ const _TraceFilter = (props: TraceFilterProps) => {kind: '',});};- }, []);+ }, [updateTraceFilters]);- const handleChangeSpanKind = (value = '') => {- props.updateTraceFilters({ ...props.traceFilters, kind: value });+ const handleChangeSpanKind = (value = ''): void => {+ updateTraceFilters({ ...traceFilters, kind: value });};return (<div>- <div>Filter Traces</div>- {/* <div>{JSON.stringify(props.traceFilters)}</div> */}-+ <Typography>Filter Traces</Typography><Formform={form_basefilter}layout="inline"@@ -401,7 +387,9 @@ const _TraceFilter = (props: TraceFilterProps) => {allowClear>{serviceList.map((s) => (- <Option value={s}>{s}</Option>+ <Option key={s} value={s}>+ {s}+ </Option>))}</Select></FormItem>@@ -415,7 +403,9 @@ const _TraceFilter = (props: TraceFilterProps) => {allowClear>{operationList.map((item) => (- <Option value={item}>{item}</Option>+ <Option key={item} value={item}>+ {item}+ </Option>))}</Select></FormItem>@@ -443,10 +433,6 @@ const _TraceFilter = (props: TraceFilterProps) => {))}</Select></FormItem>-- {/* <FormItem>- <Button type="primary" htmlType="submit">Apply Filters</Button>- </FormItem> */}</Form><FilterStateDisplay />@@ -468,11 +454,9 @@ const _TraceFilter = (props: TraceFilterProps) => {return { value: s.tagKeys };})}style={{ width: 200, textAlign: 'center' }}- // onSelect={onSelect}- // onSearch={onSearch}onChange={onChangeTagKey}- filterOption={(inputValue, option) =>- option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1+ filterOption={(inputValue, option): boolean =>+ option?.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}placeholder="Tag Key"/>@@ -505,7 +489,7 @@ const _TraceFilter = (props: TraceFilterProps) => {<LatencyModalFormonCreate={onLatencyModalApply}latencyFilterValues={latencyFilterValues}- onCancel={() => {+ onCancel={(): void => {setModalVisible(false);}}/>@@ -515,7 +499,7 @@ const _TraceFilter = (props: TraceFilterProps) => {};const mapStateToProps = (- state: StoreState,+ state: AppState,): { traceFilters: TraceFilters; globalTime: GlobalTime } => {return { traceFilters: state.traceFilters, globalTime: state.globalTime };};diff --git a/frontend/src/modules/Traces/TraceGanttChart/TraceGanttChart.tsx b/frontend/src/modules/Traces/TraceGanttChart/TraceGanttChart.tsxindex 00163ce14b..fe6e98611d 100644--- a/frontend/src/modules/Traces/TraceGanttChart/TraceGanttChart.tsx+++ b/frontend/src/modules/Traces/TraceGanttChart/TraceGanttChart.tsx@@ -1,7 +1,7 @@import './TraceGanttChart.css';-import { Button, Col,Progress, Row, Table, Tabs } from 'antd';-import { has,isEmpty, max } from 'lodash-es';+import { Button, Col, Progress, Row, Table, Tabs } from 'antd';+import { has, isEmpty, max } from 'lodash-es';import traverseTreeData from 'modules/Traces/TraceGanttChart/TraceGanttChartHelpers';import React, { useEffect, useRef, useState } from 'react';import { pushDStree } from 'store/actions';diff --git a/frontend/src/modules/Traces/TraceGanttChart/index.js b/frontend/src/modules/Traces/TraceGanttChart/index.tsxsimilarity index 100%rename from frontend/src/modules/Traces/TraceGanttChart/index.jsrename to frontend/src/modules/Traces/TraceGanttChart/index.tsxdiff --git a/frontend/src/modules/Traces/TraceGraph.tsx b/frontend/src/modules/Traces/TraceGraph.tsxindex e08e8a67a1..6840fc8322 100644--- a/frontend/src/modules/Traces/TraceGraph.tsx+++ b/frontend/src/modules/Traces/TraceGraph.tsx@@ -1,19 +1,19 @@import './TraceGraph.css';-import { Affix,Card, Col, Row, Space } from 'antd';+import { Affix, Card, Col, Row, Space } from 'antd';import * as d3 from 'd3';import { flamegraph } from 'd3-flame-graph';import * as d3Tip from 'd3-tip';import { isEmpty, sortBy } from 'lodash-es';import React, { useEffect, useState } from 'react';import { connect } from 'react-redux';-import { useLocation,useParams } from 'react-router-dom';+import { useLocation, useParams } from 'react-router-dom';import {fetchTraceItem,pushDStree,spansWSameTraceIDResponse,} from 'store/actions';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';import styled from 'styled-components';import { spanToTreeUtil } from 'utils/spanToTree';@@ -204,7 +204,7 @@ const _TraceGraph = (props: TraceGraphProps) => {};const mapStateToProps = (- state: StoreState,+ state: AppState,): { traceItem: spansWSameTraceIDResponse } => {return { traceItem: state.traceItem };};diff --git a/frontend/src/modules/Traces/TraceGraphColumn.tsx b/frontend/src/modules/Traces/TraceGraphColumn.tsxindex 8b6b0ec75c..c32524580c 100644--- a/frontend/src/modules/Traces/TraceGraphColumn.tsx+++ b/frontend/src/modules/Traces/TraceGraphColumn.tsx@@ -1,8 +1,8 @@import { Table } from 'antd';import React from 'react';import { connect } from 'react-redux';-import { pushDStree,traceResponseNew } from 'store/actions';-import { StoreState } from 'store/reducers';+import { pushDStree, traceResponseNew } from 'store/actions';+import { AppState } from 'store/reducers';interface TraceGraphColumnProps {traces: traceResponseNew;@@ -69,7 +69,7 @@ const _TraceGraphColumn = (props: TraceGraphColumnProps) => {);};-const mapStateToProps = (state: StoreState): { traces: traceResponseNew } => {+const mapStateToProps = (state: AppState): { traces: traceResponseNew } => {return { traces: state.traces };};diff --git a/frontend/src/modules/Traces/TraceList.tsx b/frontend/src/modules/Traces/TraceList.tsxindex 25ec660450..c7329ed408 100644--- a/frontend/src/modules/Traces/TraceList.tsx+++ b/frontend/src/modules/Traces/TraceList.tsx@@ -4,8 +4,8 @@ import moment from 'moment';import React, { useEffect } from 'react';import { connect } from 'react-redux';import { useHistory } from 'react-router-dom';-import { fetchTraces, pushDStree,traceResponseNew } from 'store/actions';-import { StoreState } from 'store/reducers';+import { fetchTraces, pushDStree, traceResponseNew } from 'store/actions';+import { AppState } from 'store/reducers';import styled from 'styled-components';import { isOnboardingSkipped } from 'utils/app';@@ -151,7 +151,7 @@ const _TraceList = (props: TraceListProps) => {);};-const mapStateToProps = (state: StoreState): { traces: traceResponseNew } => {+const mapStateToProps = (state: AppState): { traces: traceResponseNew } => {return { traces: state.traces };};diff --git a/frontend/src/modules/Traces/styles.ts b/frontend/src/modules/Traces/styles.tsnew file mode 100644index 0000000000..a16e487b3d--- /dev/null+++ b/frontend/src/modules/Traces/styles.ts@@ -0,0 +1,16 @@+import { Card as CardComponent, Typography } from 'antd';+import styled from 'styled-components';++export const CustomGraphContainer = styled.div`+ min-height: 30vh;+`;++export const Card = styled(CardComponent)`+ .ant-card-body {+ padding-bottom: 0;+ }+`;++export const CustomVisualizationsTitle = styled(Typography)`+ margin-bottom: 1rem;+`;diff --git a/frontend/src/modules/Usage/UsageExplorer.tsx b/frontend/src/modules/Usage/UsageExplorer.tsxindex b78f720890..0259b96366 100644--- a/frontend/src/modules/Usage/UsageExplorer.tsx+++ b/frontend/src/modules/Usage/UsageExplorer.tsx@@ -1,8 +1,9 @@-import { Card, Select, Space } from 'antd';+import { Select, Space } from 'antd';+// import { Bar } from 'react-chartjs-2';+import Graph from 'components/Graph';import { useRoute } from 'modules/RouteProvider';import moment from 'moment';import React, { useEffect, useState } from 'react';-import { Bar } from 'react-chartjs-2';import { connect } from 'react-redux';import {getServicesList,@@ -11,9 +12,10 @@ import {usageDataItem,} from 'store/actions';import { servicesListItem } from 'store/actions/MetricsActions';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';import { isOnboardingSkipped } from 'utils/app';const { Option } = Select;+import { Card } from './styles';interface UsageExplorerProps {usageData: usageDataItem[];@@ -188,15 +190,15 @@ const _UsageExplorer = (props: UsageExplorerProps) => {)}</Space>- <Card style={{ width: '90%', margin: 20 }} bodyStyle={{ padding: 20 }}>- <Bar data={data} options={options} />+ <Card>+ <Graph data={data} type="bar" /></Card></React.Fragment>);};const mapStateToProps = (- state: StoreState,+ state: AppState,): {totalCount: number;globalTime: GlobalTime;diff --git a/frontend/src/modules/Usage/styles.ts b/frontend/src/modules/Usage/styles.tsnew file mode 100644index 0000000000..26efebc856--- /dev/null+++ b/frontend/src/modules/Usage/styles.ts@@ -0,0 +1,14 @@+import { Card as CardComponent } from 'antd';+import styled from 'styled-components';++export const Card = styled(CardComponent)`+ &&& {+ width: 90%;+ margin-top: 2rem;+ }++ .ant-card-body {+ height: 100%;+ min-height: 70vh;+ }+`;diff --git a/frontend/src/modules/add-instrumentation/instrumentationPage.tsx b/frontend/src/modules/add-instrumentation/instrumentationPage.tsxindex fe12848d8a..b6e447c3be 100644--- a/frontend/src/modules/add-instrumentation/instrumentationPage.tsx+++ b/frontend/src/modules/add-instrumentation/instrumentationPage.tsx@@ -2,14 +2,14 @@ import { Space } from 'antd';import React from 'react';import { useThemeSwitcher } from 'react-css-theme-switcher';import { connect } from 'react-redux';-import { StoreState } from 'store/reducers';+import { AppState } from 'store/reducers';import styled from 'styled-components';const InstrumentCard = styled.div<{currentThemeStatus: string | undefined;}>`border-radius: 4px;- background: ${({ currentThemeStatus }) =>+ background: ${({ currentThemeStatus }): string =>currentThemeStatus === 'dark' ? '#313131' : '#ddd'};padding: 33px 23px;max-width: 800px;@@ -34,7 +34,8 @@ const InstrumentationPage = (props: InstrumentationPageProps) => {docs -<ahref={'https://signoz.io/docs/instrumentation/overview'}- target="_blank" rel="noreferrer"+ target="_blank"+ rel="noreferrer">{' '}https://signoz.io/docs/instrumentation/overview@@ -45,7 +46,8 @@ const InstrumentationPage = (props: InstrumentationPageProps) => {href={'https://signoz-community.slack.com/join/shared_invite/zt-lrjknbbp-J_mI13rlw8pGF4EWBnorJA'}- target="_blank" rel="noreferrer"+ target="_blank"+ rel="noreferrer">slack community</a>{' '}@@ -59,7 +61,7 @@ const InstrumentationPage = (props: InstrumentationPageProps) => {);};-const mapStateToProps = (state: StoreState): {} => {+const mapStateToProps = (state: AppState): {} => {return {};};diff --git a/frontend/src/pages/Dashboard/index.tsx b/frontend/src/pages/Dashboard/index.tsxnew file mode 100644index 0000000000..b3a8e72530--- /dev/null+++ b/frontend/src/pages/Dashboard/index.tsx@@ -0,0 +1,40 @@+import Spinner from 'components/Spinner';+import ListOfAllDashboard from 'container/ListOfDashboard';+import React, { useEffect } from 'react';+import { connect, useSelector } from 'react-redux';+import { bindActionCreators } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { GetAllDashboards } from 'store/actions';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import DashboardReducer from 'types/reducer/dashboards';++const Dashboard = ({ getAllDashboards }: DashboardProps): JSX.Element => {+ const { loading } = useSelector<AppState, DashboardReducer>(+ (state) => state.dashboards,+ );++ useEffect(() => {+ getAllDashboards();+ }, [getAllDashboards]);++ if (loading) {+ return <Spinner size="large" tip="Loading.." />;+ }++ return <ListOfAllDashboard />;+};++interface DispatchProps {+ getAllDashboards: () => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ getAllDashboards: bindActionCreators(GetAllDashboards, dispatch),+});++type DashboardProps = DispatchProps;++export default connect(null, mapDispatchToProps)(Dashboard);diff --git a/frontend/src/pages/DashboardWidget/index.tsx b/frontend/src/pages/DashboardWidget/index.tsxnew file mode 100644index 0000000000..b5e8853fb5--- /dev/null+++ b/frontend/src/pages/DashboardWidget/index.tsx@@ -0,0 +1,101 @@+import { Card, Typography } from 'antd';+import Spinner from 'components/Spinner';+import ROUTES from 'constants/routes';+import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';+import NewWidget from 'container/NewWidget';+import updateUrl from 'lib/updateUrl';+import React, { useEffect, useRef, useState } from 'react';+import { connect, useSelector } from 'react-redux';+import { useHistory, 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';++const DashboardWidget = ({ getDashboard }: NewDashboardProps): JSX.Element => {+ const { search } = useLocation();+ const { dashboardId } = useParams<DashboardWidgetPageParams>();++ const { push } = useHistory();+ const [selectedGraph, setSelectedGraph] = useState<GRAPH_TYPES>();+ const { loading, dashboards, error, errorMessage } = useSelector<+ AppState,+ DashboardReducer+ >((state) => state.dashboards);+ const [selectedDashboard] = dashboards;+ const params = new URLSearchParams(search);++ const widgetId = params.get('widgetId');+ const { data } = selectedDashboard || {};+ const { widgets } = data || {};++ const selectedWidget = widgets?.find((e) => e.id === widgetId);++ useEffect(() => {+ const params = new URLSearchParams(search);+ const graphType = params.get('graphType') as GRAPH_TYPES | null;++ if (graphType === null) {+ push(updateUrl(ROUTES.DASHBOARD, ':dashboardId', dashboardId));+ } else {+ setSelectedGraph(graphType);+ }+ }, [dashboardId, push, 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+ ) {+ return <Spinner tip="Loading.." />;+ }++ if (error) {+ return (+ <Card>+ <Typography>{errorMessage}</Typography>+ </Card>+ );+ }++ return <NewWidget selectedGraph={selectedGraph} />;+};++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);diff --git a/frontend/src/pages/NewDashboard/index.tsx b/frontend/src/pages/NewDashboard/index.tsxnew file mode 100644index 0000000000..577a563ec0--- /dev/null+++ b/frontend/src/pages/NewDashboard/index.tsx@@ -0,0 +1,56 @@+import Spinner from 'components/Spinner';+import NewDashboard from 'container/NewDashboard';+import React, { 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 DashboardReducer from 'types/reducer/dashboards';++const NewDashboardPage = ({ getDashboard }: NewDashboardProps): JSX.Element => {+ const { loading, dashboards, error, errorMessage } = useSelector<+ AppState,+ DashboardReducer+ >((state) => state.dashboards);++ const { dashboardId } = useParams<Params>();++ useEffect(() => {+ getDashboard({+ uuid: dashboardId,+ });+ }, [getDashboard, dashboardId]);++ if (error && !loading && dashboards.length === 0) {+ return <div>{errorMessage}</div>;+ }++ if (loading || dashboards.length === 0) {+ 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);diff --git a/frontend/src/store/actions/MetricsActions/metricsActions.ts b/frontend/src/store/actions/MetricsActions/metricsActions.tsindex d5a4ce392c..5a01c4e0de 100644--- a/frontend/src/store/actions/MetricsActions/metricsActions.ts+++ b/frontend/src/store/actions/MetricsActions/metricsActions.ts@@ -1,4 +1,4 @@-import api, { apiV1 } from 'api';+import api from 'api';import { Dispatch } from 'redux';import { GlobalTime } from 'store/actions/global';import { toUTCEpoch } from 'utils/timeUtils';@@ -7,18 +7,17 @@ import { MetricsActionTypes } from './metricsActionTypes';import * as MetricsInterfaces from './metricsInterfaces';export const getServicesList = (globalTime: GlobalTime) => {- return async (dispatch: Dispatch) => {+ return async (dispatch: Dispatch): Promise<void> => {const request_string ='/services?start=' + globalTime.minTime + '&end=' + globalTime.maxTime;const response = await api.get<MetricsInterfaces.servicesListItem[]>(- apiV1 + request_string,+ request_string,);dispatch<MetricsInterfaces.getServicesListAction>({type: MetricsActionTypes.getServicesList,payload: response.data,- //PNOTE - response.data in the axios response has the actual API response});};};@@ -27,7 +26,7 @@ export const getDbOverViewMetrics = (serviceName: string,globalTime: GlobalTime,) => {- return async (dispatch: Dispatch) => {+ return async (dispatch: Dispatch): Promise<void> => {const request_string ='/service/dbOverview?service=' +serviceName +@@ -37,7 +36,7 @@ export const getDbOverViewMetrics = (globalTime.maxTime +'&step=60';const response = await api.get<MetricsInterfaces.dbOverviewMetricsItem[]>(- apiV1 + request_string,+ request_string,);dispatch<MetricsInterfaces.getDbOverViewMetricsAction>({type: MetricsActionTypes.getDbOverviewMetrics,@@ -50,7 +49,7 @@ export const getExternalMetrics = (serviceName: string,globalTime: GlobalTime,) => {- return async (dispatch: Dispatch) => {+ return async (dispatch: Dispatch): Promise<void> => {const request_string ='/service/external?service=' +serviceName +@@ -60,7 +59,7 @@ export const getExternalMetrics = (globalTime.maxTime +'&step=60';const response = await api.get<MetricsInterfaces.externalMetricsItem[]>(- apiV1 + request_string,+ request_string,);dispatch<MetricsInterfaces.getExternalMetricsAction>({type: MetricsActionTypes.getExternalMetrics,@@ -73,7 +72,7 @@ export const getExternalAvgDurationMetrics = (serviceName: string,globalTime: GlobalTime,) => {- return async (dispatch: Dispatch) => {+ return async (dispatch: Dispatch): Promise<void> => {const request_string ='/service/externalAvgDuration?service=' +serviceName +@@ -85,7 +84,7 @@ export const getExternalAvgDurationMetrics = (const response = await api.get<MetricsInterfaces.externalMetricsAvgDurationItem[]- >(apiV1 + request_string);+ >(request_string);dispatch<MetricsInterfaces.externalMetricsAvgDurationAction>({type: MetricsActionTypes.getAvgDurationMetrics,payload: response.data,@@ -96,7 +95,7 @@ export const getExternalErrCodeMetrics = (serviceName: string,globalTime: GlobalTime,) => {- return async (dispatch: Dispatch) => {+ return async (dispatch: Dispatch): Promise<void> => {const request_string ='/service/externalErrors?service=' +serviceName +@@ -107,7 +106,7 @@ export const getExternalErrCodeMetrics = ('&step=60';const response = await api.get<MetricsInterfaces.externalErrCodeMetricsItem[]- >(apiV1 + request_string);+ >(request_string);dispatch<MetricsInterfaces.externalErrCodeMetricsActions>({type: MetricsActionTypes.getErrCodeMetrics,@@ -120,7 +119,7 @@ export const getServicesMetrics = (serviceName: string,globalTime: GlobalTime,) => {- return async (dispatch: Dispatch) => {+ return async (dispatch: Dispatch): Promise<void> => {const request_string ='/service/overview?service=' +serviceName +@@ -130,13 +129,12 @@ export const getServicesMetrics = (globalTime.maxTime +'&step=60';const response = await api.get<MetricsInterfaces.metricItem[]>(- apiV1 + request_string,+ request_string,);dispatch<MetricsInterfaces.getServiceMetricsAction>({type: MetricsActionTypes.getServiceMetrics,payload: response.data,- //PNOTE - response.data in the axios response has the actual API response});};};@@ -145,7 +143,7 @@ export const getTopEndpoints = (serviceName: string,globalTime: GlobalTime,) => {- return async (dispatch: Dispatch) => {+ return async (dispatch: Dispatch): Promise<void> => {const request_string ='/service/top_endpoints?service=' +serviceName +@@ -154,13 +152,12 @@ export const getTopEndpoints = ('&end=' +globalTime.maxTime;const response = await api.get<MetricsInterfaces.topEndpointListItem[]>(- apiV1 + request_string,+ request_string,);dispatch<MetricsInterfaces.getTopEndpointsAction>({type: MetricsActionTypes.getTopEndpoints,payload: response.data,- //PNOTE - response.data in the axios response has the actual API response});};};@@ -169,7 +166,7 @@ export const getFilteredTraceMetrics = (filter_params: string,globalTime: GlobalTime,) => {- return async (dispatch: Dispatch) => {+ return async (dispatch: Dispatch): Promise<void> => {const request_string ='/spans/aggregates?start=' +toUTCEpoch(globalTime.minTime) +@@ -178,13 +175,117 @@ export const getFilteredTraceMetrics = ('&' +filter_params;const response = await api.get<MetricsInterfaces.customMetricsItem[]>(- apiV1 + request_string,+ request_string,);dispatch<MetricsInterfaces.getFilteredTraceMetricsAction>({type: MetricsActionTypes.getFilteredTraceMetrics,payload: response.data,- //PNOTE - response.data in the axios response has the actual API response});};};++export const getInitialMerticData = ({+ serviceName,+ globalTime,+}: getInitialMerticDataProps) => {+ return async (dispatch: Dispatch): Promise<void> => {+ try {+ const dbOverviewString =+ '/service/dbOverview?service=' ++ serviceName ++ '&start=' ++ globalTime.minTime ++ '&end=' ++ globalTime.maxTime ++ '&step=60';++ const externalServicesString =+ '/service/external?service=' ++ serviceName ++ '&start=' ++ globalTime.minTime ++ '&end=' ++ globalTime.maxTime ++ '&step=60';++ const topEndPointsString =+ '/service/top_endpoints?service=' ++ serviceName ++ '&start=' ++ globalTime.minTime ++ '&end=' ++ globalTime.maxTime;++ const avgExternalDurationString =+ '/service/externalAvgDuration?service=' ++ serviceName ++ '&start=' ++ globalTime.minTime ++ '&end=' ++ globalTime.maxTime ++ '&step=60';++ const serviceOverviewString =+ '/service/overview?service=' ++ serviceName ++ '&start=' ++ globalTime.minTime ++ '&end=' ++ globalTime.maxTime ++ '&step=60';++ const externalErrorCodeMetricsString =+ '/service/externalErrors?service=' ++ serviceName ++ '&start=' ++ globalTime.minTime ++ '&end=' ++ globalTime.maxTime ++ '&step=60';++ dispatch({+ type: 'UPDATE_INITIAL_VALUE_START',+ });++ const [+ dbResponse,+ externalServiceResponse,+ topEndPointsResponse,+ avgExternalDurationResponse,+ serviceOverViewResponse,+ externalErrorCodeMetricsResponse,+ ] = await Promise.all([+ api.get<MetricsInterfaces.dbOverviewMetricsItem[]>(dbOverviewString),+ api.get<MetricsInterfaces.externalMetricsItem[]>(externalServicesString),+ api.get<MetricsInterfaces.topEndpointListItem[]>(topEndPointsString),+ api.get<MetricsInterfaces.externalMetricsAvgDurationItem[]>(+ avgExternalDurationString,+ ),+ api.get<MetricsInterfaces.metricItem[]>(serviceOverviewString),+ api.get<MetricsInterfaces.externalErrCodeMetricsItem[]>(+ externalErrorCodeMetricsString,+ ),+ ]);++ dispatch({+ type: 'UPDATE_INITIAL_VALUE',+ payload: {+ serviceOverViewResponse: serviceOverViewResponse.data,+ topEndPointsResponse: topEndPointsResponse.data,+ dbResponse: dbResponse.data,+ externalServiceResponse: externalServiceResponse.data,+ avgExternalDurationResponse: avgExternalDurationResponse.data,+ externalErrorCodeMetricsResponse: externalErrorCodeMetricsResponse.data,+ },+ });+ } catch (error) {+ console.error(error);+ }+ };+};++export interface getInitialMerticDataProps {+ serviceName: string;+ globalTime: GlobalTime;+}diff --git a/frontend/src/store/actions/dashboard/applySettingsToPanel.ts b/frontend/src/store/actions/dashboard/applySettingsToPanel.tsnew file mode 100644index 0000000000..f18dcf7052--- /dev/null+++ b/frontend/src/store/actions/dashboard/applySettingsToPanel.ts@@ -0,0 +1,24 @@+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) => {+ return (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'];+}diff --git a/frontend/src/store/actions/dashboard/createQuery.ts b/frontend/src/store/actions/dashboard/createQuery.tsnew file mode 100644index 0000000000..bd8947526e--- /dev/null+++ b/frontend/src/store/actions/dashboard/createQuery.ts@@ -0,0 +1,17 @@+import { Dispatch } from 'redux';+import AppActions from 'types/actions';++export const CreateQuery = ({ widgetId }: CreateQueryProps) => (+ dispatch: Dispatch<AppActions>,+): void => {+ dispatch({+ type: 'CREATE_NEW_QUERY',+ payload: {+ widgetId,+ },+ });+};++export interface CreateQueryProps {+ widgetId: string;+}diff --git a/frontend/src/store/actions/dashboard/deleteDashboard.ts b/frontend/src/store/actions/dashboard/deleteDashboard.tsnew file mode 100644index 0000000000..b8fca59f66--- /dev/null+++ b/frontend/src/store/actions/dashboard/deleteDashboard.ts@@ -0,0 +1,43 @@+import deleteDashboardApi from 'api/dashboard/delete';+import { Dispatch } from 'redux';+import AppActions from 'types/actions';+import { Dashboard } from 'types/api/dashboard/getAll';++export const DeleteDashboard = ({+ uuid,+}: DeleteDashboardProps): ((dispatch: Dispatch<AppActions>) => void) => {+ return async (dispatch: Dispatch<AppActions>): Promise<void> => {+ try {+ const response = await deleteDashboardApi({+ uuid: uuid,+ });++ if (response.statusCode === 200) {+ dispatch({+ type: 'DELETE_DASHBOARD_SUCCESS',+ payload: {+ uuid: uuid,+ },+ });+ } else {+ dispatch({+ type: 'DELETE_DASHBOARD_ERROR',+ payload: {+ errorMessage: response.error || 'Something went wrong',+ },+ });+ }+ } catch (error) {+ dispatch({+ type: 'DELETE_DASHBOARD_ERROR',+ payload: {+ errorMessage: error.toString() || 'Something went wrong',+ },+ });+ }+ };+};++export interface DeleteDashboardProps {+ uuid: Dashboard['uuid'];+}diff --git a/frontend/src/store/actions/dashboard/deleteWidget.ts b/frontend/src/store/actions/dashboard/deleteWidget.tsnew file mode 100644index 0000000000..d86ba2b086--- /dev/null+++ b/frontend/src/store/actions/dashboard/deleteWidget.ts@@ -0,0 +1,56 @@+import updateDashboardApi from 'api/dashboard/update';+import { AxiosError } from 'axios';+import { Dispatch } from 'redux';+import store from 'store';+import AppActions from 'types/actions';+import { Widgets } from 'types/api/dashboard/getAll';++export const DeleteWidget = ({+ widgetId,+}: DeleteWidgetProps): ((dispatch: Dispatch<AppActions>) => void) => {+ return 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 response = await updateDashboardApi({+ title: selectedDashboard.data.title,+ uuid: selectedDashboard.uuid,+ description: selectedDashboard.data.description,+ name: selectedDashboard.data.name,+ tags: selectedDashboard.data.tags,+ widgets: updatedWidgets,+ });++ if (response.statusCode === 200) {+ dispatch({+ type: 'DELETE_WIDGET_SUCCESS',+ payload: {+ widgetId,+ },+ });+ } 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'];+}diff --git a/frontend/src/store/actions/dashboard/getAllDashboard.ts b/frontend/src/store/actions/dashboard/getAllDashboard.tsnew file mode 100644index 0000000000..2569436a62--- /dev/null+++ b/frontend/src/store/actions/dashboard/getAllDashboard.ts@@ -0,0 +1,38 @@+import getAll from 'api/dashboard/getAll';+import { AxiosError } from 'axios';+import { Dispatch } from 'redux';+import AppActions from 'types/actions';++export const GetAllDashboards = (): ((+ dispatch: Dispatch<AppActions>,+) => void) => {+ return async (dispatch: Dispatch<AppActions>): Promise<void> => {+ try {+ dispatch({+ type: 'GET_ALL_DASHBOARD_LOADING_START',+ });+ const response = await getAll();++ if (response.statusCode === 200) {+ dispatch({+ type: 'GET_ALL_DASHBOARD_SUCCESS',+ payload: response.payload,+ });+ } else {+ dispatch({+ type: 'GET_ALL_DASHBOARD_ERROR',+ payload: {+ errorMessage: response.error || 'Something went wrong',+ },+ });+ }+ } catch (error) {+ dispatch({+ type: 'GET_ALL_DASHBOARD_ERROR',+ payload: {+ errorMessage: (error as AxiosError).toString() || 'Something went wrong',+ },+ });+ }+ };+};diff --git a/frontend/src/store/actions/dashboard/getDashboard.ts b/frontend/src/store/actions/dashboard/getDashboard.tsnew file mode 100644index 0000000000..5d64c87fff--- /dev/null+++ b/frontend/src/store/actions/dashboard/getDashboard.ts@@ -0,0 +1,78 @@+import getDashboard from 'api/dashboard/get';+import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';+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) => {+ return async (dispatch: Dispatch<AppActions>): Promise<void> => {+ try {+ dispatch({+ type: 'GET_DASHBOARD_LOADING_START',+ });++ const response = await getDashboard({+ uuid: 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 || 'TIME_SERIES',+ timePreferance: 'GLOBAL_TIME',+ title: '',+ queryData: {+ data: [],+ error: false,+ errorMessage: '',+ loading: false,+ },+ query: [+ {+ query: '',+ legend: '',+ },+ ],+ },+ });+ }+ } else {+ dispatch({+ type: 'GET_DASHBOARD_ERROR',+ payload: {+ errorMessage: response.error || 'Something went wrong',+ },+ });+ }+ } catch (error) {+ dispatch({+ type: 'GET_DASHBOARD_ERROR',+ payload: {+ errorMessage: error.toString() || 'Something went wrong',+ },+ });+ }+ };+};++export interface GetDashboardProps {+ uuid: Props['uuid'];+ widgetId?: string;+ graphType?: GRAPH_TYPES;+}diff --git a/frontend/src/store/actions/dashboard/getQueryResults.ts b/frontend/src/store/actions/dashboard/getQueryResults.tsnew file mode 100644index 0000000000..0912d424aa--- /dev/null+++ b/frontend/src/store/actions/dashboard/getQueryResults.ts@@ -0,0 +1,99 @@+import getQueryResult from 'api/widgets/getQuery';+import { AxiosError } from 'axios';+import { ITEMS } from 'container/NewDashboard/ComponentsSlider/menuItems';+import { timePreferenceType } from 'container/NewWidget/RightContainer/timeItems';+import GetMaxMinTime from 'lib/getMaxMinTime';+import GetStartAndEndTime from 'lib/getStartAndEndTime';+import { Dispatch } from 'redux';+import AppActions from 'types/actions';+import { Query } from 'types/api/dashboard/getAll';++export const GetQueryResults = (+ props: GetQueryResultsProps,+): ((dispatch: Dispatch<AppActions>) => void) => {+ return async (dispatch: Dispatch<AppActions>): Promise<void> => {+ try {+ const queryData = props.query;++ const getMaxMinTime = GetMaxMinTime({+ graphType: props.graphType,+ maxTime: props.maxTime,+ minTime: props.minTime,+ });++ const { end, start } = GetStartAndEndTime({+ type: props.selectedTime,+ maxTime: getMaxMinTime.maxTime,+ minTime: getMaxMinTime.minTime,+ });++ const response = await Promise.all(+ queryData+ .filter((e) => e.query)+ .map(async (query) => {+ const result = await getQueryResult({+ end,+ query: encodeURIComponent(query.query),+ start: start,+ step: '30',+ });+ return {+ query: query.query,+ queryData: result,+ legend: query.legend,+ };+ }),+ );++ const isError = response.find(+ ({ queryData }) => queryData.statusCode !== 200,+ );++ // want to make sure query is not empty+ const isEmptyQuery =+ queryData.map((e) => e.query).filter((e) => e).length ===+ queryData.map((e) => e.query).length;++ if (isError !== undefined && isEmptyQuery) {+ dispatch({+ type: 'QUERY_ERROR',+ payload: {+ errorMessage: isError.queryData.error || '',+ widgetId: props.widgetId,+ },+ });+ }++ const data = response.map((e) => ({+ query: e.query,+ legend: e.legend || '',+ queryData: e.queryData.payload?.result || [],+ }));++ dispatch({+ type: 'QUERY_SUCCESS',+ payload: {+ widgetId: props.widgetId,+ data,+ },+ });+ } catch (error) {+ dispatch({+ type: 'QUERY_ERROR',+ payload: {+ errorMessage: (error as AxiosError).toString(),+ widgetId: props.widgetId,+ },+ });+ }+ };+};++export interface GetQueryResultsProps {+ widgetId: string;+ selectedTime: timePreferenceType;+ maxTime: number;+ minTime: number;+ query: Query[];+ graphType: ITEMS;+}diff --git a/frontend/src/store/actions/dashboard/index.ts b/frontend/src/store/actions/dashboard/index.tsnew file mode 100644index 0000000000..4f0e75fa7d--- /dev/null+++ b/frontend/src/store/actions/dashboard/index.ts@@ -0,0 +1,7 @@+export * from './applySettingsToPanel';+export * from './createQuery';+export * from './deleteDashboard';+export * from './getAllDashboard';+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.tsnew file mode 100644index 0000000000..33f1a03422--- /dev/null+++ b/frontend/src/store/actions/dashboard/saveDashboard.ts@@ -0,0 +1,116 @@+import updateDashboardApi from 'api/dashboard/update';+import { AxiosError } from 'axios';+import ROUTES from 'constants/routes';+import history from 'lib/history';+import updateUrl from 'lib/updateUrl';+import { Dispatch } from 'redux';+import store from 'store';+import AppActions from 'types/actions';+import { Dashboard, Widgets } from 'types/api/dashboard/getAll';++export const SaveDashboard = ({+ uuid,+ description,+ isStacked,+ nullZeroValues,+ opacity,+ timePreferance,+ title,+ widgetId,+ dashboardId,+}: SaveDashboardProps): ((dispatch: Dispatch<AppActions>) => void) => {+ return 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.data;++ const updatedTitle = title;+ const updatedDescription = description;+ const updatedisStacked = isStacked;+ const updatednullZeroValues = nullZeroValues;+ const updatedopacity = opacity;+ const updatedtimePreferance = timePreferance;++ 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+ data.widgets?.length,+ ) || [];+ const selectedWidget = (selectedDashboard.data.widgets || [])[+ selectedWidgetIndex || 0+ ];++ const response = await updateDashboardApi({+ 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,+ },+ ...afterWidget,+ ],+ });++ if (response.statusCode === 200) {+ dispatch({+ type: 'SAVE_SETTING_TO_PANEL_SUCCESS',+ payload: response.payload,+ });+ history.push(updateUrl(ROUTES.DASHBOARD, ':dashboardId', dashboardId));+ } else {+ dispatch({+ type: 'SAVE_SETTING_TO_PANEL_ERROR',+ payload: {+ errorMessage: response.error || 'Something went wrong',+ },+ });+ }+ } 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;+}diff --git a/frontend/src/store/actions/dashboard/toggleAddWidget.ts b/frontend/src/store/actions/dashboard/toggleAddWidget.tsnew file mode 100644index 0000000000..efbae4ba02--- /dev/null+++ b/frontend/src/store/actions/dashboard/toggleAddWidget.ts@@ -0,0 +1,17 @@+import { Dispatch } from 'redux';+import AppActions from 'types/actions';++export const ToggleAddWidget = (+ props: ToggleAddWidgetProps,+): ((dispatch: Dispatch<AppActions>) => void) => {+ return (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.tsnew file mode 100644index 0000000000..bcff35bb54--- /dev/null+++ b/frontend/src/store/actions/dashboard/toggleEditMode.ts@@ -0,0 +1,12 @@+import { Dispatch } from 'react';+import AppActions from 'types/actions';++export const ToggleEditMode = (): ((+ dispatch: Dispatch<AppActions>,+) => void) => {+ return (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.tsnew file mode 100644index 0000000000..071f063fe2--- /dev/null+++ b/frontend/src/store/actions/dashboard/updateDashboardTitle.ts@@ -0,0 +1,54 @@+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) => {+ return async (dispatch: Dispatch<AppActions>): Promise<void> => {+ try {+ const data = dashboard.data;++ const response = await update({+ ...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.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.tsnew file mode 100644index 0000000000..c89895ca9a--- /dev/null+++ b/frontend/src/store/actions/dashboard/updateQuery.ts@@ -0,0 +1,44 @@+import { Dispatch } from 'redux';+import store from 'store';+import AppActions from 'types/actions';+import { Query } from 'types/api/dashboard/getAll';++export const UpdateQuery = (+ props: UpdateQueryProps,+): ((dispatch: Dispatch<AppActions>) => void) => {+ return (dispatch: Dispatch<AppActions>): void => {+ const state = store.getState();+ const dashboards = state.dashboards.dashboards;+ const [selectedDashboard] = dashboards;+ const { data } = selectedDashboard;+ const { widgets = [] } = data;+ const selectedWidgetIndex = widgets.findIndex((e) => e.id === props.widgetId);+ const selectedWidget = widgets[selectedWidgetIndex];+ const { query } = selectedWidget;+ const preQuery = query.slice(0, props.currentIndex);+ const afterQuery = query.slice(props.currentIndex + 1, query.length);+ const queryArray: Query[] = [+ ...preQuery,+ {+ query: props.query,+ legend: props.legend,+ },+ ...afterQuery,+ ];++ dispatch({+ type: 'UPDATE_QUERY',+ payload: {+ query: queryArray,+ widgetId: props.widgetId,+ },+ });+ };+};++export interface UpdateQueryProps {+ widgetId: string;+ query: string;+ legend: string;+ currentIndex: number;+}diff --git a/frontend/src/store/actions/global.ts b/frontend/src/store/actions/global.tsindex 696c1c3ad8..fe8874297a 100644--- a/frontend/src/store/actions/global.ts+++ b/frontend/src/store/actions/global.ts@@ -24,54 +24,54 @@ export const updateTimeInterval = (// set directly based on that. Assuming datetimeRange values are in ms, and minTime is 0th elementswitch (interval) {- case '1min':- maxTime = Date.now() * 1000000; // in nano sec- minTime = (Date.now() - 1 * 60 * 1000) * 1000000;- break;- case '5min':- maxTime = Date.now() * 1000000; // in nano sec- minTime = (Date.now() - 5 * 60 * 1000) * 1000000;- break;+ case '1min':+ maxTime = Date.now() * 1000000; // in nano sec+ minTime = (Date.now() - 1 * 60 * 1000) * 1000000;+ break;+ case '5min':+ maxTime = Date.now() * 1000000; // in nano sec+ minTime = (Date.now() - 5 * 60 * 1000) * 1000000;+ break;- case '15min':- maxTime = Date.now() * 1000000; // in nano sec- minTime = (Date.now() - 15 * 60 * 1000) * 1000000;- break;+ case '15min':+ maxTime = Date.now() * 1000000; // in nano sec+ minTime = (Date.now() - 15 * 60 * 1000) * 1000000;+ break;- case '30min':- maxTime = Date.now() * 1000000; // in nano sec- minTime = (Date.now() - 30 * 60 * 1000) * 1000000;- break;+ case '30min':+ maxTime = Date.now() * 1000000; // in nano sec+ minTime = (Date.now() - 30 * 60 * 1000) * 1000000;+ break;- case '1hr':- maxTime = Date.now() * 1000000; // in nano sec- minTime = (Date.now() - 1 * 60 * 60 * 1000) * 1000000;- break;+ case '1hr':+ maxTime = Date.now() * 1000000; // in nano sec+ minTime = (Date.now() - 1 * 60 * 60 * 1000) * 1000000;+ break;- case '6hr':- maxTime = Date.now() * 1000000; // in nano sec- minTime = (Date.now() - 6 * 60 * 60 * 1000) * 1000000;- break;+ case '6hr':+ maxTime = Date.now() * 1000000; // in nano sec+ minTime = (Date.now() - 6 * 60 * 60 * 1000) * 1000000;+ break;- case '1day':- maxTime = Date.now() * 1000000; // in nano sec- minTime = (Date.now() - 24 * 60 * 60 * 1000) * 1000000;- break;+ case '1day':+ maxTime = Date.now() * 1000000; // in nano sec+ minTime = (Date.now() - 24 * 60 * 60 * 1000) * 1000000;+ break;- case '1week':- maxTime = Date.now() * 1000000; // in nano sec- minTime = (Date.now() - 7 * 24 * 60 * 60 * 1000) * 1000000;- break;+ case '1week':+ maxTime = Date.now() * 1000000; // in nano sec+ minTime = (Date.now() - 7 * 24 * 60 * 60 * 1000) * 1000000;+ break;- case 'custom':- if (datetimeRange !== undefined) {- maxTime = datetimeRange[1] * 1000000; // in nano sec- minTime = datetimeRange[0] * 1000000; // in nano sec- }- break;+ case 'custom':+ if (datetimeRange !== undefined) {+ maxTime = datetimeRange[1] * 1000000; // in nano sec+ minTime = datetimeRange[0] * 1000000; // in nano sec+ }+ break;- default:- console.log('not found matching case');+ default:+ // console.log('not found matching case');}return {diff --git a/frontend/src/store/actions/index.ts b/frontend/src/store/actions/index.tsindex 3233216204..977d8b8640 100644--- a/frontend/src/store/actions/index.ts+++ b/frontend/src/store/actions/index.ts@@ -1,3 +1,4 @@+export * from './dashboard';export * from './global';export * from './MetricsActions';export * from './serviceMap';diff --git a/frontend/src/store/actions/serviceMap.ts b/frontend/src/store/actions/serviceMap.tsindex ba7c6f46fb..617a91d225 100644--- a/frontend/src/store/actions/serviceMap.ts+++ b/frontend/src/store/actions/serviceMap.ts@@ -1,4 +1,4 @@-import api, { apiV1 } from 'api';+import api from 'api';import { Dispatch } from 'redux';import { GlobalTime } from './global';@@ -50,7 +50,7 @@ export const getServiceMapItems = (globalTime: GlobalTime) => {'&end=' +globalTime.maxTime;- const response = await api.get<servicesMapItem[]>(apiV1 + request_string);+ const response = await api.get<servicesMapItem[]>(request_string);dispatch<serviceMapItemAction>({type: ActionTypes.getServiceMapItems,@@ -69,7 +69,7 @@ export const getDetailedServiceMapItems = (globalTime: GlobalTime) => {const request_string ='/services?start=' + globalTime.minTime + '&end=' + globalTime.maxTime;- const response = await api.get<servicesItem[]>(apiV1 + request_string);+ const response = await api.get<servicesItem[]>(request_string);dispatch<servicesAction>({type: ActionTypes.getServices,diff --git a/frontend/src/store/actions/traces.ts b/frontend/src/store/actions/traces.tsindex 04f57aa411..c2ffef8f6e 100644--- a/frontend/src/store/actions/traces.ts+++ b/frontend/src/store/actions/traces.ts@@ -1,4 +1,4 @@-import api, { apiV1 } from 'api';+import api from 'api';import ROUTES from 'constants/routes';import { Dispatch } from 'redux';import { toUTCEpoch } from 'utils/timeUtils';@@ -120,7 +120,7 @@ export interface FetchTraceItemAction {}export const fetchTraces = (globalTime: GlobalTime, filter_params: string) => {- return async (dispatch: Dispatch) => {+ return async (dispatch: Dispatch): void => {if (globalTime) {const request_string ='/spans?limit=100&lookback=2d&start=' +@@ -129,7 +129,7 @@ export const fetchTraces = (globalTime: GlobalTime, filter_params: string) => {toUTCEpoch(globalTime.maxTime) +'&' +filter_params;- const response = await api.get<traceResponseNew>(apiV1 + request_string);+ const response = await api.get<traceResponseNew>(request_string);dispatch<FetchTracesAction>({type: ActionTypes.fetchTraces,@@ -141,11 +141,9 @@ export const fetchTraces = (globalTime: GlobalTime, filter_params: string) => {};export const fetchTraceItem = (traceID: string) => {- return async (dispatch: Dispatch) => {+ return async (dispatch: Dispatch): Promise<void> => {const request_string = ROUTES.TRACES + '/' + traceID;- const response = await api.get<spansWSameTraceIDResponse>(- apiV1 + request_string,- );+ const response = await api.get<spansWSameTraceIDResponse>(request_string);dispatch<FetchTraceItemAction>({type: ActionTypes.fetchTraceItem,diff --git a/frontend/src/store/actions/types.ts b/frontend/src/store/actions/types.tsindex 1b0ffa0966..639b66b060 100644--- a/frontend/src/store/actions/types.ts+++ b/frontend/src/store/actions/types.ts@@ -1,7 +1,7 @@import { updateTimeIntervalAction } from './global';import { serviceMapItemAction, servicesAction } from './serviceMap';import { updateTraceFiltersAction } from './traceFilters';-import { FetchTraceItemAction,FetchTracesAction } from './traces';+import { FetchTraceItemAction, FetchTracesAction } from './traces';import { getUsageDataAction } from './usage';export enum ActionTypes {diff --git a/frontend/src/store/actions/usage.ts b/frontend/src/store/actions/usage.tsindex 57a457b8ba..c93fe9eb9c 100644--- a/frontend/src/store/actions/usage.ts+++ b/frontend/src/store/actions/usage.ts@@ -1,4 +1,4 @@-import api, { apiV1 } from 'api';+import api from 'api';import { Dispatch } from 'redux';import { toUTCEpoch } from 'utils/timeUtils';@@ -25,7 +25,7 @@ export const getUsageData = (maxTime,)}&step=${step}&service=${service ? service : ''}`;//Step can only be multiple of 3600- const response = await api.get<usageDataItem[]>(apiV1 + request_string);+ const response = await api.get<usageDataItem[]>(request_string);dispatch<getUsageDataAction>({type: ActionTypes.getUsageData,diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.tsindex af77905949..ee3ab8b134 100644--- a/frontend/src/store/index.ts+++ b/frontend/src/store/index.ts@@ -1,10 +1,15 @@-import { applyMiddleware, compose,createStore } from 'redux';-import thunk from 'redux-thunk';+import { applyMiddleware, compose, createStore } from 'redux';+import thunk, { ThunkMiddleware } from 'redux-thunk';-import reducers from './reducers';+import reducers, { AppState } from './reducers';const composeEnhancers =(window && (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose;-const store = createStore(reducers, composeEnhancers(applyMiddleware(thunk)));++const store = createStore(+ reducers,+ // @TODO Add Type for AppActions also+ composeEnhancers(applyMiddleware(thunk as ThunkMiddleware<AppState>)),+);export default store;diff --git a/frontend/src/store/reducers/dashboard.ts b/frontend/src/store/reducers/dashboard.tsnew file mode 100644index 0000000000..a0a39de747--- /dev/null+++ b/frontend/src/store/reducers/dashboard.ts@@ -0,0 +1,446 @@+import {+ APPLY_SETTINGS_TO_PANEL,+ CREATE_DEFAULT_WIDGET,+ CREATE_NEW_QUERY,+ DashboardActions,+ DELETE_DASHBOARD_SUCCESS,+ DELETE_WIDGET_SUCCESS,+ 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,+ QUERY_ERROR,+ QUERY_SUCCESS,+ SAVE_SETTING_TO_PANEL_SUCCESS,+ TOGGLE_EDIT_MODE,+ 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,+ isQueryFired: false,+ isAddWidget: false,+};++const dashboard = (+ state = InitialValue,+ action: DashboardActions,+): InitialValueTypes => {+ switch (action.type) {+ case GET_ALL_DASHBOARD_LOADING_START: {+ return {+ ...state,+ loading: true,+ };+ }++ 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.data;+ const widgets = data.widgets;+ const defaultWidget = action.payload;+ const query = action.payload.query;++ 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: query,+ id: action.payload.id,+ },+ ],+ },+ },+ ],+ };+ }++ case CREATE_NEW_QUERY: {+ const [selectedDashboard] = state.dashboards;++ const data = selectedDashboard.data;+ const widgets = data.widgets;+ const selectedWidgetId = action.payload.widgetId;+ const selectedWidgetIndex = data.widgets?.findIndex(+ (e) => e.id === selectedWidgetId,+ );++ const preWidget = data.widgets?.slice(0, selectedWidgetIndex);+ const afterWidget = data.widgets?.slice(+ (selectedWidgetIndex || 0) + 1, // this is never undefined+ widgets?.length,+ );++ const selectedWidget = (data.widgets || [])[selectedWidgetIndex || 0];++ // this condition will never run as there will a widget with this widgetId+ if (selectedWidget === undefined) {+ return {+ ...state,+ };+ }++ const newQuery = [...selectedWidget.query, { query: '', legend: '' }];++ return {+ ...state,+ dashboards: [+ {+ ...selectedDashboard,+ data: {+ ...data,+ widgets: [+ ...(preWidget || []),+ {+ ...selectedWidget,+ query: newQuery,+ },+ ...(afterWidget || []),+ ],+ },+ },+ ],+ };+ }++ case QUERY_ERROR: {+ const { widgetId, errorMessage } = action.payload;++ const [selectedDashboard] = state.dashboards;+ const data = selectedDashboard.data;++ const selectedWidgetIndex = data.widgets?.findIndex(+ (e) => e.id === widgetId,+ );+ const widgets = data.widgets;++ 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,+ queryData: {+ ...selectedWidget.queryData,+ error: true,+ errorMessage,+ },+ },+ ...(afterWidget || []),+ ],+ },+ },+ ],+ isQueryFired: true,+ };+ }++ case QUERY_SUCCESS: {+ const { widgetId, data: queryDataResponse } = 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,+ queryData: {+ data: [...queryDataResponse],+ error: selectedWidget.queryData.error,+ errorMessage: selectedWidget.queryData.errorMessage,+ loading: false,+ },+ },+ ...afterWidget,+ ],+ },+ },+ ],+ isQueryFired: true,+ };+ }++ 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: {+ const selectedDashboard = action.payload;+ return {+ ...state,+ dashboards: [+ {+ ...selectedDashboard,+ },+ ],+ };+ }++ case DELETE_WIDGET_SUCCESS: {+ const { widgetId } = 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),+ },+ },+ ],+ };+ }++ case IS_ADD_WIDGET: {+ return {+ ...state,+ isAddWidget: action.payload.isAddWidget,+ };+ }++ case UPDATE_QUERY: {+ const { query, widgetId } = 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,+ query,+ },+ ...afterWidget,+ ],+ },+ },+ ],+ };+ }+ default:+ return state;+ }+};++export default dashboard;diff --git a/frontend/src/store/reducers/global.ts b/frontend/src/store/reducers/global.tsindex 8b7c286aa5..9e6a8c6fc5 100644--- a/frontend/src/store/reducers/global.ts+++ b/frontend/src/store/reducers/global.ts@@ -9,9 +9,9 @@ export const updateGlobalTimeReducer = () => {// Initial global state is time now and 15 minute intervalswitch (action.type) {- case ActionTypes.updateTimeInterval:- return action.payload;- default:- return state;+ case ActionTypes.updateTimeInterval:+ return action.payload;+ default:+ return state;}};diff --git a/frontend/src/store/reducers/index.ts b/frontend/src/store/reducers/index.tsindex 4e1525bdd7..76153c0e6d 100644--- a/frontend/src/store/reducers/index.ts+++ b/frontend/src/store/reducers/index.ts@@ -1,31 +1,14 @@import { combineReducers } from 'redux';-import {- GlobalTime,- serviceMapStore,- spansWSameTraceIDResponse,- TraceFilters,- traceResponseNew,- usageDataItem,-} from 'store/actions';+import dashboardReducer from './dashboard';import { updateGlobalTimeReducer } from './global';-import { MetricsInitialState, metricsReducer } from './metrics';+import { metricsReducer } from './metrics';import { ServiceMapReducer } from './serviceMap';import TraceFilterReducer from './traceFilters';import { traceItemReducer, tracesReducer } from './traces';import { usageDataReducer } from './usage';-export interface StoreState {- metricsData: MetricsInitialState;- traceFilters: TraceFilters;- traces: traceResponseNew;- traceItem: spansWSameTraceIDResponse;- usageDate: usageDataItem[];- globalTime: GlobalTime;- serviceMap: serviceMapStore;-}--const reducers = combineReducers<StoreState>({+const reducers = combineReducers({traceFilters: TraceFilterReducer,traces: tracesReducer,traceItem: traceItemReducer,@@ -33,6 +16,9 @@ const reducers = combineReducers<StoreState>({globalTime: updateGlobalTimeReducer,metricsData: metricsReducer,serviceMap: ServiceMapReducer,+ dashboards: dashboardReducer,});+export type AppState = ReturnType<typeof reducers>;+export default reducers;diff --git a/frontend/src/store/reducers/metrics.ts b/frontend/src/store/reducers/metrics.tsindex 31ed55f702..130293dd85 100644--- a/frontend/src/store/reducers/metrics.ts+++ b/frontend/src/store/reducers/metrics.ts@@ -19,78 +19,18 @@ export type MetricsInitialState = {externalMetricsItem?: externalMetricsItem[];dbOverviewMetricsItem?: dbOverviewMetricsItem[];customMetricsItem?: customMetricsItem[];+ loading: boolean;};export const metricsInitialState: MetricsInitialState = {- serviceList: [- {- serviceName: '',- p99: 0,- avgDuration: 0,- numCalls: 0,- callRate: 0,- numErrors: 0,- errorRate: 0,- },- ],- metricItems: [- {- timestamp: 0,- p50: 0,- p95: 0,- p99: 0,- numCalls: 0,- callRate: 0.0,- numErrors: 0,- errorRate: 0,- },- ],- topEndpointListItem: [- {- p50: 0,- p95: 0,- p99: 0,- numCalls: 0,- name: '',- },- ],- externalMetricsAvgDurationItem: [- {- avgDuration: 0,- timestamp: 0,- },- ],- externalErrCodeMetricsItem: [- {- callRate: 0,- externalHttpUrl: '',- numCalls: 0,- timestamp: 0,- },- ],- externalMetricsItem: [- {- avgDuration: 0,- callRate: 0,- externalHttpUrl: '',- numCalls: 0,- timestamp: 0,- },- ],- dbOverviewMetricsItem: [- {- avgDuration: 0,- callRate: 0,- dbSystem: '',- numCalls: 0,- timestamp: 0,- },- ],- customMetricsItem: [- {- timestamp: 0,- value: 0,- },- ],+ serviceList: [],+ metricItems: [],+ topEndpointListItem: [],+ externalMetricsAvgDurationItem: [],+ externalErrCodeMetricsItem: [],+ externalMetricsItem: [],+ dbOverviewMetricsItem: [],+ customMetricsItem: [],+ loading: false,};type ActionType = {@@ -103,50 +43,70 @@ export const metricsReducer = (action: ActionType,) => {switch (action.type) {- case ActionTypes.getFilteredTraceMetrics:- return {- ...state,- customMetricsItem: action.payload,- };- case ActionTypes.getServiceMetrics:- return {- ...state,- metricItems: action.payload,- };- case ActionTypes.getDbOverviewMetrics:- return {- ...state,- dbOverviewMetricsItem: action.payload,- };- case ActionTypes.getExternalMetrics:- return {- ...state,- externalMetricsItem: action.payload,- };- case ActionTypes.getTopEndpoints:- return {- ...state,- topEndpointListItem: action.payload,- };- case ActionTypes.getErrCodeMetrics:- return {- ...state,- externalErrCodeMetricsItem: action.payload,- };- case ActionTypes.getAvgDurationMetrics:- return {- ...state,- externalMetricsAvgDurationItem: action.payload,- };+ case ActionTypes.getFilteredTraceMetrics:+ return {+ ...state,+ customMetricsItem: action.payload,+ };+ case ActionTypes.getServiceMetrics:+ return {+ ...state,+ metricItems: action.payload,+ };+ case ActionTypes.getDbOverviewMetrics:+ return {+ ...state,+ dbOverviewMetricsItem: action.payload,+ };+ case ActionTypes.getExternalMetrics:+ return {+ ...state,+ externalMetricsItem: action.payload,+ };+ case ActionTypes.getTopEndpoints:+ return {+ ...state,+ topEndpointListItem: action.payload,+ };+ case ActionTypes.getErrCodeMetrics:+ return {+ ...state,+ externalErrCodeMetricsItem: action.payload,+ };+ case ActionTypes.getAvgDurationMetrics:+ return {+ ...state,+ externalMetricsAvgDurationItem: action.payload,+ };- case ActionTypes.getServicesList:- return {- ...state,- serviceList: action.payload,- };- default:- return {- ...state,- };+ case ActionTypes.getServicesList:+ return {+ ...state,+ serviceList: action.payload,+ };++ case 'UPDATE_INITIAL_VALUE_START': {+ return {+ ...state,+ loading: true,+ };+ }++ case 'UPDATE_INITIAL_VALUE': {+ return {+ ...state,+ dbOverviewMetricsItem: action.payload.dbResponse,+ topEndpointListItem: action.payload.topEndPointsResponse,+ externalMetricsAvgDurationItem: action.payload.avgExternalDurationResponse,+ externalErrCodeMetricsItem: action.payload.externalErrorCodeMetricsResponse,+ metricItems: action.payload.serviceOverViewResponse,+ externalMetricsItem: action.payload.externalServiceResponse,+ loading: false,+ };+ }+ default:+ return {+ ...state,+ };}};diff --git a/frontend/src/store/reducers/serviceMap.ts b/frontend/src/store/reducers/serviceMap.tsindex c0c712adb8..ebb7408069 100644--- a/frontend/src/store/reducers/serviceMap.ts+++ b/frontend/src/store/reducers/serviceMap.ts@@ -7,17 +7,17 @@ const initialState: serviceMapStore = {export const ServiceMapReducer = (state = initialState, action: Action) => {switch (action.type) {- case ActionTypes.getServiceMapItems:- return {- ...state,- items: action.payload,- };- case ActionTypes.getServices:- return {- ...state,- services: action.payload,- };- default:- return state;+ case ActionTypes.getServiceMapItems:+ return {+ ...state,+ items: action.payload,+ };+ case ActionTypes.getServices:+ return {+ ...state,+ services: action.payload,+ };+ default:+ return state;}};diff --git a/frontend/src/store/reducers/traceFilters.ts b/frontend/src/store/reducers/traceFilters.tsindex 50279ecb99..b18d031fbe 100644--- a/frontend/src/store/reducers/traceFilters.ts+++ b/frontend/src/store/reducers/traceFilters.ts@@ -14,10 +14,10 @@ const initialState: TraceFilters = {const TraceFilterReducer = (state = initialState, action: ACTION) => {switch (action.type) {- case ActionTypes.updateTraceFilters:- return action.payload;- default:- return state;+ case ActionTypes.updateTraceFilters:+ return action.payload;+ default:+ return state;}};diff --git a/frontend/src/store/reducers/traces.ts b/frontend/src/store/reducers/traces.tsindex 11c50a6ac6..97c18dd689 100644--- a/frontend/src/store/reducers/traces.ts+++ b/frontend/src/store/reducers/traces.ts@@ -13,10 +13,10 @@ export const tracesReducer = (action: Action,) => {switch (action.type) {- case ActionTypes.fetchTraces:- return action.payload;- default:- return state;+ case ActionTypes.fetchTraces:+ return action.payload;+ default:+ return state;}};@@ -25,9 +25,9 @@ export const traceItemReducer = (action: Action,) => {switch (action.type) {- case ActionTypes.fetchTraceItem:- return action.payload;- default:- return state;+ case ActionTypes.fetchTraceItem:+ return action.payload;+ default:+ return state;}};diff --git a/frontend/src/store/reducers/usage.ts b/frontend/src/store/reducers/usage.tsindex d19b61fadb..d49be80a40 100644--- a/frontend/src/store/reducers/usage.ts+++ b/frontend/src/store/reducers/usage.ts@@ -5,9 +5,9 @@ export const usageDataReducer = (action: Action,) => {switch (action.type) {- case ActionTypes.getUsageData:- return action.payload;- default:- return state;+ case ActionTypes.getUsageData:+ return action.payload;+ default:+ return state;}};diff --git a/frontend/src/types/actions/dashboard.ts b/frontend/src/types/actions/dashboard.tsnew file mode 100644index 0000000000..965984b232--- /dev/null+++ b/frontend/src/types/actions/dashboard.ts@@ -0,0 +1,180 @@+import { ApplySettingsToPanelProps } from 'store/actions/dashboard/applySettingsToPanel';+import { Dashboard, Query, 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 CREATE_NEW_QUERY = 'CREATE_NEW_QUERY';+export const QUERY_SUCCESS = 'QUERY_SUCCESS';+export const QUERY_ERROR = 'QUERY_ERROR';++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';++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 CreateNewQuery {+ type: typeof CREATE_NEW_QUERY;+ payload: {+ widgetId: string;+ };+}++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 QuerySuccess {+ type: typeof QUERY_SUCCESS;+ payload: QuerySuccessPayload;+}++interface UpdateQuery {+ type: typeof UPDATE_QUERY;+ payload: {+ query: Query[];+ widgetId: string;+ };+}++interface QueryError {+ type: typeof QUERY_ERROR;+ payload: {+ errorMessage: string;+ widgetId: string;+ };+}++interface SaveDashboardSuccess {+ type: typeof SAVE_SETTING_TO_PANEL_SUCCESS;+ payload: Dashboard;+}++interface WidgetDeleteSuccess {+ type: typeof DELETE_WIDGET_SUCCESS;+ payload: {+ widgetId: Widgets['id'];+ };+}++export type DashboardActions =+ | GetDashboard+ | UpdateDashboard+ | DeleteDashboardSuccess+ | DashboardError+ | GetAllDashboardSuccess+ | DashboardStart+ | GetDashboardSuccess+ | UpdateDashboardTitle+ | ToggleEditMode+ | CreateDefaultWidget+ | CreateNewQuery+ | QuerySuccess+ | QueryError+ | ApplySettingsToPanel+ | SaveDashboardSuccess+ | WidgetDeleteSuccess+ | IsAddWidget+ | UpdateQuery;diff --git a/frontend/src/types/actions/index.ts b/frontend/src/types/actions/index.tsnew file mode 100644index 0000000000..db68846802--- /dev/null+++ b/frontend/src/types/actions/index.ts@@ -0,0 +1,5 @@+import { DashboardActions } from './dashboard';++type AppActions = DashboardActions;++export default AppActions;diff --git a/frontend/src/types/api/dashboard/create.ts b/frontend/src/types/api/dashboard/create.tsnew file mode 100644index 0000000000..bd0996a0d6--- /dev/null+++ b/frontend/src/types/api/dashboard/create.ts@@ -0,0 +1,8 @@+import { Dashboard } from './getAll';++export type Props = {+ uuid: Dashboard['uuid'];+ title: Dashboard['data']['title'];+};++export type PayloadProps = Dashboard;diff --git a/frontend/src/types/api/dashboard/delete.ts b/frontend/src/types/api/dashboard/delete.tsnew file mode 100644index 0000000000..78d3253d30--- /dev/null+++ b/frontend/src/types/api/dashboard/delete.ts@@ -0,0 +1,5 @@+import { Dashboard } from './getAll';++export type Props = {+ uuid: Dashboard['uuid'];+};diff --git a/frontend/src/types/api/dashboard/get.ts b/frontend/src/types/api/dashboard/get.tsnew file mode 100644index 0000000000..2c440c2f02--- /dev/null+++ b/frontend/src/types/api/dashboard/get.ts@@ -0,0 +1,7 @@+import { Dashboard } from './getAll';++export type Props = {+ uuid: Dashboard['uuid'];+};++export type PayloadProps = Dashboard;diff --git a/frontend/src/types/api/dashboard/getAll.ts b/frontend/src/types/api/dashboard/getAll.tsnew file mode 100644index 0000000000..5bdca3f493--- /dev/null+++ b/frontend/src/types/api/dashboard/getAll.ts@@ -0,0 +1,50 @@+import { GRAPH_TYPES } from 'container/NewDashboard/ComponentsSlider';+import { timePreferenceType } from 'container/NewWidget/RightContainer/timeItems';++import { QueryData } from '../widgets/getQuery';++export type PayloadProps = Dashboard[];++export interface Dashboard {+ id: number;+ uuid: string;+ created_at: string;+ updated_at: string;+ data: DashboardData;+}++export interface DashboardData {+ description?: string;+ tags?: string[];+ name?: string;+ widgets?: Widgets[];+ title: string;+}++export interface Widgets {+ isStacked: boolean;+ id: string;+ panelTypes: GRAPH_TYPES;+ title: string;+ description: string;+ opacity: string;+ nullZeroValues: string;+ timePreferance: timePreferenceType;+ query: Query[];+ queryData: {+ loading: boolean;+ error: boolean;+ errorMessage: string;+ data: {+ legend?: string;+ queryData: QueryData[];+ query: string;+ }[];+ };+ stepSize?: number;+}++export interface Query {+ query: string;+ legend?: string;+}diff --git a/frontend/src/types/api/dashboard/update.ts b/frontend/src/types/api/dashboard/update.tsnew file mode 100644index 0000000000..c58e3b5cd4--- /dev/null+++ b/frontend/src/types/api/dashboard/update.ts@@ -0,0 +1,8 @@+import { Dashboard, DashboardData } from './getAll';++export type Props = {+ title: Dashboard['data']['title'];+ uuid: Dashboard['uuid'];+} & DashboardData;++export type PayloadProps = Dashboard;diff --git a/frontend/src/types/api/index.ts b/frontend/src/types/api/index.tsnew file mode 100644index 0000000000..fbd8db5bf1--- /dev/null+++ b/frontend/src/types/api/index.ts@@ -0,0 +1,15 @@+import { ErrorStatusCode, SuccessStatusCode } from 'types/common';++export interface ErrorResponse {+ statusCode: ErrorStatusCode;+ payload: null;+ error: string;+ message: null;+}++export interface SuccessResponse<T> {+ statusCode: SuccessStatusCode;+ message: string;+ payload: T;+ error: null;+}diff --git a/frontend/src/types/api/widgets/getQuery.ts b/frontend/src/types/api/widgets/getQuery.tsnew file mode 100644index 0000000000..e6c3a3d504--- /dev/null+++ b/frontend/src/types/api/widgets/getQuery.ts@@ -0,0 +1,19 @@+export interface PayloadProps {+ status: 'success' | 'error';+ result: QueryData[];+}++export interface QueryData {+ metric?: {+ __name__: string;+ [key: string]: string;+ };+ values: [number, string][];+}++export interface Props {+ query: string;+ step: string;+ start: string;+ end: string;+}diff --git a/frontend/src/types/common/index.ts b/frontend/src/types/common/index.tsnew file mode 100644index 0000000000..7c5414ffc9--- /dev/null+++ b/frontend/src/types/common/index.ts@@ -0,0 +1,22 @@+export type Created = 201;++export type Success = 200;++export type Forbidden = 403;++export type Unauthorized = 401;++export type NotFound = 404;++export type ServerError = 500;++export type SuccessStatusCode = Created | Success;++export type ErrorStatusCode =+ | Forbidden+ | Forbidden+ | Unauthorized+ | NotFound+ | ServerError;++export type StatusCode = SuccessStatusCode | ErrorStatusCode;diff --git a/frontend/src/types/reducer/dashboards.ts b/frontend/src/types/reducer/dashboards.tsnew file mode 100644index 0000000000..8e4871b0a3--- /dev/null+++ b/frontend/src/types/reducer/dashboards.ts@@ -0,0 +1,11 @@+import { PayloadProps } from 'types/api/dashboard/getAll';++export default interface DashboardReducer {+ dashboards: PayloadProps;+ loading: boolean;+ error: boolean;+ errorMessage: string;+ isEditMode: boolean;+ isQueryFired: boolean;+ isAddWidget: boolean;+}diff --git a/frontend/src/utils/spanToTree.ts b/frontend/src/utils/spanToTree.tsindex eb238da462..e56e9854ea 100644--- a/frontend/src/utils/spanToTree.ts+++ b/frontend/src/utils/spanToTree.ts@@ -1,4 +1,4 @@-import { pushDStree, RefItem,span } from 'store/actions';+import { pushDStree, RefItem, span } from 'store/actions';// PNOTE - should the data be taken from redux or only through props? - Directly as argumentsexport const spanToTreeUtil = (spanlist: span[]): pushDStree => {@@ -102,12 +102,12 @@ export const spanToTreeUtil = (spanlist: span[]): pushDStree => {//checking for undefined [10] issuemapped_array[parentID][10].push(push_object);} else {- console.log(- `In SpanTreeUtil: mapped_array[parentID] is undefined, parentID is ${parentID}`,- );- console.log(- `In SpanTreeUtil: mapped_array[parentID] is undefined, mapped_array[parentID] is ${mapped_array[parentID]}`,- );+ // console.log(+ // `In SpanTreeUtil: mapped_array[parentID] is undefined, parentID is ${parentID}`,+ // );+ // console.log(+ // `In SpanTreeUtil: mapped_array[parentID] is undefined, mapped_array[parentID] is ${mapped_array[parentID]}`,+ // );}}} else {diff --git a/frontend/tsconfig.json b/frontend/tsconfig.jsonindex c07f2dcc81..1c644fc0f0 100644--- a/frontend/tsconfig.json+++ b/frontend/tsconfig.json@@ -19,5 +19,7 @@"noEmit": true,"baseUrl": "./src","downlevelIteration": true- }+ },+ "exclude": ["node_modules"],+ "include": ["./src", "./cypress"]}diff --git a/frontend/webpack.config.js b/frontend/webpack.config.jsindex 02965e0be7..095fa21cd7 100644--- a/frontend/webpack.config.js+++ b/frontend/webpack.config.js@@ -28,7 +28,7 @@ module.exports = {// then it will try to find another open port availble.port: portFinderSync.getPort(3000),},- target: "web",+ target: 'web',output: {filename: ({ chunk: { name, hash } }) => {return `js/${name}-${hash}.js`;diff --git a/frontend/yarn.lock b/frontend/yarn.lockindex 349dacbd81..75ff323b17 100644--- a/frontend/yarn.lock+++ b/frontend/yarn.lock@@ -55,6 +55,17 @@classnames "^2.2.6"rc-util "^5.9.4"+"@ant-design/icons@^4.6.3":+ version "4.6.4"+ resolved "https://registry.yarnpkg.com/@ant-design/icons/-/icons-4.6.4.tgz#21b037dbb90ee1bb7c632cca057006e57d992fd9"+ integrity sha512-li02J8ym721E24N3bw1oXRzFDV7m2MYQWs+WtJgVVjhNRv4sc6vL2a2M7SS8rWX3Uc/3GJfrokIJnMrmbIMuXQ==+ dependencies:+ "@ant-design/colors" "^6.0.0"+ "@ant-design/icons-svg" "^4.0.0"+ "@babel/runtime" "^7.11.2"+ classnames "^2.2.6"+ rc-util "^5.9.4"+"@ant-design/react-slick@~0.28.1":version "0.28.3"resolved "https://registry.yarnpkg.com/@ant-design/react-slick/-/react-slick-0.28.3.tgz#ad5cf1cf50363c1a3842874d69d0ce1f26696e71"@@ -2003,13 +2014,6 @@dependencies:"@babel/types" "^7.3.0"-"@types/chart.js@^2.9.28":- version "2.9.33"- resolved "https://registry.yarnpkg.com/@types/chart.js/-/chart.js-2.9.33.tgz#59c6de80b8134379156f4ba7b96c0928a721c1ab"- integrity sha512-vB6ZFx1cA91aiCoVpreLQwCQHS/Cj+9YtjBTwFlTjKXyY0douXV2KV4+fluxdI+grDZ6hTCQeg2HY/aQ9NeLHA==- dependencies:- moment "^2.10.2"-"@types/d3-array@^2":version "2.12.3"resolved "https://registry.yarnpkg.com/@types/d3-array/-/d3-array-2.12.3.tgz#8d16d51fb04ad5a5a8ebe14eb8263a579f1efdd1"@@ -2169,6 +2173,13 @@resolved "https://registry.yarnpkg.com/@types/d3-timer/-/d3-timer-2.0.1.tgz#ffb6620d290624f3726aa362c0c8a4b44c8d7200"integrity sha512-TF8aoF5cHcLO7W7403blM7L1T+6NF3XMyN3fxyUolq2uOcFeicG/khQg/dGxiCJWoAcmYulYN7LYSRKO54IXaA==+"@types/d3-tip@^3.5.5":+ version "3.5.5"+ resolved "https://registry.yarnpkg.com/@types/d3-tip/-/d3-tip-3.5.5.tgz#efaf942fa6984ddb8061db1023934598a76cbc8c"+ integrity sha512-MWt1tlChRfHZtwBh8kIOrJo//TC5cdH5UN+KwcAs4wbFi6wnQJtk/MY4LBr/ZG7b2BQmRNJXu+EMI6NnH6VmxQ==+ dependencies:+ "@types/d3" "^3"+"@types/d3-transition@^2":version "2.0.2"resolved "https://registry.yarnpkg.com/@types/d3-transition/-/d3-transition-2.0.2.tgz#d5ba1c26a3daeb0c5527d573d44b4c5ca9fae027"@@ -2184,6 +2195,11 @@"@types/d3-interpolate" "^2""@types/d3-selection" "^2"+"@types/d3@^3":+ version "3.5.45"+ resolved "https://registry.yarnpkg.com/@types/d3/-/d3-3.5.45.tgz#cceb1cd8f468b0ed1c96546ddefff3408d7463a7"+ integrity sha512-wLICfMtjDEoAJie1MF6OuksAzOapRXgJy+l5HQVpyC1yMAlvHz2QKrrasUHru8xD6cbgQNGeO+CeyjOlKtly2A==+"@types/d3@^6.2.0":version "6.7.5"resolved "https://registry.yarnpkg.com/@types/d3/-/d3-6.7.5.tgz#6ae8034ea21db10fa3e31db1f670c5887d91d8a3"@@ -2353,10 +2369,10 @@resolved "https://registry.yarnpkg.com/@types/node/-/node-14.17.10.tgz#93f4b095af275a0427114579c10ec7aa696729d7"integrity sha512-09x2d6kNBwjHgyh3jOUE2GE4DFoxDriDvWdu6mFhMP1ysynGYazt4ecZmJlL6/fe4Zi2vtYvTvtL7epjQQrBhA==-"@types/node@^14.14.7":- version "14.17.4"- resolved "https://registry.yarnpkg.com/@types/node/-/node-14.17.4.tgz#218712242446fc868d0e007af29a4408c7765bc0"- integrity sha512-8kQ3+wKGRNN0ghtEn7EGps/B8CzuBz1nXZEIGGLP2GnwbqYn4dbTs7k+VKLTq1HvZLRCIDtN3Snx1Ege8B7L5A==+"@types/node@^14.17.12":+ version "14.17.12"+ resolved "https://registry.yarnpkg.com/@types/node/-/node-14.17.12.tgz#7a31f720b85a617e54e42d24c4ace136601656c7"+ integrity sha512-vhUqgjJR1qxwTWV5Ps5txuy2XMdf7Fw+OrdChRboy8BmWUPkckOhphaohzFG6b8DW7CrxaBMdrdJ47SYFq1okw=="@types/normalize-package-data@^2.4.0":version "2.4.0"@@ -2390,6 +2406,13 @@dependencies:"@types/react" "^16"+"@types/react-grid-layout@^1.1.2":+ version "1.1.2"+ resolved "https://registry.yarnpkg.com/@types/react-grid-layout/-/react-grid-layout-1.1.2.tgz#be46ac453e5193f512b0c4c90f36342e9e82258c"+ integrity sha512-jGpMO5VTXgrCsOoxGHSzfM/9sihlN6GDNyssaMdl73Q7Vtrbe0VVYxoavodommoRXS29hLW/2RLbQ/Oj5++slg==+ dependencies:+ "@types/react" "*"+"@types/react-redux@^7.1.11", "@types/react-redux@^7.1.16":version "7.1.16"resolved "https://registry.yarnpkg.com/@types/react-redux/-/react-redux-7.1.16.tgz#0fbd04c2500c12105494c83d4a3e45c084e3cb21"@@ -2485,6 +2508,11 @@dependencies:"@types/jest" "*"+"@types/uuid@^8.3.1":+ version "8.3.1"+ resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-8.3.1.tgz#1a32969cf8f0364b3d8c8af9cc3555b7805df14f"+ integrity sha512-Y2mHTRAbqfFkpjldbkHGY8JIzRN6XqYRliG8/24FcHm2D2PwW24fl5xMRTVGdrb7iMrwCaIEbLWerGIkXuFWVg==+"@types/vis@^4.21.21":version "4.21.22"resolved "https://registry.yarnpkg.com/@types/vis/-/vis-4.21.22.tgz#0f15b8825cf4df7a02e66c96516b1d774e241847"@@ -3037,13 +3065,13 @@ [email protected], ansi-wrap@^0.1.0:resolved "https://registry.yarnpkg.com/ansi-wrap/-/ansi-wrap-0.1.0.tgz#a82250ddb0015e9a27ca82e82ea603bbfa45efaf"integrity sha1-qCJQ3bABXponyoLoLqYDu/pF768=-antd@^4.8.0:- version "4.16.6"- resolved "https://registry.yarnpkg.com/antd/-/antd-4.16.6.tgz#5f79fa103bbd8be30fac74142ef1bbf8bc872491"- integrity sha512-E7T+GClZPGjPUfmiuTbQK4+OfvsQ/Ksi5C71Bm4dwz1wlbJ4CqfxhIlpBypod9fe8mCI+bVAjtBoUpR1q/6Sow==+antd@^4.16.13:+ version "4.16.13"+ resolved "https://registry.yarnpkg.com/antd/-/antd-4.16.13.tgz#e9b9b4a590db28747aae1cab98981649a35880af"+ integrity sha512-EMPD3fzKe7oayx9keD/GA1oKatcx7j5CGlkJj5eLS0/eEDDEkxVj3DFmKOPuHYt4BK7ltTzMFS+quSTmqUXPiw==dependencies:"@ant-design/colors" "^6.0.0"- "@ant-design/icons" "^4.6.2"+ "@ant-design/icons" "^4.6.3""@ant-design/react-slick" "~0.28.1""@babel/runtime" "^7.12.5"array-tree-filter "^2.1.0"@@ -3054,17 +3082,17 @@ antd@^4.8.0:rc-cascader "~1.4.0"rc-checkbox "~2.3.0"rc-collapse "~3.1.0"- rc-dialog "~8.5.1"+ rc-dialog "~8.6.0"rc-drawer "~4.3.0"rc-dropdown "~3.2.0"rc-field-form "~1.20.0"- rc-image "~5.2.4"+ rc-image "~5.2.5"rc-input-number "~7.1.0"rc-mentions "~1.6.1"rc-menu "~9.0.12"rc-motion "^2.4.0"rc-notification "~4.5.7"- rc-pagination "~3.1.6"+ rc-pagination "~3.1.9"rc-picker "~2.5.10"rc-progress "~3.1.0"rc-rate "~2.9.0"@@ -3074,16 +3102,15 @@ antd@^4.8.0:rc-steps "~4.1.0"rc-switch "~3.2.0"rc-table "~7.15.1"- rc-tabs "~11.9.1"+ rc-tabs "~11.10.0"rc-textarea "~0.3.0"rc-tooltip "~5.1.1"rc-tree "~4.2.1"rc-tree-select "~4.3.0"- rc-trigger "^5.2.1"+ rc-trigger "^5.2.10"rc-upload "~4.3.0"rc-util "^5.13.1"scroll-into-view-if-needed "^2.2.25"- warning "^4.0.3"anymatch@^2.0.0:version "2.0.0"@@ -4259,28 +4286,15 @@ char-regex@^1.0.2:resolved "https://registry.yarnpkg.com/char-regex/-/char-regex-1.0.2.tgz#d744358226217f981ed58f479b1d6bcc29545dcf"integrity sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==-chart.js@^2.9.4:- version "2.9.4"- resolved "https://registry.yarnpkg.com/chart.js/-/chart.js-2.9.4.tgz#0827f9563faffb2dc5c06562f8eb10337d5b9684"- integrity sha512-B07aAzxcrikjAPyV+01j7BmOpxtQETxTSlQ26BEYJ+3iUkbNKaOJ/nDbT6JjyqYxseM0ON12COHYdU2cTIjC7A==- dependencies:- chartjs-color "^2.1.0"- moment "^2.10.2"--chartjs-color-string@^0.6.0:- version "0.6.0"- resolved "https://registry.yarnpkg.com/chartjs-color-string/-/chartjs-color-string-0.6.0.tgz#1df096621c0e70720a64f4135ea171d051402f71"- integrity sha512-TIB5OKn1hPJvO7JcteW4WY/63v6KwEdt6udfnDE9iCAZgy+V4SrbSxoIbTw/xkUIapjEI4ExGtD0+6D3KyFd7A==- dependencies:- color-name "^1.0.0"+chart.js@^3.4.0:+ version "3.5.1"+ resolved "https://registry.yarnpkg.com/chart.js/-/chart.js-3.5.1.tgz#73e24d23a4134a70ccdb5e79a917f156b6f3644a"+ integrity sha512-m5kzt72I1WQ9LILwQC4syla/LD/N413RYv2Dx2nnTkRS9iv/ey1xLTt0DnPc/eWV4zI+BgEgDYBIzbQhZHc/PQ==-chartjs-color@^2.1.0:- version "2.4.1"- resolved "https://registry.yarnpkg.com/chartjs-color/-/chartjs-color-2.4.1.tgz#6118bba202fe1ea79dd7f7c0f9da93467296c3b0"- integrity sha512-haqOg1+Yebys/Ts/9bLo/BqUcONQOdr/hoEr2LLTRl6C5LXctUdHxsCYfvQVg5JIxITrfCNUDr4ntqmQk9+/0w==- dependencies:- chartjs-color-string "^0.6.0"- color-convert "^1.9.3"+chartjs-adapter-date-fns@^2.0.0:+ version "2.0.0"+ resolved "https://registry.yarnpkg.com/chartjs-adapter-date-fns/-/chartjs-adapter-date-fns-2.0.0.tgz#5e53b2f660b993698f936f509c86dddf9ed44c6b"+ integrity sha512-rmZINGLe+9IiiEB0kb57vH3UugAtYw33anRiw5kS2Tu87agpetDDoouquycWc9pRsKtQo5j+vLsYHyr8etAvFw==check-more-types@^2.24.0:version "2.24.0"@@ -4346,7 +4360,7 @@ class-utils@^0.3.5:isobject "^3.0.0"static-extend "^0.1.1"[email protected], classnames@^2.2.1, classnames@^2.2.3, classnames@^2.2.5, classnames@^2.2.6:[email protected], [email protected], classnames@^2.2.1, classnames@^2.2.3, classnames@^2.2.5, classnames@^2.2.6:version "2.3.1"resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.3.1.tgz#dfcfa3891e306ec1dad105d0e88f4417b8535e8e"integrity sha512-OlQdbZ7gLfGarSqxesMesDa5uz7KFbID8Kpq/SxIoNGDqY8lSYs0D+hhtBXhcdB3rcbXArFr7vlHheLk1voeNA==@@ -4498,7 +4512,7 @@ collection-visit@^1.0.0:map-visit "^1.0.0"object-visit "^1.0.0"-color-convert@^1.9.0, color-convert@^1.9.3:+color-convert@^1.9.0:version "1.9.3"resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8"integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==@@ -4517,7 +4531,7 @@ [email protected]:resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25"integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=-color-name@^1.0.0, color-name@~1.1.4:+color-name@~1.1.4:version "1.1.4"resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==@@ -6243,6 +6257,11 @@ escodegen@^2.0.0:optionalDependencies:source-map "~0.6.1"+eslint-config-prettier@^8.3.0:+ version "8.3.0"+ resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.3.0.tgz#f7471b20b6fe8a9a9254cc684454202886a2dd7a"+ integrity sha512-BgZuLUSeKzvlL/VUjx/Yb787VQ26RU3gGjA3iiFvdsp/2bMfVIWUVP7tjxtjS0e+HP409cPlPvNkQloz8C91ew==+eslint-config-react-app@^6.0.0:version "6.0.0"resolved "https://registry.yarnpkg.com/eslint-config-react-app/-/eslint-config-react-app-6.0.0.tgz#ccff9fc8e36b322902844cbd79197982be355a0e"@@ -6344,6 +6363,13 @@ eslint-plugin-node@^11.1.0:resolve "^1.10.1"semver "^6.1.0"+eslint-plugin-prettier@^4.0.0:+ version "4.0.0"+ resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-4.0.0.tgz#8b99d1e4b8b24a762472b4567992023619cb98e0"+ integrity sha512-98MqmCJ7vJodoQK359bqQWaxOE0CS8paAz/GgjaZLyex4TTk3g9HugoO89EqWCrFiOqn9EVvcoo7gZzONCWVwQ==+ dependencies:+ prettier-linter-helpers "^1.0.0"+eslint-plugin-promise@^5.1.0:version "5.1.0"resolved "https://registry.yarnpkg.com/eslint-plugin-promise/-/eslint-plugin-promise-5.1.0.tgz#fb2188fb734e4557993733b41aa1a688f46c6f24"@@ -6771,6 +6797,11 @@ fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3:resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525"integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==+fast-diff@^1.1.2:+ version "1.2.0"+ resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.2.0.tgz#73ee11982d86caaf7959828d519cfe927fac5f03"+ integrity sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==+fast-glob@^3.1.1, fast-glob@^3.2.4:version "3.2.6"resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.6.tgz#434dd9529845176ea049acc9343e8282765c6e1a"@@ -7627,7 +7658,7 @@ he@^1.2.0:resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f"integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==-history@^4.9.0:[email protected], history@^4.9.0:version "4.10.1"resolved "https://registry.yarnpkg.com/history/-/history-4.10.1.tgz#33371a65e3a83b267434e2b3f3b1b4c58aad4cf3"integrity sha512-36nwAD620w12kuzPAsyINPWJqlNbij+hpK1k9XRloDtym8mxzGYl2c17LnV6IAGB2Dmg4tEa7G7DlawS0+qjew==@@ -9483,6 +9514,11 @@ lodash.flatten@^4.2.0:resolved "https://registry.yarnpkg.com/lodash.flatten/-/lodash.flatten-4.4.0.tgz#f31c22225a9632d2bbf8e4addbef240aa765a61f"integrity sha1-8xwiIlqWMtK7+OSt2+8kCqdlph8=+lodash.isequal@^4.0.0:+ version "4.5.0"+ resolved "https://registry.yarnpkg.com/lodash.isequal/-/lodash.isequal-4.5.0.tgz#415c4478f2bcc30120c22ce10ed3226f7d3e18e0"+ integrity sha1-QVxEePK8wwEgwizhDtMib30+GOA=+lodash.merge@^4.4.0, lodash.merge@^4.6.2:version "4.6.2"resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a"@@ -9869,7 +9905,7 @@ mkdirp@^1.0.3, mkdirp@^1.0.4:resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e"integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==-moment@>=2.13.0, moment@^2.10.2, moment@^2.24.0, moment@^2.25.3:+moment@>=2.13.0, moment@^2.24.0, moment@^2.25.3:version "2.29.1"resolved "https://registry.yarnpkg.com/moment/-/moment-2.29.1.tgz#b2be769fa31940be9eeea6469c075e35006fa3d3"integrity sha512-kHmoybcPV8Sqy59DwNDY3Jefr64lK/by/da0ViFcuA4DH0vQg5Q6Ze5VimxkfQNSC+Mls/Kx53s7TjP1RhFEDQ==@@ -11249,6 +11285,13 @@ [email protected]:resolved "https://registry.yarnpkg.com/present/-/present-0.0.6.tgz#9eeff700daa9e998613352e47f7ac2324d4faf02"integrity sha1-nu/3ANqp6ZhhM1Lkf3rCMk1PrwI=+prettier-linter-helpers@^1.0.0:+ version "1.0.0"+ resolved "https://registry.yarnpkg.com/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz#d23d41fe1375646de2d0104d3454a3008802cf7b"+ integrity sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==+ dependencies:+ fast-diff "^1.1.2"+version "2.2.1"resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.2.1.tgz#795a1a78dd52f073da0cd42b21f9c91381923ff5"@@ -11352,7 +11395,7 @@ prompts@^2.0.1:kleur "^3.0.3"sisteransi "^1.0.5"-prop-types@^15.5.10, prop-types@^15.5.8, prop-types@^15.6.1, prop-types@^15.6.2, prop-types@^15.7, prop-types@^15.7.2:[email protected], prop-types@^15.0.0, prop-types@^15.5.10, prop-types@^15.5.8, prop-types@^15.6.0, prop-types@^15.6.1, prop-types@^15.6.2, prop-types@^15.7, prop-types@^15.7.2:version "15.7.2"resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.7.2.tgz#52c41e75b8c87e72b9d9360e0206b99dcbffa6c5"integrity sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==@@ -11551,10 +11594,10 @@ rc-collapse@~3.1.0:rc-util "^5.2.1"shallowequal "^1.1.0"-rc-dialog@~8.5.0, rc-dialog@~8.5.1:- version "8.5.2"- resolved "https://registry.yarnpkg.com/rc-dialog/-/rc-dialog-8.5.2.tgz#530e289c25a31c15c85a0e8a4ba3f33414bff418"- integrity sha512-3n4taFcjqhTE9uNuzjB+nPDeqgRBTEGBfe46mb1e7r88DgDo0lL4NnxY/PZ6PJKd2tsCt+RrgF/+YeTvJ/Thsw==+rc-dialog@~8.6.0:+ version "8.6.0"+ resolved "https://registry.yarnpkg.com/rc-dialog/-/rc-dialog-8.6.0.tgz#3b228dac085de5eed8c6237f31162104687442e7"+ integrity sha512-GSbkfqjqxpZC5/zc+8H332+q5l/DKUhpQr0vdX2uDsxo5K0PhvaMEVjyoJUTkZ3+JstEADQji1PVLVb/2bJeOQ==dependencies:"@babel/runtime" "^7.10.1"classnames "^2.2.6"@@ -11588,14 +11631,14 @@ rc-field-form@~1.20.0:async-validator "^3.0.3"rc-util "^5.8.0"-rc-image@~5.2.4:- version "5.2.4"- resolved "https://registry.yarnpkg.com/rc-image/-/rc-image-5.2.4.tgz#ff1059f937bde6ca918c6f1beb316beba911f255"- integrity sha512-kWOjhZC1OoGKfvWqtDoO9r8WUNswBwnjcstI6rf7HMudz0usmbGvewcWqsOhyaBRJL9+I4eeG+xiAoxV1xi75Q==+rc-image@~5.2.5:+ version "5.2.5"+ resolved "https://registry.yarnpkg.com/rc-image/-/rc-image-5.2.5.tgz#44e6ffc842626827960e7ab72e1c0d6f3a8ce440"+ integrity sha512-qUfZjYIODxO0c8a8P5GeuclYXZjzW4hV/5hyo27XqSFo1DmTCs2HkVeQObkcIk5kNsJtgsj1KoPThVsSc/PXOw==dependencies:"@babel/runtime" "^7.11.2"classnames "^2.2.6"- rc-dialog "~8.5.0"+ rc-dialog "~8.6.0"rc-util "^5.0.6"rc-input-number@~7.1.0:@@ -11661,10 +11704,10 @@ rc-overflow@^1.0.0, rc-overflow@^1.2.0:rc-resize-observer "^1.0.0"rc-util "^5.5.1"-rc-pagination@~3.1.6:- version "3.1.7"- resolved "https://registry.yarnpkg.com/rc-pagination/-/rc-pagination-3.1.7.tgz#13ba071a7fcb0c79896076806f3944653e7bf29e"- integrity sha512-sl0HGVhv6AsMzA5H3q7cBQcbAGj/sFjoiDSLvq3+/4IjihPqScZnSSiqR4Wu9G8RLgNjrBnGrSdTGO2Kyrt3IA==+rc-pagination@~3.1.9:+ version "3.1.9"+ resolved "https://registry.yarnpkg.com/rc-pagination/-/rc-pagination-3.1.9.tgz#797ad75d85b1ef7a82801207ead410110337fdd6"+ integrity sha512-IKBKaJ4icVPeEk9qRHrFBJmHxBUrCp3+nENBYob4Ofqsu3RXjBOy4N36zONO7oubgLyiG3PxVmyAuVlTkoc7Jg==dependencies:"@babel/runtime" "^7.10.1"classnames "^2.2.1"@@ -11763,10 +11806,10 @@ rc-table@~7.15.1:rc-util "^5.13.0"shallowequal "^1.1.0"-rc-tabs@~11.9.1:- version "11.9.1"- resolved "https://registry.yarnpkg.com/rc-tabs/-/rc-tabs-11.9.1.tgz#5b2e74da9a276978c2172ef9a05ae8af14da74cb"- integrity sha512-CLNx3qaWnO8KBWPd+7r52Pfk0MoPyKtlr+2ltWq2I9iqAjd1nZu6iBpQP7wbWBwIomyeFNw/WjHdRN7VcX5Qtw==+rc-tabs@~11.10.0:+ version "11.10.1"+ resolved "https://registry.yarnpkg.com/rc-tabs/-/rc-tabs-11.10.1.tgz#7b112f78bac998480c777ae160adc425e3fdb7cb"+ integrity sha512-ey1i2uMyfnRNYbViLcUYGH+Y7hueJbdCVSLaXnXki9hxBcGqxJMPy9t5xR0n/3QFQspj7Tf6+2VTXVtmO7Yaug==dependencies:"@babel/runtime" "^7.11.2"classnames "2.x"@@ -11815,7 +11858,7 @@ rc-tree@^4.0.0, rc-tree@~4.2.1:rc-util "^5.0.0"rc-virtual-list "^3.0.1"-rc-trigger@^5.0.0, rc-trigger@^5.0.4, rc-trigger@^5.1.2, rc-trigger@^5.2.1:+rc-trigger@^5.0.0, rc-trigger@^5.0.4, rc-trigger@^5.1.2:version "5.2.9"resolved "https://registry.yarnpkg.com/rc-trigger/-/rc-trigger-5.2.9.tgz#795a787d2b038347dcde27b89a4a5cec8fc40f3e"integrity sha512-0Bxsh2Xe+etejMn73am+jZBcOpsueAZiEKLiGoDfA0fvm/JHLNOiiww3zJ0qgyPOTmbYxhsxFcGOZu+VcbaZhQ==@@ -11826,6 +11869,17 @@ rc-trigger@^5.0.0, rc-trigger@^5.0.4, rc-trigger@^5.1.2, rc-trigger@^5.2.1:rc-motion "^2.0.0"rc-util "^5.5.0"+rc-trigger@^5.2.10:+ version "5.2.10"+ resolved "https://registry.yarnpkg.com/rc-trigger/-/rc-trigger-5.2.10.tgz#8a0057a940b1b9027eaa33beec8a6ecd85cce2b1"+ integrity sha512-FkUf4H9BOFDaIwu42fvRycXMAvkttph9AlbCZXssZDVzz2L+QZ0ERvfB/4nX3ZFPh1Zd+uVGr1DEDeXxq4J1TA==+ dependencies:+ "@babel/runtime" "^7.11.2"+ classnames "^2.2.6"+ rc-align "^4.0.0"+ rc-motion "^2.0.0"+ rc-util "^5.5.0"+rc-upload@~4.3.0:version "4.3.1"resolved "https://registry.yarnpkg.com/rc-upload/-/rc-upload-4.3.1.tgz#d6ee66b8bd1e1dd2f78526c486538423f7e7ed84"@@ -11883,14 +11937,6 @@ react-autowhatever@^10.1.2:react-themeable "^1.1.0"section-iterator "^2.0.0"-react-chartjs-2@^2.11.1:- version "2.11.2"- resolved "https://registry.yarnpkg.com/react-chartjs-2/-/react-chartjs-2-2.11.2.tgz#156c0d2618600561efc23bef278bd48a335cadb6"- integrity sha512-hcPS9vmRJeAALPPf0uo02BiD8BDm0HNmneJYTZVR74UKprXOpql+Jy1rVuj93rKw0Jfx77mkcRfXPxTe5K83uw==- dependencies:- lodash "^4.17.19"- prop-types "^15.7.2"-react-chips@^0.8.0:version "0.8.0"resolved "https://registry.yarnpkg.com/react-chips/-/react-chips-0.8.0.tgz#fc50c9fb469983989b356cf4595b86097ebacc25"@@ -11944,6 +11990,14 @@ [email protected]:object-assign "^4.1.1"scheduler "^0.20.0"+react-draggable@^4.0.0, react-draggable@^4.0.3:+ version "4.4.3"+ resolved "https://registry.yarnpkg.com/react-draggable/-/react-draggable-4.4.3.tgz#0727f2cae5813e36b0e4962bf11b2f9ef2b406f3"+ integrity sha512-jV4TE59MBuWm7gb6Ns3Q1mxX8Azffb7oTtDtBgFkxRvhDp38YAARmRplrj0+XGkhOJB5XziArX+4HUUABtyZ0w==+ dependencies:+ classnames "^2.2.5"+ prop-types "^15.6.0"+react-error-overlay@^6.0.9:version "6.0.9"resolved "https://registry.yarnpkg.com/react-error-overlay/-/react-error-overlay-6.0.9.tgz#3c743010c9359608c375ecd6bc76f35d93995b0a"@@ -11972,6 +12026,17 @@ react-graph-vis@^1.0.5:vis-data "^7.1.2"vis-network "^9.0.0"+react-grid-layout@^1.2.5:+ version "1.2.5"+ resolved "https://registry.yarnpkg.com/react-grid-layout/-/react-grid-layout-1.2.5.tgz#fa40288d5a1fa783484c44ce78b1e10eb5313d26"+ integrity sha512-P/NNWAExTX/zEq+RUh6hrIG67UBicDNCOOg9LZe8BAtSdYtCnCGgVmWBS+sIbM0C8RJIiyGsFHh5dIfCddhS/w==+ dependencies:+ classnames "2.3.1"+ lodash.isequal "^4.0.0"+ prop-types "^15.0.0"+ react-draggable "^4.0.0"+ react-resizable "^3.0.1"+react-hot-loader@^4.13.0:version "4.13.0"resolved "https://registry.yarnpkg.com/react-hot-loader/-/react-hot-loader-4.13.0.tgz#c27e9408581c2a678f5316e69c061b226dc6a202"@@ -12045,6 +12110,14 @@ react-refresh@^0.8.3:resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.8.3.tgz#721d4657672d400c5e3c75d063c4a85fb2d5d68f"integrity sha512-X8jZHc7nCMjaCqoU+V2I0cOhNW+QMBwSUkeXnTi8IPe6zaRWfn60ZzvFDZqWPfmSJfjub7dDW1SP0jaHWLu/hg==+react-resizable@^3.0.1:+ version "3.0.4"+ resolved "https://registry.yarnpkg.com/react-resizable/-/react-resizable-3.0.4.tgz#aa20108eff28c52c6fddaa49abfbef8abf5e581b"+ integrity sha512-StnwmiESiamNzdRHbSSvA65b0ZQJ7eVQpPusrSmcpyGKzC0gojhtO62xxH6YOBmepk9dQTBi9yxidL3W4s3EBA==+ dependencies:+ prop-types "15.x"+ react-draggable "^4.0.3"+react-router-dom@^5.2.0:version "5.2.0"resolved "https://registry.yarnpkg.com/react-router-dom/-/react-router-dom-5.2.0.tgz#9e65a4d0c45e13289e66c7b17c7e175d0ea15662"@@ -14238,7 +14311,7 @@ uuid@^3.3.2, uuid@^3.4.0:resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee"integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==-uuid@^8.3.0:+uuid@^8.3.0, uuid@^8.3.2:version "8.3.2"resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2"integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==