handles route specific default value connected to localstorage

This commit is contained in:
dhrubesh 2021-05-16 18:35:50 +05:30
parent 8b0abbec79
commit 38770809e3
6 changed files with 138 additions and 81 deletions

View File

@ -1,3 +1,3 @@
export enum LOCAL_STORAGE { export enum LOCAL_STORAGE {
METRICS_TIME_IN_DURATION = "metricsTimeDuration", METRICS_TIME_IN_DURATION = "metricsTimeDurations",
} }

View File

@ -1,17 +1,11 @@
import React, { Suspense } from "react"; import React, { Suspense } from "react";
import { Layout, Spin } from "antd"; import { Spin } from "antd";
import { useThemeSwitcher } from "react-css-theme-switcher"; import { useThemeSwitcher } from "react-css-theme-switcher";
import ROUTES from "Src/constants/routes"; import ROUTES from "Src/constants/routes";
import { IS_LOGGED_IN } from "Src/constants/auth"; import { IS_LOGGED_IN } from "Src/constants/auth";
import { import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
BrowserRouter as Router,
Route,
Switch,
Redirect,
} from "react-router-dom";
import SideNav from "./Nav/SideNav"; import BaseLayout from "./BaseLayout";
import TopNav from "./Nav/TopNav";
import { import {
ServiceMetrics, ServiceMetrics,
ServiceMap, ServiceMap,
@ -24,8 +18,6 @@ import {
IntstrumentationPage, IntstrumentationPage,
} from "Src/pages"; } from "Src/pages";
const { Content, Footer } = Layout;
const App = () => { const App = () => {
const { status } = useThemeSwitcher(); const { status } = useThemeSwitcher();
@ -34,47 +26,44 @@ const App = () => {
} }
return ( return (
<Router basename="/"> <BrowserRouter>
<Layout style={{ minHeight: "100vh" }}> <Suspense fallback={<Spin size="large" />}>
<SideNav /> <Route path={"/"}>
<Layout className="site-layout"> <Switch>
<Content style={{ margin: "0 16px" }}> <BaseLayout>
<TopNav /> <Route path={ROUTES.SIGN_UP} exact component={Signup} />
<Suspense fallback={<Spin size="large" />}> <Route path={ROUTES.APPLICATION} exact component={ServicesTable} />
<Switch> <Route path={ROUTES.SERVICE_METRICS} exact component={ServiceMetrics} />
<Route path={ROUTES.SIGN_UP} component={Signup} /> <Route path={ROUTES.SERVICE_MAP} exact component={ServiceMap} />
<Route path={ROUTES.SERVICE_METRICS} component={ServiceMetrics} /> <Route path={ROUTES.TRACES} exact component={TraceDetail} />
<Route path={ROUTES.SERVICE_MAP} component={ServiceMap} /> <Route path={ROUTES.TRACE_GRAPH} exact component={TraceGraph} />
<Route path={ROUTES.TRACES} exact component={TraceDetail} /> <Route path={ROUTES.SETTINGS} exact component={SettingsPage} />
<Route path={ROUTES.TRACE_GRAPH} component={TraceGraph} /> <Route
<Route path={ROUTES.SETTINGS} exact component={SettingsPage} /> path={ROUTES.INSTRUMENTATION}
<Route exact
path={ROUTES.INSTRUMENTATION} component={IntstrumentationPage}
exact />
component={IntstrumentationPage} <Route
/> path={ROUTES.USAGE_EXPLORER}
<Route path={ROUTES.USAGE_EXPLORER} component={UsageExplorer} /> exactexact
<Route path={ROUTES.APPLICATION} exact component={ServicesTable} /> component={UsageExplorer}
<Route />
path="/" <Route
exact path="/"
render={() => { exact
return localStorage.getItem(IS_LOGGED_IN) === "yes" ? ( render={() => {
<Redirect to={ROUTES.APPLICATION} /> return localStorage.getItem(IS_LOGGED_IN) === "yes" ? (
) : ( <Redirect to={ROUTES.APPLICATION} />
<Redirect to={ROUTES.SIGN_UP} /> ) : (
); <Redirect to={ROUTES.SIGN_UP} />
}} );
/> }}
</Switch> />
</Suspense> </BaseLayout>
</Content> </Switch>
<Footer style={{ textAlign: "center", fontSize: 10 }}> </Route>
SigNoz Inc. ©2020{" "} </Suspense>
</Footer> </BrowserRouter>
</Layout>
</Layout>
</Router>
); );
}; };

View File

@ -0,0 +1,29 @@
import React, { ReactNode } from "react";
import { Layout } from "antd";
import SideNav from "./Nav/SideNav";
import TopNav from "./Nav/TopNav";
const { Content, Footer } = Layout;
interface BaseLayoutProps {
children: ReactNode;
}
const BaseLayout: React.FC<BaseLayoutProps> = ({ children }) => {
return (
<Layout style={{ minHeight: "100vh" }}>
<SideNav />
<Layout className="site-layout">
<Content style={{ margin: "0 16px" }}>
<TopNav />
{children}
</Content>
<Footer style={{ textAlign: "center", fontSize: 10 }}>
SigNoz Inc. ©2020{" "}
</Footer>
</Layout>
</Layout>
);
};
export default BaseLayout;

View File

@ -1,11 +1,12 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { cloneDeep } from "lodash";
import { Select as DefaultSelect, Button, Space, Form } from "antd"; import { Select as DefaultSelect, Button, Space, Form } from "antd";
import styled from "styled-components"; import styled from "styled-components";
import { withRouter } from "react-router"; import { withRouter } from "react-router";
import { getLocalStorageRouteKey } from "./utils";
import { RouteComponentProps, useLocation } from "react-router-dom"; import { RouteComponentProps, useLocation } from "react-router-dom";
import { connect } from "react-redux"; import { connect } from "react-redux";
import ROUTES from "Src/constants/routes"; import ROUTES from "Src/constants/routes";
import { findIndex } from "lodash";
import CustomDateTimeModal from "./CustomDateTimeModal"; import CustomDateTimeModal from "./CustomDateTimeModal";
import { GlobalTime, updateTimeInterval } from "../../../store/actions"; import { GlobalTime, updateTimeInterval } from "../../../store/actions";
import { StoreState } from "../../../store/reducers"; import { StoreState } from "../../../store/reducers";
@ -25,9 +26,7 @@ const DateTimeWrapper = styled.div`
margin-top: 20px; margin-top: 20px;
justify-content: flex-end !important; justify-content: flex-end !important;
`; `;
const Select = styled(DefaultSelect)` const Select = styled(DefaultSelect)``;
width: 150px;
`;
interface DateTimeSelectorProps extends RouteComponentProps<any> { interface DateTimeSelectorProps extends RouteComponentProps<any> {
currentpath?: string; currentpath?: string;
updateTimeInterval: Function; updateTimeInterval: Function;
@ -39,14 +38,23 @@ This components is mounted all the time. Use event listener to track changes.
*/ */
const _DateTimeSelector = (props: DateTimeSelectorProps) => { const _DateTimeSelector = (props: DateTimeSelectorProps) => {
const location = useLocation(); const location = useLocation();
const LocalStorageRouteKey: string = getLocalStorageRouteKey(
location.pathname,
);
const timeDurationInLocalStorage =
JSON.parse(localStorage.getItem(LOCAL_STORAGE.METRICS_TIME_IN_DURATION)) ||
{};
const options = const options =
location.pathname === ROUTES.SERVICE_MAP ? ServiceMapOptions : Options; location.pathname === ROUTES.SERVICE_MAP ? ServiceMapOptions : Options;
const defaultTime = let defaultTime = DefaultOptionsBasedOnRoute[LocalStorageRouteKey]
location.pathname === ROUTES.SERVICE_MAP || ? DefaultOptionsBasedOnRoute[LocalStorageRouteKey]
location.pathname === ROUTES.APPLICATION : DefaultOptionsBasedOnRoute.default;
? DefaultOptionsBasedOnRoute[location.pathname] if (timeDurationInLocalStorage[LocalStorageRouteKey]) {
: DefaultOptionsBasedOnRoute.default; defaultTime = timeDurationInLocalStorage[LocalStorageRouteKey];
}
const [currentLocalStorageRouteKey, setCurrentLocalStorageRouteKey] = useState(
LocalStorageRouteKey,
);
const [customDTPickerVisible, setCustomDTPickerVisible] = useState(false); const [customDTPickerVisible, setCustomDTPickerVisible] = useState(false);
const [timeInterval, setTimeInterval] = useState(defaultTime); const [timeInterval, setTimeInterval] = useState(defaultTime);
const [startTime, setStartTime] = useState<moment.Moment | null>(null); const [startTime, setStartTime] = useState<moment.Moment | null>(null);
@ -57,9 +65,6 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {
const [form_dtselector] = Form.useForm(); const [form_dtselector] = Form.useForm();
const updateTimeOnQueryParamChange = () => { const updateTimeOnQueryParamChange = () => {
const timeDurationInLocalStorage = localStorage.getItem(
LOCAL_STORAGE.METRICS_TIME_IN_DURATION,
);
const urlParams = new URLSearchParams(location.search); const urlParams = new URLSearchParams(location.search);
const intervalInQueryParam = urlParams.get(METRICS_PAGE_QUERY_PARAM.interval); const intervalInQueryParam = urlParams.get(METRICS_PAGE_QUERY_PARAM.interval);
const startTimeString = urlParams.get(METRICS_PAGE_QUERY_PARAM.startTime); const startTimeString = urlParams.get(METRICS_PAGE_QUERY_PARAM.startTime);
@ -75,25 +80,38 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {
const startTime = moment(Number(startTimeString)); const startTime = moment(Number(startTimeString));
const endTime = moment(Number(endTimeString)); const endTime = moment(Number(endTimeString));
setCustomTime(startTime, endTime, true); setCustomTime(startTime, endTime, true);
} else if (currentLocalStorageRouteKey !== LocalStorageRouteKey) {
setMetricsTimeInterval(defaultTime);
setCurrentLocalStorageRouteKey(LocalStorageRouteKey);
} }
// first pref: handle intervalInQueryParam // first pref: handle intervalInQueryParam
else if (intervalInQueryParam) { else if (intervalInQueryParam) {
window.localStorage.setItem(
LOCAL_STORAGE.METRICS_TIME_IN_DURATION,
intervalInQueryParam,
);
setMetricsTimeInterval(intervalInQueryParam); setMetricsTimeInterval(intervalInQueryParam);
} else if (timeDurationInLocalStorage) {
setMetricsTimeInterval(timeDurationInLocalStorage);
} }
}; };
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),
);
};
useEffect(() => {
setMetricsTimeInterval(defaultTime);
}, []);
// On URL Change // On URL Change
useEffect(() => { useEffect(() => {
updateTimeOnQueryParamChange(); updateTimeOnQueryParamChange();
if (findIndex(options, (option) => option.value === timeInterval) === -1) {
setTimeInterval(defaultTime);
}
}, [location]); }, [location]);
const setMetricsTimeInterval = (value: string) => { const setMetricsTimeInterval = (value: string) => {
@ -101,8 +119,7 @@ const _DateTimeSelector = (props: DateTimeSelectorProps) => {
setTimeInterval(value); setTimeInterval(value);
setEndTime(null); setEndTime(null);
setStartTime(null); setStartTime(null);
setToLocalStorage(value);
window.localStorage.setItem(LOCAL_STORAGE.METRICS_TIME_IN_DURATION, value);
}; };
const setCustomTime = ( const setCustomTime = (
startTime: moment.Moment, startTime: moment.Moment,
@ -259,8 +276,10 @@ const mapStateToProps = (state: StoreState): { globalTime: GlobalTime } => {
return { globalTime: state.globalTime }; return { globalTime: state.globalTime };
}; };
export const DateTimeSelector = connect(mapStateToProps, { export const DateTimeSelector = withRouter(
updateTimeInterval: updateTimeInterval, connect(mapStateToProps, {
})(_DateTimeSelector); updateTimeInterval: updateTimeInterval,
})(_DateTimeSelector),
);
export default withRouter(DateTimeSelector); export default DateTimeSelector;

View File

@ -19,5 +19,6 @@ export const ServiceMapOptions = [
export const DefaultOptionsBasedOnRoute = { export const DefaultOptionsBasedOnRoute = {
[ROUTES.SERVICE_MAP]: ServiceMapOptions[0].value, [ROUTES.SERVICE_MAP]: ServiceMapOptions[0].value,
[ROUTES.APPLICATION]: Options[0].value, [ROUTES.APPLICATION]: Options[0].value,
[ROUTES.SERVICE_METRICS]: Options[2].value,
default: Options[2].value, default: Options[2].value,
}; };

View File

@ -0,0 +1,19 @@
import ROUTES from "Src/constants/routes";
export const getLocalStorageRouteKey = (pathName: string) => {
let localStorageKey = "";
const pathNameSplit = pathName.split("/");
console.log("pathName", pathName);
if (!pathNameSplit[2]) {
localStorageKey = pathName;
} else {
Object.keys(ROUTES).forEach((key) => {
if (ROUTES[key].indexOf(":") > -1) {
if (ROUTES[key].indexOf(pathNameSplit[1]) > -1) {
localStorageKey = ROUTES[key];
}
}
});
}
return localStorageKey;
};