Skip to content

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

refactor(react-router): route every react-router call through a src/lib/router facade (#13173)

Vinicius Lourençobd4bcdb6ce27
diff --git a/.claude/skills/signoz-page-story/references/discovery.md b/.claude/skills/signoz-page-story/references/discovery.md
index 32314b301d..d2e878b131 100644
--- a/.claude/skills/signoz-page-story/references/discovery.md
+++ b/.claude/skills/signoz-page-story/references/discovery.md
@@ -14,7 +14,7 @@ Grep recipes, run against the page's directories:
| endpoint URLs | the api module's `axios.get\|post` |
| endpoint URLs behind a generated hook | the hook lives in `src/api/generated/services/<name>/index.ts` and the URL only appears in the fetcher body: `rg 'url: \`' src/api/generated/services/<name>/` |
| url state | `useUrlQuery\|useUrlQueryData\|useUrlSearchState\|useQueryState\|QueryParams\.` |
-| navigation | `useSafeNavigate\|history.push\|<Link` |
+| navigation | `useSafeNavigate\|useAppNavigate\|navigate\|<AppLink` |
| permissions | `useAuthZ\|AuthZGuard\|AuthZButton\|hasEditPermission\|routePermission` |
| flags and prefs | `useFeatureFlag\|FeatureKeys\.\|USER_PREFERENCES\.\|userPreferences` |
| empty and error branches | `isLoading\|isError\|isFetching\|length === 0\|!data` |
diff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.json
index da4a9ef468..36b989c14e 100644
--- a/frontend/.oxlintrc.json
+++ b/frontend/.oxlintrc.json
@@ -294,6 +294,8 @@
// Forces useDashboardFetchRequired() outside the root V2 pages (allowlisted in overrides below)
"signoz/no-msw-in-story-file": "error",
// Bans msw imports in *.stories.tsx; handlers/mock data belong in the sibling .stories.mocks.tsx
+ "signoz/no-direct-react-router-import": "error",
+ // Steers call sites to the src/lib/router facade (allowlisted in overrides below)
"no-restricted-globals": [
"error",
{
@@ -589,6 +591,23 @@
"rules": {
"no-redeclare": "off"
}
+ },
+ {
+ // The react-router allowlist: the facade itself, the route table, `useSafeNavigate`,
+ // the history singleton and the test and story router mounts. Test files are
+ // deliberately absent: they render at a route or use tests/router-mocks.
+ "files": [
+ "src/lib/router/**",
+ "src/AppRoutes/**",
+ "src/hooks/useSafeNavigate.ts",
+ "src/lib/history.ts",
+ "src/tests/router.tsx",
+ "src/storybook/providers/StorybookProviders.tsx",
+ "src/storybook/renderAtRoute.tsx"
+ ],
+ "rules": {
+ "signoz/no-direct-react-router-import": "off"
+ }
}
]
}
diff --git a/frontend/plugins/__tests__/no-direct-react-router-import.test.mjs b/frontend/plugins/__tests__/no-direct-react-router-import.test.mjs
new file mode 100644
index 0000000000..ded39bcd7b
--- /dev/null
+++ b/frontend/plugins/__tests__/no-direct-react-router-import.test.mjs
@@ -0,0 +1,126 @@
+import { ruleTester } from './rule-tester.mjs';
+
+const FACADE = 'src/lib/router facade';
+const HISTORY = 'lib/history singleton';
+const MOCK = 'tests/router-mocks helpers';
+
+await ruleTester({
+ rule: 'no-direct-react-router-import',
+ valid: [
+ {
+ name: 'facade import',
+ code: "import { useAppNavigate } from 'lib/router/useAppNavigate';",
+ },
+ {
+ name:
+ 'the history package itself is a version-bump concern, not a facade one',
+ code: "import { createBrowserHistory } from 'history';",
+ },
+ {
+ name: 'unrelated module whose name contains history',
+ code: "import { useHistoryPanel } from 'container/HistoryPanel';",
+ },
+ {
+ name: 'mocking a facade module',
+ code: "jest.mock('lib/router/navigation');",
+ },
+ {
+ name: 'jest call that does not name a module',
+ code: 'jest.fn();',
+ },
+ {
+ name: 'require of an unrelated module',
+ code: "const x = require('lib/dashboardVariables');",
+ },
+ {
+ name: 'export without a source',
+ code: 'const a = 1;\nexport { a };',
+ },
+ ],
+ invalid: [
+ {
+ name: 'jest.mock of react-router-dom',
+ code: "jest.mock('react-router-dom', () => ({}));",
+ errors: [{ message: MOCK, line: 1, column: 11 }],
+ },
+ {
+ name: 'jest.requireActual of react-router-dom',
+ code: "const actual = jest.requireActual('react-router-dom');",
+ errors: [{ message: MOCK }],
+ },
+ {
+ name: 'jest.mock of lib/history',
+ code: "jest.mock('lib/history');",
+ errors: [{ message: MOCK }],
+ },
+ {
+ name: 'jest.doMock of react-router-dom-v5-compat',
+ code: "jest.doMock('react-router-dom-v5-compat');",
+ errors: [{ message: MOCK }],
+ },
+ {
+ name: 'react-router-dom named import',
+ code: "import { useHistory } from 'react-router-dom';",
+ errors: [{ message: FACADE, line: 1, column: 28 }],
+ },
+ {
+ name: 'react-router named import',
+ code: "import { useLocation } from 'react-router';",
+ errors: [{ message: FACADE }],
+ },
+ {
+ name: 'react-router-dom type-only import',
+ code: "import type { RouteProps } from 'react-router-dom';",
+ errors: [{ message: FACADE }],
+ },
+ {
+ name: 'react-router-dom-v5-compat',
+ code: "import { useNavigate } from 'react-router-dom-v5-compat';",
+ errors: [{ message: 'compat package is an implementation detail' }],
+ },
+ {
+ name: 'lib/history default import',
+ code: "import history from 'lib/history';",
+ errors: [{ message: HISTORY }],
+ },
+ {
+ name: 'lib/history through the @/ alias',
+ code: "import history from '@/lib/history';",
+ errors: [{ message: HISTORY }],
+ },
+ {
+ name: 'jest.mock of lib/history through the @/ alias',
+ code: "jest.mock('@/lib/history');",
+ errors: [{ message: MOCK }],
+ },
+ {
+ name: 'lib/history require',
+ code: "const history = require('lib/history').default;",
+ errors: [{ message: HISTORY }],
+ },
+ {
+ name: 'dynamic import',
+ code: "const mod = await import('react-router-dom');",
+ errors: [{ message: FACADE }],
+ },
+ {
+ name: 're-export',
+ code: "export { Link } from 'react-router-dom';",
+ errors: [{ message: FACADE }],
+ },
+ {
+ name: 'export all',
+ code: "export * from 'react-router-dom';",
+ errors: [{ message: FACADE }],
+ },
+ {
+ name: 'one report per import statement',
+ code:
+ "import { Link } from 'react-router-dom';\nimport history from 'lib/history';",
+ errors: [
+ { message: FACADE, line: 1 },
+ { message: HISTORY, line: 2 },
+ ],
+ },
+ ],
+});
diff --git a/frontend/plugins/rules/no-direct-react-router-import.mjs b/frontend/plugins/rules/no-direct-react-router-import.mjs
new file mode 100644
index 0000000000..6ce8c85f58
--- /dev/null
+++ b/frontend/plugins/rules/no-direct-react-router-import.mjs
@@ -0,0 +1,123 @@
+/**
+ * Rule: no-direct-react-router-import
+ *
+ * Every router concern goes through the `src/lib/router/*` facade, so a router
+ * upgrade is a change to one directory instead of ~300 call sites. This rule
+ * keeps new call sites, and test mocks, from reaching past it.
+ *
+ * `history` (the package) is deliberately not flagged: it is a transitive concern of
+ * the version bump, not something the facade replaces.
+ *
+ * The allowlist (the facade itself, the route table, `useSafeNavigate`, the history
+ * singleton and the test and story router mounts) is applied via overrides in
+ * .oxlintrc.json, not here, so the file list stays visible next to the severity.
+ */
+
+import path from 'node:path';
+
+const HISTORY_MODULE_SUFFIX = path.join('src', 'lib', 'history');
+
+const JEST_MODULE_METHODS = new Set([
+ 'mock',
+ 'doMock',
+ 'unmock',
+ 'dontMock',
+ 'setMock',
+ 'requireActual',
+ 'requireMock',
+ 'createMockFromModule',
+]);
+
+const MESSAGE_IDS = {
+ 'react-router': 'v5Router',
+ 'react-router-dom': 'v5Router',
+ 'react-router-dom-v5-compat': 'v6Compat',
+ 'lib/history': 'historySingleton',
+ '@/lib/history': 'historySingleton',
+};
+
+/** Resolves `./history` / `../history` so files inside src/lib count too. */
+function isHistoryModule(specifier, filename) {
+ if (!specifier.startsWith('.') || !filename) {
+ return false;
+ }
+ const resolved = path.resolve(path.dirname(filename), specifier);
+ return (
+ resolved.endsWith(HISTORY_MODULE_SUFFIX) ||
+ resolved.endsWith(`${HISTORY_MODULE_SUFFIX}.ts`)
+ );
+}
+
+function messageIdFor(specifier, filename) {
+ if (MESSAGE_IDS[specifier] !== undefined) {
+ return MESSAGE_IDS[specifier];
+ }
+ return isHistoryModule(specifier, filename) ? 'historySingleton' : null;
+}
+
+export default {
+ meta: {
+ type: 'suggestion',
+ docs: {
+ description:
+ 'Disallow direct react-router / lib/history imports; import from src/lib/router instead',
+ category: 'React Router migration',
+ },
+ schema: [],
+ messages: {
+ v5Router:
+ 'Do not import react-router-dom directly. Use the src/lib/router facade (useAppNavigate, useAppLocation, useAppParams, AppLink, Redirect, matchRoute) so a router upgrade stays contained.',
+ v6Compat:
+ 'Do not import react-router-dom-v5-compat directly. Use the src/lib/router facade instead; the compat package is an implementation detail of the migration and disappears with it.',
+ historySingleton:
+ 'Do not import the lib/history singleton. Use the helpers in src/lib/router/navigation.ts, or useAppNavigate() to follow the nearest router. history loses basename handling once the router owns it.',
+ mock:
+ 'Do not mock the router directly. Render at a route with tests/test-utils, or spy on the facade with the tests/router-mocks helpers.',
+ },
+ },
+
+ create(context) {
+ const report = (sourceNode, overrideMessageId) => {
+ if (
+ sourceNode === null ||
+ sourceNode === undefined ||
+ typeof sourceNode.value !== 'string'
+ ) {
+ return;
+ }
+ const messageId = messageIdFor(sourceNode.value, context.filename);
+ if (messageId !== null) {
+ context.report({
+ node: sourceNode,
+ messageId: overrideMessageId ?? messageId,
+ });
+ }
+ };
+
+ return {
+ ImportDeclaration: (node) => report(node.source),
+ ImportExpression: (node) => report(node.source),
+ ExportAllDeclaration: (node) => report(node.source),
+ ExportNamedDeclaration: (node) => report(node.source),
+ CallExpression(node) {
+ const { callee } = node;
+ if (
+ (callee.type === 'Identifier' && callee.name === 'require') ||
+ callee.type === 'Import'
+ ) {
+ report(node.arguments[0]);
+ return;
+ }
+ if (
+ callee.type === 'MemberExpression' &&
+ callee.object.type === 'Identifier' &&
+ callee.object.name === 'jest' &&
+ callee.property.type === 'Identifier' &&
+ JEST_MODULE_METHODS.has(callee.property.name)
+ ) {
+ report(node.arguments[0], 'mock');
+ }
+ },
+ };
+ },
+};
diff --git a/frontend/plugins/signoz.mjs b/frontend/plugins/signoz.mjs
index 038a9ef8be..70bbc2a8f1 100644
--- a/frontend/plugins/signoz.mjs
+++ b/frontend/plugins/signoz.mjs
@@ -16,6 +16,7 @@ import noDashboardFetchOutsideRoot from './rules/no-dashboard-fetch-outside-root
import noConditionalTextNodesWithSiblings from './rules/no-conditional-text-nodes-with-siblings.mjs';
import noReturnTextNodes from './rules/no-return-text-nodes.mjs';
import noMswInStoryFile from './rules/no-msw-in-story-file.mjs';
+import noDirectReactRouterImport from './rules/no-direct-react-router-import.mjs';
export default {
meta: {
@@ -33,5 +34,6 @@ export default {
'no-conditional-text-nodes-with-siblings': noConditionalTextNodesWithSiblings,
'no-return-text-nodes': noReturnTextNodes,
'no-msw-in-story-file': noMswInStoryFile,
+ 'no-direct-react-router-import': noDirectReactRouterImport,
},
};
diff --git a/frontend/src/api/utils.ts b/frontend/src/api/utils.ts
index b98aa02403..c5855c1e58 100644
--- a/frontend/src/api/utils.ts
+++ b/frontend/src/api/utils.ts
@@ -1,7 +1,7 @@
import deleteLocalStorageKey from 'api/browser/localstorage/remove';
import { LOCALSTORAGE } from 'constants/localStorage';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import deleteSession from './v2/sessions/delete';
@@ -21,5 +21,5 @@ export const Logout = async (): Promise<void> => {
deleteLocalStorageKey(LOCALSTORAGE.CHAT_SUPPORT);
deleteLocalStorageKey(LOCALSTORAGE.USER_ID);
window.dispatchEvent(new CustomEvent('LOGOUT'));
- history.push(ROUTES.LOGIN);
+ navigate(ROUTES.LOGIN);
};
diff --git a/frontend/src/components/CeleryOverview/CeleryOverviewConfigOptions/CeleryOverviewConfigOptions.tsx b/frontend/src/components/CeleryOverview/CeleryOverviewConfigOptions/CeleryOverviewConfigOptions.tsx
index d602b721f7..acbb407d54 100644
--- a/frontend/src/components/CeleryOverview/CeleryOverviewConfigOptions/CeleryOverviewConfigOptions.tsx
+++ b/frontend/src/components/CeleryOverview/CeleryOverviewConfigOptions/CeleryOverviewConfigOptions.tsx
@@ -1,6 +1,7 @@
import { useCallback, useMemo, useState } from 'react';
-import { useHistory, useLocation } from 'react-router-dom';
import { Row, Select, Spin } from 'antd';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import {
getValuesFromQueryParams,
setQueryParamsFromOptions,
@@ -35,8 +36,7 @@ export function FilterSelect({
useCeleryFilterOptions(filterType);
const urlQuery = useUrlQuery();
- const history = useHistory();
- const location = useLocation();
+ const location = useAppLocation();
// Add state to track the current search input
const [searchValue, setSearchValue] = useState<string>('');
@@ -66,7 +66,7 @@ export function FilterSelect({
setQueryParamsFromOptions(
value as string[],
urlQuery,
- history,
+ navigate,
location,
queryParam,
);
@@ -77,7 +77,6 @@ export function FilterSelect({
handleSearch,
shouldSetQueryParams,
urlQuery,
- history,
location,
queryParam,
onChange,
diff --git a/frontend/src/components/CeleryTask/CeleryTaskConfigOptions/CeleryTaskConfigOptions.tsx b/frontend/src/components/CeleryTask/CeleryTaskConfigOptions/CeleryTaskConfigOptions.tsx
index b2c7a59ded..2f7805a614 100644
--- a/frontend/src/components/CeleryTask/CeleryTaskConfigOptions/CeleryTaskConfigOptions.tsx
+++ b/frontend/src/components/CeleryTask/CeleryTaskConfigOptions/CeleryTaskConfigOptions.tsx
@@ -1,5 +1,6 @@
-import { useHistory, useLocation } from 'react-router-dom';
import { Select, Spin } from 'antd';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Typography } from '@signozhq/ui/typography';
import { SelectMaxTagPlaceholder } from 'components/MessagingQueues/MQCommon/MQCommon';
import { QueryParams } from 'constants/query';
@@ -16,8 +17,7 @@ import './CeleryTaskConfigOptions.styles.scss';
function CeleryTaskConfigOptions(): JSX.Element {
const { handleSearch, isFetching, options } =
useCeleryFilterOptions('celery.task_name');
- const history = useHistory();
- const location = useLocation();
+ const location = useAppLocation();
const urlQuery = useUrlQuery();
@@ -52,7 +52,7 @@ function CeleryTaskConfigOptions(): JSX.Element {
setQueryParamsFromOptions(
value,
urlQuery,
- history,
+ navigate,
location,
QueryParams.taskName,
);
diff --git a/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskBar.tsx b/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskBar.tsx
index f826368a01..b20395b43f 100644
--- a/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskBar.tsx
+++ b/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskBar.tsx
@@ -1,8 +1,9 @@
import { useCallback, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
import { Color } from '@signozhq/design-tokens';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { ViewMenuAction } from 'container/WidgetCard/config';
@@ -50,8 +51,7 @@ function CeleryTaskBar({
queryEnabled: boolean;
checkIfDataExists?: (isDataAvailable: boolean) => void;
}): JSX.Element {
- const history = useHistory();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const dispatch = useDispatch();
const urlQuery = useUrlQuery();
const isDarkMode = useIsDarkMode();
@@ -68,13 +68,13 @@ function CeleryTaskBar({
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
}
},
- [dispatch, history, pathname, urlQuery],
+ [dispatch, pathname, urlQuery],
);
const [barState, setBarState] = useState<CeleryTaskState>(CeleryTaskState.All);
diff --git a/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskGraph.tsx b/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskGraph.tsx
index 41bd6539da..e614a729c3 100644
--- a/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskGraph.tsx
+++ b/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskGraph.tsx
@@ -1,8 +1,9 @@
import { useCallback, useMemo } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
import { ENTITY_VERSION_V4 } from 'constants/app';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { ViewMenuAction } from 'container/WidgetCard/config';
@@ -54,8 +55,7 @@ function CeleryTaskGraph({
checkIfDataExists?: (isDataAvailable: boolean) => void;
analyticsEvent?: string;
}): JSX.Element {
- const history = useHistory();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const dispatch = useDispatch();
const urlQuery = useUrlQuery();
const isDarkMode = useIsDarkMode();
@@ -83,13 +83,13 @@ function CeleryTaskGraph({
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
}
},
- [dispatch, history, pathname, urlQuery],
+ [dispatch, pathname, urlQuery],
);
return (
diff --git a/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskLatencyGraph.tsx b/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskLatencyGraph.tsx
index a1030da5ed..1ef2dd3950 100644
--- a/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskLatencyGraph.tsx
+++ b/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskLatencyGraph.tsx
@@ -1,8 +1,9 @@
import { useCallback, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
import { Col, Row } from 'antd';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import logEvent from 'api/common/logEvent';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
@@ -48,8 +49,7 @@ function CeleryTaskLatencyGraph({
queryEnabled: boolean;
checkIfDataExists?: (isDataAvailable: boolean) => void;
}): JSX.Element {
- const history = useHistory();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const dispatch = useDispatch();
const urlQuery = useUrlQuery();
const isDarkMode = useIsDarkMode();
@@ -80,13 +80,13 @@ function CeleryTaskLatencyGraph({
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
}
},
- [dispatch, history, pathname, urlQuery],
+ [dispatch, pathname, urlQuery],
);
const selectedFilters = useMemo(
diff --git a/frontend/src/components/CeleryTask/CeleryUtils.ts b/frontend/src/components/CeleryTask/CeleryUtils.ts
index d8d2c0e79b..48e247a297 100644
--- a/frontend/src/components/CeleryTask/CeleryUtils.ts
+++ b/frontend/src/components/CeleryTask/CeleryUtils.ts
@@ -1,5 +1,5 @@
import { QueryParams } from 'constants/query';
-import { History, Location } from 'history';
+import type { AppLocation, NavigateFn } from 'lib/router/types';
import getRenderer from 'lib/uPlotLib/utils/getRenderer';
import { Widgets } from 'types/api/widgets/widget';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
@@ -17,13 +17,13 @@ export function getValuesFromQueryParams(
export function setQueryParamsFromOptions(
value: string[],
urlQuery: URLSearchParams,
- history: History<unknown>,
- location: Location<unknown>,
+ navigate: NavigateFn,
+ location: AppLocation,
queryParams: QueryParams,
): void {
urlQuery.set(queryParams, value.join(','));
const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
- history.replace(generatedUrl);
+ navigate(generatedUrl, { replace: true });
}
export function getFiltersFromQueryParams(
diff --git a/frontend/src/components/CustomTimePicker/CustomTimePicker.test.tsx b/frontend/src/components/CustomTimePicker/CustomTimePicker.test.tsx
index 78387187ac..4ea218d448 100644
--- a/frontend/src/components/CustomTimePicker/CustomTimePicker.test.tsx
+++ b/frontend/src/components/CustomTimePicker/CustomTimePicker.test.tsx
@@ -1,20 +1,12 @@
import { useState } from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import dayjs from 'dayjs';
+import { mockAppLocation } from 'tests/router-mocks';
import * as timeUtils from 'utils/timeUtils';
import CustomTimePicker from './CustomTimePicker';
-jest.mock('react-router-dom', () => {
- const actual = jest.requireActual('react-router-dom');
-
- return {
- ...actual,
- useLocation: jest.fn().mockReturnValue({
- pathname: '/test-path',
- }),
- };
-});
+mockAppLocation({ pathname: '/test-path' });
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
diff --git a/frontend/src/components/CustomTimePicker/CustomTimePicker.tsx b/frontend/src/components/CustomTimePicker/CustomTimePicker.tsx
index ac49be83af..d6b24ebcf4 100644
--- a/frontend/src/components/CustomTimePicker/CustomTimePicker.tsx
+++ b/frontend/src/components/CustomTimePicker/CustomTimePicker.tsx
@@ -6,7 +6,7 @@ import {
useRef,
useState,
} from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Button } from '@signozhq/ui/button';
import { Input, InputRef, Popover, Tooltip } from 'antd';
import cx from 'classnames';
@@ -109,7 +109,7 @@ function CustomTimePicker({
const [inputErrorDetails, setInputErrorDetails] = useState<
TimeRangeValidationResult['errorDetails'] | null
>(null);
- const location = useLocation();
+ const location = useAppLocation();
const inputRef = useRef<InputRef>(null);
const initialInputValueOnOpenRef = useRef<string>('');
diff --git a/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx b/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx
index d866e5c3a8..41861a5938 100644
--- a/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx
+++ b/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx
@@ -6,7 +6,7 @@ import {
useMemo,
useState,
} from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Color } from '@signozhq/design-tokens';
import { Button } from 'antd';
import logEvent from 'api/common/logEvent';
@@ -114,7 +114,7 @@ function CustomTimePickerPopoverContent({
customDateTimeInputStatus = CustomTimePickerInputStatus.UNSET,
inputErrorDetails,
}: CustomTimePickerPopoverContentProps): JSX.Element {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const isLogsExplorerPage = useMemo(
() => pathname === ROUTES.LOGS_EXPLORER,
diff --git a/frontend/src/components/CustomTimePicker/__tests__/customTimePickerZoomOut.test.tsx b/frontend/src/components/CustomTimePicker/__tests__/customTimePickerZoomOut.test.tsx
index 258aed21a3..d1fb966386 100644
--- a/frontend/src/components/CustomTimePicker/__tests__/customTimePickerZoomOut.test.tsx
+++ b/frontend/src/components/CustomTimePicker/__tests__/customTimePickerZoomOut.test.tsx
@@ -1,6 +1,7 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { QueryParams } from 'constants/query';
+import { mockAppLocation } from 'tests/router-mocks';
import { GlobalReducer } from 'types/reducer/globalTime';
import CustomTimePicker from '../CustomTimePicker';
@@ -59,10 +60,6 @@ jest.mock('providers/Timezone', () => ({
}),
}));
-jest.mock('react-router-dom', () => ({
- useLocation: (): { pathname: string } => ({ pathname: '/logs-explorer' }),
-}));
-
const MS_PER_DAY = 24 * 60 * 60 * 1000;
const now = Date.now();
const defaultProps = {
@@ -85,6 +82,7 @@ describe('CustomTimePicker - zoom out button', () => {
beforeEach(() => {
jest.clearAllMocks();
jest.spyOn(Date, 'now').mockReturnValue(NOW_MS);
+ mockAppLocation({ pathname: '/logs-explorer' });
});
afterEach(() => {
diff --git a/frontend/src/components/HeaderRightSection/FeedbackModal.tsx b/frontend/src/components/HeaderRightSection/FeedbackModal.tsx
index 96bd0441dd..8b4ae831af 100644
--- a/frontend/src/components/HeaderRightSection/FeedbackModal.tsx
+++ b/frontend/src/components/HeaderRightSection/FeedbackModal.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useState } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { toast } from '@signozhq/ui/sonner';
import { Button, Input } from 'antd';
import { ToggleGroup } from '@signozhq/ui/toggle-group';
@@ -11,7 +11,7 @@ import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
function FeedbackModal({ onClose }: { onClose: () => void }): JSX.Element {
const [activeTab, setActiveTab] = useState('feedback');
const [feedback, setFeedback] = useState('');
- const location = useLocation();
+ const location = useAppLocation();
const { isCloudUser: isCloudUserVal } = useGetTenantLicense();
const [isLoading, setIsLoading] = useState(false);
diff --git a/frontend/src/components/HeaderRightSection/HeaderRightSection.tsx b/frontend/src/components/HeaderRightSection/HeaderRightSection.tsx
index 39179eb665..80eae43e8e 100644
--- a/frontend/src/components/HeaderRightSection/HeaderRightSection.tsx
+++ b/frontend/src/components/HeaderRightSection/HeaderRightSection.tsx
@@ -1,5 +1,5 @@
import { useCallback, useState } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Dot } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
@@ -39,7 +39,7 @@ function HeaderRightSection({
enableFeedback,
shareModalExtraOption,
}: HeaderRightSectionProps): JSX.Element | null {
- const location = useLocation();
+ const location = useAppLocation();
const [openFeedbackModal, setOpenFeedbackModal] = useState(false);
const [openShareURLModal, setOpenShareURLModal] = useState(false);
diff --git a/frontend/src/components/HeaderRightSection/ShareURLModal.tsx b/frontend/src/components/HeaderRightSection/ShareURLModal.tsx
index 88e3036cf5..f217a7928b 100644
--- a/frontend/src/components/HeaderRightSection/ShareURLModal.tsx
+++ b/frontend/src/components/HeaderRightSection/ShareURLModal.tsx
@@ -1,7 +1,8 @@
import { useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { matchPath, useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { matchRoute } from 'lib/router/matchRoute';
import { useCopyToClipboard } from 'react-use';
import { Color } from '@signozhq/design-tokens';
import { Button } from 'antd';
@@ -41,7 +42,7 @@ interface ShareURLModalProps {
function ShareURLModal({ extraOption }: ShareURLModalProps): JSX.Element {
const urlQuery = useUrlQuery();
- const location = useLocation();
+ const location = useAppLocation();
const { selectedTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
@@ -75,7 +76,7 @@ function ShareURLModal({ extraOption }: ShareURLModalProps): JSX.Element {
const isRouteToBeSharedWithTime = useMemo(
() =>
routesToBeSharedWithTime.some((route) =>
- matchPath(location.pathname, { path: route, exact: true }),
+ matchRoute(location.pathname, route, { exact: true }),
),
[location.pathname],
);
diff --git a/frontend/src/components/HeaderRightSection/__tests__/FeedbackModal.test.tsx b/frontend/src/components/HeaderRightSection/__tests__/FeedbackModal.test.tsx
index 926ced79fc..12147717b2 100644
--- a/frontend/src/components/HeaderRightSection/__tests__/FeedbackModal.test.tsx
+++ b/frontend/src/components/HeaderRightSection/__tests__/FeedbackModal.test.tsx
@@ -1,5 +1,5 @@
// Mock dependencies before imports
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { toast } from '@signozhq/ui/sonner';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -9,9 +9,8 @@ import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import FeedbackModal from '../FeedbackModal';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: jest.fn(),
+jest.mock('lib/router/useAppLocation', () => ({
+ useAppLocation: jest.fn(),
}));
jest.mock('@signozhq/ui/sonner', () => ({
@@ -30,7 +29,7 @@ jest.mock('container/Integrations/utils', () => ({
handleContactSupport: jest.fn(),
}));
-const mockUseLocation = useLocation as jest.Mock;
+const mockUseAppLocation = useAppLocation as jest.Mock;
const mockUseGetTenantLicense = useGetTenantLicense as jest.Mock;
const mockHandleContactSupport = handleContactSupport as jest.Mock;
const mockToast = toast as jest.Mocked<typeof toast>;
@@ -45,7 +44,7 @@ describe('FeedbackModal', () => {
beforeEach(() => {
jest.clearAllMocks();
logEventMock.mockReturnValue(Promise.resolve() as never);
- mockUseLocation.mockReturnValue(mockLocation);
+ mockUseAppLocation.mockReturnValue(mockLocation);
mockUseGetTenantLicense.mockReturnValue({
isCloudUser: false,
});
diff --git a/frontend/src/components/HeaderRightSection/__tests__/HeaderRightSection.test.tsx b/frontend/src/components/HeaderRightSection/__tests__/HeaderRightSection.test.tsx
index 35324c705a..ec902c15ba 100644
--- a/frontend/src/components/HeaderRightSection/__tests__/HeaderRightSection.test.tsx
+++ b/frontend/src/components/HeaderRightSection/__tests__/HeaderRightSection.test.tsx
@@ -1,5 +1,5 @@
// Mock dependencies before imports
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { logEventMock } from '__tests__/logEventMock';
@@ -7,9 +7,8 @@ import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import HeaderRightSection from '../HeaderRightSection';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: jest.fn(),
+jest.mock('lib/router/useAppLocation', () => ({
+ useAppLocation: jest.fn(),
}));
jest.mock('../FeedbackModal', () => ({
@@ -45,7 +44,7 @@ jest.mock('hooks/useIsAIAssistantEnabled', () => ({
useIsAIAssistantEnabled: (): boolean => false,
}));
-const mockUseLocation = useLocation as jest.Mock;
+const mockUseAppLocation = useAppLocation as jest.Mock;
const mockUseGetTenantLicense = useGetTenantLicense as jest.Mock;
const defaultProps = {
@@ -61,7 +60,7 @@ const mockLocation = {
describe('HeaderRightSection', () => {
beforeEach(() => {
jest.clearAllMocks();
- mockUseLocation.mockReturnValue(mockLocation);
+ mockUseAppLocation.mockReturnValue(mockLocation);
// Default to licensed user (Enterprise or Cloud)
mockUseGetTenantLicense.mockReturnValue({
isCloudUser: true,
diff --git a/frontend/src/components/HeaderRightSection/__tests__/ShareURLModal.test.tsx b/frontend/src/components/HeaderRightSection/__tests__/ShareURLModal.test.tsx
index 47506edd41..d0c6f546f6 100644
--- a/frontend/src/components/HeaderRightSection/__tests__/ShareURLModal.test.tsx
+++ b/frontend/src/components/HeaderRightSection/__tests__/ShareURLModal.test.tsx
@@ -1,7 +1,8 @@
// Mock dependencies before imports
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { matchPath, useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { matchRoute } from 'lib/router/matchRoute';
import { useCopyToClipboard } from 'react-use';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -12,10 +13,12 @@ import GetMinMax from 'lib/getMinMax';
import ShareURLModal from '../ShareURLModal';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: jest.fn(),
- matchPath: jest.fn(),
+jest.mock('lib/router/useAppLocation', () => ({
+ useAppLocation: jest.fn(),
+}));
+
+jest.mock('lib/router/matchRoute', () => ({
+ matchRoute: jest.fn(),
}));
jest.mock('hooks/useUrlQuery', () => ({
@@ -48,12 +51,12 @@ Object.defineProperty(window, 'location', {
writable: true,
});
-const mockUseLocation = useLocation as jest.Mock;
+const mockUseAppLocation = useAppLocation as jest.Mock;
const mockUseUrlQuery = useUrlQuery as jest.Mock;
const mockUseSelector = useSelector as jest.Mock;
const mockGetMinMax = GetMinMax as jest.Mock;
const mockUseCopyToClipboard = useCopyToClipboard as jest.Mock;
-const mockMatchPath = matchPath as jest.Mock;
+const mockMatchRoute = matchRoute as jest.Mock;
const mockUrlQuery = {
get: jest.fn(),
@@ -71,7 +74,7 @@ describe('ShareURLModal', () => {
beforeEach(() => {
jest.clearAllMocks();
- mockUseLocation.mockReturnValue({
+ mockUseAppLocation.mockReturnValue({
pathname: TEST_PATH,
});
@@ -88,7 +91,7 @@ describe('ShareURLModal', () => {
mockUseCopyToClipboard.mockReturnValue([null, mockHandleCopyToClipboard]);
- mockMatchPath.mockReturnValue(false);
+ mockMatchRoute.mockReturnValue(null);
// Reset URL query mocks - all return null by default
mockUrlQuery.get.mockReturnValue(null);
@@ -126,7 +129,7 @@ describe('ShareURLModal', () => {
});
it('should show absolute time toggle when on time-enabled route', () => {
- mockMatchPath.mockReturnValue(true); // Simulate being on a route that supports time
+ mockMatchRoute.mockReturnValue({}); // Simulate being on a route that supports time
render(<ShareURLModal />);
@@ -146,7 +149,7 @@ describe('ShareURLModal', () => {
it('should toggle absolute time switch', async () => {
const user = userEvent.setup();
- mockMatchPath.mockReturnValue(true);
+ mockMatchRoute.mockReturnValue({});
mockUseSelector.mockReturnValue({
selectedTime: '5min', // Non-custom time should enable absolute time by default
});
@@ -169,7 +172,7 @@ describe('ShareURLModal', () => {
// Invalid - missing start and end time for custom
mockUrlQuery.get.mockReturnValue(null);
- mockMatchPath.mockReturnValue(true);
+ mockMatchRoute.mockReturnValue({});
render(<ShareURLModal />);
@@ -181,7 +184,7 @@ describe('ShareURLModal', () => {
it('should process URL with absolute time for non-custom time', async () => {
const user = userEvent.setup();
- mockMatchPath.mockReturnValue(true);
+ mockMatchRoute.mockReturnValue({});
mockUseSelector.mockReturnValue({
selectedTime: '5min',
});
@@ -200,7 +203,7 @@ describe('ShareURLModal', () => {
it('should process URL with custom time parameters', async () => {
const user = userEvent.setup();
- mockMatchPath.mockReturnValue(true);
+ mockMatchRoute.mockReturnValue({});
mockUseSelector.mockReturnValue({
selectedTime: 'custom',
});
@@ -228,7 +231,7 @@ describe('ShareURLModal', () => {
it('should process URL with relative time when absolute time is disabled', async () => {
const user = userEvent.setup();
- mockMatchPath.mockReturnValue(true);
+ mockMatchRoute.mockReturnValue({});
mockUseSelector.mockReturnValue({
selectedTime: '5min',
});
@@ -249,12 +252,12 @@ describe('ShareURLModal', () => {
it('should handle routes that should be shared with time', async () => {
const user = userEvent.setup();
- mockUseLocation.mockReturnValue({
+ mockUseAppLocation.mockReturnValue({
pathname: ROUTES.LOGS_EXPLORER,
});
- mockMatchPath.mockImplementation(
- (pathname: string, options: any) => options.path === ROUTES.LOGS_EXPLORER,
+ mockMatchRoute.mockImplementation((pathname: string, route: string) =>
+ route === ROUTES.LOGS_EXPLORER ? {} : null,
);
render(<ShareURLModal />);
diff --git a/frontend/src/components/LaunchChatSupport/LaunchChatSupport.tsx b/frontend/src/components/LaunchChatSupport/LaunchChatSupport.tsx
index 49c03eb084..52129b7a90 100644
--- a/frontend/src/components/LaunchChatSupport/LaunchChatSupport.tsx
+++ b/frontend/src/components/LaunchChatSupport/LaunchChatSupport.tsx
@@ -1,5 +1,5 @@
import { useMemo, useState } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Button, Tooltip } from 'antd';
import AddCreditCardModal from 'components/AddCreditCardModal/AddCreditCardModal';
import logEvent from 'api/common/logEvent';
@@ -43,7 +43,7 @@ function LaunchChatSupport({
const [isAddCreditCardModalOpen, setIsAddCreditCardModalOpen] =
useState(false);
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const isChatSupportEnabled = useMemo(() => {
if (!isFetchingFeatureFlags && (featureFlags || featureFlagsFetchError)) {
diff --git a/frontend/src/components/LogDetail/LogHighlights/TraceIdField.tsx b/frontend/src/components/LogDetail/LogHighlights/TraceIdField.tsx
index 393cf27a47..80dccb1880 100644
--- a/frontend/src/components/LogDetail/LogHighlights/TraceIdField.tsx
+++ b/frontend/src/components/LogDetail/LogHighlights/TraceIdField.tsx
@@ -1,4 +1,4 @@
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import styles from './LogHighlights.module.scss';
@@ -8,7 +8,7 @@ interface TraceIdFieldProps {
function TraceIdField({ traceId }: TraceIdFieldProps): JSX.Element {
return (
- <Link
+ <AppLink
to={{ pathname: `/trace/${traceId}` }}
target="_blank"
rel="noreferrer"
@@ -16,7 +16,7 @@ function TraceIdField({ traceId }: TraceIdFieldProps): JSX.Element {
title={traceId}
>
{traceId}
- </Link>
+ </AppLink>
);
}
diff --git a/frontend/src/components/MessagingQueueHealthCheck/AttributeCheckList.tsx b/frontend/src/components/MessagingQueueHealthCheck/AttributeCheckList.tsx
index 1d216edb02..2786637d98 100644
--- a/frontend/src/components/MessagingQueueHealthCheck/AttributeCheckList.tsx
+++ b/frontend/src/components/MessagingQueueHealthCheck/AttributeCheckList.tsx
@@ -1,6 +1,5 @@
import { Typography } from '@signozhq/ui/typography';
import { ReactNode, useEffect, useState } from 'react';
-import { useHistory } from 'react-router-dom';
import {
OctagonAlert,
Bolt,
@@ -14,7 +13,7 @@ import { Modal, Select, Spin, Tooltip, Tree, TreeDataNode } from 'antd';
import { OnboardingStatusResponse } from 'api/messagingQueues/onboarding/getOnboardingStatus';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
-import { History } from 'history';
+import { navigate } from 'lib/router/navigation';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import {
KAFKA_SETUP_DOC_LINK,
@@ -45,7 +44,6 @@ export enum AttributesFilters {
function ErrorTitleAndKey({
title,
parentTitle,
- history,
isCloudUserVal,
errorMsg,
isLeaf,
@@ -53,7 +51,6 @@ function ErrorTitleAndKey({
title: string;
parentTitle: string;
isCloudUserVal: boolean;
- history: History<unknown>;
errorMsg?: string;
isLeaf?: boolean;
}): TreeDataNode {
@@ -75,7 +72,7 @@ function ErrorTitleAndKey({
}
if (isCloudUserVal && !!link) {
- history.push(link);
+ navigate(link);
} else {
openInNewTab(KAFKA_SETUP_DOC_LINK);
}
@@ -149,7 +146,6 @@ function generateTreeDataNodes(
response: OnboardingStatusResponse['data'],
parentTitle: string,
isCloudUserVal: boolean,
- history: History<unknown>,
): TreeDataNode[] {
return response
.map((item) => {
@@ -162,7 +158,6 @@ function generateTreeDataNodes(
title: item.attribute,
errorMsg: item.error_message || '',
parentTitle,
- history,
isCloudUserVal,
});
}
@@ -185,7 +180,6 @@ function AttributeCheckList({
setFilter(value);
};
const { isCloudUser: isCloudUserVal } = useGetTenantLicense();
- const history = useHistory();
useEffect(() => {
const filteredData = onboardingStatusResponses.map((response) => {
@@ -195,7 +189,6 @@ function AttributeCheckList({
errorMsg: response.errorMsg,
isLeaf: true,
parentTitle: response.title,
- history,
isCloudUserVal,
});
}
@@ -213,7 +206,6 @@ function AttributeCheckList({
filteredData,
response.title,
isCloudUserVal,
- history,
),
};
});
diff --git a/frontend/src/components/NotFound/NotFound.test.tsx b/frontend/src/components/NotFound/NotFound.test.tsx
index ec9a0edc91..b7f9112cc9 100644
--- a/frontend/src/components/NotFound/NotFound.test.tsx
+++ b/frontend/src/components/NotFound/NotFound.test.tsx
@@ -1,19 +1,19 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import store from 'store';
+import { TestRouter } from 'tests/router';
import NotFound from './index';
describe('Not Found page test', () => {
it('should render Not Found page without errors', () => {
const { asFragment } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<NotFound />
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(asFragment()).toMatchSnapshot();
});
diff --git a/frontend/src/components/NotFound/styles.ts b/frontend/src/components/NotFound/styles.ts
index 812fba7f6c..3b7dff8199 100644
--- a/frontend/src/components/NotFound/styles.ts
+++ b/frontend/src/components/NotFound/styles.ts
@@ -1,7 +1,7 @@
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import styled from 'styled-components';
-export const Button = styled(Link)`
+export const Button = styled(AppLink)`
border: 2px solid #2f80ed;
box-sizing: border-box;
border-radius: 10px;
diff --git a/frontend/src/components/RouteTab/RouteTab.test.tsx b/frontend/src/components/RouteTab/RouteTab.test.tsx
index 497b2d4eda..d0e391b0d1 100644
--- a/frontend/src/components/RouteTab/RouteTab.test.tsx
+++ b/frontend/src/components/RouteTab/RouteTab.test.tsx
@@ -1,5 +1,4 @@
-import { Router } from 'react-router-dom';
-import { createMemoryHistory } from 'history';
+import { navigate } from 'lib/router/navigation';
import { fireEvent, render, screen } from 'tests/test-utils';
import RouteTab from './index';
@@ -10,6 +9,11 @@ jest.mock('./RouteTab.module.scss', () => ({
default: { routeTab: 'routeTab' },
}));
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: jest.fn(),
+}));
+
function DummyComponent1(): JSX.Element {
return <div>Dummy Component 1</div>;
}
@@ -33,63 +37,39 @@ const testRoutes: RouteTabProps['routes'] = [
];
describe('RouteTab component', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
it('renders correctly', () => {
- const history = createMemoryHistory();
- render(
- <Router history={history}>
- <RouteTab history={history} routes={testRoutes} activeKey="Tab1" />
- </Router>,
- );
+ render(<RouteTab routes={testRoutes} activeKey="Tab1" />);
expect(screen.getByRole('tab', { name: 'Tab1' })).toBeInTheDocument();
expect(screen.getByRole('tab', { name: 'Tab2' })).toBeInTheDocument();
});
it('renders correct number of tabs', () => {
- const history = createMemoryHistory();
- render(
- <Router history={history}>
- <RouteTab history={history} routes={testRoutes} activeKey="Tab1" />
- </Router>,
- );
+ render(<RouteTab routes={testRoutes} activeKey="Tab1" />);
const tabs = screen.getAllByRole('tab');
expect(tabs).toHaveLength(testRoutes.length);
});
it('sets provided activeKey as active tab', () => {
- const history = createMemoryHistory();
- render(
- <Router history={history}>
- <RouteTab history={history} routes={testRoutes} activeKey="Tab2" />
- </Router>,
- );
+ render(<RouteTab routes={testRoutes} activeKey="Tab2" />);
expect(
screen.getByRole('tab', { name: 'Tab2', selected: true }),
).toBeInTheDocument();
});
it('navigates to correct route on tab click', () => {
- const history = createMemoryHistory();
- render(
- <Router history={history}>
- <RouteTab history={history} routes={testRoutes} activeKey="Tab1" />
- </Router>,
- );
- expect(history.location.pathname).toBe('/');
+ render(<RouteTab routes={testRoutes} activeKey="Tab1" />);
+ expect(navigate).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('tab', { name: 'Tab2' }));
- expect(history.location.pathname).toBe('/tab2');
+ expect(navigate).toHaveBeenCalledWith('/tab2');
});
it('applies the layout class alongside a custom className', () => {
- const history = createMemoryHistory();
const { container } = render(
- <Router history={history}>
- <RouteTab
- history={history}
- routes={testRoutes}
- activeKey="Tab1"
- className="custom-tabs"
- />
- </Router>,
+ <RouteTab routes={testRoutes} activeKey="Tab1" className="custom-tabs" />,
);
expect(container.querySelector('.ant-tabs')).toHaveClass(
'routeTab',
@@ -98,11 +78,8 @@ describe('RouteTab component', () => {
});
it('renders the active tab content inside an overlay scrollbar', () => {
- const history = createMemoryHistory();
const { container } = render(
- <Router history={history}>
- <RouteTab history={history} routes={testRoutes} activeKey="Tab1" />
- </Router>,
+ <RouteTab routes={testRoutes} activeKey="Tab1" />,
);
expect(
container.querySelector('.ant-tabs-tabpane-active > .overlay-scrollbar'),
@@ -111,16 +88,12 @@ describe('RouteTab component', () => {
it('calls onChangeHandler on tab change', () => {
const onChangeHandler = jest.fn();
- const history = createMemoryHistory();
render(
- <Router history={history}>
- <RouteTab
- routes={testRoutes}
- activeKey="Tab1"
- onChangeHandler={onChangeHandler}
- history={history}
- />
- </Router>,
+ <RouteTab
+ routes={testRoutes}
+ activeKey="Tab1"
+ onChangeHandler={onChangeHandler}
+ />,
);
fireEvent.click(screen.getByRole('tab', { name: 'Tab2' }));
expect(onChangeHandler).toHaveBeenCalled();
diff --git a/frontend/src/components/RouteTab/index.tsx b/frontend/src/components/RouteTab/index.tsx
index 19dccc54f6..2998723b95 100644
--- a/frontend/src/components/RouteTab/index.tsx
+++ b/frontend/src/components/RouteTab/index.tsx
@@ -1,13 +1,12 @@
-import {
- generatePath,
- matchPath,
- useLocation,
- useParams,
-} from 'react-router-dom';
import { Tabs, TabsProps } from 'antd';
import cx from 'classnames';
import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
+import { matchRoute } from 'lib/router/matchRoute';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppParams } from 'lib/router/useAppParams';
import { RouteTabProps } from './types';
@@ -28,21 +27,17 @@ function RouteTab({
routes,
activeKey,
onChangeHandler,
- history,
showRightSection,
className,
...rest
}: RouteTabProps & TabsProps): JSX.Element {
- const params = useParams<Params>();
- const location = useLocation();
+ const params = useAppParams<Params>();
+ const location = useAppLocation();
// Find the matching route for the current pathname
const currentRoute = routes.find((route) => {
const routePath = route.route.split('?')[0];
- return matchPath(location.pathname, {
- path: routePath,
- exact: true,
- });
+ return matchRoute(location.pathname, routePath, { exact: true });
});
const onChange = (activeRoute: string): void => {
@@ -53,8 +48,7 @@ function RouteTab({
const selectedRoute = routes.find((e) => e.key === activeRoute);
if (selectedRoute) {
- const resolvedRoute = generatePath(selectedRoute.route, params);
- history.push(resolvedRoute);
+ navigate(buildRoutePath(selectedRoute.route, params));
}
};
diff --git a/frontend/src/components/RouteTab/types.ts b/frontend/src/components/RouteTab/types.ts
index b9cece3355..2f284e2d36 100644
--- a/frontend/src/components/RouteTab/types.ts
+++ b/frontend/src/components/RouteTab/types.ts
@@ -1,6 +1,5 @@
import { ComponentType } from 'react';
import { TabsProps } from 'antd';
-import { History } from 'history';
export type TabRoutes = {
name: React.ReactNode;
@@ -13,6 +12,5 @@ export interface RouteTabProps {
routes: TabRoutes[];
activeKey: TabsProps['activeKey'];
onChangeHandler?: (key: string) => void;
- history: History<unknown>;
showRightSection: boolean;
}
diff --git a/frontend/src/components/cmdKPalette/__test__/cmdkPalette.test.tsx b/frontend/src/components/cmdKPalette/__test__/cmdkPalette.test.tsx
index 42f7ff6282..9114bd6488 100644
--- a/frontend/src/components/cmdKPalette/__test__/cmdkPalette.test.tsx
+++ b/frontend/src/components/cmdKPalette/__test__/cmdkPalette.test.tsx
@@ -3,7 +3,7 @@
*/
// ---- Mocks (must run BEFORE importing the component) ----
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { render, screen, userEvent } from 'tests/test-utils';
import '@testing-library/jest-dom/extend-expect';
@@ -24,61 +24,12 @@ afterAll(() => {
delete (HTMLElement.prototype as any).scrollIntoView;
});
-// mock history.push / replace / go / location
-jest.mock('lib/history', () => {
- const location = { pathname: '/', search: '', hash: '' };
-
- const stack: { pathname: string; search: string }[] = [
- { pathname: '/', search: '' },
- ];
-
- const push = jest.fn((path: string) => {
- const [rawPath, rawQuery] = path.split('?');
- const pathname = rawPath || '/';
- const search = path.includes('?') ? `?${rawQuery || ''}` : '';
-
- location.pathname = pathname;
- location.search = search;
-
- stack.push({ pathname, search });
- return undefined;
- });
-
- const replace = jest.fn((path: string) => {
- const [rawPath, rawQuery] = path.split('?');
- const pathname = rawPath || '/';
- const search = path.includes('?') ? `?${rawQuery || ''}` : '';
-
- location.pathname = pathname;
- location.search = search;
-
- if (stack.length > 0) {
- stack[stack.length - 1] = { pathname, search };
- } else {
- stack.push({ pathname, search });
- }
- return undefined;
- });
-
- const listen = jest.fn();
- const go = jest.fn((n: number) => {
- if (n < 0 && stack.length > 1) {
- stack.pop();
- }
- const top = stack[stack.length - 1] || { pathname: '/', search: '' };
- location.pathname = top.pathname;
- location.search = top.search;
- });
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: jest.fn(),
+}));
- return {
- push,
- replace,
- listen,
- go,
- location,
- __stack: stack,
- };
-});
+const mockNavigate = navigate as jest.MockedFunction<typeof navigate>;
// Mock ResizeObserver for Jest/jsdom
class ResizeObserver {
@@ -159,14 +110,14 @@ describe('CmdKPalette', () => {
expect(screen.getByText('Switch to Dark Mode')).toBeInTheDocument();
});
- it('clicking a navigation item calls history.push with correct route', async () => {
+ it('clicking a navigation item navigates to the correct route', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<CmdKPalette userRole="ADMIN" />);
const homeItem = screen.getByText(HOME_LABEL);
await user.click(homeItem);
- expect(history.push).toHaveBeenCalledWith(ROUTES.HOME);
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.HOME);
});
it('role-based filtering (basic smoke)', () => {
diff --git a/frontend/src/components/cmdKPalette/cmdKPalette.tsx b/frontend/src/components/cmdKPalette/cmdKPalette.tsx
index 6f2e970915..73362af835 100644
--- a/frontend/src/components/cmdKPalette/cmdKPalette.tsx
+++ b/frontend/src/components/cmdKPalette/cmdKPalette.tsx
@@ -1,6 +1,5 @@
import React, { useEffect } from 'react';
import cx from 'classnames';
-import { useLocation } from 'react-router-dom';
import {
CommandDialog,
CommandEmpty,
@@ -23,7 +22,8 @@ import {
import { useThemeMode } from 'hooks/useDarkMode';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { IS_DEV } from 'lib/env';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { ROLES as UserRole } from 'types/roles';
import { createShortcutActions } from '../../constants/shortcutActions';
@@ -77,7 +77,7 @@ export function CmdKPalette({
const { open, setOpen } = useCmdK();
const { setAutoSwitch, setTheme, theme } = useThemeMode();
- const location = useLocation();
+ const location = useAppLocation();
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const startNewConversation = useAIAssistantStore(
(s) => s.startNewConversation,
@@ -120,7 +120,7 @@ export function CmdKPalette({
}
function onClickHandler(key: string): void {
- history.push(key);
+ navigate(key);
}
const handleOpenAIAssistant = (): void => {
diff --git a/frontend/src/container/AIAssistant/AIAssistantDrawer/AIAssistantDrawer.tsx b/frontend/src/container/AIAssistant/AIAssistantDrawer/AIAssistantDrawer.tsx
index 1bb3cd293a..c1070119cb 100644
--- a/frontend/src/container/AIAssistant/AIAssistantDrawer/AIAssistantDrawer.tsx
+++ b/frontend/src/container/AIAssistant/AIAssistantDrawer/AIAssistantDrawer.tsx
@@ -1,6 +1,6 @@
import { useCallback } from 'react';
-import { useHistory } from 'react-router-dom';
import { Button } from '@signozhq/ui/button';
+import { navigate } from 'lib/router/navigation';
import { Tooltip } from '@signozhq/ui/tooltip';
import { Drawer } from 'antd';
import ROUTES from 'constants/routes';
@@ -12,8 +12,6 @@ import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { VariantContext } from '../VariantContext';
export default function AIAssistantDrawer(): JSX.Element {
- const history = useHistory();
-
const isDrawerOpen = useAIAssistantStore((s) => s.isDrawerOpen);
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
@@ -28,10 +26,10 @@ export default function AIAssistantDrawer(): JSX.Element {
return;
}
closeDrawer();
- history.push(
+ navigate(
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
);
- }, [activeConversationId, closeDrawer, history]);
+ }, [activeConversationId, closeDrawer]);
const handleNewConversation = useCallback(() => {
startNewConversation();
diff --git a/frontend/src/container/AIAssistant/AIAssistantModal/AIAssistantModal.tsx b/frontend/src/container/AIAssistant/AIAssistantModal/AIAssistantModal.tsx
index 73bb4bb04a..d94da60202 100644
--- a/frontend/src/container/AIAssistant/AIAssistantModal/AIAssistantModal.tsx
+++ b/frontend/src/container/AIAssistant/AIAssistantModal/AIAssistantModal.tsx
@@ -1,7 +1,8 @@
import { useCallback, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
-import { useHistory, useLocation } from 'react-router-dom';
import { Button } from '@signozhq/ui/button';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Tooltip } from '@signozhq/ui/tooltip';
import ROUTES from 'constants/routes';
import { History, Maximize2, Minus, Plus, X } from '@signozhq/icons';
@@ -31,8 +32,7 @@ import styles from './AIAssistantModal.module.scss';
*/
// eslint-disable-next-line sonarjs/cognitive-complexity
export default function AIAssistantModal(): JSX.Element | null {
- const history = useHistory();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const [showHistory, setShowHistory] = useState(false);
const isOpen = useAIAssistantStore((s) => s.isModalOpen);
@@ -94,11 +94,11 @@ export default function AIAssistantModal(): JSX.Element | null {
// Router state tells AIAssistantPage to skip its mount-time Opened fire:
// the assistant was already open in the modal, so this is a surface
// switch, not a new open.
- history.push(
+ navigate(
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
- { fromInApp: true },
+ { state: { fromInApp: true } },
);
- }, [activeConversationId, closeModal, history]);
+ }, [activeConversationId, closeModal]);
const handleNew = useCallback(() => {
void logEvent(AIAssistantEvents.NewChatClicked, {
diff --git a/frontend/src/container/AIAssistant/AIAssistantPanel/AIAssistantPanel.tsx b/frontend/src/container/AIAssistant/AIAssistantPanel/AIAssistantPanel.tsx
index f6dc50980a..fc70427f6b 100644
--- a/frontend/src/container/AIAssistant/AIAssistantPanel/AIAssistantPanel.tsx
+++ b/frontend/src/container/AIAssistant/AIAssistantPanel/AIAssistantPanel.tsx
@@ -1,6 +1,8 @@
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
-import { matchPath, useHistory, useLocation } from 'react-router-dom';
import { Button } from '@signozhq/ui/button';
+import { matchRoute } from 'lib/router/matchRoute';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Tooltip } from '@signozhq/ui/tooltip';
import ROUTES from 'constants/routes';
import { History, Maximize2, Plus, X } from '@signozhq/icons';
@@ -21,13 +23,11 @@ const AI_ASSISTANT_PANEL_OPEN_CLASS = 'ai-assistant-panel-open';
const AI_ASSISTANT_PANEL_WIDTH_VAR = '--ai-assistant-panel-width';
export default function AIAssistantPanel(): JSX.Element | null {
- const history = useHistory();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const [showHistory, setShowHistory] = useState(false);
const isOpen = useAIAssistantStore((s) => s.isDrawerOpen);
- const isFullScreenPage = !!matchPath(pathname, {
- path: ROUTES.AI_ASSISTANT,
+ const isFullScreenPage = !!matchRoute(pathname, ROUTES.AI_ASSISTANT, {
exact: true,
});
const activeConversationId = useAIAssistantStore(
@@ -47,11 +47,11 @@ export default function AIAssistantPanel(): JSX.Element | null {
// Router state tells AIAssistantPage to skip its mount-time Opened fire:
// the assistant was already open in the drawer, so this is a surface
// switch, not a new open.
- history.push(
+ navigate(
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
- { fromInApp: true },
+ { state: { fromInApp: true } },
);
- }, [activeConversationId, closeDrawer, history]);
+ }, [activeConversationId, closeDrawer]);
const handleNew = useCallback(() => {
void logEvent(AIAssistantEvents.NewChatClicked, {
diff --git a/frontend/src/container/AIAssistant/ConversationView/ConversationView.tsx b/frontend/src/container/AIAssistant/ConversationView/ConversationView.tsx
index 345e256ad2..fadcdf4ff8 100644
--- a/frontend/src/container/AIAssistant/ConversationView/ConversationView.tsx
+++ b/frontend/src/container/AIAssistant/ConversationView/ConversationView.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useLocation } from 'react-router-dom';
import cx from 'classnames';
+import { useAppLocation } from 'lib/router/useAppLocation';
import logEvent from 'api/common/logEvent';
@@ -26,7 +26,7 @@ export default function ConversationView({
}: ConversationViewProps): JSX.Element {
const variant = useVariant();
const isCompact = variant === 'panel';
- const location = useLocation();
+ const location = useAppLocation();
const conversation = useAIAssistantStore(
(s) => s.conversations[conversationId],
diff --git a/frontend/src/container/AIAssistant/ConversationView/__tests__/ConversationView.test.tsx b/frontend/src/container/AIAssistant/ConversationView/__tests__/ConversationView.test.tsx
index b065ec3230..c64e92b8fb 100644
--- a/frontend/src/container/AIAssistant/ConversationView/__tests__/ConversationView.test.tsx
+++ b/frontend/src/container/AIAssistant/ConversationView/__tests__/ConversationView.test.tsx
@@ -1,9 +1,8 @@
-import { MemoryRouter } from 'react-router-dom';
-// eslint-disable-next-line no-restricted-imports
import { fireEvent, render } from '@testing-library/react';
import { MessageContext } from 'api/ai-assistant/chat';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import { VariantContext } from 'container/AIAssistant/VariantContext';
+import { TestRouter } from 'tests/router';
const CHIP_ID = 'recent-errors';
const CHIP_TEXT = 'Show me recent errors';
@@ -87,11 +86,11 @@ function renderView(variant: 'panel' | 'page' | 'modal'): {
getByTestId: (id: string) => HTMLElement;
} {
return render(
- <MemoryRouter initialEntries={['/dashboard/dashboard-123']}>
+ <TestRouter initialRoute="/dashboard/dashboard-123">
<VariantContext.Provider value={variant}>
<ConversationView conversationId={CONVERSATION_ID} />
</VariantContext.Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
}
diff --git a/frontend/src/container/AIAssistant/components/ActionsSection/ActionsSection.tsx b/frontend/src/container/AIAssistant/components/ActionsSection/ActionsSection.tsx
index 9554c61f73..dac3877aa1 100644
--- a/frontend/src/container/AIAssistant/components/ActionsSection/ActionsSection.tsx
+++ b/frontend/src/container/AIAssistant/components/ActionsSection/ActionsSection.tsx
@@ -1,6 +1,8 @@
import { useEffect, useState } from 'react';
-import { matchPath, useHistory, useLocation } from 'react-router-dom';
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
+import { matchRoute } from 'lib/router/matchRoute';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
@@ -213,20 +215,11 @@ function signalMatchesPathname(
): boolean {
switch (signal) {
case ApplyFilterSignalDTO.logs:
- return Boolean(
- matchPath(pathname, { path: ROUTES.LOGS_EXPLORER, exact: false }),
- );
+ return Boolean(matchRoute(pathname, ROUTES.LOGS_EXPLORER));
case ApplyFilterSignalDTO.traces:
- return Boolean(
- matchPath(pathname, { path: ROUTES.TRACES_EXPLORER, exact: false }),
- );
+ return Boolean(matchRoute(pathname, ROUTES.TRACES_EXPLORER));
case ApplyFilterSignalDTO.metrics:
- return Boolean(
- matchPath(pathname, {
- path: ROUTES.METRICS_EXPLORER_EXPLORER,
- exact: false,
- }),
- );
+ return Boolean(matchRoute(pathname, ROUTES.METRICS_EXPLORER_EXPLORER));
default:
return false;
}
@@ -275,7 +268,6 @@ function explorerRouteForSignal(signal: ApplyFilterSignalDTO): string | null {
}
interface ApplyFilterDeps {
- history: ReturnType<typeof useHistory>;
pathname: string;
redirectWithQueryBuilderData: ReturnType<
typeof useQueryBuilder
@@ -317,8 +309,8 @@ function withDerivedFilterExpressions(query: Query): Query {
* page-action recipe — calling redirect alone is not sufficient because
* the URL→state effect runs after the next render and the editor binds
* to `filter.expression`, not `filters.items`.
- * - Off-page: use `history.push` so the landing explorer initializes from
- * the new URL on mount.
+ * - Off-page: `navigate()` so the landing explorer initializes from the
+ * new URL on mount.
*/
function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
// eslint-disable-next-line no-console
@@ -360,9 +352,9 @@ function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
return;
}
// eslint-disable-next-line no-console
- console.log('[apply_filter] off-page → history.push', base);
+ console.log('[apply_filter] off-page → navigate', base);
const encoded = encodeURIComponent(JSON.stringify(normalized));
- deps.history.push(`${base}?${QueryParams.compositeQuery}=${encoded}`);
+ navigate(`${base}?${QueryParams.compositeQuery}=${encoded}`);
}
/** Picks the right rollback API call for a given action kind. */
@@ -391,8 +383,7 @@ export default function ActionsSection({
actions,
messageId,
}: ActionsSectionProps): JSX.Element | null {
- const history = useHistory();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
const { threadId, page, mode } = useAIAssistantAnalyticsContext();
const { redirectWithQueryBuilderData, handleSetQueryData } = useQueryBuilder();
@@ -424,19 +415,12 @@ export default function ActionsSection({
}
autoAppliedFilterKeys.add(key);
applyFilter(action, {
- history,
pathname,
redirectWithQueryBuilderData,
handleSetQueryData,
});
});
- }, [
- actions,
- pathname,
- history,
- redirectWithQueryBuilderData,
- handleSetQueryData,
- ]);
+ }, [actions, pathname, redirectWithQueryBuilderData, handleSetQueryData]);
if (actions.length === 0) {
return null;
@@ -456,11 +440,7 @@ export default function ActionsSection({
}
setResult(key, { state: 'loading' });
try {
- await openSavedViewByKey(
- resourceId,
- resolveSavedViewSourceHint(action),
- history,
- );
+ await openSavedViewByKey(resourceId, resolveSavedViewSourceHint(action));
void logEvent(AIAssistantEvents.ResourceOpened, {
threadId,
messageId,
@@ -515,7 +495,7 @@ export default function ActionsSection({
targetModule: targetModuleForResource(resourceType),
resourceId,
});
- history.push(path);
+ navigate(path);
};
const handleClick = (key: string, action: MessageActionDTO): void => {
@@ -576,7 +556,6 @@ export default function ActionsSection({
});
}
applyFilter(action, {
- history,
pathname,
redirectWithQueryBuilderData,
handleSetQueryData,
diff --git a/frontend/src/container/AIAssistant/components/ActionsSection/utils/__tests__/openSavedView.test.ts b/frontend/src/container/AIAssistant/components/ActionsSection/utils/__tests__/openSavedView.test.ts
index 9f7351d40a..afb12de14d 100644
--- a/frontend/src/container/AIAssistant/components/ActionsSection/utils/__tests__/openSavedView.test.ts
+++ b/frontend/src/container/AIAssistant/components/ActionsSection/utils/__tests__/openSavedView.test.ts
@@ -16,10 +16,10 @@ import {
SavedviewtypesSourceDTO,
} from 'api/generated/services/sigNoz.schemas';
import ROUTES from 'constants/routes';
+import { navigate } from 'lib/router/navigation';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { DataSource } from 'types/common/queryBuilder';
-import type { History } from 'history';
import {
buildExplorerNavigationUrl,
@@ -39,6 +39,9 @@ import {
import { resourceRoute, ResourceType } from '../resourceRoute';
jest.mock('api/generated/services/saved-view');
+jest.mock('lib/router/navigation', () => ({
+ navigate: jest.fn(),
+}));
jest.mock(
'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi',
@@ -60,6 +63,7 @@ const mockedListSavedViews = listSavedViews as jest.MockedFunction<
const mockedGetSavedView = getSavedView as jest.MockedFunction<
typeof getSavedView
>;
+const mockedNavigate = navigate as jest.MockedFunction<typeof navigate>;
function makeView(
id: string,
@@ -246,15 +250,17 @@ describe('buildExplorerNavigationUrl', () => {
});
describe('openSavedView', () => {
- it('navigates with history.push and view query params', () => {
- const push = jest.fn();
- const history = { push } as unknown as History;
+ beforeEach(() => {
+ mockedNavigate.mockClear();
+ });
+
+ it('navigates with the view query params', () => {
const view = makeView('view-logs', SavedviewtypesSourceDTO.logs);
- openSavedView(view, history);
+ openSavedView(view);
- expect(push).toHaveBeenCalledTimes(1);
- const pushedUrl = push.mock.calls[0][0] as string;
+ expect(mockedNavigate).toHaveBeenCalledTimes(1);
+ const pushedUrl = mockedNavigate.mock.calls[0][0] as string;
expect(pushedUrl).toContain(ROUTES.LOGS_EXPLORER);
const params = new URLSearchParams(pushedUrl.split('?')[1]);
expect(params.get(QueryParams.viewKey)).toBe('"view-logs"');
@@ -266,18 +272,14 @@ describe('openSavedView', () => {
const view = makeView('view-logs', SavedviewtypesSourceDTO.logs);
delete view.source;
- expect(() =>
- openSavedView(view, { push: jest.fn() } as unknown as History),
- ).toThrow('Unsupported saved view source');
+ expect(() => openSavedView(view)).toThrow('Unsupported saved view source');
});
it('throws when the view has no queries', () => {
const view = makeView('view-logs', SavedviewtypesSourceDTO.logs);
view.spec.queries = [];
- expect(() =>
- openSavedView(view, { push: jest.fn() } as unknown as History),
- ).toThrow('Saved view is missing query data');
+ expect(() => openSavedView(view)).toThrow('Saved view is missing query data');
});
});
@@ -285,44 +287,39 @@ describe('openSavedViewByKey', () => {
beforeEach(() => {
mockedListSavedViews.mockReset();
mockedGetSavedView.mockReset();
+ mockedNavigate.mockClear();
});
it('prefers the direct view lookup endpoint', async () => {
const view = makeView('view-logs', SavedviewtypesSourceDTO.logs);
mockedGetSavedView.mockResolvedValueOnce(mockViewByIdResponse(view));
- const push = jest.fn();
- const history = { push } as unknown as History;
- await openSavedViewByKey('view-logs', DataSource.LOGS, history);
+ await openSavedViewByKey('view-logs', DataSource.LOGS);
expect(mockedGetSavedView).toHaveBeenCalledWith({ id: 'view-logs' });
expect(mockedListSavedViews).not.toHaveBeenCalled();
- expect(push).toHaveBeenCalled();
+ expect(mockedNavigate).toHaveBeenCalled();
});
it('falls back to list probing when direct lookup fails', async () => {
const view = makeView('view-traces', SavedviewtypesSourceDTO.traces);
mockedGetSavedView.mockRejectedValueOnce(new Error('not found'));
mockedListSavedViews.mockResolvedValueOnce(mockViewsResponse([view]));
- const push = jest.fn();
- const history = { push } as unknown as History;
- await openSavedViewByKey('view-traces', DataSource.TRACES, history);
+ await openSavedViewByKey('view-traces', DataSource.TRACES);
expect(mockedListSavedViews).toHaveBeenCalledWith({
source: SavedviewtypesSourceDTO.traces,
});
- expect(push).toHaveBeenCalled();
+ expect(mockedNavigate).toHaveBeenCalled();
});
it('throws when the saved view does not exist', async () => {
mockedGetSavedView.mockRejectedValueOnce(new Error('not found'));
mockedListSavedViews.mockResolvedValue(mockViewsResponse([]));
- await expect(
- openSavedViewByKey('missing', DataSource.LOGS, {
- push: jest.fn(),
- } as unknown as History),
- ).rejects.toThrow('Saved view not found');
+ await expect(openSavedViewByKey('missing', DataSource.LOGS)).rejects.toThrow(
+ 'Saved view not found',
+ );
});
});
diff --git a/frontend/src/container/AIAssistant/components/ActionsSection/utils/openSavedView.ts b/frontend/src/container/AIAssistant/components/ActionsSection/utils/openSavedView.ts
index a0b50731a2..6202ef46e6 100644
--- a/frontend/src/container/AIAssistant/components/ActionsSection/utils/openSavedView.ts
+++ b/frontend/src/container/AIAssistant/components/ActionsSection/utils/openSavedView.ts
@@ -10,9 +10,9 @@ import { findSavedView } from 'container/SavedViews/utils/findSavedView';
import { getSavedViewQuery } from 'container/SavedViews/utils/getSavedViewQuery';
import { toSavedViewSource } from 'container/SavedViews/utils/toSavedViewSource';
import { SOURCEPAGE_VS_ROUTES } from 'container/SavedViews/constants';
+import { navigate } from 'lib/router/navigation';
import { DataSource } from 'types/common/queryBuilder';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
-import { History } from 'history';
type SavedViewSourceHint = SavedViewSourcePage;
@@ -92,10 +92,7 @@ export function buildExplorerNavigationUrl(
return `${route}?${params.toString()}`;
}
-export function openSavedView(
- view: SavedviewtypesSavedViewDTO,
- history: History,
-): void {
+export function openSavedView(view: SavedviewtypesSavedViewDTO): void {
const route = view.source ? explorerRouteForSourcePage(view.source) : null;
if (!route) {
throw new Error('Unsupported saved view source');
@@ -110,14 +107,13 @@ export function openSavedView(
[QueryParams.panelTypes]: view.spec.panelType as unknown as PANEL_TYPES,
[QueryParams.viewKey]: view.id,
});
- history.push(url);
+ navigate(url);
}
export async function openSavedViewByKey(
viewKey: string,
sourceHint: SavedViewSourceHint | null | undefined,
- history: History,
): Promise<void> {
const view = await loadSavedView(viewKey, sourceHint);
- openSavedView(view, history);
+ openSavedView(view);
}
diff --git a/frontend/src/container/AIAssistant/getAutoContexts.ts b/frontend/src/container/AIAssistant/getAutoContexts.ts
index 83b1d7ffda..ca1e183c9f 100644
--- a/frontend/src/container/AIAssistant/getAutoContexts.ts
+++ b/frontend/src/container/AIAssistant/getAutoContexts.ts
@@ -1,9 +1,9 @@
import type { MessageContext } from 'api/ai-assistant/chat';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
+import { matchRoute } from 'lib/router/matchRoute';
import { AlertListTabs } from 'pages/AlertList/types';
import { NEW_PANEL_ID } from 'pages/DashboardPage/DashboardContainer/PanelEditor/newPanelRoute';
-import { matchPath } from 'react-router-dom';
/**
* Resolves the page the user is currently on into structured `MessageContext`
@@ -33,9 +33,10 @@ export function getAutoContexts(
// Panel editor (V2). `panel/new` has no widget id yet and the schema requires
// a non-empty `panel_edit.widgetId`, so it reports `panel_create` instead.
- const panelEditorMatch = matchPath<{ dashboardId: string; panelId: string }>(
+ const panelEditorMatch = matchRoute<'dashboardId' | 'panelId'>(
pathname,
- { path: ROUTES.DASHBOARD_PANEL_EDITOR, exact: true },
+ ROUTES.DASHBOARD_PANEL_EDITOR,
+ { exact: true },
);
if (panelEditorMatch) {
const { dashboardId, panelId } = panelEditorMatch.params;
@@ -55,8 +56,7 @@ export function getAutoContexts(
// Dashboard detail — `/dashboard/:dashboardId`. The `expandedWidgetId`
// query param signals the panel-fullscreen overlay; otherwise it's the
// plain dashboard view.
- const dashboardMatch = matchPath<{ dashboardId: string }>(pathname, {
- path: ROUTES.DASHBOARD,
+ const dashboardMatch = matchRoute<'dashboardId'>(pathname, ROUTES.DASHBOARD, {
exact: true,
});
if (dashboardMatch) {
@@ -89,7 +89,7 @@ export function getAutoContexts(
}
// Dashboard list — `/dashboard`.
- if (matchPath(pathname, { path: ROUTES.ALL_DASHBOARD, exact: true })) {
+ if (matchRoute(pathname, ROUTES.ALL_DASHBOARD, { exact: true })) {
return [
{
source: 'auto',
@@ -106,8 +106,8 @@ export function getAutoContexts(
// or `/alerts/history?ruleId=…`. Mirrors dashboard_detail: resourceId is the
// rule id and shared metadata carries the URL time range when present.
if (
- matchPath(pathname, { path: ROUTES.ALERT_OVERVIEW, exact: true }) ||
- matchPath(pathname, { path: ROUTES.ALERT_HISTORY, exact: true })
+ matchRoute(pathname, ROUTES.ALERT_OVERVIEW, { exact: true }) ||
+ matchRoute(pathname, ROUTES.ALERT_HISTORY, { exact: true })
) {
const ruleId = params.get(QueryParams.ruleId);
if (ruleId) {
@@ -129,7 +129,7 @@ export function getAutoContexts(
// Alert edit — `/alerts/edit?ruleId=…`. The form syncs its query-builder
// state to the URL (`useShareBuilderUrl`), so shared metadata carries the
// alert's query + time range, mirroring the dashboard panel editor.
- if (matchPath(pathname, { path: ROUTES.EDIT_ALERTS, exact: true })) {
+ if (matchRoute(pathname, ROUTES.EDIT_ALERTS, { exact: true })) {
const ruleId = params.get(QueryParams.ruleId);
if (ruleId) {
return [
@@ -145,7 +145,7 @@ export function getAutoContexts(
// Alert new — `/alerts/new`. No rule id yet (draft), but the query-builder
// state is on the URL, so shared metadata carries the in-progress query.
- if (matchPath(pathname, { path: ROUTES.ALERTS_NEW, exact: true })) {
+ if (matchRoute(pathname, ROUTES.ALERTS_NEW, { exact: true })) {
return [
{
source: 'auto',
@@ -157,7 +157,7 @@ export function getAutoContexts(
}
// Triggered-alerts index — `/alerts/history` without a rule id.
- if (matchPath(pathname, { path: ROUTES.ALERT_HISTORY, exact: true })) {
+ if (matchRoute(pathname, ROUTES.ALERT_HISTORY, { exact: true })) {
return [
{
source: 'auto',
@@ -172,7 +172,7 @@ export function getAutoContexts(
}
// Alerts index — `/alerts` with tab query param (defaults to Alert Rules).
- if (matchPath(pathname, { path: ROUTES.LIST_ALL_ALERT, exact: true })) {
+ if (matchRoute(pathname, ROUTES.LIST_ALL_ALERT, { exact: true })) {
const page = resolveAlertsIndexPage(params.get(QueryParams.tab));
return [
{
@@ -191,10 +191,10 @@ export function getAutoContexts(
// Service detail (covers sub-routes like top-level-operations) —
// `/services/:servicename[/...]`.
- const serviceMatch = matchPath<{ servicename: string }>(pathname, {
- path: ROUTES.SERVICE_METRICS,
- exact: false,
- });
+ const serviceMatch = matchRoute<'servicename'>(
+ pathname,
+ ROUTES.SERVICE_METRICS,
+ );
if (serviceMatch?.params.servicename) {
return [
{
@@ -210,7 +210,7 @@ export function getAutoContexts(
}
// Services list — `/services`.
- if (matchPath(pathname, { path: ROUTES.APPLICATION, exact: true })) {
+ if (matchRoute(pathname, ROUTES.APPLICATION, { exact: true })) {
return [
{
source: 'auto',
@@ -226,7 +226,7 @@ export function getAutoContexts(
// ── Logs ──────────────────────────────────────────────────────────────────
- if (matchPath(pathname, { path: ROUTES.LOGS_EXPLORER, exact: false })) {
+ if (matchRoute(pathname, ROUTES.LOGS_EXPLORER)) {
const activeLogId = params.get(QueryParams.activeLogId);
// `?activeLogId=…` indicates a log-detail panel is open. Per the
// schema, log_detail requires payload fields (timestamp, service,
@@ -251,8 +251,7 @@ export function getAutoContexts(
// Trace detail — `/trace/:id`. Treated as a detail-as-metadata page
// (resourceId null, `traceId` lives in metadata).
- const traceMatch = matchPath<{ id: string }>(pathname, {
- path: ROUTES.TRACE_DETAIL,
+ const traceMatch = matchRoute<'id'>(pathname, ROUTES.TRACE_DETAIL, {
exact: true,
});
if (traceMatch?.params.id) {
@@ -272,7 +271,7 @@ export function getAutoContexts(
];
}
- if (matchPath(pathname, { path: ROUTES.TRACES_EXPLORER, exact: false })) {
+ if (matchRoute(pathname, ROUTES.TRACES_EXPLORER)) {
return [
{
source: 'auto',
@@ -289,9 +288,7 @@ export function getAutoContexts(
// ── Metrics ───────────────────────────────────────────────────────────────
// Metrics explorer — `/metrics-explorer` and sub-routes (summary, explorer).
- if (
- matchPath(pathname, { path: ROUTES.METRICS_EXPLORER_BASE, exact: false })
- ) {
+ if (matchRoute(pathname, ROUTES.METRICS_EXPLORER_BASE)) {
return [
{
source: 'auto',
diff --git a/frontend/src/container/AIAssistant/hooks/useAIAssistantAnalyticsContext.ts b/frontend/src/container/AIAssistant/hooks/useAIAssistantAnalyticsContext.ts
index c28cb45c15..9aaf9cbcaa 100644
--- a/frontend/src/container/AIAssistant/hooks/useAIAssistantAnalyticsContext.ts
+++ b/frontend/src/container/AIAssistant/hooks/useAIAssistantAnalyticsContext.ts
@@ -1,6 +1,6 @@
-import { matchPath, useLocation } from 'react-router-dom';
-
import ROUTES from 'constants/routes';
+import { matchRoute } from 'lib/router/matchRoute';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { useVariant } from '../VariantContext';
@@ -28,7 +28,7 @@ const ROUTE_TEMPLATES = Object.values(ROUTES).sort(
export function normalizePage(pathname: string): string {
for (const template of ROUTE_TEMPLATES) {
- if (matchPath(pathname, { path: template, exact: true })) {
+ if (matchRoute(pathname, template, { exact: true })) {
return template;
}
}
@@ -46,7 +46,7 @@ export function normalizePage(pathname: string): string {
export function useAIAssistantAnalyticsContext(
conversationId?: string,
): AIAssistantAnalyticsContext {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const variant = useVariant();
const threadId = useAIAssistantStore((s) => {
const id = conversationId ?? s.activeConversationId;
diff --git a/frontend/src/container/AIAssistant/resolvePageType.ts b/frontend/src/container/AIAssistant/resolvePageType.ts
index 2f1bbbdfcd..45338acba4 100644
--- a/frontend/src/container/AIAssistant/resolvePageType.ts
+++ b/frontend/src/container/AIAssistant/resolvePageType.ts
@@ -1,7 +1,7 @@
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
-import { matchPath } from 'react-router-dom';
+import { matchRoute } from 'lib/router/matchRoute';
import { getAutoContexts } from './getAutoContexts';
@@ -45,15 +45,10 @@ export function resolvePageType(
// Pseudo-pages with no attachable resource: resolved straight from the
// route. They deliberately emit no auto-context chip (see `getAutoContexts`),
// so they can't be derived from `metadata.page` like the pages below.
- if (matchPath(pathname, { path: ROUTES.HOME, exact: true })) {
+ if (matchRoute(pathname, ROUTES.HOME, { exact: true })) {
return PageTypeDTO.homepage;
}
- if (
- matchPath(pathname, {
- path: ROUTES.INFRASTRUCTURE_MONITORING_BASE,
- exact: false,
- })
- ) {
+ if (matchRoute(pathname, ROUTES.INFRASTRUCTURE_MONITORING_BASE)) {
return PageTypeDTO.infra_entity_detail;
}
diff --git a/frontend/src/container/AlertHistory/AlertPopover/AlertPopover.tsx b/frontend/src/container/AlertHistory/AlertPopover/AlertPopover.tsx
index 913de2cd6d..eb1d6ce77c 100644
--- a/frontend/src/container/AlertHistory/AlertPopover/AlertPopover.tsx
+++ b/frontend/src/container/AlertHistory/AlertPopover/AlertPopover.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import { Color } from '@signozhq/design-tokens';
import { Popover } from 'antd';
import LogsIcon from 'assets/AlertHistory/LogsIcon';
@@ -26,7 +26,7 @@ function PopoverContent({
return (
<div className="contributor-row-popover-buttons">
{!!relatedLogsLink && (
- <Link
+ <AppLink
to={`${ROUTES.LOGS_EXPLORER}?${relatedLogsLink}`}
className="contributor-row-popover-buttons__button"
data-testid="alert-popover-view-logs"
@@ -35,10 +35,10 @@ function PopoverContent({
<LogsIcon />
</div>
<div className="text">View Logs</div>
- </Link>
+ </AppLink>
)}
{!!relatedTracesLink && (
- <Link
+ <AppLink
to={`${ROUTES.TRACES_EXPLORER}?${relatedTracesLink}`}
className="contributor-row-popover-buttons__button"
data-testid="alert-popover-view-traces"
@@ -50,7 +50,7 @@ function PopoverContent({
/>
</div>
<div className="text">View Traces</div>
- </Link>
+ </AppLink>
)}
</div>
);
diff --git a/frontend/src/container/AlertHistory/Statistics/TopContributorsCard/TopContributorsCard.tsx b/frontend/src/container/AlertHistory/Statistics/TopContributorsCard/TopContributorsCard.tsx
index ae0054e48e..66a49410fa 100644
--- a/frontend/src/container/AlertHistory/Statistics/TopContributorsCard/TopContributorsCard.tsx
+++ b/frontend/src/container/AlertHistory/Statistics/TopContributorsCard/TopContributorsCard.tsx
@@ -1,9 +1,9 @@
import { useMemo, useState } from 'react';
-import { useLocation } from 'react-router-dom';
import { Color } from '@signozhq/design-tokens';
import { Button } from 'antd';
import { useIsDarkMode } from 'hooks/useDarkMode';
-import history from 'lib/history';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { navigate } from 'lib/router/navigation';
import { ArrowRight } from '@signozhq/icons';
import TopContributorsContent from './TopContributorsContent';
@@ -16,7 +16,7 @@ function TopContributorsCard({
topContributorsData,
totalCurrentTriggers,
}: TopContributorsCardProps): JSX.Element {
- const { search } = useLocation();
+ const { search } = useAppLocation();
const searchParams = useMemo(() => new URLSearchParams(search), [search]);
const viewAllTopContributorsParam = searchParams.get('viewAllTopContributors');
@@ -43,7 +43,7 @@ function TopContributorsCard({
return newState;
});
- history.push({ search: searchParams.toString() });
+ navigate({ search: searchParams.toString() });
};
return (
diff --git a/frontend/src/container/AlertHistory/Timeline/Graph/Graph.tsx b/frontend/src/container/AlertHistory/Timeline/Graph/Graph.tsx
index b660c6acd8..281c082c7c 100644
--- a/frontend/src/container/AlertHistory/Timeline/Graph/Graph.tsx
+++ b/frontend/src/container/AlertHistory/Timeline/Graph/Graph.tsx
@@ -7,7 +7,7 @@ import { QueryParams } from 'constants/query';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useResizeObserver } from 'hooks/useDimensions';
import useUrlQuery from 'hooks/useUrlQuery';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import heatmapPlugin from 'lib/uPlotLib/plugins/heatmapPlugin';
import timelinePlugin from 'lib/uPlotLib/plugins/timelinePlugin';
import { uPlotXAxisValuesFormat } from 'lib/uPlotLib/utils/constants';
@@ -103,7 +103,7 @@ function HorizontalTimelineGraph({
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
- history.push({
+ navigate({
search: urlQuery.toString(),
});
}
diff --git a/frontend/src/container/AlertHistory/Timeline/TabsAndFilters/TabsAndFilters.tsx b/frontend/src/container/AlertHistory/Timeline/TabsAndFilters/TabsAndFilters.tsx
index 5f09a8a3b3..8e8ee0a10b 100644
--- a/frontend/src/container/AlertHistory/Timeline/TabsAndFilters/TabsAndFilters.tsx
+++ b/frontend/src/container/AlertHistory/Timeline/TabsAndFilters/TabsAndFilters.tsx
@@ -1,8 +1,8 @@
import { useMemo } from 'react';
-import { useLocation } from 'react-router-dom';
import { Color } from '@signozhq/design-tokens';
import { TimelineFilter, TimelineTab } from 'container/AlertHistory/types';
-import history from 'lib/history';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { navigate } from 'lib/router/navigation';
import { Info } from '@signozhq/icons';
import Tabs2 from 'periscope/components/Tabs2';
@@ -42,7 +42,7 @@ function TimelineTabs(): JSX.Element {
}
function TimelineFilters(): JSX.Element {
- const { search } = useLocation();
+ const { search } = useAppLocation();
const searchParams = useMemo(() => new URLSearchParams(search), [search]);
const initialSelectedTab = useMemo(
@@ -52,7 +52,7 @@ function TimelineFilters(): JSX.Element {
const handleFilter = (value: TimelineFilter): void => {
searchParams.set('timelineFilter', value);
- history.push({ search: searchParams.toString() });
+ navigate({ search: searchParams.toString() });
};
const tabs = [
diff --git a/frontend/src/container/AllError/index.tsx b/frontend/src/container/AllError/index.tsx
index 40d4f9f170..be7fbef513 100644
--- a/frontend/src/container/AllError/index.tsx
+++ b/frontend/src/container/AllError/index.tsx
@@ -4,7 +4,8 @@ import { useTranslation } from 'react-i18next';
import { useQueries } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { Link, useLocation } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Button, Card, Input, Space, TableProps, Tooltip, Flex } from 'antd';
import { Search } from '@signozhq/icons';
import type { ColumnType, TablePaginationConfig } from 'antd/es/table';
@@ -28,7 +29,7 @@ import {
import { TimestampInput } from 'hooks/useTimezoneFormatter/useTimezoneFormatter';
import useUrlQuery from 'hooks/useUrlQuery';
import createQueryParams from 'lib/createQueryParams';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { isUndefined } from 'lodash-es';
import { useAllErrorsQueryState } from 'pages/AllErrors/QueryStateContext';
import { useTimezone } from 'providers/Timezone';
@@ -67,7 +68,7 @@ function AllErrors(): JSX.Element {
const { maxTime, minTime, loading } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const params = useUrlQuery();
const { t } = useTranslation(['common']);
const {
@@ -228,7 +229,9 @@ function AllErrors(): JSX.Element {
queryParams.serviceName = serviceFilterValue;
}
- history.replace(`${pathname}?${createQueryParams(queryParams)}`);
+ navigate(`${pathname}?${createQueryParams(queryParams)}`, {
+ replace: true,
+ });
confirm();
},
[
@@ -336,13 +339,13 @@ function AllErrors(): JSX.Element {
...getFilter(onExceptionTypeFilter, 'Search By Exception', 'exceptionType'),
render: (value, record): JSX.Element => (
<Tooltip overlay={(): JSX.Element => value}>
- <Link
+ <AppLink
to={`${ROUTES.ERROR_DETAIL}?groupId=${
record.groupID
}&timestamp=${getNanoSeconds(record.lastSeen)}`}
>
{value}
- </Link>
+ </AppLink>
</Tooltip>
),
sorter: true,
@@ -438,7 +441,7 @@ function AllErrors(): JSX.Element {
exceptionType: getFilterString(params.get(urlKey.exceptionType)),
});
const compositeQuery = params.get(urlKey.compositeQuery) || '';
- history.replace(
+ navigate(
`${pathname}?${createQueryParams({
order: updatedOrder,
offset: (current - 1) * pageSize,
@@ -448,6 +451,7 @@ function AllErrors(): JSX.Element {
serviceName,
compositeQuery,
})}`,
+ { replace: true },
);
}
},
diff --git a/frontend/src/container/AllError/tests/AllError.test.tsx b/frontend/src/container/AllError/tests/AllError.test.tsx
index 33317ff893..0d793614f9 100644
--- a/frontend/src/container/AllError/tests/AllError.test.tsx
+++ b/frontend/src/container/AllError/tests/AllError.test.tsx
@@ -1,6 +1,5 @@
// eslint-disable-next-line no-restricted-imports
import { Provider, useSelector } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { ENVIRONMENT } from 'constants/env';
import { server } from 'mocks-server/server';
@@ -8,6 +7,7 @@ import { rest } from 'msw';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
import TimezoneProvider from 'providers/Timezone';
import store from 'store';
+import { TestRouter } from 'tests/router';
import '@testing-library/jest-dom';
@@ -55,9 +55,9 @@ jest.spyOn(appContextHooks, 'useAppContext').mockReturnValue({
},
} as any);
-function Exceptions({ initUrl }: { initUrl?: string[] }): JSX.Element {
+function Exceptions({ initUrl }: { initUrl?: string }): JSX.Element {
return (
- <MemoryRouter initialEntries={initUrl ?? ['/exceptions']}>
+ <TestRouter initialRoute={initUrl ?? '/exceptions'}>
<TimezoneProvider>
<Provider store={store}>
<MockQueryClientProvider>
@@ -65,12 +65,12 @@ function Exceptions({ initUrl }: { initUrl?: string[] }): JSX.Element {
</MockQueryClientProvider>
</Provider>
</TimezoneProvider>
- </MemoryRouter>
+ </TestRouter>
);
}
Exceptions.defaultProps = {
- initUrl: ['/exceptions'],
+ initUrl: '/exceptions',
};
const BASE_URL = ENVIRONMENT.baseURL;
@@ -130,7 +130,7 @@ describe('Exceptions - All Errors', () => {
});
it('should call useQueries with exact composite query object', async () => {
- render(<Exceptions initUrl={[INIT_URL_WITH_COMMON_QUERY]} />);
+ render(<Exceptions initUrl={INIT_URL_WITH_COMMON_QUERY} />);
await screen.findByText(/redis timeout/i);
expect(postListErrorsSpy).toHaveBeenCalledWith(
expect.objectContaining({
@@ -143,11 +143,7 @@ describe('Exceptions - All Errors', () => {
it('should navigate to page 2 when pageSize=100 and clicking next', async () => {
// Arrange: start with pageSize=100 and offset=0
render(
- <Exceptions
- initUrl={[
- `/exceptions?pageSize=100&offset=0&order=ascending&orderParam=serviceName`,
- ]}
- />,
+ <Exceptions initUrl="/exceptions?pageSize=100&offset=0&order=ascending&orderParam=serviceName" />,
);
// Wait for initial load
@@ -171,11 +167,7 @@ describe('Exceptions - All Errors', () => {
it('initializes current page from URL (offset/pageSize)', async () => {
// offset=100, pageSize=100 => current page should be 2
render(
- <Exceptions
- initUrl={[
- `/exceptions?pageSize=100&offset=100&order=ascending&orderParam=serviceName`,
- ]}
- />,
+ <Exceptions initUrl="/exceptions?pageSize=100&offset=100&order=ascending&orderParam=serviceName" />,
);
await screen.findByText(/redis timeout/i);
const activeItem = document.querySelector('.ant-pagination-item-active');
@@ -188,11 +180,7 @@ describe('Exceptions - All Errors', () => {
it('clicking a numbered page updates offset correctly', async () => {
// pageSize=100, click page 3 => offset = 200
render(
- <Exceptions
- initUrl={[
- `/exceptions?pageSize=100&offset=0&order=ascending&orderParam=serviceName`,
- ]}
- />,
+ <Exceptions initUrl="/exceptions?pageSize=100&offset=0&order=ascending&orderParam=serviceName" />,
);
await screen.findByText(/redis timeout/i);
const page3Item = screen.getByTitle('3');
diff --git a/frontend/src/container/ApiMonitoring/__tests__/queryParams.test.tsx b/frontend/src/container/ApiMonitoring/__tests__/queryParams.test.tsx
index 39ebf0e379..a846946bbc 100644
--- a/frontend/src/container/ApiMonitoring/__tests__/queryParams.test.tsx
+++ b/frontend/src/container/ApiMonitoring/__tests__/queryParams.test.tsx
@@ -4,16 +4,14 @@ import {
getApiMonitoringParams,
setApiMonitoringParams,
} from 'container/ApiMonitoring/queryParams';
+import { mockNavigate } from 'tests/router-mocks';
-// Mock react-router-dom hooks
-jest.mock('react-router-dom', () => {
- const originalModule = jest.requireActual('react-router-dom');
- return {
- ...originalModule,
- useLocation: jest.fn(),
- useHistory: jest.fn(),
- };
-});
+const navigateSpy = mockNavigate();
+
+function navigatedSearch(): string | undefined {
+ const [to] = navigateSpy.mock.calls[0];
+ return typeof to === 'string' ? to : to.search;
+}
describe('API Monitoring Query Params', () => {
describe('getApiMonitoringParams', () => {
@@ -58,25 +56,21 @@ describe('API Monitoring Query Params', () => {
describe('setApiMonitoringParams', () => {
it('updates URL with new params (push mode)', () => {
- const history = {
- push: jest.fn(),
- replace: jest.fn(),
- };
const search = '';
const newParams: Partial<ApiMonitoringParams> = {
showIP: false,
selectedDomain: 'updated-domain',
};
- setApiMonitoringParams(newParams, search, history as any, false);
+ setApiMonitoringParams(newParams, search, false);
- expect(history.push).toHaveBeenCalledWith({
- search: expect.stringContaining('apiMonitoringParams'),
- });
- expect(history.replace).not.toHaveBeenCalled();
+ expect(navigateSpy).toHaveBeenCalledWith(
+ { search: expect.stringContaining('apiMonitoringParams') },
+ { replace: false },
+ );
// Verify that the search string contains the expected encoded params
- const searchArg = history.push.mock.calls[0][0].search;
+ const searchArg = navigatedSearch();
const params = new URLSearchParams(searchArg);
const decoded = JSON.parse(
decodeURIComponent(params.get('apiMonitoringParams') || ''),
@@ -88,30 +82,21 @@ describe('API Monitoring Query Params', () => {
});
it('updates URL with new params (replace mode)', () => {
- const history = {
- push: jest.fn(),
- replace: jest.fn(),
- };
const search = '';
const newParams: Partial<ApiMonitoringParams> = {
showIP: false,
selectedDomain: 'updated-domain',
};
- setApiMonitoringParams(newParams, search, history as any, true);
+ setApiMonitoringParams(newParams, search, true);
- expect(history.replace).toHaveBeenCalledWith({
- search: expect.stringContaining('apiMonitoringParams'),
- });
- expect(history.push).not.toHaveBeenCalled();
+ expect(navigateSpy).toHaveBeenCalledWith(
+ { search: expect.stringContaining('apiMonitoringParams') },
+ { replace: true },
+ );
});
it('merges new params with existing params', () => {
- const history = {
- push: jest.fn(),
- replace: jest.fn(),
- };
-
// Start with some existing params
const existingParams: Partial<ApiMonitoringParams> = {
showIP: true,
@@ -132,10 +117,10 @@ describe('API Monitoring Query Params', () => {
selectedEndPointName: '/api/test',
};
- setApiMonitoringParams(newParams, search, history as any, false);
+ setApiMonitoringParams(newParams, search, false);
// Verify merged params
- const searchArg = history.push.mock.calls[0][0].search;
+ const searchArg = navigatedSearch();
const params = new URLSearchParams(searchArg);
const decoded = JSON.parse(
decodeURIComponent(params.get('apiMonitoringParams') || ''),
@@ -161,27 +146,7 @@ describe('API Monitoring Query Params', () => {
state: null,
};
- // Create mock history object
- const history = {
- push: jest.fn((args) => {
- // Simulate updating the location search
- location.search = args.search;
- }),
- replace: jest.fn((args) => {
- location.search = args.search;
- }),
- length: 1,
- location,
- };
-
- // Set up mocks for useLocation and useHistory
- const useLocationMock = jest.requireMock('react-router-dom').useLocation;
- const useHistoryMock = jest.requireMock('react-router-dom').useHistory;
-
- useLocationMock.mockReturnValue(location);
- useHistoryMock.mockReturnValue(history);
-
- return { location, history };
+ return { location };
};
it('retrieves URL params correctly from location', () => {
@@ -207,7 +172,7 @@ describe('API Monitoring Query Params', () => {
});
it('updates URL correctly with new params', () => {
- const { location, history } = mockUseLocationAndHistory();
+ const { location } = mockUseLocationAndHistory();
const newParams: Partial<ApiMonitoringParams> = {
selectedDomain: 'new-domain',
@@ -215,13 +180,14 @@ describe('API Monitoring Query Params', () => {
};
// Manually execute the core logic of the hook's setParams function
- setApiMonitoringParams(newParams, location.search, history as any);
+ setApiMonitoringParams(newParams, location.search);
- expect(history.push).toHaveBeenCalledWith({
- search: expect.stringContaining('apiMonitoringParams'),
- });
+ expect(navigateSpy).toHaveBeenCalledWith(
+ { search: expect.stringContaining('apiMonitoringParams') },
+ { replace: false },
+ );
- const searchArg = history.push.mock.calls[0][0].search;
+ const searchArg = navigatedSearch();
const params = new URLSearchParams(searchArg);
const decoded = JSON.parse(
decodeURIComponent(params.get('apiMonitoringParams') || ''),
@@ -247,20 +213,16 @@ describe('API Monitoring Query Params', () => {
const initialSearch = `?${urlParams.toString()}`;
// Set up mocks
- const { location, history } = mockUseLocationAndHistory(initialSearch);
+ const { location } = mockUseLocationAndHistory(initialSearch);
// Manually execute the core logic
- setApiMonitoringParams(
- { selectedView: 'new-view' },
- location.search,
- history as any,
- );
+ setApiMonitoringParams({ selectedView: 'new-view' }, location.search);
// Verify history was updated
- expect(history.push).toHaveBeenCalled();
+ expect(navigateSpy).toHaveBeenCalled();
// Parse the new query params from the URL
- const searchArg = history.push.mock.calls[0][0].search;
+ const searchArg = navigatedSearch();
const params = new URLSearchParams(searchArg);
const decoded = JSON.parse(
decodeURIComponent(params.get('apiMonitoringParams') || ''),
diff --git a/frontend/src/container/ApiMonitoring/queryParams.ts b/frontend/src/container/ApiMonitoring/queryParams.ts
index 74de35632b..e77c928d3d 100644
--- a/frontend/src/container/ApiMonitoring/queryParams.ts
+++ b/frontend/src/container/ApiMonitoring/queryParams.ts
@@ -1,5 +1,6 @@
import { useCallback } from 'react';
-import { useHistory, useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { navigate } from 'lib/router/navigation';
// --- Types for all API Monitoring query params ---
export interface ApiMonitoringParams {
@@ -55,7 +56,6 @@ export function getApiMonitoringParams(search: string): ApiMonitoringParams {
export function setApiMonitoringParams(
newParams: Partial<ApiMonitoringParams>,
search: string,
- history: ReturnType<typeof useHistory>,
replace = false,
): void {
const urlParams = new URLSearchParams(search);
@@ -63,11 +63,7 @@ export function setApiMonitoringParams(
const merged = { ...current, ...newParams };
urlParams.set(PARAM_KEY, encodeParams(merged));
const newSearch = `?${urlParams.toString()}`;
- if (replace) {
- history.replace({ search: newSearch });
- } else {
- history.push({ search: newSearch });
- }
+ navigate({ search: newSearch }, { replace });
}
// --- React hook to use query params in a component ---
@@ -75,15 +71,14 @@ export function useApiMonitoringParams(): [
ApiMonitoringParams,
(newParams: Partial<ApiMonitoringParams>, replace?: boolean) => void,
] {
- const location = useLocation();
- const history = useHistory();
+ const location = useAppLocation();
const params = getApiMonitoringParams(location.search);
const setParams = useCallback(
(newParams: Partial<ApiMonitoringParams>, replace = false) => {
- setApiMonitoringParams(newParams, location.search, history, replace);
+ setApiMonitoringParams(newParams, location.search, replace);
},
- [location.search, history],
+ [location.search],
);
return [params, setParams];
diff --git a/frontend/src/container/AppLayout/index.tsx b/frontend/src/container/AppLayout/index.tsx
index 1855422417..c274da0c6d 100644
--- a/frontend/src/container/AppLayout/index.tsx
+++ b/frontend/src/container/AppLayout/index.tsx
@@ -11,7 +11,7 @@ import { useTranslation } from 'react-i18next';
import { useMutation, useQueries } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import * as Sentry from '@sentry/react';
import { Toaster } from '@signozhq/ui/sonner';
import { TooltipProvider } from '@signozhq/ui/tooltip';
@@ -51,7 +51,7 @@ import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { useNotifications } from 'hooks/useNotifications';
import useTabVisibility from 'hooks/useTabFocus';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { isNull } from 'lodash-es';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import { useAppContext } from 'providers/App/App';
@@ -190,7 +190,7 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
const isDarkMode = useIsDarkMode();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const { t } = useTranslation(['titles']);
const { isCloudUser: isCloudUserVal } = useGetTenantLicense();
@@ -464,7 +464,7 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
}, [isLoggedIn]);
const handleUpgrade = useCallback((): void => {
- history.push(ROUTES.BILLING);
+ navigate(ROUTES.BILLING);
}, []);
const handleFailedPayment = useCallback((): void => {
diff --git a/frontend/src/container/BillingContainer/CancelSubscriptionBanner.test.tsx b/frontend/src/container/BillingContainer/CancelSubscriptionBanner.test.tsx
index b58b71ffbb..0588eb82ea 100644
--- a/frontend/src/container/BillingContainer/CancelSubscriptionBanner.test.tsx
+++ b/frontend/src/container/BillingContainer/CancelSubscriptionBanner.test.tsx
@@ -9,8 +9,7 @@ import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import CancelSubscriptionBanner from './CancelSubscriptionBanner';
jest.mock('utils/basePath', () => ({
- getBasePath: (): string => '/',
- withBasePath: (path: string): string => path,
+ ...jest.requireActual('utils/basePath'),
getAbsoluteUrl: (path: string): string => `https://test.signoz.io${path}`,
getBaseUrl: (): string => 'https://test.signoz.io',
}));
diff --git a/frontend/src/container/BottomStrip/AskNoz/AskNoz.tsx b/frontend/src/container/BottomStrip/AskNoz/AskNoz.tsx
index 8eabfd9185..cd57be0a1f 100644
--- a/frontend/src/container/BottomStrip/AskNoz/AskNoz.tsx
+++ b/frontend/src/container/BottomStrip/AskNoz/AskNoz.tsx
@@ -1,5 +1,4 @@
import { useCallback } from 'react';
-import { useLocation } from 'react-router-dom';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import logEvent from 'api/common/logEvent';
@@ -16,6 +15,7 @@ import {
useAIAssistantStore,
} from 'container/AIAssistant/store/useAIAssistantStore';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
+import { useAppLocation } from 'lib/router/useAppLocation';
import ROUTES from 'constants/routes';
import { Dot } from '@signozhq/icons';
@@ -30,7 +30,7 @@ import styles from './AskNoz.module.scss';
* hiding the header button would remove a notification rather than move it.
*/
function AskNoz(): JSX.Element | null {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const isDrawerOpen = useAIAssistantStore((state) => state.isDrawerOpen);
const isModalOpen = useAIAssistantStore((state) => state.isModalOpen);
diff --git a/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx b/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx
index 8d18d7bdf1..8508931862 100644
--- a/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx
+++ b/frontend/src/container/CreateAlertRule/AlertRuleDocumentationRedirection.test.tsx
@@ -6,18 +6,6 @@ import { AlertTypes } from 'types/api/alerts/alertTypes';
import { ALERT_TYPE_TO_TITLE, ALERT_TYPE_URL_MAP } from './constants';
-jest.mock('react-router-dom-v5-compat', () => ({
- ...jest.requireActual('react-router-dom-v5-compat'),
- useNavigationType: jest.fn(() => 'PUSH'),
- useLocation: jest.fn(() => ({
- pathname: '/alerts/new',
- search: '',
- hash: '',
- state: null,
- })),
- useSearchParams: jest.fn(() => [new URLSearchParams(), jest.fn()]),
-}));
-
jest
.spyOn(usePrefillAlertConditions, 'usePrefillAlertConditions')
.mockReturnValue({
diff --git a/frontend/src/container/CreateAlertRule/AnomalyAlertDocumentationRedirection.test.tsx b/frontend/src/container/CreateAlertRule/AnomalyAlertDocumentationRedirection.test.tsx
index f241fba695..76a017b0d5 100644
--- a/frontend/src/container/CreateAlertRule/AnomalyAlertDocumentationRedirection.test.tsx
+++ b/frontend/src/container/CreateAlertRule/AnomalyAlertDocumentationRedirection.test.tsx
@@ -1,4 +1,3 @@
-import { MemoryRouter, Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
import * as usePrefillAlertConditions from 'container/FormAlertRules/usePrefillAlertConditions';
import CreateAlertPage from 'pages/CreateAlert';
@@ -7,27 +6,6 @@ import { AlertTypes } from 'types/api/alerts/alertTypes';
import { ALERT_TYPE_URL_MAP } from './constants';
-// The setup guide button only exists in the classic form.
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string; search: string } => ({
- pathname: `${process.env.FRONTEND_API_ENDPOINT}${ROUTES.ALERTS_NEW}`,
- search: 'ruleType=anomaly_rule&showClassicCreateAlertsPage=true',
- }),
-}));
-
-jest.mock('react-router-dom-v5-compat', () => ({
- ...jest.requireActual('react-router-dom-v5-compat'),
- useNavigationType: jest.fn(() => 'PUSH'),
- useLocation: jest.fn(() => ({
- pathname: '/alerts/new',
- search: 'ruleType=anomaly_rule&showClassicCreateAlertsPage=true',
- hash: '',
- state: null,
- })),
- useSearchParams: jest.fn(() => [new URLSearchParams(), jest.fn()]),
-}));
-
window.ResizeObserver =
window.ResizeObserver ||
jest.fn().mockImplementation(() => ({
@@ -59,13 +37,10 @@ describe('Anomaly Alert Documentation Redirection', () => {
});
it('should handle anomaly alert documentation redirection correctly', () => {
- const { getByRole } = render(
- <MemoryRouter initialEntries={['/alerts/new']}>
- <Route path={ROUTES.ALERTS_NEW}>
- <CreateAlertPage />
- </Route>
- </MemoryRouter>,
- );
+ // The setup guide button only exists in the classic form.
+ const { getByRole } = render(<CreateAlertPage />, undefined, {
+ initialRoute: `${ROUTES.ALERTS_NEW}?ruleType=anomaly_rule&showClassicCreateAlertsPage=true`,
+ });
const alertType = AlertTypes.ANOMALY_BASED_ALERT;
diff --git a/frontend/src/container/CreateAlertRule/__tests__/CreateAlertRule.test.tsx b/frontend/src/container/CreateAlertRule/__tests__/CreateAlertRule.test.tsx
index c7257d338b..2b9699e921 100644
--- a/frontend/src/container/CreateAlertRule/__tests__/CreateAlertRule.test.tsx
+++ b/frontend/src/container/CreateAlertRule/__tests__/CreateAlertRule.test.tsx
@@ -16,18 +16,6 @@ import { DataSource } from 'types/common/queryBuilder';
import CreateAlertRule from '../index';
-jest.mock('react-router-dom-v5-compat', () => ({
- ...jest.requireActual('react-router-dom-v5-compat'),
- useNavigationType: jest.fn(() => 'PUSH'),
- useLocation: jest.fn(() => ({
- pathname: '/alerts/new',
- search: '',
- hash: '',
- state: null,
- })),
- useSearchParams: jest.fn(() => [new URLSearchParams(), jest.fn()]),
-}));
-
jest.mock('container/TopNav/DateTimeSelectionV2', () => ({
__esModule: true,
default: function MockDateTimeSelector(): JSX.Element {
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx
index 6c0c3f256c..f55bdbff53 100644
--- a/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx
@@ -1,6 +1,6 @@
import { QueryClient, QueryClientProvider } from 'react-query';
-import { MemoryRouter } from 'react-router-dom';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { TestRouter } from 'tests/router';
import { AlertTypes } from 'types/api/alerts/alertTypes';
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
@@ -129,13 +129,13 @@ const createTestQueryClient = (): QueryClient =>
const renderAlertThreshold = (): ReturnType<typeof render> => {
const queryClient = createTestQueryClient();
return render(
- <MemoryRouter>
+ <TestRouter>
<QueryClientProvider client={queryClient}>
<CreateAlertProvider initialAlertType={AlertTypes.METRICS_BASED_ALERT}>
<AlertThreshold {...mockProps} />
</CreateAlertProvider>
</QueryClientProvider>
- </MemoryRouter>,
+ </TestRouter>,
);
};
diff --git a/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/CreateAlertHeader.test.tsx b/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/CreateAlertHeader.test.tsx
index c6f8604f4a..838c58370b 100644
--- a/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/CreateAlertHeader.test.tsx
+++ b/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/CreateAlertHeader.test.tsx
@@ -4,6 +4,7 @@ import ROUTES from 'constants/routes';
import { defaultPostableAlertRuleV2 } from 'container/CreateAlertV2/constants';
import { getCreateAlertLocalStateFromAlertDef } from 'container/CreateAlertV2/utils';
import * as useSafeNavigateHook from 'hooks/useSafeNavigate';
+import { mockAppLocation } from 'tests/router-mocks';
import { AlertTypes } from 'types/api/alerts/alertTypes';
import * as rulesHook from '../../../../api/generated/services/rules';
@@ -42,12 +43,7 @@ jest.mock('uplot', () => {
};
});
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { search: string } => ({
- search: '',
- }),
-}));
+mockAppLocation({ search: '' });
const ENTER_ALERT_RULE_NAME_PLACEHOLDER = 'Enter alert rule name';
diff --git a/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx b/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx
index 80701fecde..3c846666b6 100644
--- a/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx
+++ b/frontend/src/container/CreateAlertV2/QuerySection/ChartPreview/ChartPreview.tsx
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import YAxisUnitSelector from 'components/YAxisUnitSelector';
import { YAxisSource } from 'components/YAxisUnitSelector/types';
import { PANEL_TYPES } from 'constants/queryBuilder';
@@ -41,7 +41,7 @@ function ChartPreview({
const yAxisUnit = alertState.yAxisUnit || '';
- const location = useLocation();
+ const location = useAppLocation();
const yAxisUnitFromURL = new URLSearchParams(location.search).get(
QueryParams.yAxisUnit,
);
diff --git a/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx
index 0e0784d0b9..ee56aade29 100644
--- a/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx
+++ b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/ChartPreview.test.tsx
@@ -1,7 +1,6 @@
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render, screen } from '@testing-library/react';
import { PANEL_TYPES } from 'constants/queryBuilder';
import {
@@ -10,6 +9,7 @@ import {
} from 'container/CreateAlertV2/context/constants';
import { buildInitialAlertDef } from 'container/CreateAlertV2/context/utils';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { AlertTypes } from 'types/api/alerts/alertTypes';
import { EQueryType } from 'types/common/dashboard';
@@ -130,11 +130,11 @@ const renderChartPreview = (): ReturnType<typeof render> =>
render(
<Provider store={store}>
<QueryClientProvider client={queryClient}>
- <MemoryRouter>
+ <TestRouter>
<CreateAlertProvider initialAlertType={AlertTypes.METRICS_BASED_ALERT}>
<ChartPreview alertDef={mockAlertDef} />
</CreateAlertProvider>
- </MemoryRouter>
+ </TestRouter>
</QueryClientProvider>
</Provider>,
);
diff --git a/frontend/src/container/CreateAlertV2/QuerySection/__tests__/QuerySection.test.tsx b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/QuerySection.test.tsx
index 679328a5ca..0ecd66efe6 100644
--- a/frontend/src/container/CreateAlertV2/QuerySection/__tests__/QuerySection.test.tsx
+++ b/frontend/src/container/CreateAlertV2/QuerySection/__tests__/QuerySection.test.tsx
@@ -1,7 +1,6 @@
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { QueryParams } from 'constants/query';
@@ -11,6 +10,7 @@ import {
} from 'constants/queryBuilder';
import { AlertDetectionTypes } from 'container/FormAlertRules';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { AlertTypes } from 'types/api/alerts/alertTypes';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
@@ -133,11 +133,11 @@ const renderQuerySection = (search = ''): ReturnType<typeof render> =>
render(
<Provider store={store}>
<QueryClientProvider client={queryClient}>
- <MemoryRouter initialEntries={[`/alerts/new${search}`]}>
+ <TestRouter initialRoute={`/alerts/new${search}`}>
<CreateAlertProvider initialAlertType={AlertTypes.METRICS_BASED_ALERT}>
<QuerySection />
</CreateAlertProvider>
- </MemoryRouter>
+ </TestRouter>
</QueryClientProvider>
</Provider>,
);
@@ -427,11 +427,11 @@ describe('QuerySection', () => {
render(
<Provider store={store}>
<QueryClientProvider client={queryClient}>
- <MemoryRouter>
+ <TestRouter>
<CreateAlertProvider initialAlertType={AlertTypes.LOGS_BASED_ALERT}>
<QuerySection />
</CreateAlertProvider>
- </MemoryRouter>
+ </TestRouter>
</QueryClientProvider>
</Provider>,
);
@@ -481,11 +481,11 @@ describe('QuerySection', () => {
render(
<Provider store={store}>
<QueryClientProvider client={queryClient}>
- <MemoryRouter>
+ <TestRouter>
<CreateAlertProvider initialAlertType={AlertTypes.TRACES_BASED_ALERT}>
<QuerySection />
</CreateAlertProvider>
- </MemoryRouter>
+ </TestRouter>
</QueryClientProvider>
</Provider>,
);
diff --git a/frontend/src/container/CreateAlertV2/context/__tests__/CreateAlertProvider.prefill.test.tsx b/frontend/src/container/CreateAlertV2/context/__tests__/CreateAlertProvider.prefill.test.tsx
index fab8d6c148..32940787e6 100644
--- a/frontend/src/container/CreateAlertV2/context/__tests__/CreateAlertProvider.prefill.test.tsx
+++ b/frontend/src/container/CreateAlertV2/context/__tests__/CreateAlertProvider.prefill.test.tsx
@@ -1,4 +1,4 @@
-import { useHistory } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
import { render, screen, userEvent } from 'tests/test-utils';
import { AlertTypes } from 'types/api/alerts/alertTypes';
@@ -125,12 +125,11 @@ function SearchMutator({
}: {
to?: string;
}): JSX.Element {
- const routerHistory = useHistory();
return (
<button
type="button"
data-testid="mutate-search"
- onClick={(): void => routerHistory.replace(to)}
+ onClick={(): void => navigate(to, { replace: true })}
>
change search
</button>
diff --git a/frontend/src/container/CreateAlertV2/context/index.tsx b/frontend/src/container/CreateAlertV2/context/index.tsx
index 3421600347..f88708aff3 100644
--- a/frontend/src/container/CreateAlertV2/context/index.tsx
+++ b/frontend/src/container/CreateAlertV2/context/index.tsx
@@ -10,7 +10,7 @@ import {
useRef,
useState,
} from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import {
useCreateRule,
useTestRule,
@@ -129,7 +129,7 @@ export function CreateAlertProvider(
[setCreateAlertState],
);
- const location = useLocation();
+ const location = useAppLocation();
const queryParams = new URLSearchParams(location.search);
const ruleNameFromURL = queryParams.get(QueryParams.ruleName);
const yAxisUnitFromURL = queryParams.get(QueryParams.yAxisUnit);
diff --git a/frontend/src/container/ErrorDetails/index.tsx b/frontend/src/container/ErrorDetails/index.tsx
index a7e984a47f..cad18f82a0 100644
--- a/frontend/src/container/ErrorDetails/index.tsx
+++ b/frontend/src/container/ErrorDetails/index.tsx
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery } from 'react-query';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Button, Space } from 'antd';
import { Divider } from '@signozhq/ui/divider';
import { Typography } from '@signozhq/ui/typography';
@@ -13,7 +13,7 @@ import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import { getNanoSeconds } from 'container/AllError/utils';
import { useNotifications } from 'hooks/useNotifications';
import createQueryParams from 'lib/createQueryParams';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { isUndefined } from 'lodash-es';
import { urlKey } from 'pages/ErrorDetails/utils';
import { useTimezone } from 'providers/Timezone';
@@ -29,7 +29,7 @@ import './styles.scss';
function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
const { idPayload } = props;
const { t } = useTranslation(['errorDetails', 'common']);
- const { search, pathname } = useLocation();
+ const { search, pathname } = useAppLocation();
const params = useMemo(() => new URLSearchParams(search), [search]);
@@ -100,7 +100,7 @@ function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
errorId: id,
};
- history.replace(`${pathname}?${createQueryParams(queryParams)}`);
+ navigate(`${pathname}?${createQueryParams(queryParams)}`, { replace: true });
} catch (error) {
notifications.error({
message: t('something_went_wrong'),
@@ -126,7 +126,7 @@ function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
if (isModifierKeyPressed(event)) {
openInNewTab(path);
} else {
- history.push(path);
+ navigate(path);
}
};
diff --git a/frontend/src/container/ExplorerActions/CreateAlertButton.tsx b/frontend/src/container/ExplorerActions/CreateAlertButton.tsx
index 23163d2a95..b9ab7ecb4b 100644
--- a/frontend/src/container/ExplorerActions/CreateAlertButton.tsx
+++ b/frontend/src/container/ExplorerActions/CreateAlertButton.tsx
@@ -1,9 +1,9 @@
-import { useHistory } from 'react-router-dom';
import { ConciergeBell } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import logEvent from 'api/common/logEvent';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { useAppNavigate } from 'lib/router/useAppNavigate';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
@@ -22,7 +22,7 @@ function CreateAlertButton({
sourcepage: DataSource;
isOneChartPerQuery?: boolean;
}): JSX.Element {
- const history = useHistory();
+ const navigate = useAppNavigate();
const { panelType } = useQueryBuilder();
const createAlert = (): void => {
@@ -33,7 +33,7 @@ function CreateAlertButton({
EXPLORER_ACTION_EVENTS[sourcepage].createAlert,
getExplorerActionEventPayload({ sourcepage, panelType, isOneChartPerQuery }),
);
- history.push(getCreateAlertLink({ query, panelType }));
+ navigate(getCreateAlertLink({ query, panelType }));
};
return isOneChartPerQuery ? (
diff --git a/frontend/src/container/ExplorerActions/__tests__/CreateAlertButton.test.tsx b/frontend/src/container/ExplorerActions/__tests__/CreateAlertButton.test.tsx
index 0d7ac00255..9744ac0339 100644
--- a/frontend/src/container/ExplorerActions/__tests__/CreateAlertButton.test.tsx
+++ b/frontend/src/container/ExplorerActions/__tests__/CreateAlertButton.test.tsx
@@ -1,4 +1,3 @@
-import { useHistory } from 'react-router-dom';
import logEvent from 'api/common/logEvent';
import { QueryParams } from 'constants/query';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
@@ -9,16 +8,13 @@ import {
} from 'container/LogsExplorerViews/explorerUtils';
import { getQueryByPanelType as getTracesQueryByPanelType } from 'container/TracesExplorer/explorerUtils';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { mockAppNavigate } from 'tests/router-mocks';
import { render, screen, userEvent } from 'tests/test-utils';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource, StringOperators } from 'types/common/queryBuilder';
import CreateAlertButton from '../CreateAlertButton';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: jest.fn(),
-}));
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: jest.fn(),
}));
@@ -27,8 +23,7 @@ jest.mock('api/common/logEvent', () => ({
default: jest.fn(() => Promise.resolve()),
}));
-const mockPush = jest.fn();
-const mockedUseHistory = jest.mocked(useHistory);
+const mockedNavigate = mockAppNavigate();
const mockedUseQueryBuilder = jest.mocked(useQueryBuilder);
const mockedLogEvent = jest.mocked(logEvent);
@@ -61,8 +56,8 @@ function stagedQuery(
}
function pushedQuery(): Query {
- expect(mockPush).toHaveBeenCalledTimes(1);
- const [path, search] = (mockPush.mock.calls[0][0] as string).split('?');
+ expect(mockedNavigate).toHaveBeenCalledTimes(1);
+ const [path, search] = (mockedNavigate.mock.calls[0][0] as string).split('?');
expect(path).toBe(ROUTES.ALERTS_NEW);
const raw = new URLSearchParams(search).get(QueryParams.compositeQuery);
return JSON.parse(raw as string);
@@ -86,11 +81,8 @@ async function clickCreateAlert(
describe('CreateAlertButton', () => {
beforeEach(() => {
- mockPush.mockReset();
+ mockedNavigate.mockReset();
mockedLogEvent.mockClear();
- mockedUseHistory.mockReturnValue({ push: mockPush } as unknown as ReturnType<
- typeof useHistory
- >);
});
it('is disabled and does nothing without a query', async () => {
@@ -100,7 +92,7 @@ describe('CreateAlertButton', () => {
'aria-disabled',
'true',
);
- expect(mockPush).not.toHaveBeenCalled();
+ expect(mockedNavigate).not.toHaveBeenCalled();
});
it("logs the explorer's own create alert event", async () => {
diff --git a/frontend/src/container/ForgotPassword/__tests__/ForgotPassword.test.tsx b/frontend/src/container/ForgotPassword/__tests__/ForgotPassword.test.tsx
index b3d9309ac1..3718ee7a3e 100644
--- a/frontend/src/container/ForgotPassword/__tests__/ForgotPassword.test.tsx
+++ b/frontend/src/container/ForgotPassword/__tests__/ForgotPassword.test.tsx
@@ -1,5 +1,5 @@
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import {
createErrorResponse,
handleInternalServerError,
@@ -12,19 +12,12 @@ import { OrgSessionContext } from 'types/api/v2/sessions/context/get';
import ForgotPassword, { ForgotPasswordRouteState } from '../index';
// Mock dependencies
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: jest.fn(),
- location: {
- search: '',
- },
- },
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: jest.fn(),
}));
-const mockHistoryPush = history.push as jest.MockedFunction<
- typeof history.push
->;
+const mockNavigate = navigate as jest.MockedFunction<typeof navigate>;
const FORGOT_PASSWORD_ENDPOINT = '*/api/v2/factor_password/forgot';
@@ -236,7 +229,7 @@ describe('ForgotPassword Component', () => {
const backToLoginButton = screen.getByTestId('back-to-login');
await user.click(backToLoginButton);
- expect(mockHistoryPush).toHaveBeenCalledWith(ROUTES.LOGIN);
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.LOGIN);
});
});
@@ -328,7 +321,7 @@ describe('ForgotPassword Component', () => {
const backButton = screen.getByTestId('forgot-password-back');
await user.click(backButton);
- expect(mockHistoryPush).toHaveBeenCalledWith(ROUTES.LOGIN);
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.LOGIN);
});
});
diff --git a/frontend/src/container/ForgotPassword/index.tsx b/frontend/src/container/ForgotPassword/index.tsx
index 1fb2913efb..134c03bba2 100644
--- a/frontend/src/container/ForgotPassword/index.tsx
+++ b/frontend/src/container/ForgotPassword/index.tsx
@@ -7,7 +7,7 @@ import { ErrorResponseHandlerForGeneratedAPIs } from 'api/ErrorResponseHandlerFo
import { useForgotPassword } from 'api/generated/services/users';
import AuthError from 'components/AuthError/AuthError';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import APIError from 'types/api/error';
import { OrgSessionContext } from 'types/api/v2/sessions/context/get';
import { getBaseUrl } from 'utils/basePath';
@@ -108,7 +108,7 @@ function ForgotPassword({
}, [form, forgotPasswordMutate, initialOrgId, hasMultipleOrgs]);
const handleBackToLogin = useCallback((): void => {
- history.push(ROUTES.LOGIN);
+ navigate(ROUTES.LOGIN);
}, []);
// Success screen
diff --git a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx b/frontend/src/container/FormAlertRules/ChartPreview/index.tsx
index 0f61d8d0df..c35ad03290 100644
--- a/frontend/src/container/FormAlertRules/ChartPreview/index.tsx
+++ b/frontend/src/container/FormAlertRules/ChartPreview/index.tsx
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import QueryCancelledPlaceholder from 'components/QueryCancelledPlaceholder';
import Spinner from 'components/Spinner';
@@ -28,7 +28,7 @@ import { useResizeObserver } from 'hooks/useDimensions';
import useUrlQuery from 'hooks/useUrlQuery';
import GetMinMax from 'lib/getMinMax';
import getTimeString from 'lib/getTimeString';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { LegendPosition } from 'lib/uPlotV2/components/types';
import { isEmpty } from 'lodash-es';
import { useIsAnomalyDetectionAvailable } from 'container/CreateAlertV2/useIsAnomalyDetectionAvailable';
@@ -223,7 +223,7 @@ function ChartPreview({
const isDarkMode = useIsDarkMode();
const urlQuery = useUrlQuery();
- const location = useLocation();
+ const location = useAppLocation();
const optionName =
getFormatNameByOptionId(alertDef?.condition.targetUnit || '') || '';
@@ -245,7 +245,7 @@ function ChartPreview({
urlQuery.set(QueryParams.startTime, minTime.toString());
urlQuery.set(QueryParams.endTime, maxTime.toString());
const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
},
[dispatch, location.pathname, urlQuery],
);
diff --git a/frontend/src/container/FormAlertRules/__tests__/usePrefillAlertConditions.test.ts b/frontend/src/container/FormAlertRules/__tests__/usePrefillAlertConditions.test.ts
index 073771074f..0ecb07da24 100644
--- a/frontend/src/container/FormAlertRules/__tests__/usePrefillAlertConditions.test.ts
+++ b/frontend/src/container/FormAlertRules/__tests__/usePrefillAlertConditions.test.ts
@@ -15,7 +15,7 @@ const TEST_MAPPINGS = {
},
};
-jest.mock('react-router-dom-v5-compat', () => {
+jest.mock('lib/router/useAppLocation', () => {
const mockThreshold1 = {
index: '0d11f426-a02e-48da-867c-b79c6ef1ff06',
isEditEnabled: false,
@@ -43,8 +43,7 @@ jest.mock('react-router-dom-v5-compat', () => {
thresholdValue: 900,
};
return {
- ...jest.requireActual('react-router-dom-v5-compat'),
- useLocation: jest.fn().mockReturnValue({
+ useAppLocation: jest.fn().mockReturnValue({
state: {
thresholds: [mockThreshold1, mockThreshold2],
},
diff --git a/frontend/src/container/FormAlertRules/index.tsx b/frontend/src/container/FormAlertRules/index.tsx
index ab75ca3e5b..25a5da0d99 100644
--- a/frontend/src/container/FormAlertRules/index.tsx
+++ b/frontend/src/container/FormAlertRules/index.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { useQueryClient } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { BellDot, CircleAlert, ExternalLink, Save } from '@signozhq/icons';
import { Button, FormInstance, SelectProps } from 'antd';
import { ConfirmDialog } from '@signozhq/ui/dialog';
@@ -107,7 +107,7 @@ function FormAlertRules({
>((state) => state.globalTime);
const urlQuery = useUrlQuery();
- const location = useLocation();
+ const location = useAppLocation();
const queryParams = new URLSearchParams(location.search);
const dataSource = useMemo(
diff --git a/frontend/src/container/FormAlertRules/usePrefillAlertConditions.ts b/frontend/src/container/FormAlertRules/usePrefillAlertConditions.ts
index ac1f0f802c..b61f5037b5 100644
--- a/frontend/src/container/FormAlertRules/usePrefillAlertConditions.ts
+++ b/frontend/src/container/FormAlertRules/usePrefillAlertConditions.ts
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
-import { useLocation } from 'react-router-dom-v5-compat';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { ThresholdProps } from 'types/api/widgets/threshold';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
@@ -13,7 +13,7 @@ export const usePrefillAlertConditions = (
target: number | undefined;
targetUnit: string | undefined;
} => {
- const location = useLocation();
+ const location = useAppLocation();
// Extract and set match type
const reduceTo = useMemo(() => {
diff --git a/frontend/src/container/GeneralSettings/LicenseKeyRow/LicenseRowDismissibleCallout/LicenseRowDismissibleCallout.tsx b/frontend/src/container/GeneralSettings/LicenseKeyRow/LicenseRowDismissibleCallout/LicenseRowDismissibleCallout.tsx
index 9c3de2bc72..c153cf38fa 100644
--- a/frontend/src/container/GeneralSettings/LicenseKeyRow/LicenseRowDismissibleCallout/LicenseRowDismissibleCallout.tsx
+++ b/frontend/src/container/GeneralSettings/LicenseKeyRow/LicenseRowDismissibleCallout/LicenseRowDismissibleCallout.tsx
@@ -1,5 +1,5 @@
import { useState } from 'react';
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import { Callout } from '@signozhq/ui/callout';
import getLocalStorageApi from 'api/browser/localstorage/get';
import setLocalStorageApi from 'api/browser/localstorage/set';
@@ -55,21 +55,21 @@ function LicenseRowDismissibleCallout(): JSX.Element | null {
{' '}
Find your{' '}
{hasServiceAccountsAccess && (
- <Link
+ <AppLink
to={ROUTES.SERVICE_ACCOUNTS_SETTINGS}
className="license-key-callout__link"
>
Service account here
- </Link>
+ </AppLink>
)}
{hasServiceAccountsAccess && hasIngestionAccess && ' and '}
{hasIngestionAccess && (
- <Link
+ <AppLink
to={ROUTES.INGESTION_SETTINGS}
className="license-key-callout__link"
>
Ingestion key here
- </Link>
+ </AppLink>
)}
.
</>
diff --git a/frontend/src/container/Home/AlertRules/AlertRules.tsx b/frontend/src/container/Home/AlertRules/AlertRules.tsx
index 7d71fbe930..afa845f54f 100644
--- a/frontend/src/container/Home/AlertRules/AlertRules.tsx
+++ b/frontend/src/container/Home/AlertRules/AlertRules.tsx
@@ -1,5 +1,4 @@
import { useEffect, useState } from 'react';
-import { Link, useLocation } from 'react-router-dom';
import { Button, Skeleton } from 'antd';
import { Badge } from '@signozhq/ui/badge';
import logEvent from 'api/common/logEvent';
@@ -7,7 +6,9 @@ import { useListRules } from 'api/generated/services/rules';
import type { RuletypesRuleDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { AppLink } from 'lib/router/AppLink';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
import { ArrowRight, ArrowUpRight, Plus } from '@signozhq/icons';
import Card from 'periscope/components/Card/Card';
@@ -33,7 +34,7 @@ export default function AlertRules({
[],
);
- const location = useLocation();
+ const location = useAppLocation();
const params = new URLSearchParams(location.search);
// Fetch Alerts
@@ -88,7 +89,7 @@ export default function AlertRules({
{user?.role !== USER_ROLES.VIEWER && (
<div className="empty-actions-container">
- <Link to={ROUTES.ALERTS_NEW}>
+ <AppLink to={ROUTES.ALERTS_NEW}>
<Button
type="default"
className="periscope-btn secondary"
@@ -99,7 +100,7 @@ export default function AlertRules({
>
Create Alert Rule
</Button>
- </Link>
+ </AppLink>
<Button
type="link"
@@ -146,7 +147,7 @@ export default function AlertRules({
params.set(QueryParams.ruleId, record.id);
- history.push(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`);
+ navigate(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`);
};
const renderAlertRules = (): JSX.Element => (
@@ -228,7 +229,7 @@ export default function AlertRules({
{rulesExist && (
<Card.Footer>
<div className="alert-rules-footer home-data-card-footer">
- <Link to={ROUTES.LIST_ALL_ALERT}>
+ <AppLink to={ROUTES.LIST_ALL_ALERT}>
<Button
type="link"
className="periscope-btn link learn-more-link"
@@ -238,7 +239,7 @@ export default function AlertRules({
>
All Alert Rules <ArrowRight size={12} />
</Button>
- </Link>
+ </AppLink>
</div>
</Card.Footer>
)}
diff --git a/frontend/src/container/Home/Dashboards/Dashboards.tsx b/frontend/src/container/Home/Dashboards/Dashboards.tsx
index 1acf8917d5..83841fe7b3 100644
--- a/frontend/src/container/Home/Dashboards/Dashboards.tsx
+++ b/frontend/src/container/Home/Dashboards/Dashboards.tsx
@@ -1,6 +1,6 @@
import { useEffect, useMemo } from 'react';
-import { Link } from 'react-router-dom';
import { Button, Skeleton } from 'antd';
+import { AppLink } from 'lib/router/AppLink';
import { Badge } from '@signozhq/ui/badge';
import logEvent from 'api/common/logEvent';
import { useListDashboardsForUserV2 } from 'api/generated/services/dashboard';
@@ -79,7 +79,7 @@ export default function Dashboards({
{user?.role !== USER_ROLES.VIEWER && (
<div className="empty-actions-container">
- <Link to={ROUTES.ALL_DASHBOARD}>
+ <AppLink to={ROUTES.ALL_DASHBOARD}>
<Button
type="default"
className="periscope-btn secondary"
@@ -90,7 +90,7 @@ export default function Dashboards({
>
New Dashboard
</Button>
- </Link>
+ </AppLink>
<Button
type="link"
@@ -212,7 +212,7 @@ export default function Dashboards({
{dashboardsExist && (
<Card.Footer>
<div className="dashboards-footer home-data-card-footer">
- <Link to={ROUTES.ALL_DASHBOARD}>
+ <AppLink to={ROUTES.ALL_DASHBOARD}>
<Button
type="link"
className="periscope-btn link learn-more-link"
@@ -222,7 +222,7 @@ export default function Dashboards({
>
All Dashboards <ArrowRight size={12} />
</Button>
- </Link>
+ </AppLink>
</div>
</Card.Footer>
)}
diff --git a/frontend/src/container/Home/DataSourceInfo/DataSourceInfo.tsx b/frontend/src/container/Home/DataSourceInfo/DataSourceInfo.tsx
index a8f71372ef..b340cf50da 100644
--- a/frontend/src/container/Home/DataSourceInfo/DataSourceInfo.tsx
+++ b/frontend/src/container/Home/DataSourceInfo/DataSourceInfo.tsx
@@ -4,7 +4,7 @@ import { Skeleton } from 'antd';
import logEvent from 'api/common/logEvent';
import { useGetHosts } from 'api/generated/services/zeus';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { Link2 } from '@signozhq/icons';
import Card from 'periscope/components/Card/Card';
import { useAppContext } from 'providers/App/App';
@@ -51,7 +51,7 @@ function DataSourceInfo({
logEvent('Homepage: Connect dataSource clicked', {});
if (activeLicense && activeLicense.platform === LicensePlatform.CLOUD) {
- history.push(ROUTES.GET_STARTED_WITH_CLOUD);
+ navigate(ROUTES.GET_STARTED_WITH_CLOUD);
} else {
openInNewTab(DOCS_LINKS.ADD_DATA_SOURCE);
}
diff --git a/frontend/src/container/Home/Home.tsx b/frontend/src/container/Home/Home.tsx
index 18e172b217..2194b4b10e 100644
--- a/frontend/src/container/Home/Home.tsx
+++ b/frontend/src/container/Home/Home.tsx
@@ -30,7 +30,7 @@ import { useHomeStripInfo } from 'container/Home/useHomeStripInfo';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import cloneDeep from 'lodash-es/cloneDeep';
import { AnimatePresence, motion } from 'motion/react';
import Card from 'periscope/components/Card/Card';
@@ -371,7 +371,7 @@ export default function Home(): JSX.Element {
void logEvent('Homepage: Ingestion Active Explore clicked', {
source: 'Logs',
});
- history.push(ROUTES.LOGS_EXPLORER);
+ navigate(ROUTES.LOGS_EXPLORER);
}
}}
>
@@ -414,7 +414,7 @@ export default function Home(): JSX.Element {
void logEvent('Homepage: Ingestion Active Explore clicked', {
source: 'Traces',
});
- history.push(ROUTES.TRACES_EXPLORER);
+ navigate(ROUTES.TRACES_EXPLORER);
}
}}
>
@@ -457,7 +457,7 @@ export default function Home(): JSX.Element {
void logEvent('Homepage: Ingestion Active Explore clicked', {
source: 'Metrics',
});
- history.push(ROUTES.METRICS_EXPLORER);
+ navigate(ROUTES.METRICS_EXPLORER);
}
}}
>
diff --git a/frontend/src/container/Home/HomeChecklist/HomeChecklist.tsx b/frontend/src/container/Home/HomeChecklist/HomeChecklist.tsx
index 541b234d4b..b2404c01dc 100644
--- a/frontend/src/container/Home/HomeChecklist/HomeChecklist.tsx
+++ b/frontend/src/container/Home/HomeChecklist/HomeChecklist.tsx
@@ -3,7 +3,7 @@ import { useEffect, useState } from 'react';
import { Button } from 'antd';
import logEvent from 'api/common/logEvent';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { ArrowRight, ArrowRightToLine, BookOpenText } from '@signozhq/icons';
import { useAppContext } from 'providers/App/App';
import { LicensePlatform } from 'types/api/licensesV3/getActive';
@@ -93,12 +93,12 @@ function HomeChecklist({
});
if (item.toRoute !== ROUTES.GET_STARTED_WITH_CLOUD) {
- history.push(item.toRoute || '');
+ navigate(item.toRoute || '');
} else if (
activeLicense &&
activeLicense.platform === LicensePlatform.CLOUD
) {
- history.push(item.toRoute || '');
+ navigate(item.toRoute || '');
} else {
openInNewTab(item.docsLink || '');
}
diff --git a/frontend/src/container/Home/SavedViews/SavedViews.tsx b/frontend/src/container/Home/SavedViews/SavedViews.tsx
index 1c34cd4056..c7c173c945 100644
--- a/frontend/src/container/Home/SavedViews/SavedViews.tsx
+++ b/frontend/src/container/Home/SavedViews/SavedViews.tsx
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useState } from 'react';
-import { Link } from 'react-router-dom';
import { Button, Skeleton } from 'antd';
+import { AppLink } from 'lib/router/AppLink';
import logEvent from 'api/common/logEvent';
import { useListSavedViews } from 'api/generated/services/saved-view';
import {
@@ -148,7 +148,7 @@ export default function SavedViews({
{user?.role !== USER_ROLES.VIEWER && (
<div className="empty-actions-container">
- <Link to={getStartedLink}>
+ <AppLink to={getStartedLink}>
<Button
type="default"
className="periscope-btn secondary"
@@ -161,7 +161,7 @@ export default function SavedViews({
>
Get Started &nbsp; <ArrowRight size={16} />
</Button>
- </Link>
+ </AppLink>
<Button
type="link"
diff --git a/frontend/src/container/Home/Services/ServiceMetrics.tsx b/frontend/src/container/Home/Services/ServiceMetrics.tsx
index 5d29143130..dc8a7cfde4 100644
--- a/frontend/src/container/Home/Services/ServiceMetrics.tsx
+++ b/frontend/src/container/Home/Services/ServiceMetrics.tsx
@@ -2,7 +2,6 @@ import React, { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { QueryKey } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { Link } from 'react-router-dom';
import { Button, Select, Skeleton, Table } from 'antd';
import logEvent from 'api/common/logEvent';
import { ENTITY_VERSION_V4 } from 'constants/app';
@@ -16,7 +15,8 @@ import useGetTopLevelOperations from 'hooks/useGetTopLevelOperations';
import useResourceAttribute from 'hooks/useResourceAttribute';
import { convertRawQueriesToTraceSelectedTags } from 'hooks/useResourceAttribute/utils';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
-import history from 'lib/history';
+import { AppLink } from 'lib/router/AppLink';
+import { navigate } from 'lib/router/navigation';
import { ArrowRight, ArrowUpRight } from '@signozhq/icons';
import Card from 'periscope/components/Card/Card';
import { useAppContext } from 'providers/App/App';
@@ -77,7 +77,7 @@ const EmptyState = memo(
activeLicenseV3 &&
activeLicenseV3.platform === LicensePlatform.CLOUD
) {
- history.push(ROUTES.GET_STARTED_WITH_CLOUD);
+ navigate(ROUTES.GET_STARTED_WITH_CLOUD);
} else {
openInNewTab(DOCS_LINKS.ADD_DATA_SOURCE);
}
@@ -340,7 +340,7 @@ function ServiceMetrics({
{servicesExist && (
<Card.Footer>
<div className="services-footer home-data-card-footer">
- <Link to="/services">
+ <AppLink to="/services">
<Button
type="link"
className="periscope-btn link learn-more-link"
@@ -350,7 +350,7 @@ function ServiceMetrics({
>
All Services <ArrowRight size={12} />
</Button>
- </Link>
+ </AppLink>
</div>
</Card.Footer>
)}
diff --git a/frontend/src/container/Home/Services/ServiceTraces.tsx b/frontend/src/container/Home/Services/ServiceTraces.tsx
index 9e47cbd803..77c86103a4 100644
--- a/frontend/src/container/Home/Services/ServiceTraces.tsx
+++ b/frontend/src/container/Home/Services/ServiceTraces.tsx
@@ -1,13 +1,13 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux'; // old code, TODO: fix this correctly
-import { Link } from 'react-router-dom';
import { Button, Select, Skeleton, Table } from 'antd';
import logEvent from 'api/common/logEvent';
import ROUTES from 'constants/routes';
import { useQueryService } from 'hooks/useQueryService';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
-import history from 'lib/history';
+import { AppLink } from 'lib/router/AppLink';
+import { navigate } from 'lib/router/navigation';
import { ArrowRight, ArrowUpRight } from '@signozhq/icons';
import Card from 'periscope/components/Card/Card';
import { useAppContext } from 'providers/App/App';
@@ -134,7 +134,7 @@ export default function ServiceTraces({
activeLicense &&
activeLicense.platform === LicensePlatform.CLOUD
) {
- history.push(ROUTES.GET_STARTED_WITH_CLOUD);
+ navigate(ROUTES.GET_STARTED_WITH_CLOUD);
} else {
openInNewTab(DOCS_LINKS.ADD_DATA_SOURCE);
}
@@ -238,7 +238,7 @@ export default function ServiceTraces({
{servicesExist && (
<Card.Footer>
<div className="services-footer home-data-card-footer">
- <Link to="/services">
+ <AppLink to="/services">
<Button
type="link"
className="periscope-btn link learn-more-link"
@@ -248,7 +248,7 @@ export default function ServiceTraces({
>
All Services <ArrowRight size={12} />
</Button>
- </Link>
+ </AppLink>
</div>
</Card.Footer>
)}
diff --git a/frontend/src/container/InfraMonitoringHostsV2/StatusFilter.test.tsx b/frontend/src/container/InfraMonitoringHostsV2/StatusFilter.test.tsx
index d9f1ea98ae..44e2f721a6 100644
--- a/frontend/src/container/InfraMonitoringHostsV2/StatusFilter.test.tsx
+++ b/frontend/src/container/InfraMonitoringHostsV2/StatusFilter.test.tsx
@@ -1,7 +1,6 @@
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import {
NuqsTestingAdapter,
@@ -11,6 +10,7 @@ import {
import { AppContext } from 'providers/App/App';
import TimezoneProvider from 'providers/Timezone';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { getAppContextMock } from 'tests/test-utils';
import StatusFilter from './StatusFilter';
@@ -30,7 +30,7 @@ function renderStatusFilter({
onUrlUpdate?: OnUrlUpdateFunction;
}): ReturnType<typeof render> {
return render(
- <MemoryRouter>
+ <TestRouter>
<TimezoneProvider>
<QueryClientProvider client={queryClient}>
<Provider store={store}>
@@ -45,7 +45,7 @@ function renderStatusFilter({
</Provider>
</QueryClientProvider>
</TimezoneProvider>
- </MemoryRouter>,
+ </TestRouter>,
);
}
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sExpandedRow.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sExpandedRow.tsx
index 290d44be9b..42ed824c43 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sExpandedRow.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sExpandedRow.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo } from 'react';
import { useQuery, useQueryClient } from 'react-query';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Querybuildertypesv5QueryWarnDataDTO } from 'api/generated/services/sigNoz.schemas';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
@@ -96,7 +96,7 @@ export function K8sExpandedRow<
const [, setSelectedItemParams] = useInfraMonitoringSelectedItemParams();
const [, setMainOrderBy] = useInfraMonitoringOrderBy();
const { safeNavigate } = useSafeNavigate();
- const location = useLocation();
+ const location = useAppLocation();
const queryClient = useQueryClient();
const orderByParamKey = useMemo(
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sHeader.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sHeader.tsx
index 23a4a2095a..d0faa70eec 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sHeader.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sHeader.tsx
@@ -1,5 +1,5 @@
import React, { useCallback, useMemo, useRef } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import logEvent from 'api/common/logEvent';
import QuerySearch from 'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch';
import { InfraMonitoringEvents } from 'constants/events';
@@ -44,7 +44,7 @@ function K8sHeader({
const { currentQuery } = useQueryBuilder();
const { safeNavigate } = useSafeNavigate();
- const location = useLocation();
+ const location = useAppLocation();
const invalidateQueries = useGlobalTimeQueryInvalidate();
const queryData = useMemo(
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/__tests__/K8sBaseList.test.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/__tests__/K8sBaseList.test.tsx
index 6547355f08..11dd9db11a 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/__tests__/K8sBaseList.test.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/__tests__/K8sBaseList.test.tsx
@@ -2,8 +2,6 @@ import React from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { MemoryRouter as MemoryRouterV5 } from 'react-router-dom-v5-compat';
import { VirtuosoMockContext } from 'react-virtuoso';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -18,6 +16,7 @@ import {
import { AppProvider } from 'providers/App/App';
import TimezoneProvider from 'providers/Timezone';
import store from 'store';
+import { TestRouter } from 'tests/router';
import APIError from 'types/api/error';
import { openInNewTab } from 'utils/navigation';
@@ -190,31 +189,26 @@ function renderComponent<
});
return render(
- <MemoryRouter>
- <MemoryRouterV5>
- <TimezoneProvider>
- <QueryClientProvider client={queryClient}>
- <AppProvider>
- <Provider store={store}>
- <NuqsTestingAdapter
- searchParams={queryParams}
- onUrlUpdate={onUrlUpdate}
+ <TestRouter>
+ <TimezoneProvider>
+ <QueryClientProvider client={queryClient}>
+ <AppProvider>
+ <Provider store={store}>
+ <NuqsTestingAdapter searchParams={queryParams} onUrlUpdate={onUrlUpdate}>
+ <VirtuosoMockContext.Provider
+ value={{ viewportHeight: 800, itemHeight: 50 }}
>
- <VirtuosoMockContext.Provider
- value={{ viewportHeight: 800, itemHeight: 50 }}
- >
- <K8sBaseList<T, TItemKey>
- {...props}
- detailsQueryKeyPrefix={detailsQueryKeyPrefix}
- />
- </VirtuosoMockContext.Provider>
- </NuqsTestingAdapter>
- </Provider>
- </AppProvider>
- </QueryClientProvider>
- </TimezoneProvider>
- </MemoryRouterV5>
- </MemoryRouter>,
+ <K8sBaseList<T, TItemKey>
+ {...props}
+ detailsQueryKeyPrefix={detailsQueryKeyPrefix}
+ />
+ </VirtuosoMockContext.Provider>
+ </NuqsTestingAdapter>
+ </Provider>
+ </AppProvider>
+ </QueryClientProvider>
+ </TimezoneProvider>
+ </TestRouter>,
);
}
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/components/EntityCountsSection/EntityCountsSection.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/components/EntityCountsSection/EntityCountsSection.tsx
index 1bf8a5a358..a47fff7463 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/components/EntityCountsSection/EntityCountsSection.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/components/EntityCountsSection/EntityCountsSection.tsx
@@ -3,7 +3,7 @@ import { Tooltip } from '@signozhq/ui/tooltip';
import { Typography } from '@signozhq/ui/typography';
import { Compass } from '@signozhq/icons';
import { TextNoData } from '../../../components/TextNoData';
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import { InfraMonitoringEntity } from '../../../constants';
import { getDrawerDurationMs } from '../../useDrawerLifecycleStore';
@@ -75,7 +75,7 @@ export function EntityCountsSection<T>({
) : (
<TextNoData type="typography" className={styles.countValue} />
)}
- <Link
+ <AppLink
to={buildK8sListNavigationUrl(config.targetCategory, filterExpression)}
onClick={(): void => handleCardNavigate(config.label)}
data-testid={`navigate-${config.label.toLowerCase().replace(/\s+/g, '-')}`}
@@ -95,7 +95,7 @@ export function EntityCountsSection<T>({
<Compass size={14} />
</Button>
</Tooltip>
- </Link>
+ </AppLink>
</div>
))}
</div>
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityError/EntityError.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityError/EntityError.tsx
index 46d9e6e848..09eabfae4c 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityError/EntityError.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityError/EntityError.tsx
@@ -1,6 +1,6 @@
import { Typography } from '@signozhq/ui/typography';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { ArrowRight } from '@signozhq/icons';
import { openInNewTab } from 'utils/navigation';
@@ -13,7 +13,7 @@ export default function EntityError(): JSX.Element {
const handleContactSupport = (): void => {
if (isCloudUserVal) {
- history.push('/support');
+ navigate('/support');
} else {
openInNewTab('https://signoz.io/slack');
}
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/ChartHeader.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/ChartHeader.tsx
index fe44083d6b..0c777de19a 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/ChartHeader.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/ChartHeader.tsx
@@ -1,4 +1,4 @@
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import { Compass, Info } from '@signozhq/icons';
import { Tooltip } from '@signozhq/ui/tooltip';
@@ -69,14 +69,14 @@ function ChartHeader({
{renderInfoIcon()}
{metricsExplorerUrl && (
<Tooltip title="Go to Metrics Explorer">
- <Link
+ <AppLink
to={metricsExplorerUrl}
className={styles.metricsExplorerLink}
data-testid={metricsExplorerTestId}
onClick={onExploreClick}
>
<Compass size={14} />
- </Link>
+ </AppLink>
</Tooltip>
)}
</div>
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/__tests__/EntityMetrics.test.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/__tests__/EntityMetrics.test.tsx
index d700891787..1b926f0ba5 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/__tests__/EntityMetrics.test.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/__tests__/EntityMetrics.test.tsx
@@ -1,7 +1,7 @@
import { render, screen } from '@testing-library/react';
-import { MemoryRouter } from 'react-router-dom';
import { InfraMonitoringEntity } from 'container/InfraMonitoringK8sV2/constants';
import * as appContextHooks from 'providers/App/App';
+import { TestRouter } from 'tests/router';
import { LicenseEvent } from 'types/api/licensesV3/getActive';
import uPlot from 'uplot';
@@ -290,7 +290,7 @@ const renderEntityMetrics = (overrides = {}): any => {
};
return render(
- <MemoryRouter>
+ <TestRouter>
<EntityMetrics
entity={defaultProps.entity}
eventEntity="test"
@@ -299,7 +299,7 @@ const renderEntityMetrics = (overrides = {}): any => {
queryKey={defaultProps.queryKey}
category={defaultProps.category}
/>
- </MemoryRouter>,
+ </TestRouter>,
);
};
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityOverview/__tests__/EntityOverview.test.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityOverview/__tests__/EntityOverview.test.tsx
index 07d05b5270..e78d77a6f7 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityOverview/__tests__/EntityOverview.test.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityOverview/__tests__/EntityOverview.test.tsx
@@ -1,11 +1,11 @@
import { QueryClient, QueryClientProvider } from 'react-query';
-import { MemoryRouter } from 'react-router-dom';
import { VirtuosoMockContext } from 'react-virtuoso';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { NuqsTestingAdapter, OnUrlUpdateFunction } from 'nuqs/adapters/testing';
import { TableColumnDef } from 'components/TanStackTableView';
+import { TestRouter } from 'tests/router';
import { InfraMonitoringEntity } from '../../../constants';
import EntityOverview from '../EntityOverview';
@@ -80,7 +80,7 @@ function overviewTree(
onUrlUpdate?: OnUrlUpdateFunction,
): JSX.Element {
return (
- <MemoryRouter>
+ <TestRouter>
<QueryClientProvider client={queryClient}>
<NuqsTestingAdapter onUrlUpdate={onUrlUpdate}>
<VirtuosoMockContext.Provider
@@ -97,7 +97,7 @@ function overviewTree(
</VirtuosoMockContext.Provider>
</NuqsTestingAdapter>
</QueryClientProvider>
- </MemoryRouter>
+ </TestRouter>
);
}
diff --git a/frontend/src/container/InfraMonitoringK8sV2/__tests__/InfraMonitoringK8s.test.tsx b/frontend/src/container/InfraMonitoringK8sV2/__tests__/InfraMonitoringK8s.test.tsx
index f78fa2a0b7..f59b629983 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/__tests__/InfraMonitoringK8s.test.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/__tests__/InfraMonitoringK8s.test.tsx
@@ -2,14 +2,13 @@ import React from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { MemoryRouter as MemoryRouterV5 } from 'react-router-dom-v5-compat';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { NuqsTestingAdapter, UrlUpdateEvent } from 'nuqs/adapters/testing';
import { AppProvider } from 'providers/App/App';
import { QueryBuilderProvider } from 'providers/QueryBuilder';
import TimezoneProvider from 'providers/Timezone';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { K8sCategories } from '../constants';
import InfraMonitoringK8s from '../InfraMonitoringK8s';
@@ -42,26 +41,21 @@ function renderPage(
});
render(
- <MemoryRouter>
- <MemoryRouterV5>
- <TimezoneProvider>
- <QueryClientProvider client={queryClient}>
- <AppProvider>
- <Provider store={store}>
- <NuqsTestingAdapter
- searchParams={queryParams}
- onUrlUpdate={onUrlUpdate}
- >
- <QueryBuilderProvider>
- <InfraMonitoringK8s />
- </QueryBuilderProvider>
- </NuqsTestingAdapter>
- </Provider>
- </AppProvider>
- </QueryClientProvider>
- </TimezoneProvider>
- </MemoryRouterV5>
- </MemoryRouter>,
+ <TestRouter initialRoute="/">
+ <TimezoneProvider>
+ <QueryClientProvider client={queryClient}>
+ <AppProvider>
+ <Provider store={store}>
+ <NuqsTestingAdapter searchParams={queryParams} onUrlUpdate={onUrlUpdate}>
+ <QueryBuilderProvider>
+ <InfraMonitoringK8s />
+ </QueryBuilderProvider>
+ </NuqsTestingAdapter>
+ </Provider>
+ </AppProvider>
+ </QueryClientProvider>
+ </TimezoneProvider>
+ </TestRouter>,
);
}
diff --git a/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx b/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx
index 257e81de81..90484a5d10 100644
--- a/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx
+++ b/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx
@@ -1,6 +1,6 @@
import { ChangeEvent, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useHistory } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
import { useCopyToClipboard } from 'react-use';
import { Color } from '@signozhq/design-tokens';
import { Badge } from '@signozhq/ui/badge';
@@ -209,8 +209,6 @@ function MultiIngestionSettings(): JSX.Element {
const [totalIngestionKeys, setTotalIngestionKeys] = useState(0);
- const history = useHistory();
-
const [
hasCreateLimitForIngestionKeyError,
setHasCreateLimitForIngestionKeyError,
@@ -922,7 +920,7 @@ function MultiIngestionSettings(): JSX.Element {
AlertThresholdMatchType.IN_TOTAL
}&${QueryParams.evaluationWindowPreset}=${EvaluationWindowPreset.METER}`;
- history.push(URL);
+ navigate(URL);
};
const columns: AntDTableProps<GatewaytypesIngestionKeyDTO>['columns'] = [
diff --git a/frontend/src/container/IngestionSettings/__tests__/MultiIngestionSettings.test.tsx b/frontend/src/container/IngestionSettings/__tests__/MultiIngestionSettings.test.tsx
index 2ed2347639..c4749e0337 100644
--- a/frontend/src/container/IngestionSettings/__tests__/MultiIngestionSettings.test.tsx
+++ b/frontend/src/container/IngestionSettings/__tests__/MultiIngestionSettings.test.tsx
@@ -17,13 +17,13 @@ interface TestGatewayIngestionKeysResponse {
data: GatewaytypesGettableIngestionKeysDTO;
}
-// Mock useHistory.push to capture navigation URL used by MultiIngestionSettings
-const mockPush = jest.fn() as jest.MockedFunction<(path: string) => void>;
-jest.mock('react-router-dom', () => {
- const actual = jest.requireActual('react-router-dom');
+// Mock navigate to capture navigation URL used by MultiIngestionSettings
+const mockNavigate = jest.fn() as jest.MockedFunction<(path: string) => void>;
+jest.mock('lib/router/navigation', () => {
+ const actual = jest.requireActual('lib/router/navigation');
return {
...actual,
- useHistory: (): { push: typeof mockPush } => ({ push: mockPush }),
+ navigate: (path: string): void => mockNavigate(path),
};
});
@@ -44,7 +44,7 @@ const GLOBAL_CONFIG_RESPONSE = {
describe('MultiIngestionSettings Page', () => {
beforeEach(() => {
- mockPush.mockClear();
+ mockNavigate.mockClear();
});
afterEach(() => {
@@ -120,10 +120,10 @@ describe('MultiIngestionSettings Page', () => {
);
await waitFor(() => {
- expect(mockPush).toHaveBeenCalledTimes(1);
+ expect(mockNavigate).toHaveBeenCalledTimes(1);
});
- const navigationCall = mockPush.mock.calls[0][0] as string;
+ const navigationCall = mockNavigate.mock.calls[0][0] as string;
expect(navigationCall).toContain('/alerts/new');
const urlParams = new URLSearchParams(navigationCall.split('?')[1]);
@@ -201,10 +201,10 @@ describe('MultiIngestionSettings Page', () => {
);
await waitFor(() => {
- expect(mockPush).toHaveBeenCalledTimes(1);
+ expect(mockNavigate).toHaveBeenCalledTimes(1);
});
- const navigationCall = mockPush.mock.calls[0][0] as string;
+ const navigationCall = mockNavigate.mock.calls[0][0] as string;
expect(navigationCall).toContain('/alerts/new');
const urlParams = new URLSearchParams(navigationCall.split('?')[1]);
diff --git a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AccountActions/AccountActions.tsx b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AccountActions/AccountActions.tsx
index 43a14bb594..05e9e36ac9 100644
--- a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AccountActions/AccountActions.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AccountActions/AccountActions.tsx
@@ -1,5 +1,5 @@
import { Dispatch, SetStateAction, useEffect, useMemo, useState } from 'react';
-import { useNavigate } from 'react-router-dom-v5-compat';
+import { useAppNavigate } from 'lib/router/useAppNavigate';
import { Color } from '@signozhq/design-tokens';
import { Button } from '@signozhq/ui/button';
import { Select, Skeleton } from 'antd';
@@ -120,7 +120,7 @@ function AccountActionsRenderer({
function AccountActions({ type }: { type: IntegrationType }): JSX.Element {
const urlQuery = useUrlQuery();
- const navigate = useNavigate();
+ const navigate = useAppNavigate();
const { data: listAccountsResponse, isLoading } = useListAccounts({
cloudProvider: type,
diff --git a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/EditAccount/AccountSettingsModal.tsx b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/EditAccount/AccountSettingsModal.tsx
index b8dc618a1e..16bc8b7e7f 100644
--- a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/EditAccount/AccountSettingsModal.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/EditAccount/AccountSettingsModal.tsx
@@ -7,7 +7,7 @@ import { invalidateListAccounts } from 'api/generated/services/cloudintegration'
import { INTEGRATION_TYPES } from 'container/Integrations/constants';
import { useAccountSettingsModal } from 'hooks/integration/aws/useAccountSettingsModal';
import useUrlQuery from 'hooks/useUrlQuery';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { Save } from '@signozhq/icons';
import logEvent from '../../../../../api/common/logEvent';
@@ -50,7 +50,7 @@ function AccountSettingsModal({
urlQuery.delete('cloudAccountId');
setActiveAccount(null);
handleClose();
- history.replace({ search: urlQuery.toString() });
+ navigate({ search: urlQuery.toString() }, { replace: true });
logEvent('AWS Integration: Account removed', {
id: account?.id,
diff --git a/frontend/src/container/Integrations/CloudIntegration/Header/Header.tsx b/frontend/src/container/Integrations/CloudIntegration/Header/Header.tsx
index 0483ea31eb..5822e82a76 100644
--- a/frontend/src/container/Integrations/CloudIntegration/Header/Header.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/Header/Header.tsx
@@ -1,4 +1,4 @@
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import { Button } from '@signozhq/ui/button';
import Breadcrumb from 'antd/es/breadcrumb';
import ROUTES from 'constants/routes';
@@ -16,12 +16,12 @@ function Header({ type }: { type: IntegrationType }): JSX.Element {
items={[
{
title: (
- <Link to={ROUTES.INTEGRATIONS}>
+ <AppLink to={ROUTES.INTEGRATIONS}>
<span className="cloud-header__breadcrumb-link">
<Blocks size={16} color="var(--l2-foreground)" />
<span className="cloud-header__breadcrumb-title">Integrations</span>
</span>
- </Link>
+ </AppLink>
),
},
{
diff --git a/frontend/src/container/Integrations/CloudIntegration/ServicesList.tsx b/frontend/src/container/Integrations/CloudIntegration/ServicesList.tsx
index 5f4b9b60a7..5173837918 100644
--- a/frontend/src/container/Integrations/CloudIntegration/ServicesList.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/ServicesList.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo } from 'react';
-import { useNavigate } from 'react-router-dom-v5-compat';
+import { useAppNavigate } from 'lib/router/useAppNavigate';
import { Skeleton } from 'antd';
import {
useListAccounts,
@@ -23,7 +23,7 @@ function ServicesList({
type,
}: ServicesListProps): JSX.Element {
const urlQuery = useUrlQuery();
- const navigate = useNavigate();
+ const navigate = useAppNavigate();
const isAccountConnected = Boolean(cloudAccountId);
const { data: listAccountsResponse, isLoading: isAccountsLoading } =
useListAccounts({ cloudProvider: type });
diff --git a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailPage.tsx b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailPage.tsx
index 3825dca41c..349a684539 100644
--- a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailPage.tsx
+++ b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailPage.tsx
@@ -1,5 +1,6 @@
import { useState } from 'react';
-import { useHistory, useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
+import { navigate } from 'lib/router/navigation';
import { Button } from '@signozhq/ui/button';
import { Flex, Skeleton } from 'antd';
import { Typography } from '@signozhq/ui/typography';
@@ -32,8 +33,7 @@ const cloudIntegrationTypeById: Record<string, IntegrationType> = {
// eslint-disable-next-line sonarjs/cognitive-complexity
function IntegrationDetailPage(): JSX.Element {
- const history = useHistory();
- const { integrationId } = useParams<{ integrationId?: string }>();
+ const { integrationId } = useAppParams<{ integrationId?: string }>();
const [activeDetailTab, setActiveDetailTab] = useState<string | null>(
'overview',
);
@@ -74,7 +74,7 @@ function IntegrationDetailPage(): JSX.Element {
color="secondary"
prefix={<ArrowLeft size={14} />}
onClick={(): void => {
- history.push(ROUTES.INTEGRATIONS);
+ navigate(ROUTES.INTEGRATIONS);
}}
>
All Integrations
diff --git a/frontend/src/container/Integrations/Integrations.tsx b/frontend/src/container/Integrations/Integrations.tsx
index 947d96f5d4..50b4db5ae3 100644
--- a/frontend/src/container/Integrations/Integrations.tsx
+++ b/frontend/src/container/Integrations/Integrations.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useState } from 'react';
-import { useHistory } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
import logEvent from 'api/common/logEvent';
import ROUTES from 'constants/routes';
import { IntegrationsProps } from 'types/api/integrations/types';
@@ -12,7 +12,6 @@ import OneClickIntegrations from './OneClickIntegrations/OneClickIntegrations';
import './Integrations.styles.scss';
function Integrations(): JSX.Element {
- const history = useHistory();
const [searchQuery, setSearchQuery] = useState('');
const setSelectedIntegration = useCallback(
@@ -21,12 +20,12 @@ function Integrations(): JSX.Element {
logEvent(INTEGRATION_TELEMETRY_EVENTS.INTEGRATIONS_ITEM_LIST_CLICKED, {
integration,
});
- history.push(`${ROUTES.INTEGRATIONS}/${integration.id}`);
+ navigate(`${ROUTES.INTEGRATIONS}/${integration.id}`);
} else {
- history.push(ROUTES.INTEGRATIONS);
+ navigate(ROUTES.INTEGRATIONS);
}
},
- [history],
+ [],
);
useEffect(() => {
diff --git a/frontend/src/container/Integrations/IntegrationsHeader/IntegrationsHeader.tsx b/frontend/src/container/Integrations/IntegrationsHeader/IntegrationsHeader.tsx
index 7c4c955a7c..b825ea9388 100644
--- a/frontend/src/container/Integrations/IntegrationsHeader/IntegrationsHeader.tsx
+++ b/frontend/src/container/Integrations/IntegrationsHeader/IntegrationsHeader.tsx
@@ -1,5 +1,5 @@
import { ChangeEvent, KeyboardEvent, useState } from 'react';
-import { useHistory } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
import { Button } from '@signozhq/ui/button';
import { DialogWrapper } from '@signozhq/ui/dialog';
import { Input } from '@signozhq/ui/input';
@@ -20,7 +20,6 @@ interface IntegrationsHeaderProps {
}
function IntegrationsHeader(props: IntegrationsHeaderProps): JSX.Element {
- const history = useHistory();
const { user } = useAppContext();
const { searchQuery, onSearchChange } = props;
@@ -151,7 +150,7 @@ function IntegrationsHeader(props: IntegrationsHeaderProps): JSX.Element {
size="md"
variant="solid"
color="primary"
- onClick={(): void => history.push(ROUTES.GET_STARTED_WITH_CLOUD)}
+ onClick={(): void => navigate(ROUTES.GET_STARTED_WITH_CLOUD)}
suffix={<ArrowRight size={14} />}
width="200px"
>
diff --git a/frontend/src/container/Integrations/utils.ts b/frontend/src/container/Integrations/utils.ts
index 81c70b6091..08fa3277e5 100644
--- a/frontend/src/container/Integrations/utils.ts
+++ b/frontend/src/container/Integrations/utils.ts
@@ -1,8 +1,8 @@
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
export const handleContactSupport = (isCloudUser: boolean): void => {
if (isCloudUser) {
- history.push('/support');
+ navigate('/support');
} else {
window.open('https://signoz.io/slack', '_blank');
}
diff --git a/frontend/src/container/LLMObservability/Explorer/Explorer.tsx b/frontend/src/container/LLMObservability/Explorer/Explorer.tsx
index c5450304c7..569d391556 100644
--- a/frontend/src/container/LLMObservability/Explorer/Explorer.tsx
+++ b/frontend/src/container/LLMObservability/Explorer/Explorer.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useQueryClient } from 'react-query';
-import { useSearchParams } from 'react-router-dom-v5-compat';
+import { useAppSearchParams } from 'lib/router/useAppSearchParams';
import * as Sentry from '@sentry/react';
import logEvent from 'api/common/logEvent';
import QueryCancelledPlaceholder from 'components/QueryCancelledPlaceholder';
@@ -60,7 +60,7 @@ function Explorer(): JSX.Element {
const isAIAssistantEnabled = useIsAIAssistantEnabled();
- const [searchParams] = useSearchParams();
+ const [searchParams] = useAppSearchParams();
const queryClient = useQueryClient();
const listQueryKeyRef = useRef<any>();
diff --git a/frontend/src/container/LLMObservability/Explorer/ListView/utils.tsx b/frontend/src/container/LLMObservability/Explorer/ListView/utils.tsx
index 2fda3740d7..65950bfd77 100644
--- a/frontend/src/container/LLMObservability/Explorer/ListView/utils.tsx
+++ b/frontend/src/container/LLMObservability/Explorer/ListView/utils.tsx
@@ -1,6 +1,6 @@
import type { TracesTableRow } from '../TracesTable/getFieldColumn';
-import { generatePath } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { TraceDetailsTab } from 'pages/TraceDetailsV3/constants';
import { formUrlParams } from 'utils/traceUtils';
import { QueryDataV3 } from 'types/api/widgets/getQuery';
@@ -20,12 +20,14 @@ export const getTraceLink = (record: Record<string, unknown>): string => {
return '';
}
- return `${generatePath(ROUTES.TRACE_DETAIL, { id: traceId })}${formUrlParams({
- tab: TraceDetailsTab.Thread,
- spanId,
- levelUp: 0,
- levelDown: 0,
- })}`;
+ return `${buildRoutePath(ROUTES.TRACE_DETAIL, { id: traceId })}${formUrlParams(
+ {
+ tab: TraceDetailsTab.Thread,
+ spanId,
+ levelUp: 0,
+ levelDown: 0,
+ },
+ )}`;
};
// Reshapes the query-range list payload into table rows. `id` mirrors span_id so
diff --git a/frontend/src/container/LLMObservability/Explorer/TracesTable/FieldCell.tsx b/frontend/src/container/LLMObservability/Explorer/TracesTable/FieldCell.tsx
index 517e98c7e8..6963c2bff3 100644
--- a/frontend/src/container/LLMObservability/Explorer/TracesTable/FieldCell.tsx
+++ b/frontend/src/container/LLMObservability/Explorer/TracesTable/FieldCell.tsx
@@ -1,8 +1,9 @@
-import { generatePath, Link } from 'react-router-dom';
import { Badge } from '@signozhq/ui/badge';
import TanStackTable from 'components/TanStackTableView';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import ROUTES from 'constants/routes';
+import { AppLink } from 'lib/router/AppLink';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { TraceDetailsTab } from 'pages/TraceDetailsV3/constants';
import { getMs } from 'utils/timeUtils';
import { useTimezone } from 'providers/Timezone';
@@ -44,16 +45,16 @@ function FieldCell({ name, value }: FieldCellProps): JSX.Element {
if (TRACE_ID_FIELD_NAMES.has(name)) {
return (
- <Link
+ <AppLink
to={{
- pathname: generatePath(ROUTES.TRACE_DETAIL, { id: text }),
+ pathname: buildRoutePath(ROUTES.TRACE_DETAIL, { id: text }),
search: `?tab=${TraceDetailsTab.Thread}`,
}}
data-testid="trace-id"
onClick={(e): void => e.stopPropagation()}
>
{text}
- </Link>
+ </AppLink>
);
}
diff --git a/frontend/src/container/LLMObservability/Explorer/TracesTable/TracesTable.tsx b/frontend/src/container/LLMObservability/Explorer/TracesTable/TracesTable.tsx
index a994fe312c..ae67fd3f88 100644
--- a/frontend/src/container/LLMObservability/Explorer/TracesTable/TracesTable.tsx
+++ b/frontend/src/container/LLMObservability/Explorer/TracesTable/TracesTable.tsx
@@ -1,5 +1,5 @@
import { useCallback } from 'react';
-import { useHistory } from 'react-router-dom';
+import { useAppNavigate } from 'lib/router/useAppNavigate';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import TanStackTable from 'components/TanStackTableView';
import type {
@@ -50,7 +50,7 @@ function TracesTable({
onColumnRemove,
cellTypographySize = 'medium',
}: TracesTableProps): JSX.Element {
- const history = useHistory();
+ const navigate = useAppNavigate();
const isDataAbsent =
!isLoading && !isFetching && !isError && data.length === 0;
@@ -60,9 +60,9 @@ function TracesTable({
const handleRowClick = useCallback(
(row: TracesTableRow): void => {
- history.push(getRowHref(row));
+ navigate(getRowHref(row));
},
- [history, getRowHref],
+ [navigate, getRowHref],
);
const handleRowClickNewTab = useCallback(
diff --git a/frontend/src/container/ListAlertRules/__tests__/_helpers.tsx b/frontend/src/container/ListAlertRules/__tests__/_helpers.tsx
index 905cb78823..7121a26815 100644
--- a/frontend/src/container/ListAlertRules/__tests__/_helpers.tsx
+++ b/frontend/src/container/ListAlertRules/__tests__/_helpers.tsx
@@ -1,5 +1,4 @@
import { QueryClient, QueryClientProvider } from 'react-query';
-import { MemoryRouter } from 'react-router-dom';
import { VirtuosoMockContext } from 'react-virtuoso';
import { render, RenderResult, screen } from '@testing-library/react';
import ListAlertRules from 'container/ListAlertRules';
@@ -7,6 +6,7 @@ import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { AppContext } from 'providers/App/App';
import TimezoneProvider from 'providers/Timezone';
import { onNuqsUrlUpdate, resetNuqsState } from 'tests/nuqs-helpers';
+import { TestRouter } from 'tests/router';
import { getAppContextMock } from 'tests/test-utils';
interface RenderOptions {
@@ -32,7 +32,7 @@ export function renderListAlertRules(
});
return render(
- <MemoryRouter initialEntries={[initialRoute]}>
+ <TestRouter initialRoute={initialRoute}>
<NuqsTestingAdapter
searchParams={initialSearch}
onUrlUpdate={onNuqsUrlUpdate}
@@ -51,7 +51,7 @@ export function renderListAlertRules(
</AppContext.Provider>
</QueryClientProvider>
</NuqsTestingAdapter>
- </MemoryRouter>,
+ </TestRouter>,
);
}
diff --git a/frontend/src/container/LiveLogs/LiveLogsContainer/index.tsx b/frontend/src/container/LiveLogs/LiveLogsContainer/index.tsx
index 8202f7af61..c01e92e20b 100644
--- a/frontend/src/container/LiveLogs/LiveLogsContainer/index.tsx
+++ b/frontend/src/container/LiveLogs/LiveLogsContainer/index.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Switch } from '@signozhq/ui/switch';
import { Typography } from '@signozhq/ui/typography';
import FieldsSelector from 'components/FieldsSelector';
@@ -32,7 +32,7 @@ interface LiveLogsContainerProps {
function LiveLogsContainer({
handleChangeSelectedView,
}: LiveLogsContainerProps): JSX.Element {
- const location = useLocation();
+ const location = useAppLocation();
const [logs, setLogs] = useState<ILiveLogsLog[]>([]);
const { currentQuery, stagedQuery } = useQueryBuilder();
const [showLiveLogsFrequencyChart, setShowLiveLogsFrequencyChart] =
diff --git a/frontend/src/container/LogDetailedView/ContextView/__tests__/ContextLogRenderer.test.tsx b/frontend/src/container/LogDetailedView/ContextView/__tests__/ContextLogRenderer.test.tsx
index 8507eec491..7908b6ddab 100644
--- a/frontend/src/container/LogDetailedView/ContextView/__tests__/ContextLogRenderer.test.tsx
+++ b/frontend/src/container/LogDetailedView/ContextView/__tests__/ContextLogRenderer.test.tsx
@@ -1,6 +1,5 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { VirtuosoMockContext } from 'react-virtuoso';
import {
act,
@@ -19,6 +18,7 @@ import { QueryBuilderContext } from 'providers/QueryBuilder';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
import TimezoneProvider from 'providers/Timezone';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { QueryRangePayload } from 'types/api/metrics/getQueryRange';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
@@ -70,7 +70,7 @@ const renderContextLogRenderer = (): RenderResult => {
};
return render(
- <MemoryRouter>
+ <TestRouter>
<TimezoneProvider>
<Provider store={store}>
<ErrorModalProvider>
@@ -98,7 +98,7 @@ const renderContextLogRenderer = (): RenderResult => {
</ErrorModalProvider>
</Provider>
</TimezoneProvider>
- </MemoryRouter>,
+ </TestRouter>,
);
};
diff --git a/frontend/src/container/Login/__tests__/Login.test.tsx b/frontend/src/container/Login/__tests__/Login.test.tsx
index 2c71aecdad..039bd81ad4 100644
--- a/frontend/src/container/Login/__tests__/Login.test.tsx
+++ b/frontend/src/container/Login/__tests__/Login.test.tsx
@@ -1,5 +1,5 @@
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { ErrorV2 } from 'types/api';
@@ -16,19 +16,12 @@ const CALLBACK_AUTHN_URL = 'https://sso.example.com/auth';
const PASSWORD_AUTHN_ORG = 'password_authn_org';
const PASSWORD_AUTHN_EMAIL = '[email protected]';
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: jest.fn(),
- location: {
- search: '',
- },
- },
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: jest.fn(),
}));
-const mockHistoryPush = history.push as jest.MockedFunction<
- typeof history.push
->;
+const mockNavigate = navigate as jest.MockedFunction<typeof navigate>;
// Mock data
const mockVersionSetupCompleted: Info = {
@@ -182,7 +175,7 @@ describe('Login Component', () => {
render(<Login />);
await waitFor(() => {
- expect(mockHistoryPush).toHaveBeenCalledWith(ROUTES.SIGN_UP);
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.SIGN_UP);
});
});
@@ -190,7 +183,7 @@ describe('Login Component', () => {
render(<Login />);
await waitFor(() => {
- expect(mockHistoryPush).not.toHaveBeenCalled();
+ expect(mockNavigate).not.toHaveBeenCalled();
});
});
@@ -204,7 +197,7 @@ describe('Login Component', () => {
render(<Login />);
await waitFor(() => {
- expect(mockHistoryPush).not.toHaveBeenCalled();
+ expect(mockNavigate).not.toHaveBeenCalled();
});
});
});
@@ -476,6 +469,19 @@ describe('Login Component', () => {
});
describe('Callback Authentication', () => {
+ const originalLocation = window.location;
+
+ // The redirect case swaps `window.location` for a stub. history@5 reads
+ // that object on every `history.location` access, so leaving the stub in
+ // place would freeze the URL for every later test in this file.
+ afterEach(() => {
+ Object.defineProperty(window, 'location', {
+ value: originalLocation,
+ writable: true,
+ configurable: true,
+ });
+ });
+
it('shows callback login button when callback auth is supported', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
@@ -513,13 +519,20 @@ describe('Login Component', () => {
it('redirects to callback URL on button click', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
- // Mock window.location.href
+ // Mock window.location.href. The rest of the shape matters: history@5
+ // re-reads `window.location` on every access, so a stub without a
+ // pathname breaks every later render in this file.
const mockLocation = {
href: 'http://localhost/',
+ origin: 'http://localhost',
+ pathname: '/',
+ search: '',
+ hash: '',
};
Object.defineProperty(window, 'location', {
value: mockLocation,
writable: true,
+ configurable: true,
});
server.use(
diff --git a/frontend/src/container/Login/index.tsx b/frontend/src/container/Login/index.tsx
index 29a42a28ce..87e06f0c9c 100644
--- a/frontend/src/container/Login/index.tsx
+++ b/frontend/src/container/Login/index.tsx
@@ -10,7 +10,7 @@ import afterLogin from 'AppRoutes/utils';
import AuthError from 'components/AuthError/AuthError';
import ROUTES from 'constants/routes';
import useUrlQuery from 'hooks/useUrlQuery';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { ArrowRight } from '@signozhq/icons';
import { ErrorV2 } from 'types/api';
import APIError from 'types/api/error';
@@ -92,7 +92,7 @@ function Login(): JSX.Element {
!versionError &&
!versionData.data.setupCompleted
) {
- history.push(ROUTES.SIGN_UP);
+ navigate(ROUTES.SIGN_UP);
}
}, [versionData, versionLoading, versionError]);
@@ -231,10 +231,12 @@ function Login(): JSX.Element {
return;
}
- history.push(ROUTES.FORGOT_PASSWORD, {
- email,
- orgId: sessionsOrgId,
- orgs: sessionsContext.orgs,
+ navigate(ROUTES.FORGOT_PASSWORD, {
+ state: {
+ email,
+ orgId: sessionsOrgId,
+ orgs: sessionsContext.orgs,
+ },
});
}, [form, sessionsContext, sessionsOrgId]);
diff --git a/frontend/src/container/LogsError/LogsError.tsx b/frontend/src/container/LogsError/LogsError.tsx
index d40043b241..f6c474ebc1 100644
--- a/frontend/src/container/LogsError/LogsError.tsx
+++ b/frontend/src/container/LogsError/LogsError.tsx
@@ -1,6 +1,6 @@
import { Typography } from '@signozhq/ui/typography';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { ArrowRight } from '@signozhq/icons';
import awwSnapUrl from '@/assets/Icons/awwSnap.svg';
@@ -12,7 +12,7 @@ export default function LogsError(): JSX.Element {
const handleContactSupport = (): void => {
if (isCloudUserVal) {
- history.push('/support');
+ navigate('/support');
} else {
window.open('https://signoz.io/slack', '_blank');
}
diff --git a/frontend/src/container/LogsExplorerChart/index.tsx b/frontend/src/container/LogsExplorerChart/index.tsx
index d171fe6c83..b6ce423a7e 100644
--- a/frontend/src/container/LogsExplorerChart/index.tsx
+++ b/frontend/src/container/LogsExplorerChart/index.tsx
@@ -1,7 +1,7 @@
import { memo, useCallback, useMemo, useRef } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import Spinner from 'components/Spinner';
import { QueryParams } from 'constants/query';
import BarChart from 'lib/visualization/charts/BarChart/BarChart';
@@ -34,7 +34,7 @@ function LogsExplorerChart({
}: LogsExplorerChartProps): JSX.Element {
const dispatch = useDispatch();
const urlQuery = useUrlQuery();
- const location = useLocation();
+ const location = useAppLocation();
const { safeNavigate } = useSafeNavigate();
// Access global time state for min/max range
diff --git a/frontend/src/container/LogsExplorerList/__tests__/LogsExplorerList.test.tsx b/frontend/src/container/LogsExplorerList/__tests__/LogsExplorerList.test.tsx
index ded3b3aa55..2160dfc453 100644
--- a/frontend/src/container/LogsExplorerList/__tests__/LogsExplorerList.test.tsx
+++ b/frontend/src/container/LogsExplorerList/__tests__/LogsExplorerList.test.tsx
@@ -8,6 +8,7 @@ import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { PreferenceContextProvider } from 'providers/preferences/context/PreferenceContextProvider';
import { QueryBuilderContext } from 'providers/QueryBuilder';
+import { mockAppLocation } from 'tests/router-mocks';
import { render, screen } from 'tests/test-utils';
const queryRangeURL = 'http://localhost/api/v3/query_range';
@@ -23,12 +24,7 @@ const logsQueryServerRequest = ({
),
);
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${ROUTES.LOGS_EXPLORER}`,
- }),
-}));
+mockAppLocation({ pathname: ROUTES.LOGS_EXPLORER });
jest.mock('providers/preferences/sync/usePreferenceSync', () => ({
usePreferenceSync: (): any => ({
diff --git a/frontend/src/container/LogsExplorerViews/tests/LogsExplorerPagination.test.tsx b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerPagination.test.tsx
index fd18a1a790..47e9c294b6 100644
--- a/frontend/src/container/LogsExplorerViews/tests/LogsExplorerPagination.test.tsx
+++ b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerPagination.test.tsx
@@ -9,6 +9,7 @@ import { logsresponse } from 'mocks-server/__mockdata__/query_range';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import LogsExplorer from 'pages/LogsExplorer';
+import { mockAppLocation } from 'tests/router-mocks';
import {
act,
AllTheProviders,
@@ -62,15 +63,6 @@ jest.mock('store/actions', () => {
};
});
-jest.mock('react-router-dom-v5-compat', () => ({
- ...jest.requireActual('react-router-dom-v5-compat'),
- useSearchParams: jest.fn(() => {
- const searchParams = new URLSearchParams();
-
- return [searchParams, jest.fn()];
- }),
-}));
-
// Mock the Redux store's getState method to return updated global time
const store = jest.requireActual('store').default;
const originalGetState = store.getState;
@@ -93,14 +85,11 @@ getStateSpy.mockImplementation(() => {
return originalState;
});
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { search: string; pathname: string } => ({
- pathname: ROUTES.LOGS_EXPLORER,
- search:
- '?compositeQuery=%257B%2522queryType%2522%253A%2522builder%2522%252C%2522builder%2522%253A%257B%2522queryData%2522%253A%255B%257B%2522dataSource%2522%253A%2522logs%2522%252C%2522queryName%2522%253A%2522A%2522%252C%2522aggregateOperator%2522%253A%2522noop%2522%252C%2522aggregateAttribute%2522%253A%257B%2522id%2522%253A%2522------%2522%252C%2522dataType%2522%253A%2522%2522%252C%2522key%2522%253A%2522%2522%252C%2522isColumn%2522%253Afalse%252C%2522type%2522%253A%2522%2522%252C%2522isJSON%2522%253Afalse%257D%252C%2522timeAggregation%2522%253A%2522rate%2522%252C%2522spaceAggregation%2522%253A%2522sum%2522%252C%2522functions%2522%253A%255B%255D%252C%2522filters%2522%253A%257B%2522items%2522%253A%255B%255D%252C%2522op%2522%253A%2522AND%2522%257D%252C%2522expression%2522%253A%2522A%2522%252C%2522disabled%2522%253Afalse%252C%2522stepInterval%2522%253A60%252C%2522having%2522%253A%255B%255D%252C%2522limit%2522%253Anull%252C%2522orderBy%2522%253A%255B%257B%2522columnName%2522%253A%2522timestamp%2522%252C%2522order%2522%253A%2522desc%2522%257D%255D%252C%2522groupBy%2522%253A%255B%255D%252C%2522legend%2522%253A%2522%2522%252C%2522reduceTo%2522%253A%2522avg%2522%257D%255D%252C%2522queryFormulas%2522%253A%255B%255D%257D%252C%2522promql%2522%253A%255B%257B%2522name%2522%253A%2522A%2522%252C%2522query%2522%253A%2522%2522%252C%2522legend%2522%253A%2522%2522%252C%2522disabled%2522%253Afalse%257D%255D%252C%2522clickhouse_sql%2522%253A%255B%257B%2522name%2522%253A%2522A%2522%252C%2522legend%2522%253A%2522%2522%252C%2522disabled%2522%253Afalse%252C%2522query%2522%253A%2522%2522%257D%255D%252C%2522id%2522%253A%25220d764438-8023-44b9-9bab-2f05012eca7b%2522%257D&options=%7B%22selectColumns%22%3A%5B%7B%22key%22%3A%22timestamp%22%2C%22dataType%22%3A%22string%22%2C%22type%22%3A%22tag%22%2C%22isColumn%22%3Atrue%2C%22isJSON%22%3Afalse%2C%22id%22%3A%22timestamp--string--tag--true%22%2C%22isIndexed%22%3Afalse%7D%2C%7B%22key%22%3A%22body%22%2C%22dataType%22%3A%22string%22%2C%22type%22%3A%22tag%22%2C%22isColumn%22%3Atrue%2C%22isJSON%22%3Afalse%2C%22id%22%3A%22body--string--tag--true%22%2C%22isIndexed%22%3Afalse%7D%5D%2C%22maxLines%22%3A2%2C%22format%22%3A%22raw%22%2C%22fontSize%22%3A%22small%22%2C%22version%22%3A1%7D',
- }),
-}));
+mockAppLocation({
+ pathname: ROUTES.LOGS_EXPLORER,
+ search:
+ '?compositeQuery=%257B%2522queryType%2522%253A%2522builder%2522%252C%2522builder%2522%253A%257B%2522queryData%2522%253A%255B%257B%2522dataSource%2522%253A%2522logs%2522%252C%2522queryName%2522%253A%2522A%2522%252C%2522aggregateOperator%2522%253A%2522noop%2522%252C%2522aggregateAttribute%2522%253A%257B%2522id%2522%253A%2522------%2522%252C%2522dataType%2522%253A%2522%2522%252C%2522key%2522%253A%2522%2522%252C%2522isColumn%2522%253Afalse%252C%2522type%2522%253A%2522%2522%252C%2522isJSON%2522%253Afalse%257D%252C%2522timeAggregation%2522%253A%2522rate%2522%252C%2522spaceAggregation%2522%253A%2522sum%2522%252C%2522functions%2522%253A%255B%255D%252C%2522filters%2522%253A%257B%2522items%2522%253A%255B%255D%252C%2522op%2522%253A%2522AND%2522%257D%252C%2522expression%2522%253A%2522A%2522%252C%2522disabled%2522%253Afalse%252C%2522stepInterval%2522%253A60%252C%2522having%2522%253A%255B%255D%252C%2522limit%2522%253Anull%252C%2522orderBy%2522%253A%255B%257B%2522columnName%2522%253A%2522timestamp%2522%252C%2522order%2522%253A%2522desc%2522%257D%255D%252C%2522groupBy%2522%253A%255B%255D%252C%2522legend%2522%253A%2522%2522%252C%2522reduceTo%2522%253A%2522avg%2522%257D%255D%252C%2522queryFormulas%2522%253A%255B%255D%257D%252C%2522promql%2522%253A%255B%257B%2522name%2522%253A%2522A%2522%252C%2522query%2522%253A%2522%2522%252C%2522legend%2522%253A%2522%2522%252C%2522disabled%2522%253Afalse%257D%255D%252C%2522clickhouse_sql%2522%253A%255B%257B%2522name%2522%253A%2522A%2522%252C%2522legend%2522%253A%2522%2522%252C%2522disabled%2522%253Afalse%252C%2522query%2522%253A%2522%2522%257D%255D%252C%2522id%2522%253A%25220d764438-8023-44b9-9bab-2f05012eca7b%2522%257D&options=%7B%22selectColumns%22%3A%5B%7B%22key%22%3A%22timestamp%22%2C%22dataType%22%3A%22string%22%2C%22type%22%3A%22tag%22%2C%22isColumn%22%3Atrue%2C%22isJSON%22%3Afalse%2C%22id%22%3A%22timestamp--string--tag--true%22%2C%22isIndexed%22%3Afalse%7D%2C%7B%22key%22%3A%22body%22%2C%22dataType%22%3A%22string%22%2C%22type%22%3A%22tag%22%2C%22isColumn%22%3Atrue%2C%22isJSON%22%3Afalse%2C%22id%22%3A%22body--string--tag--true%22%2C%22isIndexed%22%3Afalse%7D%5D%2C%22maxLines%22%3A2%2C%22format%22%3A%22raw%22%2C%22fontSize%22%3A%22small%22%2C%22version%22%3A1%7D',
+});
jest.mock('hooks/useSafeNavigate', () => ({
useSafeNavigate: (): any => ({
@@ -422,10 +411,7 @@ function LogsExplorerWithMockContext({
);
return (
- <AllTheProviders
- queryBuilderOverrides={contextValue as any}
- initialRoute="/logs"
- >
+ <AllTheProviders queryBuilderOverrides={contextValue as any}>
<VirtuosoMockContext.Provider value={virtuosoContextValue}>
<LogsExplorer />
</VirtuosoMockContext.Provider>
@@ -482,6 +468,8 @@ describe('Logs Explorer -> stage and run query', () => {
initialCurrentQuery={mockCurrentQuery}
onStateChange={handleStateChange}
/>,
+ undefined,
+ { initialRoute: '/logs' },
);
await waitFor(() => {
diff --git a/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx
index b96cb75262..22a688588f 100644
--- a/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx
+++ b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx
@@ -8,6 +8,7 @@ import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { PreferenceContextProvider } from 'providers/preferences/context/PreferenceContextProvider';
import { QueryBuilderContext } from 'providers/QueryBuilder';
+import { mockAppLocation } from 'tests/router-mocks';
import { fireEvent, render, RenderResult, waitFor } from 'tests/test-utils';
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
import { LogsAggregatorOperator } from 'types/common/queryBuilder';
@@ -20,12 +21,7 @@ import {
const queryRangeURL = 'http://localhost/api/v3/query_range';
const ACTIVE_LOG_ID = 'test-log-id';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${ROUTES.LOGS_EXPLORER}`,
- }),
-}));
+mockAppLocation({ pathname: ROUTES.LOGS_EXPLORER });
const lodsQueryServerRequest = (): void =>
server.use(
diff --git a/frontend/src/container/MCPServerSettings/MCPServerSettings.test.tsx b/frontend/src/container/MCPServerSettings/MCPServerSettings.test.tsx
index 56ac9cee28..783805be18 100644
--- a/frontend/src/container/MCPServerSettings/MCPServerSettings.test.tsx
+++ b/frontend/src/container/MCPServerSettings/MCPServerSettings.test.tsx
@@ -4,7 +4,7 @@ import { render, screen, userEvent } from 'tests/test-utils';
import MCPServerSettings from './MCPServerSettings';
const mockCopyToClipboard = jest.fn();
-const mockHistoryPush = jest.fn();
+const mockNavigate = jest.fn();
const mockUseGetGlobalConfig = jest.fn();
const mockUseGetHosts = jest.fn();
const mockUseGetTenantLicense = jest.fn();
@@ -37,18 +37,14 @@ jest.mock('@signozhq/ui/sonner', () => ({
},
}));
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: (...args: unknown[]): unknown => mockHistoryPush(...args),
- location: { pathname: '/', search: '', hash: '', state: null },
- },
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: (...args: unknown[]): unknown => mockNavigate(...args),
}));
jest.mock('utils/basePath', () => ({
+ ...jest.requireActual('utils/basePath'),
getBaseUrl: (): string => 'http://localhost',
- getBasePath: (): string => '/',
- withBasePath: (p: string): string => p,
}));
const MCP_URL = 'https://mcp.us.signoz.cloud/mcp';
@@ -182,7 +178,7 @@ describe('MCPServerSettings', () => {
await user.click(screen.getByText('Create service account'));
- expect(mockHistoryPush).toHaveBeenCalledWith(
+ expect(mockNavigate).toHaveBeenCalledWith(
'/settings/service-accounts?create-sa=true',
);
});
diff --git a/frontend/src/container/MCPServerSettings/MCPServerSettings.tsx b/frontend/src/container/MCPServerSettings/MCPServerSettings.tsx
index 2386f7352b..c00f893f78 100644
--- a/frontend/src/container/MCPServerSettings/MCPServerSettings.tsx
+++ b/frontend/src/container/MCPServerSettings/MCPServerSettings.tsx
@@ -5,7 +5,7 @@ import ROUTES from 'constants/routes';
import { SA_QUERY_PARAMS } from 'container/ServiceAccountsSettings/constants';
import { useGetGlobalConfig } from 'api/generated/services/global';
import { useGetHosts } from 'api/generated/services/zeus';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { useAppContext } from 'providers/App/App';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { USER_ROLES } from 'types/roles';
@@ -83,7 +83,7 @@ function MCPServerSettings(): JSX.Element {
const handleCreateServiceAccount = useCallback(() => {
void logEvent(ANALYTICS.CREATE_SA_CLICKED, {});
- history.push(
+ navigate(
`${ROUTES.SERVICE_ACCOUNTS_SETTINGS}?${SA_QUERY_PARAMS.CREATE_SA}=true`,
);
}, []);
diff --git a/frontend/src/container/MembersSettings/MembersSettings.tsx b/frontend/src/container/MembersSettings/MembersSettings.tsx
index baa0159d1c..72b2e4cbaf 100644
--- a/frontend/src/container/MembersSettings/MembersSettings.tsx
+++ b/frontend/src/container/MembersSettings/MembersSettings.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useHistory } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
import { Check, ChevronDown, Plus } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
@@ -19,7 +19,6 @@ import './MembersSettings.styles.scss';
const PAGE_SIZE = 20;
function MembersSettings(): JSX.Element {
- const history = useHistory();
const urlQuery = useUrlQuery();
const pageParam = parseInt(urlQuery.get('page') ?? '1', 10);
const currentPage = Number.isNaN(pageParam) || pageParam < 1 ? 1 : pageParam;
@@ -72,9 +71,9 @@ function MembersSettings(): JSX.Element {
const setPage = useCallback(
(page: number): void => {
urlQuery.set('page', String(page));
- history.replace({ search: urlQuery.toString() });
+ navigate({ search: urlQuery.toString() }, { replace: true });
},
- [history, urlQuery],
+ [urlQuery],
);
useEffect(() => {
diff --git a/frontend/src/container/MeterExplorer/Breakdown/BreakDown.tsx b/frontend/src/container/MeterExplorer/Breakdown/BreakDown.tsx
index 69c053c575..179e71ea3f 100644
--- a/frontend/src/container/MeterExplorer/Breakdown/BreakDown.tsx
+++ b/frontend/src/container/MeterExplorer/Breakdown/BreakDown.tsx
@@ -1,7 +1,8 @@
import { useCallback } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { navigate } from 'lib/router/navigation';
import { Alert } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import getLocalStorageApi from 'api/browser/localstorage/get';
@@ -71,8 +72,7 @@ const sections: MetricSection[] = [
function Section(section: MetricSection): JSX.Element {
const isDarkMode = useIsDarkMode();
const { title, graphs } = section;
- const history = useHistory();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const dispatch = useDispatch();
const urlQuery = useUrlQuery();
@@ -84,13 +84,13 @@ function Section(section: MetricSection): JSX.Element {
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
}
},
- [dispatch, history, pathname, urlQuery],
+ [dispatch, pathname, urlQuery],
);
return (
diff --git a/frontend/src/container/MeterExplorer/Explorer/useTimeSeriesTimeManagement.ts b/frontend/src/container/MeterExplorer/Explorer/useTimeSeriesTimeManagement.ts
index 983afe5a84..251ae8b937 100644
--- a/frontend/src/container/MeterExplorer/Explorer/useTimeSeriesTimeManagement.ts
+++ b/frontend/src/container/MeterExplorer/Explorer/useTimeSeriesTimeManagement.ts
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
import {
CustomTimeType,
@@ -10,7 +10,7 @@ import {
import useUrlQuery from 'hooks/useUrlQuery';
import GetMinMax from 'lib/getMinMax';
import getTimeString from 'lib/getTimeString';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { UpdateTimeInterval } from 'store/actions';
import { getTimeRange } from 'utils/getTimeRange';
@@ -33,7 +33,7 @@ export function useTimeSeriesTimeManagement({
}: UseTimeSeriesTimeManagementProps): UseTimeSeriesTimeManagementResult {
const dispatch = useDispatch();
const urlQuery = useUrlQuery();
- const location = useLocation();
+ const location = useAppLocation();
const [minTimeScale, setMinTimeScale] = useState<number>();
const [maxTimeScale, setMaxTimeScale] = useState<number>();
@@ -62,7 +62,7 @@ export function useTimeSeriesTimeManagement({
urlQuery.set(QueryParams.endTime, maxTime.toString());
urlQuery.delete(QueryParams.relativeTime);
const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
},
[dispatch, location.pathname, urlQuery],
);
diff --git a/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx b/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx
index a9750049b2..e3e0d0529f 100644
--- a/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/DBCall.tsx
@@ -1,7 +1,8 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch } from 'react-redux';
-import { useLocation, useParams } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppParams } from 'lib/router/useAppParams';
import { Col } from 'antd';
import logEvent from 'api/common/logEvent';
import { ENTITY_VERSION_V4 } from 'constants/app';
@@ -21,7 +22,7 @@ import {
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import getStep from 'lib/getStep';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import store from 'store';
import { UpdateTimeInterval } from 'store/actions';
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
@@ -37,7 +38,6 @@ import {
import { getWidgetQueryBuilder } from '../MetricsApplication.factory';
import { Card, GraphContainer, Row } from '../styles';
import { Button } from './styles';
-import { IServiceName } from './types';
import {
dbSystemTags,
handleNonInQueryRange,
@@ -47,13 +47,13 @@ import {
} from './util';
function DBCall(): JSX.Element {
- const { servicename: encodedServiceName } = useParams<IServiceName>();
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
- const servicename = decodeURIComponent(encodedServiceName);
+ const servicename = decodeURIComponent(encodedServiceName || '');
const [selectedTimeStamp, setSelectedTimeStamp] = useState<number>(0);
const { queries } = useResourceAttribute();
const urlQuery = useUrlQuery();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const dispatch = useDispatch();
const onDragSelect = useCallback(
@@ -64,7 +64,7 @@ function DBCall(): JSX.Element {
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
diff --git a/frontend/src/container/MetricsApplication/Tabs/External.tsx b/frontend/src/container/MetricsApplication/Tabs/External.tsx
index 39cb918ccc..f063518cb4 100644
--- a/frontend/src/container/MetricsApplication/Tabs/External.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/External.tsx
@@ -1,7 +1,8 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch } from 'react-redux';
-import { useLocation, useParams } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppParams } from 'lib/router/useAppParams';
import { Col } from 'antd';
import logEvent from 'api/common/logEvent';
import { ENTITY_VERSION_V4 } from 'constants/app';
@@ -23,7 +24,7 @@ import {
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import getStep from 'lib/getStep';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import store from 'store';
import { UpdateTimeInterval } from 'store/actions';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
@@ -39,7 +40,6 @@ import {
import { getWidgetQueryBuilder } from '../MetricsApplication.factory';
import { Card, GraphContainer, Row } from '../styles';
import GraphControlsPanel from './Overview/GraphControlsPanel/GraphControlsPanel';
-import { IServiceName } from './types';
import {
handleNonInQueryRange,
onViewAPIMonitoringPopupClick,
@@ -51,13 +51,13 @@ import {
function External(): JSX.Element {
const [selectedTimeStamp, setSelectedTimeStamp] = useState<number>(0);
const [selectedData, setSelectedData] = useState<any>(undefined);
- const { servicename: encodedServiceName } = useParams<IServiceName>();
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
- const servicename = decodeURIComponent(encodedServiceName);
+ const servicename = decodeURIComponent(encodedServiceName || '');
const { queries } = useResourceAttribute();
const urlQuery = useUrlQuery();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const dispatch = useDispatch();
const onDragSelect = useCallback(
@@ -68,7 +68,7 @@ function External(): JSX.Element {
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview.tsx
index 3ef7e6af1b..b0897a2e1c 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview.tsx
@@ -2,7 +2,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useQuery } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useLocation, useParams } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppParams } from 'lib/router/useAppParams';
import logEvent from 'api/common/logEvent';
import getTopLevelOperations, {
ServiceDataProps,
@@ -22,7 +23,7 @@ import {
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import getStep from 'lib/getStep';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';
import { defaultTo } from 'lodash-es';
import { useAppContext } from 'providers/App/App';
@@ -51,7 +52,6 @@ import TopLevelOperation from './Overview/TopLevelOperations';
import TopOperation from './Overview/TopOperation';
import TopOperationMetrics from './Overview/TopOperationMetrics';
import { Button, Card } from './styles';
-import { IServiceName } from './types';
import {
generateExplorerPath,
handleNonInQueryRange,
@@ -62,15 +62,15 @@ import {
} from './util';
function Application(): JSX.Element {
- const { servicename: encodedServiceName } = useParams<IServiceName>();
- const servicename = decodeURIComponent(encodedServiceName);
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
+ const servicename = decodeURIComponent(encodedServiceName || '');
const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
const [selectedTimeStamp, setSelectedTimeStamp] = useState<number>(0);
- const { search, pathname } = useLocation();
+ const { search, pathname } = useAppLocation();
const { queries } = useResourceAttribute();
const urlQuery = useUrlQuery();
@@ -212,7 +212,7 @@ function Application(): JSX.Element {
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
@@ -261,7 +261,7 @@ function Application(): JSX.Element {
if (isModifierKeyPressed(e)) {
openInNewTab(newPath);
} else {
- history.push(newPath);
+ navigate(newPath);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetrics.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetrics.tsx
index 05a66bc191..34c64f5c16 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetrics.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetrics.tsx
@@ -1,5 +1,5 @@
import { ReactNode, useMemo } from 'react';
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import { Space } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import TextToolTip from 'components/TextToolTip';
@@ -21,8 +21,6 @@ import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsAppli
import { apDexMetricsQueryBuilderQueries } from 'container/MetricsApplication/MetricsPageQueries/OverviewQueries';
import { EQueryType } from 'types/common/dashboard';
import { v4 as uuid } from 'uuid';
-
-import { IServiceName } from '../../types';
import { ApDexMetricsProps } from './types';
function ApDexMetrics({
@@ -34,8 +32,8 @@ function ApDexMetrics({
topLevelOperationsRoute,
handleGraphClick,
}: ApDexMetricsProps): JSX.Element {
- const { servicename: encodedServiceName } = useParams<IServiceName>();
- const servicename = decodeURIComponent(encodedServiceName);
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
+ const servicename = decodeURIComponent(encodedServiceName || '');
const apDexMetricsWidget = useMemo(
() =>
getWidgetQueryBuilder({
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetricsApplication.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetricsApplication.tsx
index 4415017558..5ed417aab1 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetricsApplication.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/ApDexMetricsApplication.tsx
@@ -1,10 +1,9 @@
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import Spinner from 'components/Spinner';
import { useGetMetricMeta } from 'hooks/apDex/useGetMetricMeta';
import useErrorNotification from 'hooks/useErrorNotification';
import { WidgetKeys } from '../../../constant';
-import { IServiceName } from '../../types';
import ApDexMetrics from './ApDexMetrics';
import { ApDexDataSwitcherProps } from './types';
@@ -15,8 +14,8 @@ function ApDexMetricsApplication({
thresholdValue,
topLevelOperationsRoute,
}: ApDexDataSwitcherProps): JSX.Element {
- const { servicename: encodedServiceName } = useParams<IServiceName>();
- const servicename = decodeURIComponent(encodedServiceName);
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
+ const servicename = decodeURIComponent(encodedServiceName || '');
const { data, isLoading, error } = useGetMetricMeta(
WidgetKeys.SignozLatencyBucket,
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/index.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/index.tsx
index e34419d535..c914ec6acf 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/index.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/ApDex/index.tsx
@@ -1,11 +1,9 @@
import { memo, useEffect } from 'react';
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import Spinner from 'components/Spinner';
import { Card, GraphContainer } from 'container/MetricsApplication/styles';
import { useGetApDexSettings } from 'hooks/apDex/useGetApDexSettings';
import { useNotifications } from 'hooks/useNotifications';
-
-import { IServiceName } from '../../types';
import ApDexMetricsApplication from './ApDexMetricsApplication';
import { ApDexApplicationProps } from './types';
@@ -15,8 +13,8 @@ function ApDexApplication({
topLevelOperationsRoute,
tagFilterItems,
}: ApDexApplicationProps): JSX.Element {
- const { servicename: encodedServiceName } = useParams<IServiceName>();
- const servicename = decodeURIComponent(encodedServiceName);
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
+ const servicename = decodeURIComponent(encodedServiceName || '');
const { notifications } = useNotifications();
const { data, isLoading, error, isRefetching } =
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/ServiceOverview.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/ServiceOverview.tsx
index 457df8f51d..06edd57d1e 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/ServiceOverview.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/ServiceOverview.tsx
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { FeatureKeys } from 'constants/features';
import { PANEL_TYPES } from 'constants/queryBuilder';
@@ -20,7 +20,6 @@ import { useAppContext } from 'providers/App/App';
import { EQueryType } from 'types/common/dashboard';
import { v4 as uuid } from 'uuid';
-import { IServiceName } from '../types';
import {
handleNonInQueryRange,
onViewTracePopupClick,
@@ -38,8 +37,8 @@ function ServiceOverview({
topLevelOperationsIsLoading,
stepInterval,
}: ServiceOverviewProps): JSX.Element {
- const { servicename: encodedServiceName } = useParams<IServiceName>();
- const servicename = decodeURIComponent(encodedServiceName);
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
+ const servicename = decodeURIComponent(encodedServiceName || '');
const { featureFlags } = useAppContext();
const isSpanMetricEnable =
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperation.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperation.tsx
index 614afa3fba..42bb292487 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperation.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperation.tsx
@@ -2,7 +2,7 @@ import { useMemo, useState } from 'react';
import { useQuery } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import getTopOperations from 'api/metrics/getTopOperations';
import TopOperationsTable from 'container/MetricsApplication/TopOperationsTable';
import useResourceAttribute from 'hooks/useResourceAttribute';
@@ -16,7 +16,7 @@ function TopOperation(): JSX.Element {
const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
- const { servicename: encodedServiceName } = useParams<{
+ const { servicename: encodedServiceName } = useAppParams<{
servicename?: string;
}>();
const servicename = decodeURIComponent(encodedServiceName || '');
diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperationMetrics.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperationMetrics.tsx
index 8cacff5974..dca67698b9 100644
--- a/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperationMetrics.tsx
+++ b/frontend/src/container/MetricsApplication/Tabs/Overview/TopOperationMetrics.tsx
@@ -1,7 +1,7 @@
import { ReactNode, useMemo } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { topOperationMetricsDownloadOptions } from 'container/MetricsApplication/constant';
@@ -19,14 +19,13 @@ import { EQueryType } from 'types/common/dashboard';
import { GlobalReducer } from 'types/reducer/globalTime';
import { v4 as uuid } from 'uuid';
-import { IServiceName } from '../types';
import { title } from './config';
import ColumnWithLink from './TableRenderer/ColumnWithLink';
import { getTableColumnRenderer } from './TableRenderer/TableColumnRenderer';
function TopOperationMetrics(): JSX.Element {
- const { servicename: encodedServiceName } = useParams<IServiceName>();
- const servicename = decodeURIComponent(encodedServiceName);
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
+ const servicename = decodeURIComponent(encodedServiceName || '');
const { notifications } = useNotifications();
diff --git a/frontend/src/container/MetricsApplication/TopOperationsTable.tsx b/frontend/src/container/MetricsApplication/TopOperationsTable.tsx
index 96a2a827a3..d75e82e408 100644
--- a/frontend/src/container/MetricsApplication/TopOperationsTable.tsx
+++ b/frontend/src/container/MetricsApplication/TopOperationsTable.tsx
@@ -1,7 +1,7 @@
import { useRef } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import { Search } from '@signozhq/icons';
import {
InputRef,
@@ -24,7 +24,6 @@ import { Query, TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
import { GlobalReducer } from 'types/reducer/globalTime';
import { v4 as uuid } from 'uuid';
-import { IServiceName } from './Tabs/types';
import { useGetAPMToTracesQueries } from './Tabs/util';
import {
convertedTracesToDownloadData,
@@ -41,9 +40,9 @@ function TopOperationsTable({
onEntryPointToggle,
}: TopOperationsTableProps): JSX.Element {
const searchInput = useRef<InputRef>(null);
- const { servicename: encodedServiceName } = useParams<IServiceName>();
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
const { safeNavigate } = useSafeNavigate();
- const servicename = decodeURIComponent(encodedServiceName);
+ const servicename = decodeURIComponent(encodedServiceName || '');
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
@@ -55,11 +54,11 @@ function TopOperationsTable({
const apmToTraceQuery = useGetAPMToTracesQueries({ servicename });
- const params = useParams<{ servicename: string }>();
+ const params = useAppParams<'servicename'>();
const handleOnClick = (operation: string, openInNewTab: boolean): void => {
const { servicename: encodedServiceName } = params;
- const servicename = decodeURIComponent(encodedServiceName);
+ const servicename = decodeURIComponent(encodedServiceName || '');
const opFilters: TagFilterItem[] = [
{
diff --git a/frontend/src/container/MetricsApplication/__tests__/TopOperationsTable.test.tsx b/frontend/src/container/MetricsApplication/__tests__/TopOperationsTable.test.tsx
index d9997117ad..ce03783e68 100644
--- a/frontend/src/container/MetricsApplication/__tests__/TopOperationsTable.test.tsx
+++ b/frontend/src/container/MetricsApplication/__tests__/TopOperationsTable.test.tsx
@@ -11,6 +11,7 @@ import {
import useResourceAttribute from 'hooks/useResourceAttribute';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
+import { mockAppParams } from 'tests/router-mocks';
import {
createMockStore,
@@ -33,12 +34,7 @@ jest.mock('hooks/useSafeNavigate', () => ({
}),
}));
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useParams: (): { servicename: string } => ({
- servicename: encodeURIComponent('test-service'),
- }),
-}));
+mockAppParams({ servicename: encodeURIComponent('test-service') });
// Mock the util functions that TopOperationsTable uses
jest.mock('../Tabs/util', () => ({
diff --git a/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx b/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx
index 6341dcde96..4a28041816 100644
--- a/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx
+++ b/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
-import { useSearchParams } from 'react-router-dom-v5-compat';
+import { useAppSearchParams } from 'lib/router/useAppSearchParams';
import * as Sentry from '@sentry/react';
import { Filter } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
@@ -101,7 +101,7 @@ function Explorer(): JSX.Element {
[units, isMetricUnitsLoading, isMetricUnitsError],
);
- const [searchParams, setSearchParams] = useSearchParams();
+ const [searchParams, setSearchParams] = useAppSearchParams();
const isOneChartPerQueryEnabled =
searchParams.get(ONE_CHART_PER_QUERY_ENABLED_KEY) === 'true';
diff --git a/frontend/src/container/MetricsExplorer/Explorer/__tests__/Explorer.test.tsx b/frontend/src/container/MetricsExplorer/Explorer/__tests__/Explorer.test.tsx
index 47039548fd..56cccf2421 100644
--- a/frontend/src/container/MetricsExplorer/Explorer/__tests__/Explorer.test.tsx
+++ b/frontend/src/container/MetricsExplorer/Explorer/__tests__/Explorer.test.tsx
@@ -1,8 +1,6 @@
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { useSearchParams } from 'react-router-dom-v5-compat';
import { render, screen } from '@testing-library/react';
import {
MetrictypesTemporalityDTO,
@@ -17,6 +15,7 @@ import { ErrorModalProvider } from 'providers/ErrorModalProvider';
import { PreferenceContextProvider } from 'providers/preferences/context/PreferenceContextProvider';
import * as timezoneHooks from 'providers/Timezone';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { LicenseEvent } from 'types/api/licensesV3/getActive';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { DataSource, QueryBuilderContextType } from 'types/common/queryBuilder';
@@ -25,7 +24,6 @@ import Explorer from '../Explorer';
import * as useGetMetricsHooks from '../utils';
import { MOCK_METRIC_METADATA } from './testUtils';
-const mockSetSearchParams = jest.fn();
const queryClient = new QueryClient();
const mockUpdateAllQueriesOperators = jest
.fn()
@@ -48,14 +46,6 @@ const mockUseQueryBuilderData = {
isDefaultQuery: jest.fn(),
};
-jest.mock('react-router-dom-v5-compat', () => {
- const actual = jest.requireActual('react-router-dom-v5-compat');
- return {
- ...actual,
- useSearchParams: jest.fn(),
- useNavigationType: (): any => 'PUSH',
- };
-});
jest.mock('hooks/useDimensions', () => ({
useResizeObserver: (): { width: number; height: number } => ({
width: 800,
@@ -141,10 +131,10 @@ jest
const Y_AXIS_UNIT_SELECTOR_TEST_ID = 'y-axis-unit-selector';
-function renderExplorer(): void {
+function renderExplorer(initialRoute = '/'): void {
render(
<QueryClientProvider client={queryClient}>
- <MemoryRouter>
+ <TestRouter initialRoute={initialRoute}>
<Provider store={store}>
<ErrorModalProvider>
<PreferenceContextProvider>
@@ -152,7 +142,7 @@ function renderExplorer(): void {
</PreferenceContextProvider>
</ErrorModalProvider>
</Provider>
- </MemoryRouter>
+ </TestRouter>
</QueryClientProvider>,
);
}
@@ -163,34 +153,26 @@ describe('Explorer', () => {
});
it('should enable one chart per query toggle when oneChartPerQuery=true in URL', () => {
- (useSearchParams as jest.Mock).mockReturnValue([
- new URLSearchParams({ isOneChartPerQueryEnabled: 'true' }),
- mockSetSearchParams,
- ]);
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
metrics: [MOCK_METRIC_METADATA, MOCK_METRIC_METADATA],
});
- renderExplorer();
+ renderExplorer('/?isOneChartPerQueryEnabled=true');
const toggle = screen.getByRole('switch');
expect(toggle).toBeChecked();
});
it('should disable one chart per query toggle when oneChartPerQuery=false in URL', () => {
- (useSearchParams as jest.Mock).mockReturnValue([
- new URLSearchParams({ isOneChartPerQueryEnabled: 'false' }),
- mockSetSearchParams,
- ]);
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
metrics: [MOCK_METRIC_METADATA, MOCK_METRIC_METADATA],
});
- renderExplorer();
+ renderExplorer('/?isOneChartPerQueryEnabled=false');
const toggle = screen.getByRole('switch');
expect(toggle).not.toBeChecked();
@@ -210,17 +192,13 @@ describe('Explorer', () => {
});
it('should not render y axis unit selector for mutliple metrics with same unit', () => {
- (useSearchParams as jest.Mock).mockReturnValueOnce([
- new URLSearchParams({ isOneChartPerQueryEnabled: 'true' }),
- mockSetSearchParams,
- ]);
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
metrics: [MOCK_METRIC_METADATA, MOCK_METRIC_METADATA],
});
- renderExplorer();
+ renderExplorer('/?isOneChartPerQueryEnabled=true');
const yAxisUnitSelector = screen.queryByTestId(Y_AXIS_UNIT_SELECTOR_TEST_ID);
expect(yAxisUnitSelector).not.toBeInTheDocument();
@@ -257,12 +235,7 @@ describe('Explorer', () => {
],
});
- (useSearchParams as jest.Mock).mockReturnValue([
- new URLSearchParams({ isOneChartPerQueryEnabled: 'false' }),
- mockSetSearchParams,
- ]);
-
- renderExplorer();
+ renderExplorer('/?isOneChartPerQueryEnabled=false');
const oneChartPerQueryToggle = screen.getByRole('switch');
expect(oneChartPerQueryToggle).toBeChecked();
@@ -374,12 +347,7 @@ describe('Explorer', () => {
metrics: [metricWithNoUnit, metricWithNoUnit],
});
- (useSearchParams as jest.Mock).mockReturnValue([
- new URLSearchParams({ isOneChartPerQueryEnabled: 'false' }),
- mockSetSearchParams,
- ]);
-
- renderExplorer();
+ renderExplorer('/?isOneChartPerQueryEnabled=false');
const oneChartPerQueryToggle = screen.getByRole('switch');
// Toggle should be enabled (not forced/disabled) since both metrics
@@ -392,10 +360,6 @@ describe('Explorer', () => {
const EMPTY_STATE_TEXT = 'Select a metric and run a query to see the results';
it('should show empty state when no metric is selected', () => {
- (useSearchParams as jest.Mock).mockReturnValue([
- new URLSearchParams({}),
- mockSetSearchParams,
- ]);
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
@@ -411,10 +375,6 @@ describe('Explorer', () => {
});
it('should not show empty state when saved view has v5 aggregations format', () => {
- (useSearchParams as jest.Mock).mockReturnValue([
- new URLSearchParams({}),
- mockSetSearchParams,
- ]);
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
@@ -458,10 +418,6 @@ describe('Explorer', () => {
});
it('should not show empty state when query uses v3 aggregateAttribute format', () => {
- (useSearchParams as jest.Mock).mockReturnValue([
- new URLSearchParams({}),
- mockSetSearchParams,
- ]);
jest.spyOn(useGetMetricsHooks, 'useGetMetrics').mockReturnValue({
isLoading: false,
isError: false,
diff --git a/frontend/src/container/MetricsExplorer/Inspect/__tests__/Inspect.test.tsx b/frontend/src/container/MetricsExplorer/Inspect/__tests__/Inspect.test.tsx
index a8fcc57c73..d6eb3dfc42 100644
--- a/frontend/src/container/MetricsExplorer/Inspect/__tests__/Inspect.test.tsx
+++ b/frontend/src/container/MetricsExplorer/Inspect/__tests__/Inspect.test.tsx
@@ -7,7 +7,6 @@ import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';
import * as appContextHooks from 'providers/App/App';
import store from 'store';
-import ROUTES from '../../../../constants/routes';
import { LicenseEvent } from '../../../../types/api/licensesV3/getActive';
import { INITIAL_INSPECT_METRICS_OPTIONS } from '../constants';
import Inspect from '../Inspect';
@@ -68,13 +67,6 @@ jest.spyOn(metricsGeneratedAPI, 'useGetMetricMetadata').mockReturnValue({
},
} as any);
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${ROUTES.METRICS_EXPLORER_BASE}`,
- }),
-}));
-
const mockResizeObserver = jest.fn();
mockResizeObserver.mockImplementation(() => ({
observe: (): void => undefined,
diff --git a/frontend/src/container/MetricsExplorer/Inspect/__tests__/QueryBuilder.test.tsx b/frontend/src/container/MetricsExplorer/Inspect/__tests__/QueryBuilder.test.tsx
index 12bfa555bd..f7aa519083 100644
--- a/frontend/src/container/MetricsExplorer/Inspect/__tests__/QueryBuilder.test.tsx
+++ b/frontend/src/container/MetricsExplorer/Inspect/__tests__/QueryBuilder.test.tsx
@@ -8,7 +8,6 @@ import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';
import * as appContextHooks from 'providers/App/App';
import store from 'store';
-import ROUTES from '../../../../constants/routes';
import { LicenseEvent } from '../../../../types/api/licensesV3/getActive';
import QueryBuilder from '../QueryBuilder';
import {
@@ -17,13 +16,6 @@ import {
TimeAggregationOptions,
} from '../types';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${ROUTES.METRICS_EXPLORER_BASE}`,
- }),
-}));
-
jest.mock('api/generated/services/metrics', () => ({
useListMetrics: jest.fn().mockReturnValue({
isFetching: false,
diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsx
index 3f1c581f6c..e1ea481a63 100644
--- a/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsx
+++ b/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsx
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
-import { generatePath } from 'react-router-dom';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { Color } from '@signozhq/design-tokens';
import { Dropdown, type DropdownItemType } from '@signozhq/ui/dropdown';
import { Skeleton } from 'antd';
@@ -96,7 +96,7 @@ function DashboardsAndAlertsPopover({
key={dashboard.dashboardId}
onClick={(): void => {
openInNewTab(
- generatePath(ROUTES.DASHBOARD, {
+ buildRoutePath(ROUTES.DASHBOARD, {
dashboardId: dashboard.dashboardId,
}),
);
diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsx
index eb0c4037a7..4d36a152c9 100644
--- a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsx
+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsx
@@ -1,6 +1,7 @@
import { render, screen } from '@testing-library/react';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';
+import { mockAppLocation } from 'tests/router-mocks';
import { userEvent } from 'tests/test-utils';
import ROUTES from '../../../../constants/routes';
@@ -8,12 +9,7 @@ import AllAttributes from '../AllAttributes';
import { AllAttributesValue } from '../AllAttributesValue';
import { getMockMetricAttributesData, MOCK_METRIC_NAME } from './testUtlls';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${ROUTES.METRICS_EXPLORER}`,
- }),
-}));
+mockAppLocation({ pathname: ROUTES.METRICS_EXPLORER });
const useGetMetricAttributesMock = jest.spyOn(
metricsExplorerHooks,
diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsx
index 0448407f36..bc62046cb1 100644
--- a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsx
+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsx
@@ -1,6 +1,5 @@
import { render, screen } from '@testing-library/react';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
-import ROUTES from 'constants/routes';
import * as useHandleExplorerTabChange from 'hooks/useHandleExplorerTabChange';
import { userEvent } from 'tests/test-utils';
@@ -18,12 +17,6 @@ jest
handleExplorerTabChange: mockHandleExplorerTabChange,
});
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${ROUTES.METRICS_EXPLORER}`,
- }),
-}));
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: jest.fn().mockReturnValue({
diff --git a/frontend/src/container/MetricsExplorer/Summary/Summary.tsx b/frontend/src/container/MetricsExplorer/Summary/Summary.tsx
index 6f8437779e..25ec048f35 100644
--- a/frontend/src/container/MetricsExplorer/Summary/Summary.tsx
+++ b/frontend/src/container/MetricsExplorer/Summary/Summary.tsx
@@ -2,7 +2,7 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux'; // old code, TODO: fix this correctly
-import { useSearchParams } from 'react-router-dom-v5-compat';
+import { useAppSearchParams } from 'lib/router/useAppSearchParams';
import * as Sentry from '@sentry/react';
import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
@@ -78,7 +78,7 @@ function Summary(): JSX.Element {
[stagedQuery],
);
- const [searchParams, setSearchParams] = useSearchParams();
+ const [searchParams, setSearchParams] = useAppSearchParams();
const [isMetricDetailsOpen, setIsMetricDetailsOpen] = useState(
() => searchParams.get(IS_METRIC_DETAILS_OPEN_KEY) === 'true' || false,
);
diff --git a/frontend/src/container/MetricsExplorer/Summary/__tests__/MetricsTable.test.tsx b/frontend/src/container/MetricsExplorer/Summary/__tests__/MetricsTable.test.tsx
index ca0d647eeb..1d381b3749 100644
--- a/frontend/src/container/MetricsExplorer/Summary/__tests__/MetricsTable.test.tsx
+++ b/frontend/src/container/MetricsExplorer/Summary/__tests__/MetricsTable.test.tsx
@@ -1,11 +1,11 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { fireEvent, render, screen } from '@testing-library/react';
import * as metricsGeneratedAPI from 'api/generated/services/metrics';
import { Filter } from 'api/v5/v5';
import * as useQueryBuilderOperationsHooks from 'hooks/queryBuilder/useQueryBuilderOperations';
import store from 'store';
+import { TestRouter } from 'tests/router';
import APIError from 'types/api/error';
import MetricsTable from '../MetricsTable';
@@ -36,14 +36,6 @@ const mockQueryFilterExpression: Filter = {
expression: '',
};
-jest.mock('react-router-dom-v5-compat', () => {
- const actual = jest.requireActual('react-router-dom-v5-compat');
- return {
- ...actual,
- useSearchParams: jest.fn().mockReturnValue([{}, jest.fn()]),
- useNavigationType: (): any => 'PUSH',
- };
-});
describe('MetricsTable', () => {
beforeEach(() => {
jest
@@ -83,7 +75,7 @@ describe('MetricsTable', () => {
it('renders table with data correctly', () => {
render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<MetricsTable
isLoading={false}
@@ -99,7 +91,7 @@ describe('MetricsTable', () => {
onFilterChange={jest.fn()}
/>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(screen.getByText('List View')).toBeInTheDocument();
@@ -109,7 +101,7 @@ describe('MetricsTable', () => {
it('shows loading state', () => {
render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<MetricsTable
isError={false}
@@ -125,7 +117,7 @@ describe('MetricsTable', () => {
onFilterChange={jest.fn()}
/>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(screen.getByTestId('metrics-table-loading-state')).toBeInTheDocument();
@@ -143,7 +135,7 @@ describe('MetricsTable', () => {
});
render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<MetricsTable
isLoading={false}
@@ -160,7 +152,7 @@ describe('MetricsTable', () => {
onFilterChange={jest.fn()}
/>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(screen.getByText('400')).toBeInTheDocument();
@@ -169,7 +161,7 @@ describe('MetricsTable', () => {
it('shows empty state when no data', () => {
render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<MetricsTable
isLoading={false}
@@ -185,7 +177,7 @@ describe('MetricsTable', () => {
onFilterChange={jest.fn()}
/>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(screen.getByTestId('metrics-table-empty-state')).toBeInTheDocument();
@@ -199,7 +191,7 @@ describe('MetricsTable', () => {
it('calls openMetricDetails when row is clicked', () => {
const mockOpenMetricDetails = jest.fn();
render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<MetricsTable
isLoading={false}
@@ -215,7 +207,7 @@ describe('MetricsTable', () => {
onFilterChange={jest.fn()}
/>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
fireEvent.click(screen.getByText('Metric 1'));
@@ -229,7 +221,7 @@ describe('MetricsTable', () => {
it('calls setOrderBy when column header is clicked', () => {
const mockSetOrderBy = jest.fn();
render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<MetricsTable
isLoading={false}
@@ -245,7 +237,7 @@ describe('MetricsTable', () => {
onFilterChange={jest.fn()}
/>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
const samplesHeader = screen.getByText('SAMPLES');
diff --git a/frontend/src/container/MetricsExplorer/Summary/__tests__/MetricsTreemap.test.tsx b/frontend/src/container/MetricsExplorer/Summary/__tests__/MetricsTreemap.test.tsx
index 6a7345b813..388c1c297e 100644
--- a/frontend/src/container/MetricsExplorer/Summary/__tests__/MetricsTreemap.test.tsx
+++ b/frontend/src/container/MetricsExplorer/Summary/__tests__/MetricsTreemap.test.tsx
@@ -1,9 +1,9 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render, screen } from '@testing-library/react';
import { MetricsexplorertypesTreemapModeDTO } from 'api/generated/services/sigNoz.schemas';
import store from 'store';
+import { TestRouter } from 'tests/router';
import MetricsTreemap from '../MetricsTreemap';
@@ -42,7 +42,7 @@ const mockData = [
describe('MetricsTreemap', () => {
it('renders treemap with data correctly', () => {
render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<MetricsTreemap
isLoading={false}
@@ -56,7 +56,7 @@ describe('MetricsTreemap', () => {
setHeatmapView={jest.fn()}
/>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(screen.getByText('Proportion View')).toBeInTheDocument();
@@ -64,7 +64,7 @@ describe('MetricsTreemap', () => {
it('shows loading state', () => {
render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<MetricsTreemap
isLoading
@@ -78,7 +78,7 @@ describe('MetricsTreemap', () => {
setHeatmapView={jest.fn()}
/>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(
@@ -88,7 +88,7 @@ describe('MetricsTreemap', () => {
it('shows error state', () => {
render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<MetricsTreemap
isLoading={false}
@@ -102,7 +102,7 @@ describe('MetricsTreemap', () => {
setHeatmapView={jest.fn()}
/>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(screen.getByTestId('metrics-treemap-error-state')).toBeInTheDocument();
@@ -115,7 +115,7 @@ describe('MetricsTreemap', () => {
it('shows empty state when no data', () => {
render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<MetricsTreemap
isLoading={false}
@@ -126,7 +126,7 @@ describe('MetricsTreemap', () => {
setHeatmapView={jest.fn()}
/>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(screen.getByTestId('metrics-treemap-empty-state')).toBeInTheDocument();
diff --git a/frontend/src/container/MetricsExplorer/Summary/__tests__/Summary.test.tsx b/frontend/src/container/MetricsExplorer/Summary/__tests__/Summary.test.tsx
index 4094d80b07..647421db37 100644
--- a/frontend/src/container/MetricsExplorer/Summary/__tests__/Summary.test.tsx
+++ b/frontend/src/container/MetricsExplorer/Summary/__tests__/Summary.test.tsx
@@ -1,4 +1,3 @@
-import { useSearchParams } from 'react-router-dom-v5-compat';
import * as metricsHooks from 'api/generated/services/metrics';
import { initialQueriesMap } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
@@ -26,20 +25,6 @@ jest.mock('d3-hierarchy', () => ({
jest.mock('react-use', () => ({
useWindowSize: jest.fn().mockReturnValue({ width: 1000, height: 1000 }),
}));
-jest.mock('react-router-dom-v5-compat', () => {
- const actual = jest.requireActual('react-router-dom-v5-compat');
- return {
- ...actual,
- useSearchParams: jest.fn(),
- useNavigationType: (): any => 'PUSH',
- };
-});
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${ROUTES.METRICS_EXPLORER_BASE}`,
- }),
-}));
jest.mock('hooks/queryBuilder/useShareBuilderUrl', () => ({
useShareBuilderUrl: jest.fn(),
}));
@@ -57,7 +42,6 @@ jest.mock('../MetricsSearch', () => {
};
});
-const mockSetSearchParams = jest.fn();
const mockGetMetricsStats = jest.fn();
const mockGetMetricsTreemap = jest.fn();
@@ -88,11 +72,6 @@ describe('Summary', () => {
beforeEach(() => {
jest.clearAllMocks();
- (useSearchParams as jest.Mock).mockReturnValue([
- new URLSearchParams(),
- mockSetSearchParams,
- ]);
-
useGetMetricsStatsSpy.mockReturnValue({
data: null,
mutate: mockGetMetricsStats,
@@ -146,7 +125,9 @@ describe('Summary', () => {
currentQuery: staleQuery,
} as Partial<QueryBuilderContextType> as QueryBuilderContextType);
- const { rerender } = render(<Summary />);
+ const { rerender } = render(<Summary />, undefined, {
+ initialRoute: ROUTES.METRICS_EXPLORER_BASE,
+ });
expect(screen.getByTestId('metrics-search-expression')).toHaveTextContent(
staleFilterExpression,
@@ -169,29 +150,17 @@ describe('Summary', () => {
});
it('persists inspect modal open state across page refresh', () => {
- (useSearchParams as jest.Mock).mockReturnValue([
- new URLSearchParams({
- isInspectModalOpen: 'true',
- selectedMetricName: 'test-metric',
- }),
- mockSetSearchParams,
- ]);
-
- render(<Summary />);
+ render(<Summary />, undefined, {
+ initialRoute: `${ROUTES.METRICS_EXPLORER_BASE}?isInspectModalOpen=true&selectedMetricName=test-metric`,
+ });
expect(screen.queryByText('Proportion View')).not.toBeInTheDocument();
});
it('persists metric details modal state across page refresh', () => {
- (useSearchParams as jest.Mock).mockReturnValue([
- new URLSearchParams({
- isMetricDetailsOpen: 'true',
- selectedMetricName: 'test-metric',
- }),
- mockSetSearchParams,
- ]);
-
- render(<Summary />);
+ render(<Summary />, undefined, {
+ initialRoute: `${ROUTES.METRICS_EXPLORER_BASE}?isMetricDetailsOpen=true&selectedMetricName=test-metric`,
+ });
expect(screen.queryByText('Proportion View')).not.toBeInTheDocument();
});
diff --git a/frontend/src/container/NoLogs/NoLogs.tsx b/frontend/src/container/NoLogs/NoLogs.tsx
index 803f07d082..2ba8cbafdb 100644
--- a/frontend/src/container/NoLogs/NoLogs.tsx
+++ b/frontend/src/container/NoLogs/NoLogs.tsx
@@ -2,7 +2,7 @@ import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
import ROUTES from 'constants/routes';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { ArrowUpRight } from '@signozhq/icons';
import { DataSource } from 'types/common/queryBuilder';
import DOCLINKS from 'utils/docLinks';
@@ -33,7 +33,7 @@ export default function NoLogs({
} else if (dataSource === DataSource.METRICS) {
logEvent('Metrics Explorer: Navigate to onboarding', {});
}
- history.push(ROUTES.GET_STARTED_WITH_CLOUD);
+ navigate(ROUTES.GET_STARTED_WITH_CLOUD);
} else if (dataSource === 'traces') {
openInNewTab(DOCLINKS.TRACES_EXPLORER_EMPTY_STATE);
} else if (dataSource === DataSource.METRICS) {
diff --git a/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx b/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx
index 18732210e1..b46e32d3bc 100644
--- a/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx
+++ b/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx
@@ -4,17 +4,9 @@ import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import OnboardingQuestionaire from '../index';
// Mock dependencies
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: jest.fn(),
- location: {
- pathname: '/onboarding',
- search: '',
- hash: '',
- state: null,
- },
- },
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: jest.fn(),
}));
// API Endpoints
diff --git a/frontend/src/container/OnboardingQuestionaire/index.tsx b/frontend/src/container/OnboardingQuestionaire/index.tsx
index 9da7fe63e6..e3380cc17e 100644
--- a/frontend/src/container/OnboardingQuestionaire/index.tsx
+++ b/frontend/src/container/OnboardingQuestionaire/index.tsx
@@ -12,7 +12,7 @@ import { SOMETHING_WENT_WRONG } from 'constants/api';
import { ORG_PREFERENCES } from 'constants/orgPreferences';
import ROUTES from 'constants/routes';
import { useNotifications } from 'hooks/useNotifications';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { useAppContext } from 'providers/App/App';
import {
@@ -95,7 +95,7 @@ function OnboardingQuestionaire(): JSX.Element {
logEvent('Org Onboarding: Redirecting to Get Started', {});
- history.push(ROUTES.GET_STARTED_WITH_CLOUD);
+ navigate(ROUTES.GET_STARTED_WITH_CLOUD);
},
onError: () => {
setUpdatingOrgOnboardingStatus(false);
diff --git a/frontend/src/container/PipelinePage/Layouts/ChangeHistory/tests/ChangeHistory.test.tsx b/frontend/src/container/PipelinePage/Layouts/ChangeHistory/tests/ChangeHistory.test.tsx
index e6d9938cb5..a5811d5188 100644
--- a/frontend/src/container/PipelinePage/Layouts/ChangeHistory/tests/ChangeHistory.test.tsx
+++ b/frontend/src/container/PipelinePage/Layouts/ChangeHistory/tests/ChangeHistory.test.tsx
@@ -2,11 +2,11 @@ import { I18nextProvider } from 'react-i18next';
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import TimezoneProvider from 'providers/Timezone';
import i18n from 'ReactI18';
import store from 'store';
+import { TestRouter } from 'tests/router';
import ChangeHistory from '../index';
import { pipelineData, pipelineDataHistory } from './testUtils';
@@ -22,7 +22,7 @@ const queryClient = new QueryClient({
describe('ChangeHistory test', () => {
it('should render changeHistory correctly', () => {
const { getAllByText, getByText } = render(
- <MemoryRouter>
+ <TestRouter>
<QueryClientProvider client={queryClient}>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
@@ -32,7 +32,7 @@ describe('ChangeHistory test', () => {
</I18nextProvider>
</Provider>
</QueryClientProvider>
- </MemoryRouter>,
+ </TestRouter>,
);
// change History table headers
@@ -51,7 +51,7 @@ describe('ChangeHistory test', () => {
it('test deployment stage and icon based on history data', () => {
const { getByText, container } = render(
- <MemoryRouter>
+ <TestRouter>
<QueryClientProvider client={queryClient}>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
@@ -66,7 +66,7 @@ describe('ChangeHistory test', () => {
</I18nextProvider>
</Provider>
</QueryClientProvider>
- </MemoryRouter>,
+ </TestRouter>,
);
// assertion for different deployment stages
diff --git a/frontend/src/container/PipelinePage/tests/CreatePipelineButton.test.tsx b/frontend/src/container/PipelinePage/tests/CreatePipelineButton.test.tsx
index f56e58ff67..a0e3b0d3a7 100644
--- a/frontend/src/container/PipelinePage/tests/CreatePipelineButton.test.tsx
+++ b/frontend/src/container/PipelinePage/tests/CreatePipelineButton.test.tsx
@@ -1,12 +1,12 @@
import { I18nextProvider } from 'react-i18next';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { logEventMock } from '__tests__/logEventMock';
import i18n from 'ReactI18';
import store from 'store';
+import { TestRouter } from 'tests/router';
import CreatePipelineButton from '../Layouts/Pipeline/CreatePipelineButton';
import { pipelineApiResponseMockData } from '../mocks/pipeline';
@@ -14,7 +14,7 @@ import { pipelineApiResponseMockData } from '../mocks/pipeline';
describe('PipelinePage container test', () => {
it('should render CreatePipelineButton section', async () => {
const { asFragment } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<CreatePipelineButton
@@ -25,14 +25,14 @@ describe('PipelinePage container test', () => {
/>
</I18nextProvider>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(asFragment()).toMatchSnapshot();
});
it('CreatePipelineButton - edit mode & tracking', async () => {
const { getByText } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<CreatePipelineButton
@@ -43,7 +43,7 @@ describe('PipelinePage container test', () => {
/>
</I18nextProvider>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
// enter_edit_mode click and track event data
@@ -61,7 +61,7 @@ describe('PipelinePage container test', () => {
it('CreatePipelineButton - add new mode & tracking', async () => {
const { getByText } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<CreatePipelineButton
@@ -72,7 +72,7 @@ describe('PipelinePage container test', () => {
/>
</I18nextProvider>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
// new_pipeline click and track event data
const editButton = getByText('new_pipeline');
diff --git a/frontend/src/container/PipelinePage/tests/DeleteAction.test.tsx b/frontend/src/container/PipelinePage/tests/DeleteAction.test.tsx
index 2b5f12c742..13ad638120 100644
--- a/frontend/src/container/PipelinePage/tests/DeleteAction.test.tsx
+++ b/frontend/src/container/PipelinePage/tests/DeleteAction.test.tsx
@@ -1,22 +1,22 @@
import { I18nextProvider } from 'react-i18next';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import DeleteAction from 'container/PipelinePage/PipelineListsView/TableComponents/TableActions/DeleteAction';
import i18n from 'ReactI18';
import store from 'store';
+import { TestRouter } from 'tests/router';
describe('PipelinePage container test', () => {
it('should render DeleteAction section', () => {
const { asFragment } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<DeleteAction isPipelineAction deleteAction={jest.fn()} />
</I18nextProvider>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(asFragment()).toMatchSnapshot();
});
diff --git a/frontend/src/container/PipelinePage/tests/DragAction.test.tsx b/frontend/src/container/PipelinePage/tests/DragAction.test.tsx
index c5592600ba..e51697d708 100644
--- a/frontend/src/container/PipelinePage/tests/DragAction.test.tsx
+++ b/frontend/src/container/PipelinePage/tests/DragAction.test.tsx
@@ -1,22 +1,22 @@
import { I18nextProvider } from 'react-i18next';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import DragAction from 'container/PipelinePage/PipelineListsView/TableComponents/DragAction';
import i18n from 'ReactI18';
import store from 'store';
+import { TestRouter } from 'tests/router';
describe('PipelinePage container test', () => {
it('should render DragAction section', () => {
const { asFragment } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<DragAction isEnabled onChange={jest.fn()} />
</I18nextProvider>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(asFragment()).toMatchSnapshot();
});
diff --git a/frontend/src/container/PipelinePage/tests/EditAction.test.tsx b/frontend/src/container/PipelinePage/tests/EditAction.test.tsx
index 99e1421263..23829856c7 100644
--- a/frontend/src/container/PipelinePage/tests/EditAction.test.tsx
+++ b/frontend/src/container/PipelinePage/tests/EditAction.test.tsx
@@ -1,22 +1,22 @@
import { I18nextProvider } from 'react-i18next';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import EditAction from 'container/PipelinePage/PipelineListsView/TableComponents/TableActions/EditAction';
import i18n from 'ReactI18';
import store from 'store';
+import { TestRouter } from 'tests/router';
describe('PipelinePage container test', () => {
it('should render EditAction section', () => {
const { asFragment } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<EditAction isPipelineAction editAction={jest.fn()} />
</I18nextProvider>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(asFragment()).toMatchSnapshot();
});
diff --git a/frontend/src/container/PipelinePage/tests/PipelineActions.test.tsx b/frontend/src/container/PipelinePage/tests/PipelineActions.test.tsx
index f97f20cf58..d23c6223f9 100644
--- a/frontend/src/container/PipelinePage/tests/PipelineActions.test.tsx
+++ b/frontend/src/container/PipelinePage/tests/PipelineActions.test.tsx
@@ -1,10 +1,10 @@
import { I18nextProvider } from 'react-i18next';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import i18n from 'ReactI18';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { pipelineMockData } from '../mocks/pipeline';
import PipelineActions from '../PipelineListsView/TableComponents/PipelineActions';
@@ -12,7 +12,7 @@ import PipelineActions from '../PipelineListsView/TableComponents/PipelineAction
describe('PipelinePage container test', () => {
it('should render PipelineActions section', () => {
const { asFragment } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<PipelineActions
@@ -22,7 +22,7 @@ describe('PipelinePage container test', () => {
/>
</I18nextProvider>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(asFragment()).toMatchSnapshot();
});
diff --git a/frontend/src/container/PipelinePage/tests/PipelinesSearchSection.test.tsx b/frontend/src/container/PipelinePage/tests/PipelinesSearchSection.test.tsx
index 48561e2750..3119b6481a 100644
--- a/frontend/src/container/PipelinePage/tests/PipelinesSearchSection.test.tsx
+++ b/frontend/src/container/PipelinePage/tests/PipelinesSearchSection.test.tsx
@@ -1,24 +1,24 @@
import { I18nextProvider } from 'react-i18next';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import i18n from 'ReactI18';
import store from 'store';
+import { TestRouter } from 'tests/router';
import PipelinesSearchSection from '../Layouts/Pipeline/PipelinesSearchSection';
describe('PipelinePage container test', () => {
it('should render PipelinesSearchSection section', () => {
const { asFragment } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<PipelinesSearchSection setPipelineSearchValue={jest.fn()} />
</I18nextProvider>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(asFragment()).toMatchSnapshot();
});
@@ -26,13 +26,13 @@ describe('PipelinePage container test', () => {
it.skip('should handle search', async () => {
const setPipelineValue = jest.fn();
const { getByPlaceholderText, container } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<PipelinesSearchSection setPipelineSearchValue={setPipelineValue} />
</I18nextProvider>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
const searchInput = getByPlaceholderText('search_pipeline_placeholder');
diff --git a/frontend/src/container/PipelinePage/tests/TableExpandIcon.test.tsx b/frontend/src/container/PipelinePage/tests/TableExpandIcon.test.tsx
index b84a03828b..31e1c8b0b9 100644
--- a/frontend/src/container/PipelinePage/tests/TableExpandIcon.test.tsx
+++ b/frontend/src/container/PipelinePage/tests/TableExpandIcon.test.tsx
@@ -1,17 +1,17 @@
import { I18nextProvider } from 'react-i18next';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render } from '@testing-library/react';
import { pipelineMockData } from 'container/PipelinePage/mocks/pipeline';
import TableExpandIcon from 'container/PipelinePage/PipelineListsView/TableComponents/TableExpandIcon';
import i18n from 'ReactI18';
import store from 'store';
+import { TestRouter } from 'tests/router';
describe('PipelinePage container test', () => {
it('should render TableExpandIcon section', () => {
const { asFragment } = render(
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>
<I18nextProvider i18n={i18n}>
<TableExpandIcon
@@ -21,7 +21,7 @@ describe('PipelinePage container test', () => {
/>
</I18nextProvider>
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
expect(asFragment()).toMatchSnapshot();
});
diff --git a/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx b/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx
index 72ae988ef1..b6734ff6ce 100644
--- a/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx
+++ b/frontend/src/container/PlannedDowntime/PlannedDowntime.tsx
@@ -5,7 +5,7 @@ import React, {
useMemo,
useState,
} from 'react';
-import { useHistory } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
import { Plus, Search } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
@@ -60,7 +60,6 @@ export function PlannedDowntime(): JSX.Element {
const [form] = Form.useForm();
const { user } = useAppContext();
const { showErrorModal } = useErrorModal();
- const history = useHistory();
const urlQuery = useUrlQuery();
const [initialValues, setInitialValues] =
@@ -98,7 +97,7 @@ export function PlannedDowntime(): JSX.Element {
urlQuery.delete('search');
}
const url = `/alerts?${urlQuery.toString()}`;
- history.replace(url);
+ navigate(url, { replace: true });
}, 300);
const {
diff --git a/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx b/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx
index bdf1c896c8..3ba7963888 100644
--- a/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx
+++ b/frontend/src/container/PlannedDowntime/__test__/PlannedDowntime.test.tsx
@@ -11,6 +11,7 @@ import {
} from 'api/generated/services/sigNoz.schemas';
import type { ErrorType } from 'api/generatedAPIInstance';
import { mockLocation } from 'container/RoutingPolicies/__tests__/testUtils';
+import { mockAppLocation } from 'tests/router-mocks';
import { render, userEvent } from 'tests/test-utils';
import { USER_ROLES } from 'types/roles';
@@ -99,15 +100,9 @@ const mockDowntimeQueryResult: Partial<DowntimeQueryResult> = {
refetch: jest.fn(),
};
-const mockUseLocation = jest.fn().mockReturnValue({
- pathname: '/alerts',
-});
let mockUrlQuery: URLSearchParams;
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): void => mockUseLocation(),
-}));
+mockAppLocation({ pathname: '/alerts' });
jest.mock('hooks/useUrlQuery', () => ({
__esModule: true,
diff --git a/frontend/src/container/QueryBuilder/components/QBEntityOptions/QBEntityOptions.tsx b/frontend/src/container/QueryBuilder/components/QBEntityOptions/QBEntityOptions.tsx
index e4250759c0..52b2b19844 100644
--- a/frontend/src/container/QueryBuilder/components/QBEntityOptions/QBEntityOptions.tsx
+++ b/frontend/src/container/QueryBuilder/components/QBEntityOptions/QBEntityOptions.tsx
@@ -1,4 +1,4 @@
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Button, Col, Tooltip } from 'antd';
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
import cx from 'classnames';
@@ -79,7 +79,7 @@ export default function QBEntityOptions({
}
};
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const isLogsExplorerPage = pathname === ROUTES.LOGS_EXPLORER;
diff --git a/frontend/src/container/QueryTable/Drilldown/__tests__/Breakout.test.tsx b/frontend/src/container/QueryTable/Drilldown/__tests__/Breakout.test.tsx
index c7866b0a9e..4407338c4d 100644
--- a/frontend/src/container/QueryTable/Drilldown/__tests__/Breakout.test.tsx
+++ b/frontend/src/container/QueryTable/Drilldown/__tests__/Breakout.test.tsx
@@ -1,15 +1,14 @@
import React from 'react';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { fireEvent, render, screen } from '@testing-library/react';
import { Button } from 'antd';
-import ROUTES from 'constants/routes';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import ContextMenu, { useCoordinates } from 'periscope/components/ContextMenu';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import useTableContextMenu from '../useTableContextMenu';
@@ -46,13 +45,6 @@ jest.mock('container/WidgetCard/hooks/useResolveQuery', () => ({
}),
}));
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${process.env.FRONTEND_API_ENDPOINT}/${ROUTES.DASHBOARD}/`,
- }),
-}));
-
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: (): any => ({
@@ -126,9 +118,9 @@ const renderWithProviders = (
): ReturnType<typeof render> =>
render(
<MockQueryClientProvider>
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>{component}</Provider>
- </MemoryRouter>
+ </TestRouter>
</MockQueryClientProvider>,
);
diff --git a/frontend/src/container/QueryTable/Drilldown/__tests__/TableDrilldown.test.tsx b/frontend/src/container/QueryTable/Drilldown/__tests__/TableDrilldown.test.tsx
index acbbc10244..b50c10811d 100644
--- a/frontend/src/container/QueryTable/Drilldown/__tests__/TableDrilldown.test.tsx
+++ b/frontend/src/container/QueryTable/Drilldown/__tests__/TableDrilldown.test.tsx
@@ -1,13 +1,13 @@
import React from 'react';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { fireEvent, render, screen } from '@testing-library/react';
import { Button } from 'antd';
import ROUTES from 'constants/routes';
import ContextMenu, { useCoordinates } from 'periscope/components/ContextMenu';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
@@ -37,13 +37,6 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
}),
}));
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${process.env.FRONTEND_API_ENDPOINT}/${ROUTES.DASHBOARD}/`,
- }),
-}));
-
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: (): any => ({
@@ -119,9 +112,9 @@ const renderWithProviders = (
): ReturnType<typeof render> =>
render(
<MockQueryClientProvider>
- <MemoryRouter>
+ <TestRouter>
<Provider store={store}>{component}</Provider>
- </MemoryRouter>
+ </TestRouter>
</MockQueryClientProvider>,
);
diff --git a/frontend/src/container/QueryTable/Drilldown/__tests__/useBaseAggregateOptions.test.tsx b/frontend/src/container/QueryTable/Drilldown/__tests__/useBaseAggregateOptions.test.tsx
index d5a410eca6..8530596bc8 100644
--- a/frontend/src/container/QueryTable/Drilldown/__tests__/useBaseAggregateOptions.test.tsx
+++ b/frontend/src/container/QueryTable/Drilldown/__tests__/useBaseAggregateOptions.test.tsx
@@ -29,11 +29,6 @@ jest.mock('hooks/useSafeNavigate', () => ({
useSafeNavigate: (): unknown => ({ safeNavigate: jest.fn() }),
}));
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({ pathname: '/services/socky-api' }),
-}));
-
const QUERY = {
builder: {
queryData: [{ queryName: 'A', dataSource: 'traces', aggregations: [] }],
diff --git a/frontend/src/container/QueryTable/QueryTable.tsx b/frontend/src/container/QueryTable/QueryTable.tsx
index 1df8038356..d0ecf11f4c 100644
--- a/frontend/src/container/QueryTable/QueryTable.tsx
+++ b/frontend/src/container/QueryTable/QueryTable.tsx
@@ -1,9 +1,8 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import cx from 'classnames';
import { ResizeTable } from 'components/ResizeTable';
import Download from 'container/Download/Download';
-import { IServiceName } from 'container/MetricsApplication/Tabs/types';
import {
createTableColumnsFromQuery,
RowData,
@@ -36,8 +35,8 @@ export function QueryTable({
const { isDownloadEnabled = false, fileName = '' } = downloadOption || {};
const isQueryTypeBuilder = query.queryType === 'builder';
- const { servicename: encodedServiceName } = useParams<IServiceName>();
- const servicename = decodeURIComponent(encodedServiceName);
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
+ const servicename = decodeURIComponent(encodedServiceName || '');
const { loading, enableDrillDown = false, contextLinks } = props;
const {
diff --git a/frontend/src/container/QueryTable/__test__/QueryTable.test.tsx b/frontend/src/container/QueryTable/__test__/QueryTable.test.tsx
index 5480579f67..37add0aadb 100644
--- a/frontend/src/container/QueryTable/__test__/QueryTable.test.tsx
+++ b/frontend/src/container/QueryTable/__test__/QueryTable.test.tsx
@@ -1,15 +1,11 @@
import WidgetHeader from 'container/WidgetCard/Header';
+import { mockAppLocation } from 'tests/router-mocks';
import { fireEvent, render } from 'tests/test-utils';
import { QueryTable } from '../QueryTable';
import { QueryTableProps, WidgetHeaderProps } from './mocks';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: ``,
- }),
-}));
+mockAppLocation({ pathname: '' });
// Mock useDashabord hook
diff --git a/frontend/src/container/ResetPassword/TokenError.tsx b/frontend/src/container/ResetPassword/TokenError.tsx
index 3a1a6fdaa5..e198c9850a 100644
--- a/frontend/src/container/ResetPassword/TokenError.tsx
+++ b/frontend/src/container/ResetPassword/TokenError.tsx
@@ -4,7 +4,7 @@ import { Typography } from '@signozhq/ui/typography';
import AuthError from 'components/AuthError/AuthError';
import AuthPageContainer from 'components/AuthPageContainer';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import APIError from 'types/api/error';
import './ResetPassword.styles.scss';
@@ -69,7 +69,7 @@ function TokenError({ error }: TokenErrorProps): JSX.Element {
variant="solid"
testId="back-to-login"
prefix={<ArrowLeft size={12} />}
- onClick={(): void => history.push(ROUTES.LOGIN)}
+ onClick={(): void => navigate(ROUTES.LOGIN)}
>
Back to login
</Button>
diff --git a/frontend/src/container/ResetPassword/__tests__/ResetPassword.test.tsx b/frontend/src/container/ResetPassword/__tests__/ResetPassword.test.tsx
index 448dae0b08..050227ca1d 100644
--- a/frontend/src/container/ResetPassword/__tests__/ResetPassword.test.tsx
+++ b/frontend/src/container/ResetPassword/__tests__/ResetPassword.test.tsx
@@ -1,19 +1,14 @@
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import ResetPassword from '../index';
// Mock dependencies
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: jest.fn(),
- location: {
- search: '?token=reset-token-123',
- },
- },
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: jest.fn(),
}));
const mockSuccessNotification = jest.fn();
@@ -35,9 +30,7 @@ jest.mock('hooks/useNotifications', () => ({
const RESET_PASSWORD_ENDPOINT = '*/api/v2/factor_password/reset';
-const mockHistoryPush = history.push as jest.MockedFunction<
- typeof history.push
->;
+const mockNavigate = navigate as jest.MockedFunction<typeof navigate>;
describe('ResetPassword Component', () => {
beforeEach(() => {
@@ -232,7 +225,7 @@ describe('ResetPassword Component', () => {
await waitFor(() => {
expect(mockSuccessNotification).toHaveBeenCalled();
- expect(mockHistoryPush).toHaveBeenCalledWith(ROUTES.LOGIN);
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.LOGIN);
});
});
});
diff --git a/frontend/src/container/ResetPassword/index.tsx b/frontend/src/container/ResetPassword/index.tsx
index f9b6c2ee4e..8077e9a91e 100644
--- a/frontend/src/container/ResetPassword/index.tsx
+++ b/frontend/src/container/ResetPassword/index.tsx
@@ -11,7 +11,7 @@ import AuthError from 'components/AuthError/AuthError';
import AuthPageContainer from 'components/AuthPageContainer';
import ROUTES from 'constants/routes';
import { useNotifications } from 'hooks/useNotifications';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { ArrowRight, CircleAlert, KeyRound } from '@signozhq/icons';
import { Label } from 'pages/SignUp/styles';
@@ -73,7 +73,7 @@ function ResetPassword({ version }: ResetPasswordProps): JSX.Element {
ns: 'common',
}),
});
- history.push(ROUTES.LOGIN);
+ navigate(ROUTES.LOGIN);
},
},
);
diff --git a/frontend/src/container/ResourceAttributesFilter/__tests__/ResourceAttributesFilter.test.tsx b/frontend/src/container/ResourceAttributesFilter/__tests__/ResourceAttributesFilter.test.tsx
index 130e2f3656..42665b58fe 100644
--- a/frontend/src/container/ResourceAttributesFilter/__tests__/ResourceAttributesFilter.test.tsx
+++ b/frontend/src/container/ResourceAttributesFilter/__tests__/ResourceAttributesFilter.test.tsx
@@ -1,24 +1,16 @@
import { ReactNode } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
-import { Router } from 'react-router-dom';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import ROUTES from 'constants/routes';
-import { createMemoryHistory, MemoryHistory } from 'history';
import { ResourceProvider } from 'hooks/useResourceAttribute';
import { IResourceAttribute } from 'hooks/useResourceAttribute/types';
import { encode } from 'js-base64';
+import { TestRouter } from 'tests/router';
+import { resetTestRoute } from 'tests/router-utils';
import ResourceAttributesFilter from '../ResourceAttributesFilter';
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: jest.fn(),
- location: { search: '', pathname: '/' },
- },
-}));
-
jest.mock('api/metrics/getResourceAttributes', () => ({
getResourceAttributesTagKeys: jest.fn(),
getResourceAttributesTagValues: jest.fn(),
@@ -30,8 +22,6 @@ import {
getResourceAttributesTagValues,
// eslint-disable-next-line import/newline-after-import
} from 'api/metrics/getResourceAttributes';
-// eslint-disable-next-line import/first, import/order
-import history from 'lib/history';
const mockTagKeys = getResourceAttributesTagKeys as jest.MockedFunction<
typeof getResourceAttributesTagKeys
@@ -67,18 +57,18 @@ function tagValuesPayload(values: string[]): never {
} as unknown as never;
}
-function seedUrl(queries: IResourceAttribute[], pathname: string): void {
- const location = history.location as { search: string; pathname: string };
- location.search = queries.length
- ? `?resourceAttribute=${encode(JSON.stringify(queries))}`
- : '';
- location.pathname = pathname;
+function routeWithQueries(
+ queries: IResourceAttribute[],
+ pathname: string,
+): string {
+ if (!queries.length) {
+ return pathname;
+ }
+
+ return `${pathname}?resourceAttribute=${encode(JSON.stringify(queries))}`;
}
-function renderFilter(pathname: string): MemoryHistory {
- const routerHistory = createMemoryHistory({
- initialEntries: [`${pathname}${history.location.search}`],
- });
+function renderFilter(route: string): void {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
@@ -86,9 +76,9 @@ function renderFilter(pathname: string): MemoryHistory {
function Wrapper({ children }: { children: ReactNode }): JSX.Element {
return (
<QueryClientProvider client={queryClient}>
- <Router history={routerHistory}>
+ <TestRouter initialRoute={route}>
<ResourceProvider>{children}</ResourceProvider>
- </Router>
+ </TestRouter>
</QueryClientProvider>
);
}
@@ -98,8 +88,6 @@ function renderFilter(pathname: string): MemoryHistory {
<ResourceAttributesFilter />
</Wrapper>,
);
-
- return routerHistory;
}
describe('ResourceAttributesFilter', () => {
@@ -110,30 +98,30 @@ describe('ResourceAttributesFilter', () => {
tagKeysPayload(['resource_deployment.environment']),
);
mockTagValues.mockResolvedValue(tagValuesPayload(['production', 'staging']));
- seedUrl([], '/');
+ resetTestRoute();
});
it('shows every applied filter on the service map, including ones it cannot apply', async () => {
- seedUrl(
- [
- {
- id: 'svc',
- tagKey: 'resource_service_name',
- operator: 'IN',
- tagValue: ['frontend'],
- },
- {
- id: 'env',
- tagKey: 'resource_deployment.environment',
- operator: 'IN',
- tagValue: ['production'],
- },
- ],
- ROUTES.SERVICE_MAP,
+ renderFilter(
+ routeWithQueries(
+ [
+ {
+ id: 'svc',
+ tagKey: 'resource_service_name',
+ operator: 'IN',
+ tagValue: ['frontend'],
+ },
+ {
+ id: 'env',
+ tagKey: 'resource_deployment.environment',
+ operator: 'IN',
+ tagValue: ['production'],
+ },
+ ],
+ ROUTES.SERVICE_MAP,
+ ),
);
- renderFilter(ROUTES.SERVICE_MAP);
-
await waitFor(() =>
expect(screen.getByText(/service\.name/)).toBeInTheDocument(),
);
diff --git a/frontend/src/container/RolesSettings/CreateEditRolePage/CreateEditRolePage.tsx b/frontend/src/container/RolesSettings/CreateEditRolePage/CreateEditRolePage.tsx
index 5e7050feb5..4bd83c4d63 100644
--- a/frontend/src/container/RolesSettings/CreateEditRolePage/CreateEditRolePage.tsx
+++ b/frontend/src/container/RolesSettings/CreateEditRolePage/CreateEditRolePage.tsx
@@ -1,6 +1,8 @@
import { useCallback, useState } from 'react';
-import { matchPath, useHistory, useLocation } from 'react-router-dom';
import { ArrowLeft, SolidAlertTriangle } from '@signozhq/icons';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppNavigate } from 'lib/router/useAppNavigate';
+import { matchRoute } from 'lib/router/matchRoute';
import { Button } from '@signozhq/ui/button';
import { ConfirmDialog } from '@signozhq/ui/dialog';
import { Input } from '@signozhq/ui/input';
@@ -43,12 +45,10 @@ function authzCheckFn(
}
function CreateEditRolePageContent(): JSX.Element {
- const history = useHistory();
- const { pathname } = useLocation();
+ const navigate = useAppNavigate();
+ const { pathname } = useAppLocation();
const urlQuery = useUrlQuery();
- const match = matchPath<{ roleId: string }>(pathname, {
- path: ROUTES.ROLE_DETAILS,
- });
+ const match = matchRoute<'roleId'>(pathname, ROUTES.ROLE_DETAILS);
const roleId = match?.params?.roleId ?? 'new';
const roleName = urlQuery.get('name') ?? '';
const [hasJsonError, setHasJsonError] = useState(false);
@@ -85,16 +85,16 @@ function CreateEditRolePageContent(): JSX.Element {
if (success) {
allowNextNavigation();
if (isCreateMode) {
- history.push(ROUTES.ROLES_SETTINGS);
+ navigate(ROUTES.ROLES_SETTINGS);
} else {
const viewUrl = `${ROUTES.ROLE_DETAILS.replace(':roleId', roleId)}?name=${encodeURIComponent(roleName)}`;
- history.push(viewUrl);
+ navigate(viewUrl);
}
}
}, [
handleSave,
allowNextNavigation,
- history,
+ navigate,
hasJsonError,
isCreateMode,
roleId,
diff --git a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateEditRolePage.featureGate.test.tsx b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateEditRolePage.featureGate.test.tsx
index 10133f452d..48ac40f3b7 100644
--- a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateEditRolePage.featureGate.test.tsx
+++ b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateEditRolePage.featureGate.test.tsx
@@ -1,5 +1,3 @@
-import { Route, Switch } from 'react-router-dom';
-import ROUTES from 'constants/routes';
import { server } from 'mocks-server/server';
import { render, screen } from 'tests/test-utils';
import {
@@ -20,18 +18,10 @@ afterEach(() => {
function renderCreatePage(
appContextOverrides?: Record<string, unknown>,
): ReturnType<typeof render> {
- return render(
- <Switch>
- <Route path={ROUTES.ROLES_SETTINGS} exact>
- <div data-testid="roles-list-redirect" />
- </Route>
- <Route path={ROUTES.ROLE_CREATE}>
- <CreateEditRolePage />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: '/settings/roles/new', appContextOverrides },
- );
+ return render(<CreateEditRolePage />, undefined, {
+ initialRoute: '/settings/roles/new',
+ appContextOverrides,
+ });
}
function renderEditPage(
@@ -39,21 +29,10 @@ function renderEditPage(
roleName: string,
appContextOverrides?: Record<string, unknown>,
): ReturnType<typeof render> {
- return render(
- <Switch>
- <Route path={ROUTES.ROLES_SETTINGS} exact>
- <div data-testid="roles-list-redirect" />
- </Route>
- <Route path={ROUTES.ROLE_EDIT}>
- <CreateEditRolePage />
- </Route>
- </Switch>,
- undefined,
- {
- initialRoute: `/settings/roles/${roleId}/edit?name=${encodeURIComponent(roleName)}`,
- appContextOverrides,
- },
- );
+ return render(<CreateEditRolePage />, undefined, {
+ initialRoute: `/settings/roles/${roleId}/edit?name=${encodeURIComponent(roleName)}`,
+ appContextOverrides,
+ });
}
describe('CreateEditRolePage - Feature Gate', () => {
diff --git a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateRolePage.authz.test.tsx b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateRolePage.authz.test.tsx
index d7bdf26a27..4939f3c19b 100644
--- a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateRolePage.authz.test.tsx
+++ b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateRolePage.authz.test.tsx
@@ -1,5 +1,3 @@
-import { Route, Switch } from 'react-router-dom';
-import ROUTES from 'constants/routes';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen } from 'tests/test-utils';
@@ -15,18 +13,9 @@ afterEach(() => {
});
function renderCreatePage(): ReturnType<typeof render> {
- return render(
- <Switch>
- <Route path={ROUTES.ROLES_SETTINGS} exact>
- <div data-testid="roles-list-redirect" />
- </Route>
- <Route path={ROUTES.ROLE_CREATE}>
- <CreateEditRolePage />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: '/settings/roles/new' },
- );
+ return render(<CreateEditRolePage />, undefined, {
+ initialRoute: '/settings/roles/new',
+ });
}
describe('CreateRolePage - AuthZ', () => {
diff --git a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateRolePage.test.tsx b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateRolePage.test.tsx
index b882981414..fc4f5c795b 100644
--- a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateRolePage.test.tsx
+++ b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/CreateRolePage.test.tsx
@@ -1,9 +1,9 @@
-import { Route, Switch } from 'react-router-dom';
import ROUTES from 'constants/routes';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
+import { getCurrentLocation } from 'lib/router/navigation';
import CreateEditRolePage from '../CreateEditRolePage';
@@ -18,18 +18,9 @@ afterEach(() => {
});
async function renderCreatePage(): Promise<ReturnType<typeof render>> {
- const result = render(
- <Switch>
- <Route path={ROUTES.ROLES_SETTINGS} exact>
- <div data-testid="roles-list-redirect" />
- </Route>
- <Route path={ROUTES.ROLE_CREATE}>
- <CreateEditRolePage />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: '/settings/roles/new' },
- );
+ const result = render(<CreateEditRolePage />, undefined, {
+ initialRoute: '/settings/roles/new',
+ });
await screen.findByTestId('create-edit-role-page');
return result;
}
@@ -136,9 +127,9 @@ describe('CreateRolePage', () => {
const cancelBtn = screen.getByTestId('cancel-button');
await user.click(cancelBtn);
- await expect(
- screen.findByTestId('roles-list-redirect'),
- ).resolves.toBeInTheDocument();
+ await waitFor(() => {
+ expect(getCurrentLocation().pathname).toBe(ROUTES.ROLES_SETTINGS);
+ });
});
});
@@ -180,9 +171,9 @@ describe('CreateRolePage', () => {
);
});
- await expect(
- screen.findByTestId('roles-list-redirect'),
- ).resolves.toBeInTheDocument();
+ await waitFor(() => {
+ expect(getCurrentLocation().pathname).toBe(ROUTES.ROLES_SETTINGS);
+ });
});
});
diff --git a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/EditRolePage.authz.test.tsx b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/EditRolePage.authz.test.tsx
index 7503198546..65b9bcdb08 100644
--- a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/EditRolePage.authz.test.tsx
+++ b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/EditRolePage.authz.test.tsx
@@ -1,5 +1,3 @@
-import { Route, Switch } from 'react-router-dom';
-import ROUTES from 'constants/routes';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen } from 'tests/test-utils';
@@ -42,18 +40,9 @@ afterEach(() => {
});
function renderEditPage(): ReturnType<typeof render> {
- return render(
- <Switch>
- <Route path={ROUTES.ROLES_SETTINGS} exact>
- <div data-testid="roles-list-redirect" />
- </Route>
- <Route path={ROUTES.ROLE_DETAILS}>
- <CreateEditRolePage />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: `/settings/roles/${EDIT_ROLE_ID}?name=${EDIT_ROLE_NAME}` },
- );
+ return render(<CreateEditRolePage />, undefined, {
+ initialRoute: `/settings/roles/${EDIT_ROLE_ID}?name=${EDIT_ROLE_NAME}`,
+ });
}
describe('EditRolePage - AuthZ', () => {
@@ -115,18 +104,9 @@ describe('EditRolePage - AuthZ', () => {
it('renders the form instead of denying it', async () => {
server.use(setupAuthzAdmin());
- render(
- <Switch>
- <Route path={ROUTES.ROLES_SETTINGS} exact>
- <div data-testid="roles-list-redirect" />
- </Route>
- <Route path={ROUTES.ROLE_DETAILS}>
- <CreateEditRolePage />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: `/settings/roles/${EDIT_ROLE_ID}` },
- );
+ render(<CreateEditRolePage />, undefined, {
+ initialRoute: `/settings/roles/${EDIT_ROLE_ID}`,
+ });
await expect(
screen.findByTestId('role-description-input'),
diff --git a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/EditRolePage.test.tsx b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/EditRolePage.test.tsx
index 7f6029fb3e..564265df7e 100644
--- a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/EditRolePage.test.tsx
+++ b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/EditRolePage.test.tsx
@@ -1,15 +1,19 @@
-import { Route, Switch } from 'react-router-dom';
import ROUTES from 'constants/routes';
import { customRoleResponse } from 'mocks-server/__mockdata__/roles';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
+import { getCurrentLocation } from 'lib/router/navigation';
import CreateEditRolePage from '../CreateEditRolePage';
const CUSTOM_ROLE_ID = '019c24aa-3333-0001-aaaa-111111111111';
const rolesApiBase = '*/api/v1/roles';
+const VIEW_ROLE_URL = `${ROUTES.ROLE_DETAILS.replace(
+ ':roleId',
+ CUSTOM_ROLE_ID,
+)}?name=${encodeURIComponent('Custom Role')}`;
const roleWithTransactionGroups = {
status: 'success',
@@ -41,21 +45,9 @@ afterEach(() => {
});
function renderEditPage(roleId = CUSTOM_ROLE_ID): ReturnType<typeof render> {
- return render(
- <Switch>
- <Route path={ROUTES.ROLES_SETTINGS} exact>
- <div data-testid="roles-list-redirect" />
- </Route>
- <Route path={ROUTES.ROLE_DETAILS} exact>
- <div data-testid="role-details-redirect" />
- </Route>
- <Route path={ROUTES.ROLE_EDIT}>
- <CreateEditRolePage />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: `/settings/roles/${roleId}/edit?name=Custom%20Role` },
- );
+ return render(<CreateEditRolePage />, undefined, {
+ initialRoute: `/settings/roles/${roleId}/edit?name=Custom%20Role`,
+ });
}
describe('EditRolePage', () => {
@@ -144,9 +136,10 @@ describe('EditRolePage', () => {
const cancelButton = await screen.findByTestId('cancel-button');
await user.click(cancelButton);
- await expect(
- screen.findByTestId('role-details-redirect'),
- ).resolves.toBeInTheDocument();
+ await waitFor(() => {
+ const { pathname, search } = getCurrentLocation();
+ expect(`${pathname}${search}`).toBe(VIEW_ROLE_URL);
+ });
});
});
@@ -268,9 +261,10 @@ describe('EditRolePage', () => {
const cancelBtn = screen.getByTestId('cancel-button');
await user.click(cancelBtn);
- await expect(
- screen.findByTestId('role-details-redirect'),
- ).resolves.toBeInTheDocument();
+ await waitFor(() => {
+ const { pathname, search } = getCurrentLocation();
+ expect(`${pathname}${search}`).toBe(VIEW_ROLE_URL);
+ });
});
});
@@ -292,9 +286,10 @@ describe('EditRolePage', () => {
const saveBtn = screen.getByTestId('save-button');
await user.click(saveBtn);
- await expect(
- screen.findByTestId('role-details-redirect'),
- ).resolves.toBeInTheDocument();
+ await waitFor(() => {
+ const { pathname, search } = getCurrentLocation();
+ expect(`${pathname}${search}`).toBe(VIEW_ROLE_URL);
+ });
});
it('calls update API when save clicked', async () => {
diff --git a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/JsonEditor.test.tsx b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/JsonEditor.test.tsx
index d20e223559..f2b4228cec 100644
--- a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/JsonEditor.test.tsx
+++ b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/JsonEditor.test.tsx
@@ -1,5 +1,3 @@
-import { Route, Switch } from 'react-router-dom';
-import ROUTES from 'constants/routes';
import { server } from 'mocks-server/server';
import { render, screen, userEvent, within } from 'tests/test-utils';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
@@ -15,18 +13,9 @@ afterEach(() => {
});
function renderPage(): ReturnType<typeof render> {
- return render(
- <Switch>
- <Route path={ROUTES.ROLES_SETTINGS} exact>
- <div data-testid="roles-list-redirect" />
- </Route>
- <Route path={ROUTES.ROLE_CREATE}>
- <CreateEditRolePage />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: '/settings/roles/new' },
- );
+ return render(<CreateEditRolePage />, undefined, {
+ initialRoute: '/settings/roles/new',
+ });
}
async function switchToJsonMode(): Promise<void> {
diff --git a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/testUtils.tsx b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/testUtils.tsx
index 13752b7704..660358b953 100644
--- a/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/testUtils.tsx
+++ b/frontend/src/container/RolesSettings/CreateEditRolePage/__tests__/testUtils.tsx
@@ -1,5 +1,3 @@
-import { Route, Switch } from 'react-router-dom';
-import ROUTES from 'constants/routes';
import { render, screen, userEvent, within } from 'tests/test-utils';
import CreateEditRolePage from '../CreateEditRolePage';
@@ -7,18 +5,9 @@ import CreateEditRolePage from '../CreateEditRolePage';
export async function renderCreateRolePage(): Promise<
ReturnType<typeof render>
> {
- const result = render(
- <Switch>
- <Route path={ROUTES.ROLES_SETTINGS} exact>
- <div data-testid="roles-list-redirect" />
- </Route>
- <Route path={ROUTES.ROLE_CREATE}>
- <CreateEditRolePage />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: '/settings/roles/new' },
- );
+ const result = render(<CreateEditRolePage />, undefined, {
+ initialRoute: '/settings/roles/new',
+ });
await screen.findByTestId('permission-editor');
return result;
}
diff --git a/frontend/src/container/RolesSettings/CreateEditRolePage/useCreateEditRolePageActions.ts b/frontend/src/container/RolesSettings/CreateEditRolePage/useCreateEditRolePageActions.ts
index 914c027084..f67da467b4 100644
--- a/frontend/src/container/RolesSettings/CreateEditRolePage/useCreateEditRolePageActions.ts
+++ b/frontend/src/container/RolesSettings/CreateEditRolePage/useCreateEditRolePageActions.ts
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useHistory } from 'react-router-dom';
import { toast } from '@signozhq/ui/sonner';
+import { useAppNavigate } from 'lib/router/useAppNavigate';
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
import type { ErrorType } from 'api/generatedAPIInstance';
import ROUTES from 'constants/routes';
@@ -48,7 +48,7 @@ export function useCreateEditRolePageActions(
roleId: string,
roleName: string,
): UseCreateEditRolePageCallbacksResult {
- const history = useHistory();
+ const navigate = useAppNavigate();
const isCreateMode = roleId === 'new';
const [formData, setFormData] = useState<RoleFormData>({
@@ -215,12 +215,12 @@ export function useCreateEditRolePageActions(
const handleCancel = useCallback((): void => {
if (isCreateMode) {
- history.push(ROUTES.ROLES_SETTINGS);
+ navigate(ROUTES.ROLES_SETTINGS);
} else {
const viewUrl = `${ROUTES.ROLE_DETAILS.replace(':roleId', roleId)}?name=${encodeURIComponent(roleName)}`;
- history.push(viewUrl);
+ navigate(viewUrl);
}
- }, [history, isCreateMode, roleId, roleName]);
+ }, [navigate, isCreateMode, roleId, roleName]);
return {
formData,
diff --git a/frontend/src/container/RolesSettings/RolesComponents/RolesListingTable.tsx b/frontend/src/container/RolesSettings/RolesComponents/RolesListingTable.tsx
index 004977e439..59d0de1e72 100644
--- a/frontend/src/container/RolesSettings/RolesComponents/RolesListingTable.tsx
+++ b/frontend/src/container/RolesSettings/RolesComponents/RolesListingTable.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo } from 'react';
-import { useHistory } from 'react-router-dom';
import cx from 'classnames';
+import { useAppNavigate } from 'lib/router/useAppNavigate';
import { Pagination, Skeleton } from 'antd';
import { useListRoles } from 'api/generated/services/role';
import { AuthtypesGettableRoleDTO } from 'api/generated/services/sigNoz.schemas';
@@ -32,7 +32,7 @@ function RolesListContent({ searchQuery }: RolesListContentProps): JSX.Element {
const { data, isLoading, isError, error } = useListRoles();
const { formatTimezoneAdjustedTimestampOptional } = useTimezone();
- const history = useHistory();
+ const navigate = useAppNavigate();
const urlQuery = useUrlQuery();
const pageParam = parseInt(urlQuery.get('page') ?? '1', 10);
const currentPage = Number.isNaN(pageParam) || pageParam < 1 ? 1 : pageParam;
@@ -40,9 +40,9 @@ function RolesListContent({ searchQuery }: RolesListContentProps): JSX.Element {
const setCurrentPage = useCallback(
(page: number): void => {
urlQuery.set('page', String(page));
- history.replace({ search: urlQuery.toString() });
+ navigate({ search: urlQuery.toString() }, { replace: true });
},
- [history, urlQuery],
+ [navigate, urlQuery],
);
const roles = useMemo(() => data?.data ?? [], [data]);
@@ -130,10 +130,10 @@ function RolesListContent({ searchQuery }: RolesListContentProps): JSX.Element {
(roleId: string, roleName: string): void => {
if (isRolesEnabled) {
const url = `${ROUTES.ROLE_DETAILS.replace(':roleId', roleId)}?name=${encodeURIComponent(roleName)}`;
- history.push(url);
+ navigate(url);
}
},
- [isRolesEnabled, history],
+ [isRolesEnabled, navigate],
);
const showPaginationItem = (total: number, range: number[]): JSX.Element => (
diff --git a/frontend/src/container/RolesSettings/RolesComponents/__tests__/RolesListingTable.pagination.test.tsx b/frontend/src/container/RolesSettings/RolesComponents/__tests__/RolesListingTable.pagination.test.tsx
new file mode 100644
index 0000000000..fcda718751
--- /dev/null
+++ b/frontend/src/container/RolesSettings/RolesComponents/__tests__/RolesListingTable.pagination.test.tsx
@@ -0,0 +1,45 @@
+import userEvent from '@testing-library/user-event';
+import { customRoles } from 'mocks-server/__mockdata__/roles';
+import { server } from 'mocks-server/server';
+import { rest } from 'msw';
+import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
+import { getCurrentLocation } from 'lib/router/navigation';
+import { render, screen, waitFor } from 'tests/test-utils';
+
+import RolesListingTable from '../RolesListingTable';
+
+const manyRoles = Array.from({ length: 25 }, (_, index) => ({
+ ...customRoles[0],
+ id: `custom-role-${index}`,
+ name: `custom-role-${index}`,
+}));
+
+beforeEach(() => {
+ server.use(
+ setupAuthzAdmin(),
+ rest.get('*/api/v1/roles', (_req, res, ctx) =>
+ res(ctx.status(200), ctx.json({ status: 'success', data: manyRoles })),
+ ),
+ );
+});
+
+afterEach(() => {
+ server.resetHandlers();
+});
+
+describe('RolesListingTable - pagination', () => {
+ it('writes the page into the search and keeps the pathname', async () => {
+ const user = userEvent.setup();
+ render(<RolesListingTable searchQuery="" />, undefined, {
+ initialRoute: '/settings/roles',
+ });
+
+ await screen.findByText('custom-role-0');
+ await user.click(screen.getByTitle('2'));
+
+ await waitFor(() => {
+ expect(getCurrentLocation().search).toBe('?page=2');
+ });
+ expect(getCurrentLocation().pathname).toBe('/settings/roles');
+ });
+});
diff --git a/frontend/src/container/RolesSettings/RolesSettings.tsx b/frontend/src/container/RolesSettings/RolesSettings.tsx
index a44edbac82..57386e20e3 100644
--- a/frontend/src/container/RolesSettings/RolesSettings.tsx
+++ b/frontend/src/container/RolesSettings/RolesSettings.tsx
@@ -1,6 +1,6 @@
import { useState } from 'react';
-import { useHistory } from 'react-router-dom';
import { Plus } from '@signozhq/icons';
+import { useAppNavigate } from 'lib/router/useAppNavigate';
import { Input } from '@signozhq/ui/input';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
@@ -17,7 +17,7 @@ import styles from './RolesSettings.module.scss';
function RolesSettings(): JSX.Element {
const [searchQuery, setSearchQuery] = useState('');
- const history = useHistory();
+ const navigate = useAppNavigate();
const { isRolesEnabled } = useRolesFeatureGate();
return (
@@ -60,7 +60,7 @@ function RolesSettings(): JSX.Element {
variant="solid"
color="primary"
width={156}
- onClick={(): void => history.push(ROUTES.ROLE_CREATE)}
+ onClick={(): void => navigate(ROUTES.ROLE_CREATE)}
prefix={<Plus size={14} />}
>
Custom role
diff --git a/frontend/src/container/RolesSettings/ViewRolePage/__tests__/ViewRolePage.actions.test.tsx b/frontend/src/container/RolesSettings/ViewRolePage/__tests__/ViewRolePage.actions.test.tsx
index 9c35eae05d..93a2ee01cd 100644
--- a/frontend/src/container/RolesSettings/ViewRolePage/__tests__/ViewRolePage.actions.test.tsx
+++ b/frontend/src/container/RolesSettings/ViewRolePage/__tests__/ViewRolePage.actions.test.tsx
@@ -1,7 +1,8 @@
-import { Route, Switch } from 'react-router-dom';
import userEvent from '@testing-library/user-event';
import * as roleApi from 'api/generated/services/role';
+import ROUTES from 'constants/routes';
import { render, screen, waitFor, within } from 'tests/test-utils';
+import { getCurrentLocation } from 'lib/router/navigation';
import ViewRolePage from '../ViewRolePage';
@@ -24,42 +25,24 @@ describe('ViewRolePage - Actions', () => {
it('navigates to roles list when Cancel clicked', async () => {
const user = userEvent.setup();
- render(
- <Switch>
- <Route path="/settings/roles/:roleId">
- <ViewRolePage />
- </Route>
- <Route path="/settings/roles">
- <div data-testid="roles-list-target" />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: buildViewRoleRoute(CUSTOM_ROLE_ID, CUSTOM_ROLE_NAME) },
- );
+ render(<ViewRolePage />, undefined, {
+ initialRoute: buildViewRoleRoute(CUSTOM_ROLE_ID, CUSTOM_ROLE_NAME),
+ });
const cancelBtn = await screen.findByTestId('cancel-button');
await user.click(cancelBtn);
- await expect(
- screen.findByTestId('roles-list-target'),
- ).resolves.toBeInTheDocument();
+ await waitFor(() => {
+ expect(getCurrentLocation().pathname).toBe(ROUTES.ROLES_SETTINGS);
+ });
});
it('navigates to edit page when Update clicked', async () => {
const user = userEvent.setup();
- render(
- <Switch>
- <Route path="/settings/roles/:roleId/edit">
- <div data-testid="edit-page-target" />
- </Route>
- <Route path="/settings/roles/:roleId">
- <ViewRolePage />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: buildViewRoleRoute(CUSTOM_ROLE_ID, CUSTOM_ROLE_NAME) },
- );
+ render(<ViewRolePage />, undefined, {
+ initialRoute: buildViewRoleRoute(CUSTOM_ROLE_ID, CUSTOM_ROLE_NAME),
+ });
const updateBtn = await screen.findByTestId('save-button');
await waitFor(() => {
@@ -67,9 +50,12 @@ describe('ViewRolePage - Actions', () => {
});
await user.click(updateBtn);
- await expect(
- screen.findByTestId('edit-page-target'),
- ).resolves.toBeInTheDocument();
+ await waitFor(() => {
+ const { pathname, search } = getCurrentLocation();
+ expect(`${pathname}${search}`).toBe(
+ `${ROUTES.ROLE_EDIT.replace(':roleId', CUSTOM_ROLE_ID)}?name=${CUSTOM_ROLE_NAME}`,
+ );
+ });
});
it('opens delete modal when Delete clicked', async () => {
@@ -98,18 +84,9 @@ describe('ViewRolePage - Actions', () => {
mutateAsync: mockDeleteRole,
} as unknown as ReturnType<typeof roleApi.useDeleteRole>);
- render(
- <Switch>
- <Route path="/settings/roles/:roleId">
- <ViewRolePage />
- </Route>
- <Route path="/settings/roles">
- <div data-testid="roles-list-target" />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: buildViewRoleRoute(CUSTOM_ROLE_ID, CUSTOM_ROLE_NAME) },
- );
+ render(<ViewRolePage />, undefined, {
+ initialRoute: buildViewRoleRoute(CUSTOM_ROLE_ID, CUSTOM_ROLE_NAME),
+ });
const deleteBtn = await screen.findByTestId('delete-button');
await waitFor(() => {
@@ -133,8 +110,8 @@ describe('ViewRolePage - Actions', () => {
});
});
- await expect(
- screen.findByTestId('roles-list-target'),
- ).resolves.toBeInTheDocument();
+ await waitFor(() => {
+ expect(getCurrentLocation().pathname).toBe(ROUTES.ROLES_SETTINGS);
+ });
});
});
diff --git a/frontend/src/container/RolesSettings/ViewRolePage/__tests__/ViewRolePage.error.test.tsx b/frontend/src/container/RolesSettings/ViewRolePage/__tests__/ViewRolePage.error.test.tsx
index e476a078da..9b63b84584 100644
--- a/frontend/src/container/RolesSettings/ViewRolePage/__tests__/ViewRolePage.error.test.tsx
+++ b/frontend/src/container/RolesSettings/ViewRolePage/__tests__/ViewRolePage.error.test.tsx
@@ -1,10 +1,11 @@
-import { Route, Switch } from 'react-router-dom';
import userEvent from '@testing-library/user-event';
import * as roleApi from 'api/generated/services/role';
+import ROUTES from 'constants/routes';
import { customRoleResponse } from 'mocks-server/__mockdata__/roles';
import { server } from 'mocks-server/server';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
-import { render, screen } from 'tests/test-utils';
+import { render, screen, waitFor } from 'tests/test-utils';
+import { getCurrentLocation } from 'lib/router/navigation';
import * as useRolePermissionsModule from '../../hooks/useRolePermissions';
import ViewRolePage from '../ViewRolePage';
@@ -95,24 +96,15 @@ describe('ViewRolePage - Error State', () => {
error: new Error('Failed to fetch role'),
} as ReturnType<typeof roleApi.useGetRole>);
- render(
- <Switch>
- <Route path="/settings/roles/:roleId">
- <ViewRolePage />
- </Route>
- <Route path="/settings/roles">
- <div data-testid="roles-list-target" />
- </Route>
- </Switch>,
- undefined,
- { initialRoute: buildViewRoleRoute(CUSTOM_ROLE_ID, CUSTOM_ROLE_NAME) },
- );
+ render(<ViewRolePage />, undefined, {
+ initialRoute: buildViewRoleRoute(CUSTOM_ROLE_ID, CUSTOM_ROLE_NAME),
+ });
const cancelButton = await screen.findByTestId('cancel-button');
await user.click(cancelButton);
- await expect(
- screen.findByTestId('roles-list-target'),
- ).resolves.toBeInTheDocument();
+ await waitFor(() => {
+ expect(getCurrentLocation().pathname).toBe(ROUTES.ROLES_SETTINGS);
+ });
});
});
diff --git a/frontend/src/container/RolesSettings/ViewRolePage/useViewRolePageActions.ts b/frontend/src/container/RolesSettings/ViewRolePage/useViewRolePageActions.ts
index 80cbb4f097..cf37ccc6c1 100644
--- a/frontend/src/container/RolesSettings/ViewRolePage/useViewRolePageActions.ts
+++ b/frontend/src/container/RolesSettings/ViewRolePage/useViewRolePageActions.ts
@@ -1,6 +1,8 @@
import { useCallback, useState } from 'react';
-import { matchPath, useHistory, useLocation } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppNavigate } from 'lib/router/useAppNavigate';
+import { matchRoute } from 'lib/router/matchRoute';
import useUrlQuery from 'hooks/useUrlQuery';
import { parseAsStringLiteral, useQueryState } from 'nuqs';
@@ -24,13 +26,11 @@ interface UseViewRolePageCallbacksResult {
}
export function useViewRolePageActions(): UseViewRolePageCallbacksResult {
- const { pathname } = useLocation();
- const history = useHistory();
+ const { pathname } = useAppLocation();
+ const navigate = useAppNavigate();
const urlQuery = useUrlQuery();
- const match = matchPath<{ roleId: string }>(pathname, {
- path: ROUTES.ROLE_DETAILS,
- });
+ const match = matchRoute<'roleId'>(pathname, ROUTES.ROLE_DETAILS);
const roleId = match?.params?.roleId;
const roleName = urlQuery.get('name') ?? '';
@@ -52,12 +52,12 @@ export function useViewRolePageActions(): UseViewRolePageCallbacksResult {
}
const updateUrl = `${ROUTES.ROLE_EDIT.replace(':roleId', roleId)}?name=${roleName}`;
- history.push(updateUrl);
- }, [history, roleId, roleName]);
+ navigate(updateUrl);
+ }, [navigate, roleId, roleName]);
const handleCancel = useCallback((): void => {
- history.push(ROUTES.ROLES_SETTINGS);
- }, [history]);
+ navigate(ROUTES.ROLES_SETTINGS);
+ }, [navigate]);
const handleModeChange = useCallback(
(value: string): void => {
diff --git a/frontend/src/container/RoutingPolicies/__tests__/useRoutingPolicies.test.tsx b/frontend/src/container/RoutingPolicies/__tests__/useRoutingPolicies.test.tsx
index 64c9e3d7ee..93996d1173 100644
--- a/frontend/src/container/RoutingPolicies/__tests__/useRoutingPolicies.test.tsx
+++ b/frontend/src/container/RoutingPolicies/__tests__/useRoutingPolicies.test.tsx
@@ -1,5 +1,4 @@
import { QueryClient, QueryClientProvider, UseQueryResult } from 'react-query';
-import { Router } from 'react-router-dom';
import {
act,
renderHook,
@@ -7,7 +6,7 @@ import {
waitFor,
} from '@testing-library/react';
import { GetRoutingPoliciesResponse } from 'api/routingPolicies/getRoutingPolicies';
-import { createMemoryHistory } from 'history';
+import { TestRouter } from 'tests/router';
import { SuccessResponseV2 } from 'types/api';
import { UseRoutingPoliciesReturn } from '../types';
@@ -20,13 +19,10 @@ import {
MOCK_ROUTING_POLICY_2,
} from './testUtils';
-const mockHistoryReplace = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: (): any => ({
- ...jest.requireActual('react-router-dom').useHistory(),
- replace: mockHistoryReplace,
- }),
+const mockNavigate = jest.fn();
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: (...args: unknown[]): void => mockNavigate(...args),
}));
const mockDebouncedFn = jest.fn((fn: () => void) => fn);
@@ -94,17 +90,15 @@ describe('useRoutingPolicies', () => {
let queryClient: QueryClient;
const renderHookWithWrapper = (
- initialEntries: string[] = ['/alerts'],
+ initialRoute = '/alerts',
): RenderHookResult<UseRoutingPoliciesReturn, unknown> => {
- const history = createMemoryHistory({ initialEntries });
-
const wrapper = ({
children,
}: {
children: React.ReactNode;
}): React.ReactElement => (
<QueryClientProvider client={queryClient}>
- <Router history={history}>{children}</Router>
+ <TestRouter initialRoute={initialRoute}>{children}</TestRouter>
</QueryClientProvider>
);
@@ -175,9 +169,9 @@ describe('useRoutingPolicies', () => {
});
it('should initialize search term from URL query parameter', () => {
- const { result } = renderHookWithWrapper([
+ const { result } = renderHookWithWrapper(
`/alerts?search=${encodeURIComponent(ROUTING_POLICY_1_NAME)}`,
- ]);
+ );
expect(result.current.searchTerm).toBe(ROUTING_POLICY_1_NAME);
expect(result.current.routingPoliciesData).toHaveLength(1);
@@ -187,7 +181,7 @@ describe('useRoutingPolicies', () => {
});
it('should initialize with empty search when no search param in URL', () => {
- const { result } = renderHookWithWrapper(['/alerts']);
+ const { result } = renderHookWithWrapper('/alerts');
expect(result.current.searchTerm).toBe('');
expect(result.current.routingPoliciesData).toHaveLength(2);
@@ -201,25 +195,25 @@ describe('useRoutingPolicies', () => {
});
await waitFor(() => {
- expect(mockHistoryReplace).toHaveBeenCalled();
+ expect(mockNavigate).toHaveBeenCalled();
});
- const callArg = mockHistoryReplace.mock.calls[0][0];
+ const callArg = mockNavigate.mock.calls[0][0];
expect(callArg).toContain('search=test+search');
});
it('should remove search param from URL when search is cleared', async () => {
- const { result } = renderHookWithWrapper(['/alerts?search=existing']);
+ const { result } = renderHookWithWrapper('/alerts?search=existing');
act(() => {
result.current.setSearchTerm('');
});
await waitFor(() => {
- expect(mockHistoryReplace).toHaveBeenCalled();
+ expect(mockNavigate).toHaveBeenCalled();
});
- const callArg = mockHistoryReplace.mock.calls[0][0];
+ const callArg = mockNavigate.mock.calls[0][0];
expect(callArg).toBe('/alerts?');
});
diff --git a/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts b/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts
index 761306a5bc..12ebe1c3a2 100644
--- a/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts
+++ b/frontend/src/container/RoutingPolicies/useRoutingPolicies.ts
@@ -1,6 +1,6 @@
import { useCallback, useMemo, useState } from 'react';
import { useQueryClient } from 'react-query';
-import { useHistory } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
import { toast } from '@signozhq/ui/sonner';
import { GetRoutingPoliciesResponse } from 'api/routingPolicies/getRoutingPolicies';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
@@ -30,7 +30,6 @@ import './styles.scss';
function useRoutingPolicies(): UseRoutingPoliciesReturn {
const queryClient = useQueryClient();
const urlQuery = useUrlQuery();
- const history = useHistory();
// Local state
const [searchTerm, setSearchTerm] = useState(urlQuery.get('search') || '');
@@ -51,7 +50,7 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
urlQuery.delete('search');
}
const url = `/alerts?${urlQuery.toString()}`;
- history.replace(url);
+ navigate(url, { replace: true });
}, 300);
const handleSearch = (value: string): void => {
diff --git a/frontend/src/container/SavedViews/__tests__/savedViewsTestUtils.tsx b/frontend/src/container/SavedViews/__tests__/savedViewsTestUtils.tsx
index 0a5292aee4..b5b08cfc42 100644
--- a/frontend/src/container/SavedViews/__tests__/savedViewsTestUtils.tsx
+++ b/frontend/src/container/SavedViews/__tests__/savedViewsTestUtils.tsx
@@ -2,8 +2,6 @@ import { ReactElement, useEffect, useMemo } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { Router } from 'react-router-dom';
-import { CompatRouter } from 'react-router-dom-v5-compat';
import { render, RenderResult } from '@testing-library/react';
import { safeNavigateMock } from '__tests__/safeNavigateMock';
import {
@@ -14,10 +12,10 @@ import {
} from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
-import { createMemoryHistory, MemoryHistory } from 'history';
import { useGetPanelTypesQueryParam } from 'hooks/queryBuilder/useGetPanelTypesQueryParam';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
+import { navigate } from 'lib/router/navigation';
import { NuqsAdapter } from 'nuqs/adapters/react';
import { AppContext } from 'providers/App/App';
import { PreferenceContextProvider } from 'providers/preferences/context/PreferenceContextProvider';
@@ -26,6 +24,7 @@ import TimezoneProvider from 'providers/Timezone';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { getAppContextMock } from 'tests/test-utils';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
@@ -183,30 +182,30 @@ function ExplorerShell({ dataSource }: { dataSource: DataSource }): null {
return null;
}
+export interface ExplorerUrl {
+ push: (url: string) => void;
+ location: Pick<Location, 'pathname' | 'search'>;
+}
+
export function renderWithExplorerProviders(
ui: ReactElement,
initialUrl: string,
dataSource: DataSource = DataSource.TRACES,
-): RenderResult & { history: MemoryHistory } {
- const history = createMemoryHistory({ initialEntries: [initialUrl] });
- // Parts of the explorer read window.location directly, so it follows the
- // router's history.
- const syncWindowLocation = (): void =>
- window.history.replaceState(
- null,
- '',
- `${history.location.pathname}${history.location.search}`,
- );
- syncWindowLocation();
- history.listen(syncWindowLocation);
+): RenderResult & { history: ExplorerUrl } {
+ const history: ExplorerUrl = {
+ push: (url) => navigate(url),
+ get location() {
+ return window.location;
+ },
+ };
__setSearchParamsGetterForTest(
- () => new URLSearchParams(history.location.search),
+ () => new URLSearchParams(window.location.search),
);
safeNavigateMock.mockImplementation((to) => {
- history.push(
+ navigate(
typeof to === 'string'
? to
- : `${to.pathname ?? history.location.pathname}${to.search ?? ''}`,
+ : `${to.pathname ?? window.location.pathname}${to.search ?? ''}`,
);
});
@@ -224,31 +223,29 @@ export function renderWithExplorerProviders(
};
const result = render(
- <Router history={history}>
- <CompatRouter>
- <NuqsAdapter>
- <QueryClientProvider client={queryClient}>
- <Provider store={mockStore(store.getState())}>
- <AppContext.Provider value={appContext}>
- <TimezoneProvider>
- <PreferenceContextProvider>
- <QueryBuilderProvider>
- <ExplorerShell dataSource={dataSource} />
- {ui}
- </QueryBuilderProvider>
- </PreferenceContextProvider>
- </TimezoneProvider>
- </AppContext.Provider>
- </Provider>
- </QueryClientProvider>
- </NuqsAdapter>
- </CompatRouter>
- </Router>,
+ <TestRouter initialRoute={initialUrl}>
+ <NuqsAdapter>
+ <QueryClientProvider client={queryClient}>
+ <Provider store={mockStore(store.getState())}>
+ <AppContext.Provider value={appContext}>
+ <TimezoneProvider>
+ <PreferenceContextProvider>
+ <QueryBuilderProvider>
+ <ExplorerShell dataSource={dataSource} />
+ {ui}
+ </QueryBuilderProvider>
+ </PreferenceContextProvider>
+ </TimezoneProvider>
+ </AppContext.Provider>
+ </Provider>
+ </QueryClientProvider>
+ </NuqsAdapter>
+ </TestRouter>,
);
return { ...result, history };
}
-export function urlParam(history: MemoryHistory, key: string): string | null {
+export function urlParam(history: ExplorerUrl, key: string): string | null {
return new URLSearchParams(history.location.search).get(key);
}
diff --git a/frontend/src/container/SavedViews/hooks/useSavedViewActions.ts b/frontend/src/container/SavedViews/hooks/useSavedViewActions.ts
index caaa3f9bb1..d7dda584e5 100644
--- a/frontend/src/container/SavedViews/hooks/useSavedViewActions.ts
+++ b/frontend/src/container/SavedViews/hooks/useSavedViewActions.ts
@@ -1,6 +1,5 @@
import { useCallback } from 'react';
import { useQueryClient } from 'react-query';
-import { useLocation } from 'react-router-dom';
import { toast } from '@signozhq/ui/sonner';
import {
useCreateSavedView,
@@ -20,6 +19,7 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useGetSavedViewParams } from 'hooks/saveViews/useGetSavedViewParams';
import { useHandleExplorerTabChange } from 'hooks/useHandleExplorerTabChange';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
import { DataSource } from 'types/common/queryBuilder';
import { toAPIError } from 'utils/errorUtils';
@@ -51,7 +51,7 @@ export function useSavedViewActions(
source: SavedviewtypesSourceDTO,
): UseSavedViewActionsResult {
const queryClient = useQueryClient();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const { safeNavigate } = useSafeNavigate();
const { currentQuery, stagedQuery, panelType, redirectWithQueryBuilderData } =
useQueryBuilder();
diff --git a/frontend/src/container/SavedViews/hooks/useSavedViewRowActions.ts b/frontend/src/container/SavedViews/hooks/useSavedViewRowActions.ts
index 9995dbe00f..73c750dd11 100644
--- a/frontend/src/container/SavedViews/hooks/useSavedViewRowActions.ts
+++ b/frontend/src/container/SavedViews/hooks/useSavedViewRowActions.ts
@@ -1,6 +1,5 @@
import { useCallback } from 'react';
import { useQueryClient } from 'react-query';
-import { useLocation } from 'react-router-dom';
import { useCopyToClipboard } from 'react-use';
import { toast } from '@signozhq/ui/sonner';
import {
@@ -15,6 +14,7 @@ import {
import { ErrorType } from 'api/generatedAPIInstance';
import { QueryParams } from 'constants/query';
import { buildExplorerNavigationUrl } from 'container/AIAssistant/components/ActionsSection/utils/openSavedView';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { getAbsoluteUrl } from 'utils/basePath';
import { toAPIError } from 'utils/errorUtils';
@@ -42,7 +42,7 @@ export function useSavedViewRowActions(
source: SavedviewtypesSourceDTO,
): UseSavedViewRowActionsResult {
const queryClient = useQueryClient();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const [, copyToClipboard] = useCopyToClipboard();
const logSavedViewEvent = useSavedViewLogEvent(source);
const { mutateAsync: updateSavedView, isLoading: isRenaming } =
diff --git a/frontend/src/container/ServiceApplication/Columns/GetColumnSearchProps.tsx b/frontend/src/container/ServiceApplication/Columns/GetColumnSearchProps.tsx
index 9793a6f3c4..dd9a879214 100644
--- a/frontend/src/container/ServiceApplication/Columns/GetColumnSearchProps.tsx
+++ b/frontend/src/container/ServiceApplication/Columns/GetColumnSearchProps.tsx
@@ -1,11 +1,11 @@
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import { Info, Search } from '@signozhq/icons';
import { Popconfirm, PopconfirmProps } from 'antd';
import type { ColumnType } from 'antd/es/table';
import ROUTES from 'constants/routes';
import { routeConfig } from 'container/SideNav/config';
import { getQueryString } from 'container/SideNav/helper';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { ServicesList } from 'types/api/metrics/getService';
import { filterDropdown } from '../Filter/FilterDropdown';
@@ -49,7 +49,7 @@ export const getColumnSearchProps = (
const topLevelOperations = record?.dataWarning?.topLevelOps || [];
const handleShowTopLevelOperations: PopconfirmProps['onConfirm'] = () => {
- history.push(
+ navigate(
`${ROUTES.APPLICATION}/${encodeURIComponent(metrics)}/top-level-operations`,
);
};
@@ -76,13 +76,13 @@ export const getColumnSearchProps = (
</Popconfirm>
)}
- <Link
+ <AppLink
to={`${ROUTES.APPLICATION}/${encodeURIComponent(
metrics,
)}?${queryString.join('')}`}
>
{metrics}
- </Link>
+ </AppLink>
</div>
);
},
diff --git a/frontend/src/container/ServiceApplication/ServiceMetrics/ServiceMetricTable.tsx b/frontend/src/container/ServiceApplication/ServiceMetrics/ServiceMetricTable.tsx
index fc2786d5ad..7ca68f420e 100644
--- a/frontend/src/container/ServiceApplication/ServiceMetrics/ServiceMetricTable.tsx
+++ b/frontend/src/container/ServiceApplication/ServiceMetrics/ServiceMetricTable.tsx
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { SolidAlertTriangle } from '@signozhq/icons';
import { Flex } from 'antd';
import { Typography } from '@signozhq/ui/typography';
@@ -70,7 +70,7 @@ function ServiceMetricTable({
useServicesStripInfo(services.length);
- const { search } = useLocation();
+ const { search } = useAppLocation();
const tableColumns = useMemo(() => getColumns(search, true), [search]);
const [RPS, setRPS] = useState(0);
diff --git a/frontend/src/container/ServiceApplication/ServiceTraces/ServiceTracesTable.tsx b/frontend/src/container/ServiceApplication/ServiceTraces/ServiceTracesTable.tsx
index ec91bbbe06..e505cc6fa8 100644
--- a/frontend/src/container/ServiceApplication/ServiceTraces/ServiceTracesTable.tsx
+++ b/frontend/src/container/ServiceApplication/ServiceTraces/ServiceTracesTable.tsx
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Flex } from 'antd';
import { SolidAlertTriangle } from '@signozhq/icons';
import { Typography } from '@signozhq/ui/typography';
@@ -18,7 +18,7 @@ function ServiceTraceTable({
services,
loading,
}: ServiceTableProps): JSX.Element {
- const { search } = useLocation();
+ const { search } = useAppLocation();
const [RPS, setRPS] = useState(0);
const { t: getText } = useTranslation(['services']);
diff --git a/frontend/src/container/ServiceTable/Columns/GetColumnSearchProps.tsx b/frontend/src/container/ServiceTable/Columns/GetColumnSearchProps.tsx
index 5de9ec0953..53b17ca924 100644
--- a/frontend/src/container/ServiceTable/Columns/GetColumnSearchProps.tsx
+++ b/frontend/src/container/ServiceTable/Columns/GetColumnSearchProps.tsx
@@ -1,4 +1,4 @@
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import { Search } from '@signozhq/icons';
import type { ColumnType } from 'antd/es/table';
import ROUTES from 'constants/routes';
@@ -34,9 +34,9 @@ export const getColumnSearchProps = (
const queryString = getQueryString(avialableParams, urlParams);
return (
- <Link to={`${ROUTES.APPLICATION}/${metrics}?${queryString.join('')}`}>
+ <AppLink to={`${ROUTES.APPLICATION}/${metrics}?${queryString.join('')}`}>
<Name>{metrics}</Name>
- </Link>
+ </AppLink>
);
},
});
diff --git a/frontend/src/container/ServiceTable/index.tsx b/frontend/src/container/ServiceTable/index.tsx
index a890038e69..dd6c91da10 100644
--- a/frontend/src/container/ServiceTable/index.tsx
+++ b/frontend/src/container/ServiceTable/index.tsx
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { ResizeTable } from 'components/ResizeTable';
import { getColumns } from './Columns/ServiceColumn';
@@ -7,7 +7,7 @@ import { Container } from './styles';
import ServiceTableProp from './types';
function Services({ services, isLoading }: ServiceTableProp): JSX.Element {
- const { search } = useLocation();
+ const { search } = useAppLocation();
const tableColumns = useMemo(() => getColumns(search), [search]);
diff --git a/frontend/src/container/SideNav/SideNav.tsx b/frontend/src/container/SideNav/SideNav.tsx
index 316d9a7a9c..66d3a2955a 100644
--- a/frontend/src/container/SideNav/SideNav.tsx
+++ b/frontend/src/container/SideNav/SideNav.tsx
@@ -10,7 +10,7 @@ import {
import { useMutation } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import {
closestCenter,
DndContext,
@@ -41,7 +41,7 @@ import useComponentPermission from 'hooks/useComponentPermission';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { useNotifications } from 'hooks/useNotifications';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { isArray } from 'lodash-es';
import {
ArrowUpRight,
@@ -126,7 +126,7 @@ function SortableFilter({ item }: { item: SidebarItem }): JSX.Element {
// eslint-disable-next-line sonarjs/cognitive-complexity
function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
const { openCmdK } = useCmdK();
- const { pathname, search } = useLocation();
+ const { pathname, search } = useAppLocation();
const { currentVersion, latestVersion, isCurrentVersionError } = useSelector<
AppState,
AppReducer
@@ -472,7 +472,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
if (isModifierKeyPressed(event)) {
openInNewTab(ROUTES.GET_STARTED_WITH_CLOUD);
} else {
- history.push(ROUTES.GET_STARTED_WITH_CLOUD);
+ navigate(ROUTES.GET_STARTED_WITH_CLOUD);
}
};
@@ -488,8 +488,8 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
if (event && isModifierKeyPressed(event)) {
openInNewTab(url);
} else {
- history.push(url, {
- from: pathname,
+ navigate(url, {
+ state: { from: pathname },
});
}
}
@@ -637,7 +637,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
if (isModifierKeyPressed(event)) {
openInNewTab(settingsRoute);
} else {
- history.push(settingsRoute);
+ navigate(settingsRoute);
}
} else if (item.key === 'quick-search') {
openCmdK();
@@ -655,7 +655,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
if (isModifierKeyPressed(event)) {
openInNewTab(aiPath);
} else {
- history.push(aiPath);
+ navigate(aiPath);
}
} else if (item) {
onClickHandler(item?.key as string, event);
@@ -848,14 +848,14 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
if (event && isModifierKeyPressed(event)) {
openInNewTab(ROUTES.SHORTCUTS);
} else {
- history.push(ROUTES.SHORTCUTS);
+ navigate(ROUTES.SHORTCUTS);
}
break;
case 'invite-collaborators':
if (event && isModifierKeyPressed(event)) {
openInNewTab(`${ROUTES.MEMBERS_SETTINGS}?invite=true`);
} else {
- history.push(`${ROUTES.MEMBERS_SETTINGS}?invite=true`);
+ navigate(`${ROUTES.MEMBERS_SETTINGS}?invite=true`);
}
break;
case 'chat-support':
@@ -888,28 +888,28 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
if (isModifierKeyPressed(event)) {
openInNewTab(ROUTES.MY_SETTINGS);
} else {
- history.push(ROUTES.MY_SETTINGS);
+ navigate(ROUTES.MY_SETTINGS);
}
break;
case 'workspace':
if (isModifierKeyPressed(event)) {
openInNewTab(ROUTES.SETTINGS);
} else {
- history.push(ROUTES.SETTINGS);
+ navigate(ROUTES.SETTINGS);
}
break;
case 'license':
if (isModifierKeyPressed(event)) {
openInNewTab(ROUTES.LIST_LICENSES);
} else {
- history.push(ROUTES.LIST_LICENSES);
+ navigate(ROUTES.LIST_LICENSES);
}
break;
case 'keyboard-shortcuts':
if (isModifierKeyPressed(event)) {
openInNewTab(ROUTES.SHORTCUTS);
} else {
- history.push(ROUTES.SHORTCUTS);
+ navigate(ROUTES.SHORTCUTS);
}
break;
case 'logout':
diff --git a/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx b/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx
index 3b096c3d9a..7e506395ab 100644
--- a/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx
+++ b/frontend/src/container/TimeSeriesView/TimeSeriesView.tsx
@@ -10,7 +10,7 @@ import {
} from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import cx from 'classnames';
import logEvent from 'api/common/logEvent';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
@@ -32,7 +32,7 @@ import { useResizeObserver } from 'hooks/useDimensions';
import useUrlQuery from 'hooks/useUrlQuery';
import GetMinMax from 'lib/getMinMax';
import getTimeString from 'lib/getTimeString';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { stackSeries } from 'lib/visualization/charts/utils/stackSeriesUtils';
import { getUPlotChartOptions } from 'lib/uPlotLib/getUplotChartOptions';
import { getUPlotChartData } from 'lib/uPlotLib/utils/getUplotChartData';
@@ -74,7 +74,7 @@ function TimeSeriesView({
const dispatch = useDispatch();
const urlQuery = useUrlQuery();
- const location = useLocation();
+ const location = useAppLocation();
const { currentQuery } = useQueryBuilder();
const rawChartData = useMemo(
@@ -159,7 +159,7 @@ function TimeSeriesView({
urlQuery.set(QueryParams.endTime, maxTime.toString());
urlQuery.delete(QueryParams.relativeTime);
const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
},
[dispatch, location.pathname, urlQuery],
);
diff --git a/frontend/src/container/TimeSeriesView/__tests__/TimeSeriesView.test.tsx b/frontend/src/container/TimeSeriesView/__tests__/TimeSeriesView.test.tsx
index 2ed5059449..e3d40196fc 100644
--- a/frontend/src/container/TimeSeriesView/__tests__/TimeSeriesView.test.tsx
+++ b/frontend/src/container/TimeSeriesView/__tests__/TimeSeriesView.test.tsx
@@ -1,9 +1,9 @@
import { render } from '@testing-library/react';
-import { MemoryRouter } from 'react-router-dom';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import store from 'store';
+import { TestRouter } from 'tests/router';
import { DataSource } from 'types/common/queryBuilder';
import TimeSeriesView from '../TimeSeriesView';
@@ -88,7 +88,7 @@ function renderView(props: {
const { allowExport, withRawV5 = true, onYAxisUnitChange } = props;
return render(
<Provider store={mockStore}>
- <MemoryRouter>
+ <TestRouter>
<TimeSeriesView
isLoading={false}
isError={false}
@@ -98,7 +98,7 @@ function renderView(props: {
allowExport={allowExport}
onYAxisUnitChange={onYAxisUnitChange}
/>
- </MemoryRouter>
+ </TestRouter>
</Provider>,
);
}
diff --git a/frontend/src/container/Toolbar/Toolbar.tsx b/frontend/src/container/Toolbar/Toolbar.tsx
index 2a81d73fd3..c05a84adbb 100644
--- a/frontend/src/container/Toolbar/Toolbar.tsx
+++ b/frontend/src/container/Toolbar/Toolbar.tsx
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import ROUTES from 'constants/routes';
import LiveLogsPauseResume from 'container/LiveLogs/LiveLogsPauseResume/LiveLogsPauseResume';
import DateTimeSelectionV2 from 'container/TopNav/DateTimeSelectionV2';
@@ -26,7 +26,7 @@ export default function Toolbar({
onGoLive,
onExitLiveLogs,
}: ToolbarProps): JSX.Element {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const isLogsExplorerPage = useMemo(
() => pathname === ROUTES.LOGS_EXPLORER,
diff --git a/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefresh.test.tsx b/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefresh.test.tsx
index 566e0f8b36..7b837f8f76 100644
--- a/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefresh.test.tsx
+++ b/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefresh.test.tsx
@@ -1,12 +1,12 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { act, render, screen } from '@testing-library/react';
import set from 'api/browser/localstorage/set';
import { DASHBOARD_TIME_IN_DURATION } from 'constants/app';
import configureStore, { MockStoreEnhanced } from 'redux-mock-store';
import { AppState } from 'store/reducers';
import { UPDATE_TIME_INTERVAL } from 'types/actions/globalTime';
+import { TestRouter } from 'tests/router';
import { GlobalReducer } from 'types/reducer/globalTime';
import AutoRefresh from '../index';
@@ -37,11 +37,11 @@ function renderAutoRefresh(
const store = mockStore({ globalTime });
render(
- <MemoryRouter initialEntries={[PATHNAME]}>
+ <TestRouter initialRoute={PATHNAME}>
<Provider store={store}>
<AutoRefresh {...props} />
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
return store;
diff --git a/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefreshTicker.test.tsx b/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefreshTicker.test.tsx
index f3390153e4..dfc46c2c5e 100644
--- a/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefreshTicker.test.tsx
+++ b/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefreshTicker.test.tsx
@@ -1,12 +1,12 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { act, render } from '@testing-library/react';
import set from 'api/browser/localstorage/set';
import { DASHBOARD_TIME_IN_DURATION } from 'constants/app';
import configureStore, { MockStoreEnhanced } from 'redux-mock-store';
import { AppState } from 'store/reducers';
import { UPDATE_TIME_INTERVAL } from 'types/actions/globalTime';
+import { TestRouter } from 'tests/router';
import { GlobalReducer } from 'types/reducer/globalTime';
import AutoRefresh from '../index';
@@ -37,11 +37,11 @@ function renderTicker(
const store = mockStore({ globalTime });
render(
- <MemoryRouter initialEntries={[PATHNAME]}>
+ <TestRouter initialRoute={PATHNAME}>
<Provider store={store}>
<AutoRefreshTicker />
</Provider>
- </MemoryRouter>,
+ </TestRouter>,
);
return store;
@@ -133,11 +133,11 @@ describe('AutoRefresh full screen handover', () => {
}
const renderHarness = (active: boolean): JSX.Element => (
- <MemoryRouter initialEntries={[PATHNAME]}>
+ <TestRouter initialRoute={PATHNAME}>
<Provider store={store}>
<Harness active={active} />
</Provider>
- </MemoryRouter>
+ </TestRouter>
);
const { rerender } = render(renderHarness(false));
diff --git a/frontend/src/container/TopNav/AutoRefreshV2/index.tsx b/frontend/src/container/TopNav/AutoRefreshV2/index.tsx
index e49ce8f915..eea26cf16e 100644
--- a/frontend/src/container/TopNav/AutoRefreshV2/index.tsx
+++ b/frontend/src/container/TopNav/AutoRefreshV2/index.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Check, ChevronDown } from '@signozhq/icons';
import { Button, Popover } from 'antd';
import { Checkbox } from '@signozhq/ui/checkbox';
@@ -34,7 +34,7 @@ function AutoRefresh({
const globalTime = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const isDisabled = useMemo(
() =>
diff --git a/frontend/src/container/TopNav/AutoRefreshV2/useAutoRefreshSelection.ts b/frontend/src/container/TopNav/AutoRefreshV2/useAutoRefreshSelection.ts
index b44fcc12f8..4a3981cc74 100644
--- a/frontend/src/container/TopNav/AutoRefreshV2/useAutoRefreshSelection.ts
+++ b/frontend/src/container/TopNav/AutoRefreshV2/useAutoRefreshSelection.ts
@@ -1,6 +1,6 @@
-import { useLocation } from 'react-router-dom';
import get from 'api/browser/localstorage/get';
import { DASHBOARD_TIME_IN_DURATION } from 'constants/app';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { refreshIntervalOptions } from './constants';
@@ -14,7 +14,7 @@ export interface AutoRefreshSelection {
* Read on every render because localStorage isn't reactive.
*/
export function useAutoRefreshSelection(): AutoRefreshSelection {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const selectedOption = JSON.parse(get(DASHBOARD_TIME_IN_DURATION) || '{}')[
pathname
diff --git a/frontend/src/container/TopNav/DateTimeSelectionV2/__tests__/DateTimeSelectionV2.regression.test.tsx b/frontend/src/container/TopNav/DateTimeSelectionV2/__tests__/DateTimeSelectionV2.regression.test.tsx
index e349bda704..3d6c49fe8e 100644
--- a/frontend/src/container/TopNav/DateTimeSelectionV2/__tests__/DateTimeSelectionV2.regression.test.tsx
+++ b/frontend/src/container/TopNav/DateTimeSelectionV2/__tests__/DateTimeSelectionV2.regression.test.tsx
@@ -1,6 +1,5 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter, Route } from 'react-router-dom';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { QueryClient, QueryClientProvider } from 'react-query';
import {
@@ -18,7 +17,7 @@ import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import store from 'store';
import { getAppContextMock } from 'tests/test-utils';
-import { CompatRouter } from 'react-router-dom-v5-compat';
+import { TestRouter } from 'tests/router';
import DateTimeSelection from '../index';
import {
@@ -115,26 +114,22 @@ function TestWrapper({
});
return (
- <MemoryRouter initialEntries={[initialEntry]}>
- <CompatRouter>
- <NuqsTestingAdapter
- searchParams={initialSearchParams}
- onUrlUpdate={onUrlUpdate}
- >
- <QueryClientProvider client={queryClient}>
- <Provider store={mockedStore}>
- <AppContext.Provider value={getAppContextMock('ADMIN')}>
- <TimezoneProvider>
- <QueryBuilderProvider>
- <Route path="*">{children}</Route>
- </QueryBuilderProvider>
- </TimezoneProvider>
- </AppContext.Provider>
- </Provider>
- </QueryClientProvider>
- </NuqsTestingAdapter>
- </CompatRouter>
- </MemoryRouter>
+ <TestRouter initialRoute={initialEntry}>
+ <NuqsTestingAdapter
+ searchParams={initialSearchParams}
+ onUrlUpdate={onUrlUpdate}
+ >
+ <QueryClientProvider client={queryClient}>
+ <Provider store={mockedStore}>
+ <AppContext.Provider value={getAppContextMock('ADMIN')}>
+ <TimezoneProvider>
+ <QueryBuilderProvider>{children}</QueryBuilderProvider>
+ </TimezoneProvider>
+ </AppContext.Provider>
+ </Provider>
+ </QueryClientProvider>
+ </NuqsTestingAdapter>
+ </TestRouter>
);
}
diff --git a/frontend/src/container/TopNav/DateTimeSelectionV2/__tests__/testUtils.tsx b/frontend/src/container/TopNav/DateTimeSelectionV2/__tests__/testUtils.tsx
index c3037e4517..b358fa6423 100644
--- a/frontend/src/container/TopNav/DateTimeSelectionV2/__tests__/testUtils.tsx
+++ b/frontend/src/container/TopNav/DateTimeSelectionV2/__tests__/testUtils.tsx
@@ -1,6 +1,5 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter, Route } from 'react-router-dom';
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { QueryClient, QueryClientProvider } from 'react-query';
import { AppContext } from 'providers/App/App';
@@ -10,7 +9,7 @@ import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import store from 'store';
import { getAppContextMock } from 'tests/test-utils';
-import { CompatRouter } from 'react-router-dom-v5-compat';
+import { TestRouter } from 'tests/router';
export const queryClient = new QueryClient({
defaultOptions: {
@@ -56,26 +55,22 @@ export function TestWrapper({
});
return (
- <MemoryRouter initialEntries={[initialEntry]}>
- <CompatRouter>
- <NuqsTestingAdapter
- searchParams={initialSearchParams}
- onUrlUpdate={onUrlUpdate}
- >
- <QueryClientProvider client={queryClient}>
- <Provider store={mockedStore}>
- <AppContext.Provider value={getAppContextMock('ADMIN')}>
- <TimezoneProvider>
- <QueryBuilderProvider>
- <Route path="*">{children}</Route>
- </QueryBuilderProvider>
- </TimezoneProvider>
- </AppContext.Provider>
- </Provider>
- </QueryClientProvider>
- </NuqsTestingAdapter>
- </CompatRouter>
- </MemoryRouter>
+ <TestRouter initialRoute={initialEntry}>
+ <NuqsTestingAdapter
+ searchParams={initialSearchParams}
+ onUrlUpdate={onUrlUpdate}
+ >
+ <QueryClientProvider client={queryClient}>
+ <Provider store={mockedStore}>
+ <AppContext.Provider value={getAppContextMock('ADMIN')}>
+ <TimezoneProvider>
+ <QueryBuilderProvider>{children}</QueryBuilderProvider>
+ </TimezoneProvider>
+ </AppContext.Provider>
+ </Provider>
+ </QueryClientProvider>
+ </NuqsTestingAdapter>
+ </TestRouter>
);
}
diff --git a/frontend/src/container/TopNav/DateTimeSelectionV2/index.tsx b/frontend/src/container/TopNav/DateTimeSelectionV2/index.tsx
index 1636bc8047..0f8b8045bf 100644
--- a/frontend/src/container/TopNav/DateTimeSelectionV2/index.tsx
+++ b/frontend/src/container/TopNav/DateTimeSelectionV2/index.tsx
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { connect, useDispatch, useSelector } from 'react-redux';
-import { RouteComponentProps, withRouter } from 'react-router-dom';
-import { useNavigationType } from 'react-router-dom-v5-compat';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppNavigationType } from 'lib/router/useAppNavigationType';
import { RefreshCw, Undo } from '@signozhq/icons';
import { Button } from 'antd';
import getLocalStorageKey from 'api/browser/localstorage/get';
@@ -60,7 +60,6 @@ import './DateTimeSelectionV2.styles.scss';
function DateTimeSelection({
showAutoRefresh,
showRefreshText = true,
- location,
updateTimeInterval,
globalTimeLoading,
showResetButton = false,
@@ -76,9 +75,10 @@ function DateTimeSelection({
disableUrlSync = false,
showRecentlyUsed = true,
}: Props): JSX.Element {
+ const location = useAppLocation();
const [formSelector] = Form.useForm();
const { safeNavigate } = useSafeNavigate();
- const navigationType = useNavigationType(); // Returns 'POP' for back/forward navigation
+ const navigationType = useAppNavigationType(); // Returns 'POP' for back/forward navigation
const dispatch = useDispatch();
const { maxTime, minTime, selectedTime } = useSelector<
@@ -835,6 +835,6 @@ const mapDispatchToProps = (
globalTimeLoading: bindActionCreators(GlobalTimeLoading, dispatch),
});
-type Props = DateTimeSelectionV2Props & DispatchProps & RouteComponentProps;
+type Props = DateTimeSelectionV2Props & DispatchProps;
-export default connect(null, mapDispatchToProps)(withRouter(DateTimeSelection));
+export default connect(null, mapDispatchToProps)(DateTimeSelection);
diff --git a/frontend/src/container/TopNav/index.tsx b/frontend/src/container/TopNav/index.tsx
index e58daf388b..6552c00d05 100644
--- a/frontend/src/container/TopNav/index.tsx
+++ b/frontend/src/container/TopNav/index.tsx
@@ -1,5 +1,6 @@
import { useMemo } from 'react';
-import { matchPath, useHistory } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { matchRoute } from 'lib/router/matchRoute';
import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
import ROUTES from 'constants/routes';
@@ -9,12 +10,12 @@ import { routesToDisable, routesToSkip } from './DateTimeSelectionV2/constants';
import './TopNav.styles.scss';
function TopNav(): JSX.Element | null {
- const { location } = useHistory();
+ const location = useAppLocation();
const isRouteToSkip = useMemo(
() =>
routesToSkip.some((route) =>
- matchPath(location.pathname, { path: route, exact: true }),
+ matchRoute(location.pathname, route, { exact: true }),
),
[location.pathname],
);
@@ -22,18 +23,18 @@ function TopNav(): JSX.Element | null {
const isDisabled = useMemo(
() =>
routesToDisable.some((route) =>
- matchPath(location.pathname, { path: route, exact: true }),
+ matchRoute(location.pathname, route, { exact: true }),
),
[location.pathname],
);
const isSignUpPage = useMemo(
- () => matchPath(location.pathname, { path: ROUTES.SIGN_UP, exact: true }),
+ () => matchRoute(location.pathname, ROUTES.SIGN_UP, { exact: true }),
[location.pathname],
);
const isAlertCreationPage = useMemo(
- () => matchPath(location.pathname, { path: ROUTES.ALERTS_NEW, exact: true }),
+ () => matchRoute(location.pathname, ROUTES.ALERTS_NEW, { exact: true }),
[location.pathname],
);
diff --git a/frontend/src/container/TracesExplorer/ListView/utils.tsx b/frontend/src/container/TracesExplorer/ListView/utils.tsx
index 27bceefb62..4a0e80791d 100644
--- a/frontend/src/container/TracesExplorer/ListView/utils.tsx
+++ b/frontend/src/container/TracesExplorer/ListView/utils.tsx
@@ -1,4 +1,5 @@
-import { generatePath, Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import type { TableColumnsType as ColumnsType } from 'antd';
import { Badge } from '@signozhq/ui/badge';
import { Typography } from '@signozhq/ui/typography';
@@ -26,13 +27,13 @@ export function BlockLink({
}): any {
// Display block to make the whole cell clickable
return (
- <Link
+ <AppLink
to={to}
style={{ display: 'block' }}
target={openInNewTab ? '_blank' : '_self'}
>
{children}
- </Link>
+ </AppLink>
);
}
@@ -57,11 +58,13 @@ export const getTraceLink = (record: Record<string, unknown>): string => {
return '';
}
- return `${generatePath(ROUTES.TRACE_DETAIL, { id: traceId })}${formUrlParams({
- spanId,
- levelUp: 0,
- levelDown: 0,
- })}`;
+ return `${buildRoutePath(ROUTES.TRACE_DETAIL, { id: traceId })}${formUrlParams(
+ {
+ spanId,
+ levelUp: 0,
+ levelDown: 0,
+ },
+ )}`;
};
export const getListColumns = (
diff --git a/frontend/src/container/TracesExplorer/TracesTable/FieldCell.tsx b/frontend/src/container/TracesExplorer/TracesTable/FieldCell.tsx
index d2a5ca72ac..43373d2602 100644
--- a/frontend/src/container/TracesExplorer/TracesTable/FieldCell.tsx
+++ b/frontend/src/container/TracesExplorer/TracesTable/FieldCell.tsx
@@ -1,4 +1,5 @@
-import { generatePath, Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { Badge } from '@signozhq/ui/badge';
import TanStackTable from 'components/TanStackTableView';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
@@ -43,13 +44,13 @@ function FieldCell({ name, value }: FieldCellProps): JSX.Element {
if (TRACE_ID_FIELD_NAMES.has(name)) {
return (
- <Link
- to={generatePath(ROUTES.TRACE_DETAIL, { id: text })}
+ <AppLink
+ to={buildRoutePath(ROUTES.TRACE_DETAIL, { id: text })}
data-testid="trace-id"
onClick={(e): void => e.stopPropagation()}
>
{text}
- </Link>
+ </AppLink>
);
}
diff --git a/frontend/src/container/TracesExplorer/TracesTable/TracesTable.tsx b/frontend/src/container/TracesExplorer/TracesTable/TracesTable.tsx
index b449325b04..3f0480c617 100644
--- a/frontend/src/container/TracesExplorer/TracesTable/TracesTable.tsx
+++ b/frontend/src/container/TracesExplorer/TracesTable/TracesTable.tsx
@@ -1,5 +1,5 @@
import { useCallback } from 'react';
-import { useHistory } from 'react-router-dom';
+import { useAppNavigate } from 'lib/router/useAppNavigate';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import TanStackTable from 'components/TanStackTableView';
import type {
@@ -50,16 +50,16 @@ function TracesTable({
onColumnRemove,
cellTypographySize = 'medium',
}: TracesTableProps): JSX.Element {
- const history = useHistory();
+ const navigate = useAppNavigate();
const isDataAbsent =
!isLoading && !isFetching && !isError && data.length === 0;
const handleRowClick = useCallback(
(row: TracesTableRow): void => {
- history.push(getRowHref(row));
+ navigate(getRowHref(row));
},
- [history, getRowHref],
+ [navigate, getRowHref],
);
const handleRowClickNewTab = useCallback(
diff --git a/frontend/src/container/TracesTableComponent/TracesTableComponent.tsx b/frontend/src/container/TracesTableComponent/TracesTableComponent.tsx
index c6550770b9..1ae9cafda7 100644
--- a/frontend/src/container/TracesTableComponent/TracesTableComponent.tsx
+++ b/frontend/src/container/TracesTableComponent/TracesTableComponent.tsx
@@ -22,7 +22,7 @@ import {
import { Pagination } from 'hooks/queryPagination';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { RowData } from 'lib/query/createTableColumnsFromQuery';
import { useTimezone } from 'providers/Timezone';
import { SuccessResponse } from 'types/api';
@@ -91,7 +91,7 @@ function TracesTableComponent({
if (event.metaKey || event.ctrlKey) {
openInNewTab(getTraceLink(record));
} else {
- history.push(getTraceLink(record));
+ navigate(getTraceLink(record));
}
},
}),
diff --git a/frontend/src/container/TriggeredAlerts/__tests__/_helpers.tsx b/frontend/src/container/TriggeredAlerts/__tests__/_helpers.tsx
index 2077504b0a..79c0dedf07 100644
--- a/frontend/src/container/TriggeredAlerts/__tests__/_helpers.tsx
+++ b/frontend/src/container/TriggeredAlerts/__tests__/_helpers.tsx
@@ -1,5 +1,4 @@
import { QueryClient, QueryClientProvider } from 'react-query';
-import { MemoryRouter } from 'react-router-dom';
import { VirtuosoMockContext } from 'react-virtuoso';
import { render, RenderResult, screen } from '@testing-library/react';
import TriggeredAlerts from 'container/TriggeredAlerts';
@@ -7,6 +6,7 @@ import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
import { AppContext } from 'providers/App/App';
import TimezoneProvider from 'providers/Timezone';
import { onNuqsUrlUpdate, resetNuqsState } from 'tests/nuqs-helpers';
+import { TestRouter } from 'tests/router';
import { getAppContextMock } from 'tests/test-utils';
interface RenderOptions {
@@ -31,7 +31,7 @@ export function renderTriggeredAlerts(
});
return render(
- <MemoryRouter initialEntries={[initialRoute]}>
+ <TestRouter initialRoute={initialRoute}>
<NuqsTestingAdapter
searchParams={initialSearch}
onUrlUpdate={onNuqsUrlUpdate}
@@ -50,7 +50,7 @@ export function renderTriggeredAlerts(
</AppContext.Provider>
</QueryClientProvider>
</NuqsTestingAdapter>
- </MemoryRouter>,
+ </TestRouter>,
);
}
diff --git a/frontend/src/container/WidgetCard/Card/WidgetGraphComponent.test.tsx b/frontend/src/container/WidgetCard/Card/WidgetGraphComponent.test.tsx
index 42067f4416..147b22d6f7 100644
--- a/frontend/src/container/WidgetCard/Card/WidgetGraphComponent.test.tsx
+++ b/frontend/src/container/WidgetCard/Card/WidgetGraphComponent.test.tsx
@@ -8,6 +8,7 @@ import { AppProvider } from 'providers/App/App';
import { ErrorModalProvider } from 'providers/ErrorModalProvider';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
import store from 'store';
+import { mockAppLocation } from 'tests/router-mocks';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
@@ -19,12 +20,9 @@ import {
import { WidgetGraphComponentProps } from 'container/WidgetCard/Card/types';
import WidgetGraphComponent from 'container/WidgetCard/Card/WidgetGraphComponent';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${process.env.FRONTEND_API_ENDPOINT}/${ROUTES.DASHBOARD}/624652db-6097-42f5-bbca-e9012901db00`,
- }),
-}));
+mockAppLocation({
+ pathname: `${process.env.FRONTEND_API_ENDPOINT}/${ROUTES.DASHBOARD}/624652db-6097-42f5-bbca-e9012901db00`,
+});
jest.mock('hooks/useSafeNavigate', () => ({
useSafeNavigate: (): any => ({
diff --git a/frontend/src/container/WidgetCard/Card/WidgetGraphComponent.tsx b/frontend/src/container/WidgetCard/Card/WidgetGraphComponent.tsx
index 151bc63987..069ebbe5a9 100644
--- a/frontend/src/container/WidgetCard/Card/WidgetGraphComponent.tsx
+++ b/frontend/src/container/WidgetCard/Card/WidgetGraphComponent.tsx
@@ -1,5 +1,5 @@
import { RefObject, useEffect, useRef, useState } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Skeleton, Tooltip } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import cx from 'classnames';
@@ -59,7 +59,7 @@ function WidgetGraphComponent({
}: WidgetGraphComponentProps): JSX.Element {
const { safeNavigate } = useSafeNavigate();
const { notifications } = useNotifications();
- const { pathname, search } = useLocation();
+ const { pathname, search } = useAppLocation();
const params = useUrlQuery();
diff --git a/frontend/src/container/WidgetCard/Header/__tests__/WidgetHeader.test.tsx b/frontend/src/container/WidgetCard/Header/__tests__/WidgetHeader.test.tsx
index 94fc5cc0bb..630411a921 100644
--- a/frontend/src/container/WidgetCard/Header/__tests__/WidgetHeader.test.tsx
+++ b/frontend/src/container/WidgetCard/Header/__tests__/WidgetHeader.test.tsx
@@ -2,7 +2,6 @@ import React, { MutableRefObject } from 'react';
import { QueryClient, QueryClientProvider, UseQueryResult } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render as rtlRender, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { PANEL_TYPES } from 'constants/queryBuilder';
@@ -11,6 +10,7 @@ import { AppContext } from 'providers/App/App';
import { IAppContext } from 'providers/App/types';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
+import { TestRouter } from 'tests/router';
import { SuccessResponse, Warning } from 'types/api';
import { Widgets } from 'types/api/widgets/widget';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
@@ -72,7 +72,7 @@ const createMockAppContext = (): Partial<IAppContext> => ({
const render = (ui: React.ReactElement): ReturnType<typeof rtlRender> =>
rtlRender(
- <MemoryRouter>
+ <TestRouter>
<QueryClientProvider client={queryClient}>
<Provider store={createMockStore()}>
<AppContext.Provider value={createMockAppContext() as IAppContext}>
@@ -80,7 +80,7 @@ const render = (ui: React.ReactElement): ReturnType<typeof rtlRender> =>
</AppContext.Provider>
</Provider>
</QueryClientProvider>
- </MemoryRouter>,
+ </TestRouter>,
);
jest.mock('hooks/queryBuilder/useCreateAlerts', () => ({
diff --git a/frontend/src/container/WidgetCard/Panels/ValuePanel/index.tsx b/frontend/src/container/WidgetCard/Panels/ValuePanel/index.tsx
index 0f1f9deae4..9b4d32638f 100644
--- a/frontend/src/container/WidgetCard/Panels/ValuePanel/index.tsx
+++ b/frontend/src/container/WidgetCard/Panels/ValuePanel/index.tsx
@@ -1,5 +1,5 @@
import { memo, useMemo } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Typography } from '@signozhq/ui/typography';
import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
import ValueGraph from 'components/ValueGraph';
@@ -26,7 +26,7 @@ function GridValueComponent({
}: GridValueComponentProps): JSX.Element {
const value = ((data[1] || [])[0] || 0) as number;
- const location = useLocation();
+ const location = useAppLocation();
const gridTitle = useMemo(() => generateGridTitle(title), [title]);
const isDashboardPage = location.pathname.split('/').length === 3;
diff --git a/frontend/src/hooks/ResizeTable/useSortableTable.ts b/frontend/src/hooks/ResizeTable/useSortableTable.ts
index 4ff50651db..fb9bf41e12 100644
--- a/frontend/src/hooks/ResizeTable/useSortableTable.ts
+++ b/frontend/src/hooks/ResizeTable/useSortableTable.ts
@@ -1,5 +1,7 @@
import { useEffect, useState } from 'react';
-import { useHistory, useLocation } from 'react-router-dom';
+
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { TableProps } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
@@ -11,14 +13,13 @@ const useSortableTable = <T>(
sortedInfo: SorterResult<T>;
handleChange: TableProps<T>['onChange'];
} => {
- const history = useHistory();
- const { search } = useLocation();
+ const { search } = useAppLocation();
useEffect(() => {
const searchParams = new URLSearchParams(search);
searchParams.set('search', searchString);
- history.replace({ search: searchParams.toString() });
- }, [history, search, searchString]);
+ navigate({ search: searchParams.toString() }, { replace: true });
+ }, [search, searchString]);
const [sortedInfo, setSortedInfo] = useState<SorterResult<T>>({
order: initialOrder,
@@ -37,7 +38,7 @@ const useSortableTable = <T>(
'page',
pagination.current ? pagination.current.toString() : '1',
);
- history.replace({ search: searchParams.toString() });
+ navigate({ search: searchParams.toString() }, { replace: true });
};
return { sortedInfo, handleChange };
diff --git a/frontend/src/hooks/__tests__/useNavigationBlocker.history.test.tsx b/frontend/src/hooks/__tests__/useNavigationBlocker.history.test.tsx
new file mode 100644
index 0000000000..bf8a04957b
--- /dev/null
+++ b/frontend/src/hooks/__tests__/useNavigationBlocker.history.test.tsx
@@ -0,0 +1,73 @@
+import { act, renderHook } from '@testing-library/react';
+import { getCurrentLocation, navigate } from 'lib/router/navigation';
+
+import { useNavigationBlocker } from '../useNavigationBlocker';
+
+function settle(): Promise<void> {
+ return new Promise((resolve) => {
+ setTimeout(resolve, 60);
+ });
+}
+
+describe('useNavigationBlocker against the real history', () => {
+ beforeEach(async () => {
+ navigate('/start');
+ navigate('/a');
+ navigate('/b');
+ navigate('/c');
+ await settle();
+ });
+
+ it('lets a bypassed browser Back through without showing the modal', async () => {
+ const { result } = renderHook(() => useNavigationBlocker(true));
+
+ act(() => result.current.allowNextNavigation());
+ act(() => window.history.back());
+ await settle();
+
+ expect(getCurrentLocation().pathname).toBe('/b');
+ expect(result.current.isBlocked).toBe(false);
+ });
+
+ it('keeps blocking after a bypassed navigation', async () => {
+ const { result } = renderHook(() => useNavigationBlocker(true));
+
+ act(() => result.current.allowNextNavigation());
+ act(() => window.history.back());
+ await settle();
+ act(() => navigate('/elsewhere'));
+
+ expect(getCurrentLocation().pathname).toBe('/b');
+ expect(result.current.isBlocked).toBe(true);
+ });
+
+ it('replays a blocked Forward on confirm', async () => {
+ act(() => window.history.go(-2));
+ await settle();
+ const { result } = renderHook(() => useNavigationBlocker(true));
+
+ act(() => window.history.forward());
+ await settle();
+
+ expect(result.current.isBlocked).toBe(true);
+ expect(getCurrentLocation().pathname).toBe('/a');
+
+ act(() => result.current.confirmNavigation());
+ await settle();
+
+ expect(getCurrentLocation().pathname).toBe('/b');
+ });
+
+ it('replays a blocked multi-entry jump on confirm', async () => {
+ act(() => window.history.go(-2));
+ await settle();
+ const { result } = renderHook(() => useNavigationBlocker(true));
+
+ act(() => window.history.go(2));
+ await settle();
+ act(() => result.current.confirmNavigation());
+ await settle();
+
+ expect(getCurrentLocation().pathname).toBe('/c');
+ });
+});
diff --git a/frontend/src/hooks/__tests__/useNavigationBlocker.test.ts b/frontend/src/hooks/__tests__/useNavigationBlocker.test.ts
index 4019971464..6019e02e36 100644
--- a/frontend/src/hooks/__tests__/useNavigationBlocker.test.ts
+++ b/frontend/src/hooks/__tests__/useNavigationBlocker.test.ts
@@ -4,18 +4,10 @@ import { useNavigationBlocker } from '../useNavigationBlocker';
const mockUnblock = jest.fn();
const mockBlock = jest.fn().mockReturnValue(mockUnblock);
-const mockPush = jest.fn();
-const mockReplace = jest.fn();
-const mockGoBack = jest.fn();
-
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: (): object => ({
- block: mockBlock,
- push: mockPush,
- replace: mockReplace,
- goBack: mockGoBack,
- }),
+const mockRetry = jest.fn();
+
+jest.mock('lib/router/navigation', () => ({
+ blockNavigation: (blocker: unknown): unknown => mockBlock(blocker),
}));
describe('useNavigationBlocker', () => {
@@ -27,6 +19,19 @@ describe('useNavigationBlocker', () => {
key: 'test-key',
};
+ /**
+ * `blockNavigation` hands the blocker one transition object and cancels the
+ * navigation on its own; `retry()` is the only way through, which is why
+ * these cases assert on `retry` rather than on a returned `false`.
+ */
+ function transition(action: string): {
+ location: typeof mockLocation;
+ action: string;
+ retry: jest.Mock;
+ } {
+ return { location: mockLocation, action, retry: mockRetry };
+ }
+
beforeEach(() => {
jest.clearAllMocks();
mockBlock.mockReturnValue(mockUnblock);
@@ -48,15 +53,15 @@ describe('useNavigationBlocker', () => {
});
});
- describe('history.block behavior', () => {
- it('calls history.block when shouldBlock is true', () => {
+ describe('blockNavigation behavior', () => {
+ it('registers a blocker when shouldBlock is true', () => {
renderHook(() => useNavigationBlocker(true));
expect(mockBlock).toHaveBeenCalledTimes(1);
expect(mockBlock).toHaveBeenCalledWith(expect.any(Function));
});
- it('does not call history.block when shouldBlock is false', () => {
+ it('does not register a blocker when shouldBlock is false', () => {
renderHook(() => useNavigationBlocker(false));
expect(mockBlock).not.toHaveBeenCalled();
@@ -97,13 +102,12 @@ describe('useNavigationBlocker', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
- let blockResult: boolean | undefined;
act(() => {
- blockResult = blockCallback(mockLocation, 'PUSH');
+ blockCallback(transition('PUSH'));
});
- expect(blockResult).toBe(false);
+ expect(mockRetry).not.toHaveBeenCalled();
expect(result.current.isBlocked).toBe(true);
expect(result.current.blockedNavigationDetails).toStrictEqual({
location: mockLocation,
@@ -117,7 +121,7 @@ describe('useNavigationBlocker', () => {
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
- blockCallback(mockLocation, 'REPLACE');
+ blockCallback(transition('REPLACE'));
});
expect(result.current.isBlocked).toBe(true);
@@ -130,7 +134,7 @@ describe('useNavigationBlocker', () => {
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
- blockCallback(mockLocation, 'POP');
+ blockCallback(transition('POP'));
});
expect(result.current.isBlocked).toBe(true);
@@ -146,18 +150,16 @@ describe('useNavigationBlocker', () => {
result.current.confirmNavigation();
});
- expect(mockPush).not.toHaveBeenCalled();
- expect(mockReplace).not.toHaveBeenCalled();
- expect(mockGoBack).not.toHaveBeenCalled();
+ expect(mockRetry).not.toHaveBeenCalled();
});
- it('performs PUSH navigation when confirming blocked PUSH', () => {
+ it('unblocks before retrying, or the blocker would catch the retry too', () => {
const { result } = renderHook(() => useNavigationBlocker(true));
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
- blockCallback(mockLocation, 'PUSH');
+ blockCallback(transition('PUSH'));
});
act(() => {
@@ -165,42 +167,31 @@ describe('useNavigationBlocker', () => {
});
expect(mockUnblock).toHaveBeenCalled();
- expect(mockPush).toHaveBeenCalledWith(mockLocation);
+ expect(mockUnblock.mock.invocationCallOrder[0]).toBeLessThan(
+ mockRetry.mock.invocationCallOrder[0],
+ );
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
});
- it('performs REPLACE navigation when confirming blocked REPLACE', () => {
- const { result } = renderHook(() => useNavigationBlocker(true));
-
- const blockCallback = mockBlock.mock.calls[0][0];
+ it.each(['PUSH', 'REPLACE', 'POP'])(
+ 'retries the blocked %s, which replays it with its own action',
+ (action) => {
+ const { result } = renderHook(() => useNavigationBlocker(true));
- act(() => {
- blockCallback(mockLocation, 'REPLACE');
- });
+ const blockCallback = mockBlock.mock.calls[0][0];
- act(() => {
- result.current.confirmNavigation();
- });
+ act(() => {
+ blockCallback(transition(action));
+ });
- expect(mockReplace).toHaveBeenCalledWith(mockLocation);
- });
-
- it('performs goBack when confirming blocked POP', () => {
- const { result } = renderHook(() => useNavigationBlocker(true));
-
- const blockCallback = mockBlock.mock.calls[0][0];
-
- act(() => {
- blockCallback(mockLocation, 'POP');
- });
-
- act(() => {
- result.current.confirmNavigation();
- });
+ act(() => {
+ result.current.confirmNavigation();
+ });
- expect(mockGoBack).toHaveBeenCalled();
- });
+ expect(mockRetry).toHaveBeenCalledTimes(1);
+ },
+ );
});
describe('cancelNavigation', () => {
@@ -210,7 +201,7 @@ describe('useNavigationBlocker', () => {
const blockCallback = mockBlock.mock.calls[0][0];
act(() => {
- blockCallback(mockLocation, 'PUSH');
+ blockCallback(transition('PUSH'));
});
expect(result.current.isBlocked).toBe(true);
@@ -221,9 +212,7 @@ describe('useNavigationBlocker', () => {
expect(result.current.isBlocked).toBe(false);
expect(result.current.blockedNavigationDetails).toBeNull();
- expect(mockPush).not.toHaveBeenCalled();
- expect(mockReplace).not.toHaveBeenCalled();
- expect(mockGoBack).not.toHaveBeenCalled();
+ expect(mockRetry).not.toHaveBeenCalled();
});
});
@@ -236,14 +225,39 @@ describe('useNavigationBlocker', () => {
});
const blockCallback = mockBlock.mock.calls[0][0];
- let blockResult: boolean | undefined;
act(() => {
- blockResult = blockCallback(mockLocation, 'PUSH');
+ blockCallback(transition('PUSH'));
+ });
+
+ expect(mockRetry).toHaveBeenCalledTimes(1);
+ expect(result.current.isBlocked).toBe(false);
+ expect(mockBlock).toHaveBeenCalledTimes(1);
+ expect(mockUnblock).not.toHaveBeenCalled();
+ });
+
+ it('drops a pending prompt when a bypassed navigation goes through', () => {
+ const { result } = renderHook(() => useNavigationBlocker(true));
+ const blockCallback = mockBlock.mock.calls[0][0];
+ const stale = jest.fn();
+
+ act(() => {
+ blockCallback({ ...transition('PUSH'), retry: stale });
+ });
+ expect(result.current.isBlocked).toBe(true);
+
+ act(() => {
+ result.current.allowNextNavigation();
+ });
+ act(() => {
+ blockCallback(transition('PUSH'));
+ });
+ act(() => {
+ result.current.confirmNavigation();
});
- expect(blockResult).toBeUndefined();
expect(result.current.isBlocked).toBe(false);
+ expect(stale).not.toHaveBeenCalled();
});
it('resumes blocking after bypassed navigation', () => {
@@ -256,15 +270,15 @@ describe('useNavigationBlocker', () => {
});
act(() => {
- blockCallback(mockLocation, 'PUSH');
+ blockCallback(transition('PUSH'));
});
- let blockResult: boolean | undefined;
+ mockRetry.mockClear();
act(() => {
- blockResult = blockCallback(mockLocation, 'PUSH');
+ blockCallback(transition('PUSH'));
});
- expect(blockResult).toBe(false);
+ expect(mockRetry).not.toHaveBeenCalled();
expect(result.current.isBlocked).toBe(true);
});
@@ -282,13 +296,12 @@ describe('useNavigationBlocker', () => {
rerender({ shouldBlock: true });
const blockCallback = mockBlock.mock.calls[1][0];
- let blockResult: boolean | undefined;
act(() => {
- blockResult = blockCallback(mockLocation, 'PUSH');
+ blockCallback(transition('PUSH'));
});
- expect(blockResult).toBe(false);
+ expect(mockRetry).not.toHaveBeenCalled();
expect(result.current.isBlocked).toBe(true);
});
});
diff --git a/frontend/src/hooks/__tests__/useUrlQueryData.test.tsx b/frontend/src/hooks/__tests__/useUrlQueryData.test.tsx
index fb8909e28a..210851f8b6 100644
--- a/frontend/src/hooks/__tests__/useUrlQueryData.test.tsx
+++ b/frontend/src/hooks/__tests__/useUrlQueryData.test.tsx
@@ -1,8 +1,7 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
-import { Router } from 'react-router-dom';
import { act, renderHook } from '@testing-library/react';
-import { createMemoryHistory } from 'history';
+import { TestRouter } from 'tests/router';
import useUrlQueryData from '../useUrlQueryData';
@@ -22,31 +21,22 @@ describe('useUrlQueryData', () => {
const renderHookWithRouter = (
queryKey: string,
defaultData?: any,
- initialEntries: string[] = ['/test'],
- ) => {
- const history = createMemoryHistory({ initialEntries });
-
- // Mock window.location.search to match the current route
- Object.defineProperty(window, 'location', {
- value: {
- search: history.location.search,
- pathname: history.location.pathname,
- origin: 'http://localhost',
- },
- writable: true,
+ initialRoute = '/test',
+ ) =>
+ renderHook(() => useUrlQueryData(queryKey, defaultData), {
+ wrapper: ({ children }) => (
+ <TestRouter initialRoute={initialRoute}>{children}</TestRouter>
+ ),
});
- return renderHook(() => useUrlQueryData(queryKey, defaultData), {
- wrapper: ({ children }) => <Router history={history}>{children}</Router>,
- });
- };
-
describe('query parsing', () => {
it('should parse valid JSON query parameter', () => {
const testData = { name: 'test', value: 123 };
- const { result } = renderHookWithRouter('testKey', {}, [
+ const { result } = renderHookWithRouter(
+ 'testKey',
+ {},
`/test?testKey=${encodeURIComponent(JSON.stringify(testData))}`,
- ]);
+ );
expect(result.current.query).toBe(JSON.stringify(testData));
expect(result.current.queryData).toStrictEqual(testData);
@@ -62,9 +52,11 @@ describe('useUrlQueryData', () => {
it('should return default data when query parameter is empty', () => {
const defaultData = { default: 'value' };
- const { result } = renderHookWithRouter('testKey', defaultData, [
+ const { result } = renderHookWithRouter(
+ 'testKey',
+ defaultData,
'/test?testKey=',
- ]);
+ );
expect(result.current.query).toBe('');
expect(result.current.queryData).toStrictEqual(defaultData);
@@ -74,9 +66,11 @@ describe('useUrlQueryData', () => {
const defaultData = { default: 'value' };
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();
- const { result } = renderHookWithRouter('testKey', defaultData, [
+ const { result } = renderHookWithRouter(
+ 'testKey',
+ defaultData,
'/test?testKey=invalid-json',
- ]);
+ );
expect(result.current.query).toBe('invalid-json');
expect(result.current.queryData).toStrictEqual(defaultData);
@@ -96,7 +90,7 @@ describe('useUrlQueryData', () => {
const { result } = renderHookWithRouter(
'testKey',
defaultData,
- ['/test?testKey={"name":"test",}'], // Missing closing brace
+ '/test?testKey={"name":"test",}', // Missing closing brace
);
expect(result.current.query).toBe('{"name":"test",}');
@@ -122,9 +116,11 @@ describe('useUrlQueryData', () => {
},
};
- const { result } = renderHookWithRouter('complexKey', {}, [
+ const { result } = renderHookWithRouter(
+ 'complexKey',
+ {},
`/test?complexKey=${encodeURIComponent(JSON.stringify(complexData))}`,
- ]);
+ );
expect(result.current.query).toBe(JSON.stringify(complexData));
expect(result.current.queryData).toStrictEqual(complexData);
@@ -132,9 +128,11 @@ describe('useUrlQueryData', () => {
it('should handle primitive values', () => {
const stringData = 'simple string';
- const { result } = renderHookWithRouter('stringKey', '', [
+ const { result } = renderHookWithRouter(
+ 'stringKey',
+ '',
`/test?stringKey=${encodeURIComponent(JSON.stringify(stringData))}`,
- ]);
+ );
expect(result.current.query).toBe(JSON.stringify(stringData));
expect(result.current.queryData).toBe(stringData);
@@ -160,9 +158,11 @@ describe('useUrlQueryData', () => {
});
it('should preserve existing query parameters when adding new one', () => {
- const { result } = renderHookWithRouter('newKey', {}, [
+ const { result } = renderHookWithRouter(
+ 'newKey',
+ {},
'/test?existingKey=existingValue',
- ]);
+ );
const newData = { name: 'new' };
act(() => {
@@ -178,9 +178,11 @@ describe('useUrlQueryData', () => {
it('should update existing query parameter', () => {
const initialData = { name: 'old' };
- const { result } = renderHookWithRouter('testKey', {}, [
+ const { result } = renderHookWithRouter(
+ 'testKey',
+ {},
`/test?testKey=${encodeURIComponent(JSON.stringify(initialData))}`,
- ]);
+ );
const newData = { name: 'new', value: 789 };
act(() => {
@@ -279,9 +281,11 @@ describe('useUrlQueryData', () => {
const testData = { name: 'test with spaces', value: 'special&chars' };
const encodedData = encodeURIComponent(JSON.stringify(testData));
- const { result } = renderHookWithRouter('testKey', {}, [
+ const { result } = renderHookWithRouter(
+ 'testKey',
+ {},
`/test?testKey=${encodedData}`,
- ]);
+ );
expect(result.current.queryData).toStrictEqual(testData);
});
diff --git a/frontend/src/hooks/__tests__/useZoomOut.test.ts b/frontend/src/hooks/__tests__/useZoomOut.test.ts
index 67b61aaa9d..8781bfaa5f 100644
--- a/frontend/src/hooks/__tests__/useZoomOut.test.ts
+++ b/frontend/src/hooks/__tests__/useZoomOut.test.ts
@@ -1,5 +1,6 @@
import { act, renderHook } from '@testing-library/react';
import { QueryParams } from 'constants/query';
+import { mockAppLocation } from 'tests/router-mocks';
import { GlobalReducer } from 'types/reducer/globalTime';
import { useZoomOut } from '../useZoomOut';
@@ -27,9 +28,7 @@ jest.mock('react-redux', () => ({
},
}));
-jest.mock('react-router-dom', () => ({
- useLocation: (): { pathname: string } => ({ pathname: '/logs-explorer' }),
-}));
+mockAppLocation({ pathname: '/logs-explorer' });
jest.mock('hooks/useSafeNavigate', () => ({
useSafeNavigate: (): { safeNavigate: typeof mockSafeNavigate } => ({
diff --git a/frontend/src/hooks/aiAssistant/__tests__/useResolvePageType.test.ts b/frontend/src/hooks/aiAssistant/__tests__/useResolvePageType.test.ts
index ded08705c6..fd63b74b7a 100644
--- a/frontend/src/hooks/aiAssistant/__tests__/useResolvePageType.test.ts
+++ b/frontend/src/hooks/aiAssistant/__tests__/useResolvePageType.test.ts
@@ -2,17 +2,12 @@ import { renderHook } from '@testing-library/react';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import type { AIAssistantVariant } from 'container/AIAssistant/VariantContext';
import ROUTES from 'constants/routes';
+import { mockAppLocation } from 'tests/router-mocks';
import { useResolvePageType } from '../useResolvePageType';
-const mockUseLocation = jest.fn();
const mockUseVariant = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): unknown => mockUseLocation(),
-}));
-
jest.mock('container/AIAssistant/VariantContext', () => ({
useVariant: (): unknown => mockUseVariant(),
}));
@@ -22,7 +17,7 @@ function setup(
search: string,
variant: AIAssistantVariant,
): PageTypeDTO {
- mockUseLocation.mockReturnValue({ pathname, search });
+ mockAppLocation({ pathname, search });
mockUseVariant.mockReturnValue(variant);
return renderHook(() => useResolvePageType()).result.current;
diff --git a/frontend/src/hooks/aiAssistant/useResolvePageType.ts b/frontend/src/hooks/aiAssistant/useResolvePageType.ts
index 3fb3db6637..4602f0700d 100644
--- a/frontend/src/hooks/aiAssistant/useResolvePageType.ts
+++ b/frontend/src/hooks/aiAssistant/useResolvePageType.ts
@@ -1,5 +1,6 @@
import { useMemo } from 'react';
-import { useLocation } from 'react-router-dom';
+
+import { useAppLocation } from 'lib/router/useAppLocation';
import { PageTypeDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
import { resolvePageType } from 'container/AIAssistant/resolvePageType';
@@ -10,7 +11,7 @@ import { useVariant } from 'container/AIAssistant/VariantContext';
* `page_type` from the active location and assistant variant.
*/
export function useResolvePageType(): PageTypeDTO {
- const location = useLocation();
+ const location = useAppLocation();
const variant = useVariant();
return useMemo(
diff --git a/frontend/src/hooks/dashboard/__test__/useDashboardsListQueryParams.test.ts b/frontend/src/hooks/dashboard/__test__/useDashboardsListQueryParams.test.tsx
similarity index 97%
rename from frontend/src/hooks/dashboard/__test__/useDashboardsListQueryParams.test.ts
rename to frontend/src/hooks/dashboard/__test__/useDashboardsListQueryParams.test.tsx
index a51c969711..53013a0b68 100644
--- a/frontend/src/hooks/dashboard/__test__/useDashboardsListQueryParams.test.ts
+++ b/frontend/src/hooks/dashboard/__test__/useDashboardsListQueryParams.test.tsx
@@ -1,6 +1,6 @@
import React from 'react';
-import { MemoryRouter } from 'react-router-dom';
import { act, renderHook } from '@testing-library/react';
+import { TestRouter } from 'tests/router';
import useDashboardsListQueryParams, {
DASHBOARDS_LIST_QUERY_PARAMS_STORAGE_KEY,
@@ -23,11 +23,7 @@ function createTestWrapper(
}: {
children: React.ReactNode;
}): JSX.Element {
- return React.createElement(
- MemoryRouter,
- { initialEntries: [initialUrl] },
- children,
- ) as JSX.Element;
+ return <TestRouter initialRoute={initialUrl}>{children}</TestRouter>;
};
}
diff --git a/frontend/src/hooks/logs/useCopyLogLink.ts b/frontend/src/hooks/logs/useCopyLogLink.ts
index 1e4127aaa8..9a7ce1965f 100644
--- a/frontend/src/hooks/logs/useCopyLogLink.ts
+++ b/frontend/src/hooks/logs/useCopyLogLink.ts
@@ -1,7 +1,7 @@
import { MouseEvent, useCallback, useEffect, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { useCopyToClipboard } from 'react-use';
import { toast } from '@signozhq/ui/sonner';
import { QueryParams } from 'constants/query';
@@ -18,7 +18,7 @@ import { UseCopyLogLink } from './types';
export const useCopyLogLink = (logId?: string): UseCopyLogLink => {
const urlQuery = useUrlQuery();
- const { pathname, search } = useLocation();
+ const { pathname, search } = useAppLocation();
const [, setCopy] = useCopyToClipboard();
const { safeNavigate } = useSafeNavigate();
diff --git a/frontend/src/hooks/queryBuilder/useGetCompositeQueryParam.ts b/frontend/src/hooks/queryBuilder/useGetCompositeQueryParam.ts
index b03cc83741..739188ffdd 100644
--- a/frontend/src/hooks/queryBuilder/useGetCompositeQueryParam.ts
+++ b/frontend/src/hooks/queryBuilder/useGetCompositeQueryParam.ts
@@ -1,5 +1,4 @@
import { useMemo } from 'react';
-import { useLocation } from 'react-router-dom';
import {
convertAggregationToExpression,
convertFiltersToExpressionWithExistingQuery,
@@ -7,6 +6,7 @@ import {
} from 'components/QueryBuilderV2/utils';
import { QueryParams } from 'constants/query';
import useUrlQuery from 'hooks/useUrlQuery';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { isPlainObject } from 'lodash-es';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
@@ -18,7 +18,7 @@ import {
export const useNormalizedCompositeQueryParam = (): NormalizedQuery | null => {
const urlQuery = useUrlQuery();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
return useMemo(() => {
const compositeQuery = urlQuery.get(QueryParams.compositeQuery);
diff --git a/frontend/src/hooks/trace/__tests__/useCopySpanLink.test.tsx b/frontend/src/hooks/trace/__tests__/useCopySpanLink.test.tsx
index 9a4f783e9b..9d822494d4 100644
--- a/frontend/src/hooks/trace/__tests__/useCopySpanLink.test.tsx
+++ b/frontend/src/hooks/trace/__tests__/useCopySpanLink.test.tsx
@@ -1,6 +1,6 @@
import { MouseEvent, ReactNode } from 'react';
-import { MemoryRouter } from 'react-router-dom';
import { renderHook } from '@testing-library/react';
+import { TestRouter } from 'tests/router';
import {
__resetSearchParamsGetter,
__setSearchParamsGetterForTest,
@@ -21,9 +21,9 @@ jest.mock('@signozhq/ui/sonner', () => ({
// The router only knows the stale URL; nuqs has since written ?tab=thread.
const wrapper = ({ children }: { children: ReactNode }): JSX.Element => (
- <MemoryRouter initialEntries={['/trace/abc?tab=overview&spanId=old']}>
+ <TestRouter initialRoute="/trace/abc?tab=overview&spanId=old">
{children}
- </MemoryRouter>
+ </TestRouter>
);
const clickEvent = {
diff --git a/frontend/src/hooks/trace/useCopySpanLink.ts b/frontend/src/hooks/trace/useCopySpanLink.ts
index 270d3ffc73..c6c0239473 100644
--- a/frontend/src/hooks/trace/useCopySpanLink.ts
+++ b/frontend/src/hooks/trace/useCopySpanLink.ts
@@ -1,5 +1,5 @@
import { MouseEventHandler, useCallback } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { useCopyToClipboard } from 'react-use';
import { toast } from '@signozhq/ui/sonner';
import { getAbsoluteUrl } from 'utils/basePath';
@@ -15,7 +15,7 @@ interface SpanLike {
export const useCopySpanLink = (
span?: SpanLike,
): { onSpanCopy: MouseEventHandler<HTMLElement> } => {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const [, setCopy] = useCopyToClipboard();
const onSpanCopy: MouseEventHandler<HTMLElement> = useCallback(
diff --git a/frontend/src/hooks/useNavigationBlocker.ts b/frontend/src/hooks/useNavigationBlocker.ts
index 9b49c97b35..617a9db45d 100644
--- a/frontend/src/hooks/useNavigationBlocker.ts
+++ b/frontend/src/hooks/useNavigationBlocker.ts
@@ -1,10 +1,14 @@
import { useCallback, useEffect, useRef, useState } from 'react';
-import { useHistory } from 'react-router-dom';
-import type { Location, Action } from 'history';
+import { blockNavigation } from 'lib/router/navigation';
+import type {
+ AppLocation,
+ BlockedTransition,
+ NavigationAction,
+} from 'lib/router/types';
interface BlockedNavigationDetails {
- location: Location;
- action: Action;
+ location: AppLocation;
+ action: NavigationAction;
}
interface UseNavigationBlockerResult {
@@ -35,7 +39,7 @@ interface UseNavigationBlockerResult {
* const handleSave = async () => {
* await save();
* allowNextNavigation();
- * history.push('/next');
+ * navigate('/next');
* };
* ```
*
@@ -44,10 +48,10 @@ interface UseNavigationBlockerResult {
export function useNavigationBlocker(
shouldBlock: boolean,
): UseNavigationBlockerResult {
- const history = useHistory();
const [blockedNavigation, setBlockedNavigation] =
useState<BlockedNavigationDetails | null>(null);
const unblockRef = useRef<(() => void) | null>(null);
+ const retryRef = useRef<(() => void) | null>(null);
const bypassNextRef = useRef(false);
useEffect(() => {
@@ -60,13 +64,19 @@ export function useNavigationBlocker(
return;
}
- unblockRef.current = history.block((location, action) => {
+ unblockRef.current = blockNavigation((transition: BlockedTransition) => {
if (bypassNextRef.current) {
bypassNextRef.current = false;
- return undefined;
+ retryRef.current = null;
+ setBlockedNavigation(null);
+ transition.retry();
+ return;
}
- setBlockedNavigation({ location, action });
- return false;
+ retryRef.current = transition.retry;
+ setBlockedNavigation({
+ location: transition.location,
+ action: transition.action,
+ });
});
return (): void => {
@@ -76,7 +86,7 @@ export function useNavigationBlocker(
}
bypassNextRef.current = false;
};
- }, [shouldBlock, history]);
+ }, [shouldBlock]);
useEffect(() => {
if (!shouldBlock) {
@@ -104,23 +114,17 @@ export function useNavigationBlocker(
unblockRef.current = null;
}
- const { location, action } = blockedNavigation;
setBlockedNavigation(null);
- switch (action) {
- case 'PUSH':
- history.push(location);
- break;
- case 'REPLACE':
- history.replace(location);
- break;
- case 'POP':
- history.goBack();
- break;
- }
- }, [blockedNavigation, history]);
+ // The transition replays itself, so a blocked REPLACE stays a REPLACE and
+ // a blocked POP still walks the history stack.
+ const retry = retryRef.current;
+ retryRef.current = null;
+ retry?.();
+ }, [blockedNavigation]);
const cancelNavigation = useCallback((): void => {
+ retryRef.current = null;
setBlockedNavigation(null);
}, []);
diff --git a/frontend/src/hooks/useResourceAttribute/ResourceProvider.tsx b/frontend/src/hooks/useResourceAttribute/ResourceProvider.tsx
index 8a7c73b778..5c00e6ca12 100644
--- a/frontend/src/hooks/useResourceAttribute/ResourceProvider.tsx
+++ b/frontend/src/hooks/useResourceAttribute/ResourceProvider.tsx
@@ -1,5 +1,5 @@
import { ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
@@ -25,7 +25,7 @@ type ResourceStep = 'Idle' | 'TagKey' | 'Operator' | 'TagValue';
type ResourceEvent = 'NEXT' | 'onBlur' | 'RESET';
function ResourceProvider({ children }: Props): JSX.Element {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const [loading, setLoading] = useState(true);
const [selectedQuery, setSelectedQueries] = useState<string[]>([]);
const [staging, setStaging] = useState<string[]>([]);
diff --git a/frontend/src/hooks/useResourceAttribute/__tests__/ResourceProvider.test.tsx b/frontend/src/hooks/useResourceAttribute/__tests__/ResourceProvider.test.tsx
index e439ec0152..6dc890d7f7 100644
--- a/frontend/src/hooks/useResourceAttribute/__tests__/ResourceProvider.test.tsx
+++ b/frontend/src/hooks/useResourceAttribute/__tests__/ResourceProvider.test.tsx
@@ -1,10 +1,10 @@
import { ReactNode } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
-import { Router } from 'react-router-dom';
import { act, renderHook, waitFor } from '@testing-library/react';
import ROUTES from 'constants/routes';
-import { createMemoryHistory, MemoryHistory } from 'history';
import { encode } from 'js-base64';
+import { navigate } from 'lib/router/navigation';
+import { TestRouter } from 'tests/router';
import ResourceProvider from '../ResourceProvider';
import useResourceAttribute from '../useResourceAttribute';
@@ -17,17 +17,6 @@ jest.mock('hooks/useSafeNavigate', () => ({
}),
}));
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: jest.fn(),
- location: {
- search: '',
- pathname: '/',
- },
- },
-}));
-
jest.mock('api/metrics/getResourceAttributes', () => ({
getResourceAttributesTagKeys: jest.fn(),
getResourceAttributesTagValues: jest.fn(),
@@ -37,10 +26,7 @@ jest.mock('api/metrics/getResourceAttributes', () => ({
import {
getResourceAttributesTagKeys,
getResourceAttributesTagValues,
- // eslint-disable-next-line import/newline-after-import
} from 'api/metrics/getResourceAttributes';
-// eslint-disable-next-line import/first, import/order
-import history from 'lib/history';
const mockTagKeys = getResourceAttributesTagKeys as jest.MockedFunction<
typeof getResourceAttributesTagKeys
@@ -50,9 +36,9 @@ const mockTagValues = getResourceAttributesTagValues as jest.MockedFunction<
>;
function createWrapper({
- routerHistory,
+ initialRoute,
}: {
- routerHistory: MemoryHistory;
+ initialRoute: string;
}): ({ children }: { children: ReactNode }) => JSX.Element {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -60,19 +46,14 @@ function createWrapper({
return function Wrapper({ children }: { children: ReactNode }): JSX.Element {
return (
<QueryClientProvider client={queryClient}>
- <Router history={routerHistory}>
+ <TestRouter initialRoute={initialRoute}>
<ResourceProvider>{children}</ResourceProvider>
- </Router>
+ </TestRouter>
</QueryClientProvider>
);
};
}
-function mockLibHistory(search = '', pathname = '/'): void {
- (history.location as { search: string; pathname: string }).search = search;
- (history.location as { search: string; pathname: string }).pathname = pathname;
-}
-
type TagKeysPayload = Parameters<typeof mockTagKeys.mockResolvedValue>[0];
type TagValuesPayload = Parameters<typeof mockTagValues.mockResolvedValue>[0];
@@ -112,14 +93,12 @@ describe('ResourceProvider', () => {
mockSafeNavigate.mockReset();
mockTagKeys.mockReset();
mockTagValues.mockReset();
- mockLibHistory('', '/');
});
describe('initial state', () => {
it('starts loading with empty staging, selectedQuery, and queries', () => {
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/' }),
});
expect(result.current.loading).toBe(true);
@@ -141,11 +120,10 @@ describe('ResourceProvider', () => {
tagValue: ['frontend'],
},
];
- mockLibHistory(`?resourceAttribute=${encode(JSON.stringify(seeded))}`, '/');
-
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({
+ initialRoute: `/?resourceAttribute=${encode(JSON.stringify(seeded))}`,
+ }),
});
expect(result.current.queries).toStrictEqual(seeded);
@@ -157,9 +135,8 @@ describe('ResourceProvider', () => {
mockTagKeys.mockResolvedValue(
successTagKeysPayload(['resource_service_name']),
);
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/' }),
});
act(() => {
@@ -179,9 +156,8 @@ describe('ResourceProvider', () => {
mockTagKeys.mockResolvedValue(
successTagKeysPayload(['resource_service_name']),
);
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/' }),
});
act(() => {
@@ -207,9 +183,8 @@ describe('ResourceProvider', () => {
mockTagValues.mockResolvedValue(
successTagValuesPayload(['frontend', 'backend']),
);
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/' }),
});
act(() => {
@@ -240,9 +215,8 @@ describe('ResourceProvider', () => {
successTagKeysPayload(['resource_service_name']),
);
mockTagValues.mockResolvedValue(successTagValuesPayload(['frontend']));
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/' }),
});
act(() => {
@@ -288,9 +262,8 @@ describe('ResourceProvider', () => {
successTagKeysPayload(['resource_service_name']),
);
mockTagValues.mockResolvedValue(successTagValuesPayload(['frontend']));
- const routerHistory = createMemoryHistory({ initialEntries: ['/svc'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/svc' }),
});
act(() => {
@@ -328,9 +301,8 @@ describe('ResourceProvider', () => {
mockTagKeys.mockResolvedValue(
successTagKeysPayload(['resource_service_name']),
);
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/' }),
});
act(() => {
@@ -355,11 +327,10 @@ describe('ResourceProvider', () => {
{ id: 'a', tagKey: 'resource_a', operator: 'IN', tagValue: ['x'] },
{ id: 'b', tagKey: 'resource_b', operator: 'IN', tagValue: ['y'] },
];
- mockLibHistory(`?resourceAttribute=${encode(JSON.stringify(seeded))}`, '/');
-
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({
+ initialRoute: `/?resourceAttribute=${encode(JSON.stringify(seeded))}`,
+ }),
});
expect(result.current.queries).toHaveLength(2);
@@ -378,11 +349,10 @@ describe('ResourceProvider', () => {
const seeded = [
{ id: 'a', tagKey: 'resource_a', operator: 'IN', tagValue: ['x'] },
];
- mockLibHistory(`?resourceAttribute=${encode(JSON.stringify(seeded))}`, '/');
-
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({
+ initialRoute: `/?resourceAttribute=${encode(JSON.stringify(seeded))}`,
+ }),
});
act(() => {
@@ -402,9 +372,8 @@ describe('ResourceProvider', () => {
describe('handleEnvironmentChange', () => {
it('adds a dotted environment query when envs are provided', async () => {
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/' }),
});
act(() => {
@@ -436,11 +405,10 @@ describe('ResourceProvider', () => {
tagValue: ['frontend'],
},
];
- mockLibHistory(`?resourceAttribute=${encode(JSON.stringify(seeded))}`, '/');
-
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({
+ initialRoute: `/?resourceAttribute=${encode(JSON.stringify(seeded))}`,
+ }),
});
act(() => {
@@ -463,11 +431,10 @@ describe('ResourceProvider', () => {
tagValue: ['production'],
},
];
- mockLibHistory(`?resourceAttribute=${encode(JSON.stringify(seeded))}`, '/');
-
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({
+ initialRoute: `/?resourceAttribute=${encode(JSON.stringify(seeded))}`,
+ }),
});
act(() => {
@@ -484,11 +451,8 @@ describe('ResourceProvider', () => {
});
it('preserves unrelated query params when dispatching', async () => {
- const routerHistory = createMemoryHistory({
- initialEntries: ['/?tab=overview'],
- });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/?tab=overview' }),
});
act(() => {
@@ -521,30 +485,24 @@ describe('ResourceProvider', () => {
];
it('exposes every query from the URL, including ones the map cannot apply', () => {
- mockLibHistory(
- `?resourceAttribute=${encode(JSON.stringify(seeded))}`,
- ROUTES.SERVICE_MAP,
- );
-
- const routerHistory = createMemoryHistory({
- initialEntries: [ROUTES.SERVICE_MAP],
- });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({
+ initialRoute: `${ROUTES.SERVICE_MAP}?resourceAttribute=${encode(
+ JSON.stringify(seeded),
+ )}`,
+ }),
});
expect(result.current.queries).toStrictEqual(seeded);
});
it('returns all queries on non-SERVICE_MAP routes', () => {
- mockLibHistory(
- `?resourceAttribute=${encode(JSON.stringify(seeded))}`,
- '/services',
- );
-
- const routerHistory = createMemoryHistory({ initialEntries: ['/services'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({
+ initialRoute: `/services?resourceAttribute=${encode(
+ JSON.stringify(seeded),
+ )}`,
+ }),
});
expect(result.current.queries).toHaveLength(2);
@@ -557,13 +515,8 @@ describe('ResourceProvider', () => {
'resource_k8s_cluster_name',
]),
);
- mockLibHistory('', ROUTES.SERVICE_MAP);
-
- const routerHistory = createMemoryHistory({
- initialEntries: [ROUTES.SERVICE_MAP],
- });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: ROUTES.SERVICE_MAP }),
});
act(() => {
@@ -584,9 +537,8 @@ describe('ResourceProvider', () => {
describe('URL re-hydration and in-flight loading', () => {
it('re-hydrates queries when the router URL changes mid-session', async () => {
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/' }),
});
expect(result.current.queries).toStrictEqual([]);
@@ -601,12 +553,10 @@ describe('ResourceProvider', () => {
];
const encoded = encode(JSON.stringify(seeded));
- // The useEffect that re-hydrates reads from lib/history (mocked singleton)
- // but is triggered by urlQuery, which comes from the router.
- // Update both to simulate a real URL change.
- mockLibHistory(`?resourceAttribute=${encoded}`, '/');
+ // The effect that re-hydrates reads the URL through lib/history, the same
+ // history the router runs on, so one navigation drives both.
act(() => {
- routerHistory.push(`/?resourceAttribute=${encoded}`);
+ navigate(`/?resourceAttribute=${encoded}`);
});
await waitFor(() => {
@@ -619,9 +569,8 @@ describe('ResourceProvider', () => {
mockTagKeys.mockResolvedValueOnce(
successTagKeysPayload(['resource_service_name']),
);
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/' }),
});
act(() => {
@@ -674,9 +623,8 @@ describe('ResourceProvider', () => {
payload: null,
} as unknown as TagKeysPayload);
- const routerHistory = createMemoryHistory({ initialEntries: ['/'] });
const { result } = renderHook(() => useResourceAttribute(), {
- wrapper: createWrapper({ routerHistory }),
+ wrapper: createWrapper({ initialRoute: '/' }),
});
act(() => {
diff --git a/frontend/src/hooks/useResourceAttribute/__tests__/useResourceAttribute.test.tsx b/frontend/src/hooks/useResourceAttribute/__tests__/useResourceAttribute.test.tsx
index 06ec856c32..07df8e99df 100644
--- a/frontend/src/hooks/useResourceAttribute/__tests__/useResourceAttribute.test.tsx
+++ b/frontend/src/hooks/useResourceAttribute/__tests__/useResourceAttribute.test.tsx
@@ -1,8 +1,8 @@
import { QueryClient, QueryClientProvider } from 'react-query';
-import { Router } from 'react-router-dom';
import { act, renderHook, waitFor } from '@testing-library/react';
-import { createMemoryHistory } from 'history';
+import { getCurrentLocation } from 'lib/router/navigation';
import { AppProvider } from 'providers/App/App';
+import { TestRouter } from 'tests/router';
import ResourceProvider from '../ResourceProvider';
import useResourceAttribute from '../useResourceAttribute';
@@ -17,15 +17,12 @@ jest.mock('hooks/useSafeNavigate', () => ({
describe('useResourceAttribute component hook', () => {
it('should not change other query params except for resourceAttribute', async () => {
- const history = createMemoryHistory({
- initialEntries: ['/inital-url?tab=overview'],
- });
const wrapper = ({ children }: { children: any }): JSX.Element => (
<QueryClientProvider client={queryClient}>
<AppProvider>
- <Router history={history}>
+ <TestRouter initialRoute="/inital-url?tab=overview">
<ResourceProvider>{children}</ResourceProvider>
- </Router>
+ </TestRouter>
</AppProvider>
</QueryClientProvider>
);
@@ -36,7 +33,7 @@ describe('useResourceAttribute component hook', () => {
});
await waitFor(() =>
- expect(history.location.search).toContain('tab=overview'),
+ expect(getCurrentLocation().search).toContain('tab=overview'),
);
});
});
diff --git a/frontend/src/hooks/useResourceAttribute/utils.ts b/frontend/src/hooks/useResourceAttribute/utils.ts
index 43aec688f1..962add084a 100644
--- a/frontend/src/hooks/useResourceAttribute/utils.ts
+++ b/frontend/src/hooks/useResourceAttribute/utils.ts
@@ -14,7 +14,7 @@ import {
IResourceAttributeProps,
} from 'hooks/useResourceAttribute/types';
import { decode } from 'js-base64';
-import history from 'lib/history';
+import { getCurrentLocation } from 'lib/router/navigation';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
import { OperatorValues, Tags } from 'hooks/useResourceAttribute/types';
@@ -252,7 +252,7 @@ export const updateQuery = (
export function getResourceAttributeQueriesFromURL(): IResourceAttribute[] {
const resourceAttributeQuery = new URLSearchParams(
- history.location.search,
+ getCurrentLocation().search,
).get('resourceAttribute');
try {
diff --git a/frontend/src/hooks/useUrlQuery.test.tsx b/frontend/src/hooks/useUrlQuery.test.tsx
index f599420d29..f814446f37 100644
--- a/frontend/src/hooks/useUrlQuery.test.tsx
+++ b/frontend/src/hooks/useUrlQuery.test.tsx
@@ -1,17 +1,17 @@
-import { Router } from 'react-router-dom';
import { act, renderHook } from '@testing-library/react';
-import { createMemoryHistory } from 'history';
+import { navigate } from 'lib/router/navigation';
+import { TestRouter } from 'tests/router';
import useUrlQuery from './useUrlQuery';
describe('useUrlQuery', () => {
it('returns URLSearchParams object for the current URL search', () => {
- const history = createMemoryHistory({
- initialEntries: ['/test?param1=value1&param2=value2'],
- });
-
const { result } = renderHook(() => useUrlQuery(), {
- wrapper: ({ children }) => <Router history={history}>{children}</Router>,
+ wrapper: ({ children }) => (
+ <TestRouter initialRoute="/test?param1=value1&param2=value2">
+ {children}
+ </TestRouter>
+ ),
});
expect(result.current.get('param1')).toBe('value1');
@@ -19,19 +19,17 @@ describe('useUrlQuery', () => {
});
it('updates URLSearchParams object when URL search changes', () => {
- const history = createMemoryHistory({
- initialEntries: ['/test?param1=value1'],
- });
-
const { result, rerender } = renderHook(() => useUrlQuery(), {
- wrapper: ({ children }) => <Router history={history}>{children}</Router>,
+ wrapper: ({ children }) => (
+ <TestRouter initialRoute="/test?param1=value1">{children}</TestRouter>
+ ),
});
expect(result.current.get('param1')).toBe('value1');
expect(result.current.get('param2')).toBeNull();
act(() => {
- history.push('/test?param1=newValue1&param2=value2');
+ navigate('/test?param1=newValue1&param2=value2');
});
rerender();
@@ -41,12 +39,10 @@ describe('useUrlQuery', () => {
});
it('returns empty URLSearchParams object when no query parameters are present', () => {
- const history = createMemoryHistory({
- initialEntries: ['/test'],
- });
-
const { result } = renderHook(() => useUrlQuery(), {
- wrapper: ({ children }) => <Router history={history}>{children}</Router>,
+ wrapper: ({ children }) => (
+ <TestRouter initialRoute="/test">{children}</TestRouter>
+ ),
});
expect(result.current.toString()).toBe('');
diff --git a/frontend/src/hooks/useUrlQuery.ts b/frontend/src/hooks/useUrlQuery.ts
index 11cb555485..92c03abfcc 100644
--- a/frontend/src/hooks/useUrlQuery.ts
+++ b/frontend/src/hooks/useUrlQuery.ts
@@ -1,8 +1,8 @@
import { useMemo } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
function useUrlQuery(): URLSearchParams {
- const { search } = useLocation();
+ const { search } = useAppLocation();
return useMemo(() => new URLSearchParams(search), [search]);
}
diff --git a/frontend/src/hooks/useUrlQueryData.ts b/frontend/src/hooks/useUrlQueryData.ts
index 81be3e546e..cc8e26ee84 100644
--- a/frontend/src/hooks/useUrlQueryData.ts
+++ b/frontend/src/hooks/useUrlQueryData.ts
@@ -1,5 +1,5 @@
import { useCallback, useMemo } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { useSafeNavigate } from './useSafeNavigate';
import useUrlQuery from './useUrlQuery';
@@ -8,7 +8,7 @@ const useUrlQueryData = <T>(
queryKey: string,
defaultData?: T,
): UseUrlQueryData<T> => {
- const location = useLocation();
+ const location = useAppLocation();
const urlQuery = useUrlQuery();
const { safeNavigate } = useSafeNavigate();
diff --git a/frontend/src/hooks/useZoomOut.ts b/frontend/src/hooks/useZoomOut.ts
index 03432b88b6..b0cd2c18de 100644
--- a/frontend/src/hooks/useZoomOut.ts
+++ b/frontend/src/hooks/useZoomOut.ts
@@ -1,7 +1,7 @@
import { useCallback, useRef } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
@@ -35,7 +35,7 @@ export function useZoomOut(options: UseZoomOutOptions = {}): () => void {
(state) => state.globalTime,
);
const urlQuery = useUrlQuery();
- const location = useLocation();
+ const location = useAppLocation();
const { safeNavigate } = useSafeNavigate();
return useCallback((): void => {
diff --git a/frontend/src/lib/authz/components/withAuthZ/withAuthZ.authz.test.tsx b/frontend/src/lib/authz/components/withAuthZ/withAuthZ.authz.test.tsx
index 4e04897c6b..e52ad02d7f 100644
--- a/frontend/src/lib/authz/components/withAuthZ/withAuthZ.authz.test.tsx
+++ b/frontend/src/lib/authz/components/withAuthZ/withAuthZ.authz.test.tsx
@@ -15,20 +15,12 @@ import {
buildObjectString,
buildPermission,
} from 'lib/authz/hooks/useAuthZ/utils';
+import { mockAppLocation, mockAppParams } from 'tests/router-mocks';
import { withAuthZ, RouterContext } from './withAuthZ';
import { withAuthZContent } from './withAuthZContent';
import { withAuthZPage } from './withAuthZPage';
-const mockUseParams = jest.fn();
-const mockUseLocation = jest.fn();
-
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useParams: (): Record<string, string> => mockUseParams(),
- useLocation: (): { pathname: string; search: string } => mockUseLocation(),
-}));
-
const readPerm = buildPermission('read', 'role:*' as AuthZObject<'read'>);
function Base(): JSX.Element {
@@ -36,8 +28,8 @@ function Base(): JSX.Element {
}
beforeEach(() => {
- mockUseParams.mockReturnValue({});
- mockUseLocation.mockReturnValue({ pathname: '/', search: '' });
+ mockAppParams({});
+ mockAppLocation({ pathname: '/', search: '' });
});
describe('withAuthZ', () => {
@@ -138,7 +130,7 @@ describe('withAuthZContent', () => {
describe('withAuthZ router context', () => {
it('extracts checks from route params via router.params', async () => {
- mockUseParams.mockReturnValue({ roleId: 'r-123' });
+ mockAppParams({ roleId: 'r-123' });
const rolePerm = buildPermission(
'read',
@@ -164,7 +156,7 @@ describe('withAuthZ router context', () => {
});
it('extracts checks from query params via router.searchParams', async () => {
- mockUseLocation.mockReturnValue({
+ mockAppLocation({
pathname: '/roles',
search: '?roleId=r-456',
});
@@ -193,7 +185,7 @@ describe('withAuthZ router context', () => {
});
it('extracts checks from pathname via router.matchPath', async () => {
- mockUseLocation.mockReturnValue({
+ mockAppLocation({
pathname: '/settings/roles/r-789/edit',
search: '',
});
@@ -229,7 +221,7 @@ describe('withAuthZ router context', () => {
});
it('denies when router-derived permission is not allowed', async () => {
- mockUseParams.mockReturnValue({ roleId: 'r-denied' });
+ mockAppParams({ roleId: 'r-denied' });
const deniedPerm = buildPermission(
'read',
@@ -271,8 +263,8 @@ describe('withAuthZ router context stability', () => {
});
it('does not re-render when useParams returns new object with same values', async () => {
- mockUseParams.mockReturnValue({ roleId: 'r-1' });
- mockUseLocation.mockReturnValue({ pathname: '/', search: '' });
+ mockAppParams({ roleId: 'r-1' });
+ mockAppLocation({ pathname: '/', search: '' });
const Guarded = withAuthZ(RenderCounter, {
checks: (_props, router: RouterContext) => [
@@ -292,7 +284,7 @@ describe('withAuthZ router context stability', () => {
const initialCount = renderCount;
// Return NEW object with SAME values — should not cause re-render
- mockUseParams.mockReturnValue({ roleId: 'r-1' });
+ mockAppParams({ roleId: 'r-1' });
rerender(<Guarded />);
// Allow any pending effects to flush
@@ -302,8 +294,8 @@ describe('withAuthZ router context stability', () => {
});
it('does not re-render when useLocation returns new object with same pathname', async () => {
- mockUseParams.mockReturnValue({});
- mockUseLocation.mockReturnValue({ pathname: '/roles', search: '' });
+ mockAppParams({});
+ mockAppLocation({ pathname: '/roles', search: '' });
const Guarded = withAuthZ(RenderCounter, {
checks: (_props, router: RouterContext) => {
@@ -323,7 +315,7 @@ describe('withAuthZ router context stability', () => {
const initialCount = renderCount;
// Return NEW object with SAME pathname — should not cause re-render
- mockUseLocation.mockReturnValue({ pathname: '/roles', search: '' });
+ mockAppLocation({ pathname: '/roles', search: '' });
rerender(<Guarded />);
await waitFor(() => {
@@ -332,8 +324,8 @@ describe('withAuthZ router context stability', () => {
});
it('does not re-render when useLocation returns new object with same search params', async () => {
- mockUseParams.mockReturnValue({});
- mockUseLocation.mockReturnValue({ pathname: '/', search: '?tab=keys' });
+ mockAppParams({});
+ mockAppLocation({ pathname: '/', search: '?tab=keys' });
const Guarded = withAuthZ(RenderCounter, {
checks: (_props, router: RouterContext) => {
@@ -352,7 +344,7 @@ describe('withAuthZ router context stability', () => {
const initialCount = renderCount;
// Return NEW object with SAME search — should not cause re-render
- mockUseLocation.mockReturnValue({ pathname: '/', search: '?tab=keys' });
+ mockAppLocation({ pathname: '/', search: '?tab=keys' });
rerender(<Guarded />);
await waitFor(() => {
@@ -361,8 +353,8 @@ describe('withAuthZ router context stability', () => {
});
it('re-renders when params values actually change', async () => {
- mockUseParams.mockReturnValue({ roleId: 'r-1' });
- mockUseLocation.mockReturnValue({ pathname: '/', search: '' });
+ mockAppParams({ roleId: 'r-1' });
+ mockAppLocation({ pathname: '/', search: '' });
const Guarded = withAuthZ(RenderCounter, {
checks: (_props, router: RouterContext) => [
@@ -383,7 +375,7 @@ describe('withAuthZ router context stability', () => {
unmount();
// Return DIFFERENT values — re-mount with new mock values
- mockUseParams.mockReturnValue({ roleId: 'r-2' });
+ mockAppParams({ roleId: 'r-2' });
render(<Guarded />);
await waitFor(() => {
@@ -392,8 +384,8 @@ describe('withAuthZ router context stability', () => {
});
it('re-renders when pathname actually changes', async () => {
- mockUseParams.mockReturnValue({});
- mockUseLocation.mockReturnValue({ pathname: '/roles', search: '' });
+ mockAppParams({});
+ mockAppLocation({ pathname: '/roles', search: '' });
const Guarded = withAuthZ(RenderCounter, {
checks: [readPerm],
@@ -409,7 +401,7 @@ describe('withAuthZ router context stability', () => {
unmount();
// DIFFERENT pathname — re-mount with new mock values
- mockUseLocation.mockReturnValue({ pathname: '/users', search: '' });
+ mockAppLocation({ pathname: '/users', search: '' });
render(<Guarded />);
await waitFor(() => {
@@ -418,8 +410,8 @@ describe('withAuthZ router context stability', () => {
});
it('re-renders when search params actually change', async () => {
- mockUseParams.mockReturnValue({});
- mockUseLocation.mockReturnValue({ pathname: '/', search: '?tab=keys' });
+ mockAppParams({});
+ mockAppLocation({ pathname: '/', search: '?tab=keys' });
const Guarded = withAuthZ(RenderCounter, {
checks: [readPerm],
@@ -435,7 +427,7 @@ describe('withAuthZ router context stability', () => {
unmount();
// DIFFERENT search — re-mount with new mock values
- mockUseLocation.mockReturnValue({ pathname: '/', search: '?tab=details' });
+ mockAppLocation({ pathname: '/', search: '?tab=details' });
render(<Guarded />);
await waitFor(() => {
diff --git a/frontend/src/lib/authz/components/withAuthZ/withAuthZ.utils.tsx b/frontend/src/lib/authz/components/withAuthZ/withAuthZ.utils.tsx
index fb0a425aad..1add3aaa0e 100644
--- a/frontend/src/lib/authz/components/withAuthZ/withAuthZ.utils.tsx
+++ b/frontend/src/lib/authz/components/withAuthZ/withAuthZ.utils.tsx
@@ -1,12 +1,10 @@
import { ComponentType, ReactElement, createElement, useMemo } from 'react';
-import {
- matchPath as reactRouterMatchPath,
- useLocation,
- useParams,
-} from 'react-router-dom';
import type { AuthZGuardProps } from 'lib/authz/components/AuthZGuard/AuthZGuard';
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
+import { matchRoute } from 'lib/router/matchRoute';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppParams } from 'lib/router/useAppParams';
export type RouterContext = {
/**
@@ -64,14 +62,14 @@ export type WithAuthZOptions<P> = {
};
function useStableParams(): Record<string, string | undefined> {
- const params = useParams();
+ const params = useAppParams();
const paramsJson = JSON.stringify(params);
return useMemo(() => JSON.parse(paramsJson), [paramsJson]);
}
function useRouterContext(): RouterContext {
const params = useStableParams();
- const { pathname, search } = useLocation();
+ const { pathname, search } = useAppLocation();
const searchParams = useMemo(() => new URLSearchParams(search), [search]);
return useMemo(
@@ -82,11 +80,8 @@ function useRouterContext(): RouterContext {
matchPath: <Params extends Record<string, string>>(
pattern: string,
): Params | null => {
- const match = reactRouterMatchPath<Params>(pathname, {
- path: pattern,
- exact: false,
- });
- return match?.params ?? null;
+ const match = matchRoute(pathname, pattern, { exact: false });
+ return (match?.params as Params) ?? null;
},
}),
[params, pathname, searchParams],
diff --git a/frontend/src/lib/router/AppLink.tsx b/frontend/src/lib/router/AppLink.tsx
new file mode 100644
index 0000000000..33ecf8a234
--- /dev/null
+++ b/frontend/src/lib/router/AppLink.tsx
@@ -0,0 +1,34 @@
+import { forwardRef } from 'react';
+import type { AnchorHTMLAttributes, ReactNode } from 'react';
+import { Link } from 'react-router-dom';
+
+import type { To } from './types';
+import { useAppLocation } from './useAppLocation';
+import { withState } from './utils';
+
+export interface AppLinkProps extends Omit<
+ AnchorHTMLAttributes<HTMLAnchorElement>,
+ 'href'
+> {
+ to: To;
+ replace?: boolean;
+ state?: unknown;
+ children?: ReactNode;
+}
+
+export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
+ function AppLink({ to, replace, state, children, ...rest }, ref) {
+ const location = useAppLocation();
+
+ return (
+ <Link
+ ref={ref}
+ to={withState(to, state, location)}
+ replace={replace}
+ {...rest}
+ >
+ {children}
+ </Link>
+ );
+ },
+);
diff --git a/frontend/src/lib/router/Redirect.tsx b/frontend/src/lib/router/Redirect.tsx
new file mode 100644
index 0000000000..7f7fae56be
--- /dev/null
+++ b/frontend/src/lib/router/Redirect.tsx
@@ -0,0 +1,27 @@
+import { Redirect as RouterRedirect } from 'react-router-dom';
+
+import type { To } from './types';
+import { withState } from './utils';
+
+export interface RedirectProps {
+ to: To;
+ /**
+ * Defaults to `true`, matching v5's `<Redirect>`. v6's `<Navigate>` pushes
+ * unless told otherwise, which is invisible until someone presses Back.
+ */
+ replace?: boolean;
+ state?: unknown;
+}
+
+export function Redirect({
+ to,
+ replace = true,
+ state,
+}: RedirectProps): JSX.Element {
+ return <RouterRedirect to={withState(to, state)} push={!replace} />;
+}
+
+Redirect.defaultProps = {
+ replace: true,
+ state: undefined,
+};
diff --git a/frontend/src/lib/router/__tests__/AppLink.test.tsx b/frontend/src/lib/router/__tests__/AppLink.test.tsx
new file mode 100644
index 0000000000..a3f41128b7
--- /dev/null
+++ b/frontend/src/lib/router/__tests__/AppLink.test.tsx
@@ -0,0 +1,172 @@
+import { createRef } from 'react';
+import type { ReactNode } from 'react';
+import { useHistory } from 'react-router-dom';
+import { cleanup, fireEvent, render, screen } from 'tests/test-utils';
+
+import { AppLink, type AppLinkProps } from '../AppLink';
+import { useAppLocation } from '../useAppLocation';
+
+function LocationProbe(): JSX.Element {
+ const location = useAppLocation();
+ const history = useHistory();
+
+ return (
+ <div>
+ <span data-testid="pathname">{location.pathname}</span>
+ <span data-testid="search">{location.search}</span>
+ <span data-testid="hash">{location.hash}</span>
+ <span data-testid="state">{JSON.stringify(location.state ?? null)}</span>
+ <span data-testid="length">{history.length}</span>
+ </div>
+ );
+}
+
+function renderLink(
+ props: AppLinkProps,
+ children: ReactNode = 'go',
+ initialEntry = '/',
+): void {
+ render(
+ <>
+ <AppLink {...props}>{children}</AppLink>
+ <LocationProbe />
+ </>,
+ undefined,
+ { initialRoute: initialEntry },
+ );
+}
+
+describe('AppLink', () => {
+ it('renders an anchor with the resolved href', () => {
+ renderLink({ to: '/logs?a=1', 'data-testid': 'link' } as AppLinkProps);
+
+ expect(screen.getByTestId('link')).toHaveAttribute('href', '/logs?a=1');
+ });
+
+ it('resolves an object target', () => {
+ renderLink({
+ to: { pathname: '/logs', search: '?a=1' },
+ 'data-testid': 'link',
+ } as AppLinkProps);
+
+ expect(screen.getByTestId('link')).toHaveAttribute('href', '/logs?a=1');
+ });
+
+ it('forwards anchor attributes and children', () => {
+ renderLink(
+ {
+ to: '/logs',
+ className: 'nav-item',
+ target: '_blank',
+ title: 'Logs',
+ 'data-testid': 'link',
+ } as AppLinkProps,
+ <span data-testid="child">Logs</span>,
+ );
+
+ const link = screen.getByTestId('link');
+ expect(link).toHaveClass('nav-item');
+ expect(link).toHaveAttribute('target', '_blank');
+ expect(link).toHaveAttribute('title', 'Logs');
+ expect(screen.getByTestId('child')).toBeInTheDocument();
+ });
+
+ it('navigates on click', () => {
+ renderLink({ to: '/logs?a=1#top', 'data-testid': 'link' } as AppLinkProps);
+ fireEvent.click(screen.getByTestId('link'));
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ expect(screen.getByTestId('search')).toHaveTextContent('?a=1');
+ expect(screen.getByTestId('hash')).toHaveTextContent('#top');
+ });
+
+ it('carries state without folding search and hash into the pathname', () => {
+ renderLink({
+ to: '/logs?a=1#top',
+ state: { from: 'test' },
+ 'data-testid': 'link',
+ } as AppLinkProps);
+ fireEvent.click(screen.getByTestId('link'));
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ expect(screen.getByTestId('search')).toHaveTextContent('?a=1');
+ expect(screen.getByTestId('hash')).toHaveTextContent('#top');
+ expect(screen.getByTestId('state')).toHaveTextContent('{"from":"test"}');
+ });
+
+ it('keeps the current pathname for a search-only string with state', () => {
+ renderLink(
+ { to: '?tab=2', state: { a: 1 }, 'data-testid': 'link' } as AppLinkProps,
+ 'go',
+ '/x/y?q=1',
+ );
+
+ expect(screen.getByTestId('link')).toHaveAttribute('href', '/x/y?tab=2');
+ fireEvent.click(screen.getByTestId('link'));
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/x/y');
+ expect(screen.getByTestId('search')).toHaveTextContent('?tab=2');
+ expect(screen.getByTestId('state')).toHaveTextContent('{"a":1}');
+ });
+
+ it('keeps the current pathname for a hash-only string with state', () => {
+ renderLink(
+ { to: '#h', state: { a: 1 }, 'data-testid': 'link' } as AppLinkProps,
+ 'go',
+ '/x/y?q=1',
+ );
+
+ expect(screen.getByTestId('link')).toHaveAttribute('href', '/x/y#h');
+ });
+
+ it('decodes a string target with state once, as without state', () => {
+ renderLink({ to: '/a%2520b', 'data-testid': 'link' } as AppLinkProps);
+ fireEvent.click(screen.getByTestId('link'));
+ const withoutState = screen.getByTestId('pathname').textContent;
+ cleanup();
+
+ renderLink({
+ to: '/a%2520b',
+ state: { a: 1 },
+ 'data-testid': 'link',
+ } as AppLinkProps);
+ fireEvent.click(screen.getByTestId('link'));
+
+ expect(screen.getByTestId('pathname').textContent).toBe(withoutState);
+ });
+
+ it('carries state on an object target', () => {
+ renderLink({
+ to: { pathname: '/logs' },
+ state: { from: 'test' },
+ 'data-testid': 'link',
+ } as AppLinkProps);
+ fireEvent.click(screen.getByTestId('link'));
+
+ expect(screen.getByTestId('state')).toHaveTextContent('{"from":"test"}');
+ });
+
+ it('replaces the entry when replace is set', () => {
+ renderLink({
+ to: '/logs',
+ replace: true,
+ 'data-testid': 'link',
+ } as AppLinkProps);
+ const before = screen.getByTestId('length').textContent;
+ fireEvent.click(screen.getByTestId('link'));
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ expect(screen.getByTestId('length').textContent).toBe(before);
+ });
+
+ it('forwards a ref to the anchor', () => {
+ const ref = createRef<HTMLAnchorElement>();
+ render(
+ <AppLink ref={ref} to="/logs">
+ go
+ </AppLink>,
+ );
+
+ expect(ref.current).toBeInstanceOf(HTMLAnchorElement);
+ });
+});
diff --git a/frontend/src/lib/router/__tests__/Redirect.test.tsx b/frontend/src/lib/router/__tests__/Redirect.test.tsx
new file mode 100644
index 0000000000..16b14b091e
--- /dev/null
+++ b/frontend/src/lib/router/__tests__/Redirect.test.tsx
@@ -0,0 +1,65 @@
+import { useHistory } from 'react-router-dom';
+import { render, screen } from 'tests/test-utils';
+
+import { Redirect, type RedirectProps } from '../Redirect';
+import { useAppLocation } from '../useAppLocation';
+
+function LocationProbe(): JSX.Element {
+ const location = useAppLocation();
+ const history = useHistory();
+
+ return (
+ <div>
+ <span data-testid="pathname">{location.pathname}</span>
+ <span data-testid="search">{location.search}</span>
+ <span data-testid="state">{JSON.stringify(location.state ?? null)}</span>
+ <span data-testid="action">{history.action}</span>
+ </div>
+ );
+}
+
+function renderRedirect(props: RedirectProps): void {
+ render(
+ <>
+ <Redirect {...props} />
+ <LocationProbe />
+ </>,
+ );
+}
+
+describe('Redirect', () => {
+ it('navigates to the target', () => {
+ renderRedirect({ to: '/logs?a=1' });
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ expect(screen.getByTestId('search')).toHaveTextContent('?a=1');
+ });
+
+ it('replaces by default, so Back does not re-run the redirect', () => {
+ renderRedirect({ to: '/logs' });
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ expect(screen.getByTestId('action')).toHaveTextContent('REPLACE');
+ });
+
+ it('pushes when replace is false', () => {
+ renderRedirect({ to: '/logs', replace: false });
+
+ expect(screen.getByTestId('action')).toHaveTextContent('PUSH');
+ });
+
+ it('resolves an object target', () => {
+ renderRedirect({ to: { pathname: '/logs', search: '?a=1' } });
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ expect(screen.getByTestId('search')).toHaveTextContent('?a=1');
+ });
+
+ it('carries state without folding search into the pathname', () => {
+ renderRedirect({ to: '/logs?a=1', state: { from: 'test' } });
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ expect(screen.getByTestId('search')).toHaveTextContent('?a=1');
+ expect(screen.getByTestId('state')).toHaveTextContent('{"from":"test"}');
+ });
+});
diff --git a/frontend/src/lib/router/__tests__/buildRoutePath.test.ts b/frontend/src/lib/router/__tests__/buildRoutePath.test.ts
new file mode 100644
index 0000000000..2525d1a147
--- /dev/null
+++ b/frontend/src/lib/router/__tests__/buildRoutePath.test.ts
@@ -0,0 +1,62 @@
+import ROUTES from 'constants/routes';
+
+import { buildRoutePath } from '../buildRoutePath';
+
+/**
+ * These assertions pin every URL `buildRoutePath` produces, so a router
+ * upgrade cannot change one unnoticed.
+ */
+describe('buildRoutePath', () => {
+ it('fills a single param', () => {
+ expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: 'abc123' })).toBe(
+ '/trace/abc123',
+ );
+ });
+
+ it('fills multiple params', () => {
+ expect(
+ buildRoutePath('/dashboard/:dashboardId/new-panel/:panelId', {
+ dashboardId: 'd1',
+ panelId: 'p2',
+ }),
+ ).toBe('/dashboard/d1/new-panel/p2');
+ });
+
+ it('is a no-op on a pattern without params', () => {
+ expect(buildRoutePath(ROUTES.ALERT_HISTORY)).toBe('/alerts/history');
+ });
+
+ it('leaves uuids and hex ids byte-identical', () => {
+ const uuid = '6f532456-8cc0-4514-a93b-aed665c32b47';
+ expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: uuid })).toBe(
+ `/trace/${uuid}`,
+ );
+ });
+
+ describe('param encoding', () => {
+ it.each([
+ ['/', 'a/b', '/trace/a%2Fb'],
+ ['?', 'a?b', '/trace/a%3Fb'],
+ ['#', 'a#b', '/trace/a%23b'],
+ ['%', 'a%b', '/trace/a%25b'],
+ ['a space', 'a b', '/trace/a%20b'],
+ ['non-ascii', 'aé', '/trace/a%C3%A9'],
+ ])('percent-encodes %s', (_label, value, expected) => {
+ expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: value })).toBe(expected);
+ });
+
+ it('leaves a colon alone', () => {
+ expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: 'a:b' })).toBe(
+ '/trace/a:b',
+ );
+ });
+ });
+
+ it('stringifies a numeric param', () => {
+ expect(buildRoutePath(ROUTES.TRACE_DETAIL, { id: 42 })).toBe('/trace/42');
+ });
+
+ it('throws when a required param is missing', () => {
+ expect(() => buildRoutePath(ROUTES.TRACE_DETAIL)).toThrow(/id/);
+ });
+});
diff --git a/frontend/src/lib/router/__tests__/matchRoute.test.ts b/frontend/src/lib/router/__tests__/matchRoute.test.ts
new file mode 100644
index 0000000000..588fe1fd7b
--- /dev/null
+++ b/frontend/src/lib/router/__tests__/matchRoute.test.ts
@@ -0,0 +1,106 @@
+import ROUTES from 'constants/routes';
+
+import { buildRoutePath } from '../buildRoutePath';
+import { matchRoute } from '../matchRoute';
+
+describe('matchRoute', () => {
+ describe('exact defaults to false (v5 string-form semantics)', () => {
+ it('prefix-matches when no options are passed', () => {
+ expect(matchRoute('/settings/roles', ROUTES.SETTINGS)).not.toBeNull();
+ });
+
+ it('reports end: false on the returned pattern', () => {
+ expect(
+ matchRoute('/settings/roles', ROUTES.SETTINGS)?.pattern,
+ ).toStrictEqual({
+ path: ROUTES.SETTINGS,
+ caseSensitive: false,
+ end: false,
+ });
+ });
+
+ it('behaves the same for an explicit exact: false', () => {
+ expect(
+ matchRoute('/settings/roles', ROUTES.SETTINGS, { exact: false }),
+ ).toStrictEqual(matchRoute('/settings/roles', ROUTES.SETTINGS));
+ });
+
+ it('prefix-matches the two call sites that pass no options', () => {
+ expect(matchRoute('/trace/abc123', ROUTES.TRACE_DETAIL)).not.toBeNull();
+ expect(
+ matchRoute('/trace/abc123/child', ROUTES.TRACE_DETAIL)?.params,
+ ).toStrictEqual({ id: 'abc123' });
+ });
+ });
+
+ describe('exact: true', () => {
+ it('rejects a longer pathname', () => {
+ expect(
+ matchRoute('/settings/roles', ROUTES.SETTINGS, { exact: true }),
+ ).toBeNull();
+ });
+
+ it('matches the pathname itself', () => {
+ expect(
+ matchRoute('/settings', ROUTES.SETTINGS, { exact: true }),
+ ).not.toBeNull();
+ });
+
+ it('reports end: true on the returned pattern', () => {
+ expect(
+ matchRoute('/alerts/history', ROUTES.ALERT_HISTORY, { exact: true })
+ ?.pattern,
+ ).toStrictEqual({
+ path: ROUTES.ALERT_HISTORY,
+ caseSensitive: false,
+ end: true,
+ });
+ });
+ });
+
+ describe('result shape', () => {
+ it('extracts params', () => {
+ const match = matchRoute<'roleId'>(
+ '/settings/roles/1f8b',
+ ROUTES.ROLE_DETAILS,
+ { exact: true },
+ );
+ expect(match?.params.roleId).toBe('1f8b');
+ });
+
+ it('reports the matched portion as pathname and pathnameBase', () => {
+ const match = matchRoute('/settings/roles/1f8b', ROUTES.SETTINGS);
+ expect(match?.pathname).toBe('/settings');
+ expect(match?.pathnameBase).toBe('/settings');
+ });
+
+ it('returns null when the pattern does not match', () => {
+ expect(matchRoute('/logs', ROUTES.SETTINGS)).toBeNull();
+ });
+
+ it('does not partially match a path segment', () => {
+ expect(matchRoute('/settingsx', ROUTES.SETTINGS)).toBeNull();
+ });
+
+ it('un-escapes %2F in param values, as v6 does', () => {
+ expect(
+ matchRoute<'id'>('/trace/a%2Fb', ROUTES.TRACE_DETAIL, { exact: true })
+ ?.params.id,
+ ).toBe('a/b');
+ });
+
+ it('leaves every other escape sequence alone, as v6 does', () => {
+ expect(
+ matchRoute<'id'>('/trace/a%20b', ROUTES.TRACE_DETAIL, { exact: true })
+ ?.params.id,
+ ).toBe('a%20b');
+ });
+
+ it('round-trips a value built by buildRoutePath', () => {
+ const path = buildRoutePath(ROUTES.TRACE_DETAIL, { id: 'a/b' });
+ expect(
+ matchRoute<'id'>(path, ROUTES.TRACE_DETAIL, { exact: true })?.params.id,
+ ).toBe('a/b');
+ });
+ });
+});
diff --git a/frontend/src/lib/router/__tests__/navigation.test.ts b/frontend/src/lib/router/__tests__/navigation.test.ts
new file mode 100644
index 0000000000..a288b108f1
--- /dev/null
+++ b/frontend/src/lib/router/__tests__/navigation.test.ts
@@ -0,0 +1,411 @@
+import type { BlockedTransition } from '../types';
+
+/**
+ * `lib/history` is a module-level singleton that reads the base path at import
+ * time, so every case loads it in isolation with a fresh DOM.
+ */
+type NavigationModule = typeof import('../navigation');
+
+function loadNavigation(baseHref?: string): NavigationModule {
+ if (baseHref !== undefined) {
+ const base = document.createElement('base');
+ base.setAttribute('href', baseHref);
+ document.head.append(base);
+ }
+
+ let mod!: NavigationModule;
+ jest.isolateModules(() => {
+ // oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
+ mod = require('../navigation');
+ });
+ return mod;
+}
+
+function settle(): Promise<void> {
+ return new Promise((resolve) => {
+ setTimeout(resolve, 60);
+ });
+}
+
+beforeEach(() => {
+ window.history.replaceState(null, '', '/');
+});
+
+afterEach(() => {
+ for (const element of document.head.querySelectorAll('base')) {
+ element.remove();
+ }
+});
+
+describe('navigate', () => {
+ it('pushes a string target', () => {
+ const nav = loadNavigation();
+ nav.navigate('/logs');
+ expect(nav.getCurrentLocation().pathname).toBe('/logs');
+ });
+
+ it('carries search and hash from a string target', () => {
+ const nav = loadNavigation();
+ nav.navigate('/logs?a=1#top');
+ expect(nav.getCurrentLocation()).toMatchObject({
+ pathname: '/logs',
+ search: '?a=1',
+ hash: '#top',
+ });
+ });
+
+ it('pushes an object target', () => {
+ const nav = loadNavigation();
+ nav.navigate({ pathname: '/logs', search: '?a=1' });
+ expect(nav.getCurrentLocation()).toMatchObject({
+ pathname: '/logs',
+ search: '?a=1',
+ });
+ });
+
+ it('attaches state to a string target', () => {
+ const nav = loadNavigation();
+ nav.navigate('/logs', { state: { from: 'test' } });
+ expect(nav.getCurrentLocation().state).toStrictEqual({ from: 'test' });
+ });
+
+ it('attaches state to an object target', () => {
+ const nav = loadNavigation();
+ nav.navigate({ pathname: '/logs' }, { state: { from: 'test' } });
+ expect(nav.getCurrentLocation().state).toStrictEqual({ from: 'test' });
+ });
+
+ it('replaces without adding a history entry', () => {
+ const nav = loadNavigation();
+ const before = window.history.length;
+ nav.navigate('/logs', { replace: true });
+ expect(nav.getCurrentLocation().pathname).toBe('/logs');
+ expect(window.history).toHaveLength(before);
+ });
+
+ it('adds a history entry when pushing', () => {
+ const nav = loadNavigation();
+ const before = window.history.length;
+ nav.navigate('/logs');
+ expect(window.history).toHaveLength(before + 1);
+ });
+
+ it('does not suppress a same-URL push', () => {
+ const nav = loadNavigation();
+ nav.navigate('/logs');
+ const before = window.history.length;
+ nav.navigate('/logs');
+ expect(window.history).toHaveLength(before + 1);
+ });
+});
+
+describe('basename ownership', () => {
+ it('takes basename-free paths and writes a prefixed browser URL', () => {
+ const nav = loadNavigation('/signoz/');
+ nav.navigate('/logs');
+ expect(window.location.pathname).toBe('/signoz/logs');
+ });
+
+ it('returns a basename-free pathname', () => {
+ const nav = loadNavigation('/signoz/');
+ nav.navigate('/logs');
+ expect(nav.getCurrentLocation().pathname).toBe('/logs');
+ });
+
+ it('does not double-prefix a path that already carries the base path', () => {
+ const nav = loadNavigation('/signoz/');
+ nav.navigate('/logs');
+ nav.navigate(nav.getCurrentLocation().pathname);
+ expect(window.location.pathname).toBe('/signoz/logs');
+ });
+});
+
+describe('back', () => {
+ it('restores the previous location', async () => {
+ const nav = loadNavigation();
+ nav.navigate('/logs');
+ nav.navigate('/traces');
+
+ nav.back();
+ await settle();
+
+ expect(nav.getCurrentLocation().pathname).toBe('/logs');
+ });
+});
+
+describe('hasInAppHistory', () => {
+ it('is false before any in-app push', () => {
+ const nav = loadNavigation();
+ expect(nav.hasInAppHistory()).toBe(false);
+ });
+
+ it('is false after a replace', () => {
+ const nav = loadNavigation();
+ nav.navigate('/logs', { replace: true });
+ expect(nav.hasInAppHistory()).toBe(false);
+ });
+
+ it('is true after a push', () => {
+ const nav = loadNavigation();
+ nav.navigate('/logs');
+ expect(nav.hasInAppHistory()).toBe(true);
+ });
+});
+
+describe('blockNavigation', () => {
+ it('hands the blocker a transition and cancels the navigation', () => {
+ const nav = loadNavigation();
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+
+ nav.navigate('/logs');
+
+ expect(seen).toHaveLength(1);
+ expect(seen[0].action).toBe('PUSH');
+ expect(seen[0].location.pathname).toBe('/logs');
+ expect(typeof seen[0].retry).toBe('function');
+ expect(nav.getCurrentLocation().pathname).toBe('/');
+ unblock();
+ });
+
+ it('completes the navigation when retry runs after unblocking', () => {
+ const nav = loadNavigation();
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+
+ nav.navigate('/logs');
+ unblock();
+ seen[0].retry();
+
+ expect(nav.getCurrentLocation().pathname).toBe('/logs');
+ });
+
+ it('blocks again when retry runs while still blocked, as history@5 does', () => {
+ const nav = loadNavigation();
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+
+ nav.navigate('/logs');
+ seen[0].retry();
+
+ expect(seen).toHaveLength(2);
+ expect(nav.getCurrentLocation().pathname).toBe('/');
+ unblock();
+ });
+
+ it('lets a POP through when retry runs inside the blocker', async () => {
+ const nav = loadNavigation();
+ nav.navigate('/logs');
+ nav.navigate('/traces');
+
+ const seen: BlockedTransition[] = [];
+ let unblock = (): void => {};
+ unblock = nav.blockNavigation((tx) => {
+ seen.push(tx);
+ unblock();
+ tx.retry();
+ });
+ nav.back();
+ await settle();
+
+ expect(seen).toHaveLength(1);
+ expect(seen[0].action).toBe('POP');
+ expect(nav.getCurrentLocation().pathname).toBe('/logs');
+ });
+
+ it('replays a blocked Forward by one entry', async () => {
+ const nav = loadNavigation();
+ nav.navigate('/logs');
+ nav.navigate('/traces');
+ nav.back();
+ await settle();
+
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+ window.history.forward();
+ await settle();
+ unblock();
+ seen[0].retry();
+ await settle();
+
+ expect(seen[0].action).toBe('POP');
+ expect(nav.getCurrentLocation().pathname).toBe('/traces');
+ });
+
+ it('replays a blocked multi-entry jump by its full distance', async () => {
+ const nav = loadNavigation();
+ nav.navigate('/a');
+ nav.navigate('/b');
+ nav.navigate('/c');
+ window.history.go(-2);
+ await settle();
+
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+ window.history.go(2);
+ await settle();
+ unblock();
+ seen[0].retry();
+ await settle();
+
+ expect(nav.getCurrentLocation().pathname).toBe('/c');
+ });
+
+ it('replays a blocked Back to an entry from before a reload', async () => {
+ const earlier = loadNavigation();
+ earlier.navigate('/a');
+ earlier.navigate('/b');
+ earlier.navigate('/c');
+
+ const nav = loadNavigation();
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+ window.history.back();
+ await settle();
+ unblock();
+ seen[0].retry();
+ await settle();
+
+ expect(seen[0].action).toBe('POP');
+ expect(nav.getCurrentLocation().pathname).toBe('/b');
+ expect(window.location.pathname).toBe('/b');
+ });
+
+ it('replays a blocked Forward after leaving through an entry from before a reload', async () => {
+ const earlier = loadNavigation();
+ earlier.navigate('/a');
+ earlier.navigate('/b');
+
+ const nav = loadNavigation();
+ nav.navigate('/c');
+ window.history.go(-2);
+ await settle();
+ expect(nav.getCurrentLocation().pathname).toBe('/a');
+
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+ window.history.forward();
+ await settle();
+ unblock();
+ seen[0].retry();
+ await settle();
+
+ expect(seen[0].action).toBe('POP');
+ expect(nav.getCurrentLocation().pathname).toBe('/b');
+ expect(window.location.pathname).toBe('/b');
+ });
+
+ it('replays a blocked Forward that skips from an entry from before a reload past the first known one', async () => {
+ const earlier = loadNavigation();
+ earlier.navigate('/a');
+ earlier.navigate('/b');
+
+ const nav = loadNavigation();
+ nav.navigate('/c');
+ window.history.go(-2);
+ await settle();
+
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+ window.history.go(2);
+ await settle();
+ unblock();
+ seen[0].retry();
+ await settle();
+
+ expect(nav.getCurrentLocation().pathname).toBe('/c');
+ expect(window.location.pathname).toBe('/c');
+ window.history.back();
+ await settle();
+ expect(window.location.pathname).toBe('/b');
+ });
+
+ it('replays a blocked Back that skips from a known entry to one from before a reload', async () => {
+ const earlier = loadNavigation();
+ earlier.navigate('/a');
+ earlier.navigate('/b');
+
+ const nav = loadNavigation();
+ nav.navigate('/c');
+
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+ window.history.go(-2);
+ await settle();
+ unblock();
+ seen[0].retry();
+ await settle();
+
+ expect(nav.getCurrentLocation().pathname).toBe('/a');
+ expect(window.location.pathname).toBe('/a');
+ window.history.forward();
+ await settle();
+ expect(window.location.pathname).toBe('/b');
+ });
+
+ it('catches the router up when history@4 does not revert a blocked POP', async () => {
+ const nav = loadNavigation();
+ nav.navigate('/p');
+ // nuqs pushes like this, so both entries carry the same history@4 key.
+ window.history.pushState(window.history.state, '', '/p?x=1');
+ window.history.back();
+ await settle();
+
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+ window.history.forward();
+ await settle();
+ unblock();
+ seen[0].retry();
+
+ expect(nav.getCurrentLocation().search).toBe('?x=1');
+ expect(window.location.search).toBe('?x=1');
+ });
+
+ it('keeps the blocker armed when retry runs inside it', () => {
+ const nav = loadNavigation();
+ let allowNext = true;
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => {
+ seen.push(tx);
+ if (allowNext) {
+ allowNext = false;
+ tx.retry();
+ }
+ });
+
+ nav.navigate('/logs');
+ nav.navigate('/traces');
+
+ expect(nav.getCurrentLocation().pathname).toBe('/logs');
+ expect(seen).toHaveLength(2);
+ unblock();
+ });
+
+ it('preserves the replace action through retry', () => {
+ const nav = loadNavigation();
+ nav.navigate('/logs');
+ const before = window.history.length;
+
+ const seen: BlockedTransition[] = [];
+ const unblock = nav.blockNavigation((tx) => seen.push(tx));
+ nav.navigate('/traces', { replace: true });
+ unblock();
+ seen[0].retry();
+
+ expect(seen[0].action).toBe('REPLACE');
+ expect(nav.getCurrentLocation().pathname).toBe('/traces');
+ expect(window.history).toHaveLength(before);
+ });
+
+ it('stops blocking after unblock', () => {
+ const nav = loadNavigation();
+ const listener = jest.fn();
+ nav.blockNavigation(listener)();
+
+ nav.navigate('/logs');
+
+ expect(listener).not.toHaveBeenCalled();
+ expect(nav.getCurrentLocation().pathname).toBe('/logs');
+ });
+});
diff --git a/frontend/src/lib/router/__tests__/useAppLocation.test.tsx b/frontend/src/lib/router/__tests__/useAppLocation.test.tsx
new file mode 100644
index 0000000000..a50de1a8e2
--- /dev/null
+++ b/frontend/src/lib/router/__tests__/useAppLocation.test.tsx
@@ -0,0 +1,43 @@
+import type { ReactNode } from 'react';
+import { TestRouter } from 'tests/router';
+import { renderHook } from 'tests/test-utils';
+
+import { navigate } from '../navigation';
+import { useAppLocation } from '../useAppLocation';
+
+function wrapperAt(route: string) {
+ return function Wrapper({ children }: { children: ReactNode }): JSX.Element {
+ return <TestRouter initialRoute={route}>{children}</TestRouter>;
+ };
+}
+
+describe('useAppLocation', () => {
+ it('returns pathname, search and hash', () => {
+ const { result } = renderHook(() => useAppLocation(), {
+ wrapper: wrapperAt('/logs?a=1#top'),
+ });
+
+ expect(result.current).toMatchObject({
+ pathname: '/logs',
+ search: '?a=1',
+ hash: '#top',
+ });
+ });
+
+ it('returns the entry state', () => {
+ navigate('/logs', { replace: true, state: { from: 'test' } });
+ const { result } = renderHook(() => useAppLocation<{ from: string }>(), {
+ wrapper: TestRouter,
+ });
+
+ expect(result.current.state.from).toBe('test');
+ });
+
+ it('defaults search and hash to empty strings', () => {
+ const { result } = renderHook(() => useAppLocation(), {
+ wrapper: wrapperAt('/logs'),
+ });
+
+ expect(result.current).toMatchObject({ search: '', hash: '' });
+ });
+});
diff --git a/frontend/src/lib/router/__tests__/useAppNavigate.test.tsx b/frontend/src/lib/router/__tests__/useAppNavigate.test.tsx
new file mode 100644
index 0000000000..e5b0425852
--- /dev/null
+++ b/frontend/src/lib/router/__tests__/useAppNavigate.test.tsx
@@ -0,0 +1,81 @@
+import { useHistory } from 'react-router-dom';
+import { fireEvent, render, screen } from 'tests/test-utils';
+
+import type { NavigateOptions, To } from '../types';
+import { useAppLocation } from '../useAppLocation';
+import { useAppNavigate } from '../useAppNavigate';
+
+function Probe({
+ to,
+ options,
+}: {
+ to: To;
+ options?: NavigateOptions;
+}): JSX.Element {
+ const navigate = useAppNavigate();
+ const location = useAppLocation();
+ const history = useHistory();
+
+ return (
+ <div>
+ <button
+ type="button"
+ data-testid="navigate"
+ aria-label="navigate"
+ onClick={(): void => navigate(to, options)}
+ />
+ <span data-testid="pathname">{location.pathname}</span>
+ <span data-testid="search">{location.search}</span>
+ <span data-testid="state">{JSON.stringify(location.state ?? null)}</span>
+ <span data-testid="length">{history.length}</span>
+ </div>
+ );
+}
+
+function renderProbe(to: To, options?: NavigateOptions): void {
+ render(<Probe to={to} options={options} />);
+}
+
+describe('useAppNavigate', () => {
+ it('pushes a string target', () => {
+ renderProbe('/logs?a=1');
+ fireEvent.click(screen.getByTestId('navigate'));
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ expect(screen.getByTestId('search')).toHaveTextContent('?a=1');
+ });
+
+ it('pushes an object target', () => {
+ renderProbe({ pathname: '/logs', search: '?a=1' });
+ fireEvent.click(screen.getByTestId('navigate'));
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ expect(screen.getByTestId('search')).toHaveTextContent('?a=1');
+ });
+
+ it('carries state', () => {
+ renderProbe('/logs', { state: { from: 'test' } });
+ fireEvent.click(screen.getByTestId('navigate'));
+
+ expect(screen.getByTestId('state')).toHaveTextContent('{"from":"test"}');
+ });
+
+ it('adds a history entry by default', () => {
+ renderProbe('/logs');
+ const before = screen.getByTestId('length').textContent;
+ fireEvent.click(screen.getByTestId('navigate'));
+
+ expect(Number(screen.getByTestId('length').textContent)).toBe(
+ Number(before) + 1,
+ );
+ });
+
+ it('does not add a history entry when replacing', () => {
+ renderProbe('/logs', { replace: true });
+ const before = screen.getByTestId('length').textContent;
+ fireEvent.click(screen.getByTestId('navigate'));
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ expect(screen.getByTestId('length').textContent).toBe(before);
+ });
+});
diff --git a/frontend/src/lib/router/__tests__/useAppParams.test.tsx b/frontend/src/lib/router/__tests__/useAppParams.test.tsx
new file mode 100644
index 0000000000..6fc4e1fc2f
--- /dev/null
+++ b/frontend/src/lib/router/__tests__/useAppParams.test.tsx
@@ -0,0 +1,55 @@
+import type { ReactNode } from 'react';
+import { TestRouter } from 'tests/router';
+import { renderHook } from 'tests/test-utils';
+
+import { useAppParams } from '../useAppParams';
+
+function wrapperAt(route: string, routePath: string) {
+ return function Wrapper({ children }: { children: ReactNode }): JSX.Element {
+ return (
+ <TestRouter initialRoute={route} routePath={routePath}>
+ {children}
+ </TestRouter>
+ );
+ };
+}
+
+describe('useAppParams', () => {
+ it('reads a param with the record generic', () => {
+ const { result } = renderHook(() => useAppParams<{ roleId: string }>(), {
+ wrapper: wrapperAt('/settings/roles/1f8b', '/settings/roles/:roleId'),
+ });
+
+ expect(result.current.roleId).toBe('1f8b');
+ });
+
+ it('reads a param with the key-union generic', () => {
+ const { result } = renderHook(() => useAppParams<'roleId'>(), {
+ wrapper: wrapperAt('/settings/roles/1f8b', '/settings/roles/:roleId'),
+ });
+
+ expect(result.current.roleId).toBe('1f8b');
+ });
+
+ it('reads multiple params', () => {
+ const { result } = renderHook(
+ () => useAppParams<'dashboardId' | 'panelId'>(),
+ {
+ wrapper: wrapperAt(
+ '/dashboard/d1/new-panel/p2',
+ '/dashboard/:dashboardId/new-panel/:panelId',
+ ),
+ },
+ );
+
+ expect(result.current).toMatchObject({ dashboardId: 'd1', panelId: 'p2' });
+ });
+
+ it('returns an empty object on a route without params', () => {
+ const { result } = renderHook(() => useAppParams(), {
+ wrapper: wrapperAt('/logs', '/logs'),
+ });
+
+ expect(result.current).toStrictEqual({});
+ });
+});
diff --git a/frontend/src/lib/router/__tests__/utils.test.ts b/frontend/src/lib/router/__tests__/utils.test.ts
new file mode 100644
index 0000000000..657f646005
--- /dev/null
+++ b/frontend/src/lib/router/__tests__/utils.test.ts
@@ -0,0 +1,146 @@
+import type { History } from 'history';
+
+import { applyNavigate, retryTransition, withState } from '../utils';
+
+function fakeHistory(): {
+ history: History;
+ push: jest.Mock;
+ replace: jest.Mock;
+ go: jest.Mock;
+} {
+ const push = jest.fn();
+ const replace = jest.fn();
+ const go = jest.fn();
+ return {
+ history: { push, replace, go } as unknown as History,
+ push,
+ replace,
+ go,
+ };
+}
+
+describe('applyNavigate', () => {
+ it('pushes a string target with no second argument', () => {
+ const { history, push } = fakeHistory();
+
+ applyNavigate(history, '/logs');
+
+ expect(push).toHaveBeenCalledWith('/logs');
+ });
+
+ it('pushes an object target with no state key', () => {
+ const { history, push } = fakeHistory();
+
+ applyNavigate(history, { pathname: '/logs', search: '?a=1' });
+
+ expect(push).toHaveBeenCalledWith({ pathname: '/logs', search: '?a=1' });
+ });
+
+ it('forwards state when there is state to forward', () => {
+ const { history, push } = fakeHistory();
+
+ applyNavigate(history, '/logs', { state: { from: '/home' } });
+
+ expect(push).toHaveBeenCalledWith('/logs', { from: '/home' });
+ });
+
+ it('attaches state to an object target', () => {
+ const { history, push } = fakeHistory();
+
+ applyNavigate(history, { pathname: '/logs' }, { state: { from: '/home' } });
+
+ expect(push).toHaveBeenCalledWith({ pathname: '/logs' }, { from: '/home' });
+ });
+
+ it('replaces instead of pushing', () => {
+ const { history, push, replace } = fakeHistory();
+
+ applyNavigate(history, '/logs', { replace: true });
+
+ expect(replace).toHaveBeenCalledWith('/logs');
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it('replaces with state', () => {
+ const { history, replace } = fakeHistory();
+
+ applyNavigate(history, '/logs', { replace: true, state: { a: 1 } });
+
+ expect(replace).toHaveBeenCalledWith('/logs', { a: 1 });
+ });
+});
+
+describe('retryTransition', () => {
+ const location = { pathname: '/logs', search: '', hash: '', state: undefined };
+
+ it('walks a blocked POP by its distance', () => {
+ const { history, go } = fakeHistory();
+
+ retryTransition(history, location, 'POP', 2);
+
+ expect(go).toHaveBeenCalledWith(2);
+ });
+
+ it('does not reload when a blocked POP has no distance', () => {
+ const { history, go } = fakeHistory();
+
+ retryTransition(history, location, 'POP', 0);
+
+ expect(go).not.toHaveBeenCalled();
+ });
+
+ it('settles on the carried location when a blocked POP has an unknown distance', () => {
+ const { history, go, replace } = fakeHistory();
+
+ retryTransition(history, location, 'POP', null);
+
+ expect(go).not.toHaveBeenCalled();
+ expect(replace).toHaveBeenCalledWith(location);
+ });
+
+ it('replays PUSH and REPLACE from the carried location', () => {
+ const { history, push, replace } = fakeHistory();
+
+ retryTransition(history, location, 'PUSH', 0);
+ retryTransition(history, location, 'REPLACE', 0);
+
+ expect(push).toHaveBeenCalledWith(location);
+ expect(replace).toHaveBeenCalledWith(location);
+ });
+});
+
+describe('withState', () => {
+ it('returns the target untouched when there is no state', () => {
+ expect(withState('/logs?a=1', undefined)).toBe('/logs?a=1');
+ });
+
+ it('splits a string target before attaching state', () => {
+ expect(withState('/logs?a=1#top', { from: '/home' })).toStrictEqual({
+ pathname: '/logs',
+ search: '?a=1',
+ hash: '#top',
+ state: { from: '/home' },
+ });
+ });
+
+ it('resolves a search-only string against the current location', () => {
+ expect(
+ withState(
+ '?tab=2',
+ { from: '/home' },
+ { pathname: '/x/y', search: '?q=1', hash: '', state: null },
+ ),
+ ).toMatchObject({
+ pathname: '/x/y',
+ search: '?tab=2',
+ state: { from: '/home' },
+ });
+ });
+
+ it('attaches state to an object target', () => {
+ expect(withState({ pathname: '/logs' }, { from: '/home' })).toStrictEqual({
+ pathname: '/logs',
+ state: { from: '/home' },
+ });
+ });
+});
diff --git a/frontend/src/lib/router/buildRoutePath.ts b/frontend/src/lib/router/buildRoutePath.ts
new file mode 100644
index 0000000000..8d05ec77cb
--- /dev/null
+++ b/frontend/src/lib/router/buildRoutePath.ts
@@ -0,0 +1,16 @@
+import { generatePath } from 'react-router-dom';
+
+/**
+ * Fills `:param` segments in a route pattern.
+ *
+ * Param values are URI-encoded. `/`, `?` and `#` come back percent-encoded, so
+ * a value can never introduce extra path segments or a query string. v5's
+ * `generatePath` does this via path-to-regexp; v7's runs `encodeURIComponent`,
+ * which also encodes `:`.
+ */
+export function buildRoutePath(
+ pattern: string,
+ params?: Record<string, string | number | boolean | undefined>,
+): string {
+ return generatePath(pattern, params);
+}
diff --git a/frontend/src/lib/router/matchRoute.ts b/frontend/src/lib/router/matchRoute.ts
new file mode 100644
index 0000000000..a2ec926b29
--- /dev/null
+++ b/frontend/src/lib/router/matchRoute.ts
@@ -0,0 +1,46 @@
+import { matchPath } from 'react-router-dom';
+
+import type { AppParams, RouteMatch } from './types';
+
+interface MatchRouteOptions {
+ /**
+ * Defaults to `false`, matching v5's string form. v6's `end` defaults to
+ * `true`, so callers that pass no options rely on this default and would
+ * silently flip to exact matching without it.
+ */
+ exact?: boolean;
+}
+
+export function matchRoute<Key extends string = string>(
+ pathname: string,
+ pattern: string,
+ options: MatchRouteOptions = {},
+): RouteMatch<Key> | null {
+ const end = options.exact ?? false;
+
+ const match = matchPath<Record<string, string | undefined>>(pathname, {
+ path: pattern,
+ exact: end,
+ });
+
+ if (match === null) {
+ return null;
+ }
+
+ // v6.30 un-escapes `%2F` in param values (and nothing else); v5 hands them
+ // back raw. Doing it here keeps `buildRoutePath` -> `matchRoute` a round trip
+ // for values containing a slash, on both versions.
+ const params = Object.fromEntries(
+ Object.entries(match.params).map(([key, value]) => [
+ key,
+ value?.replace(/%2F/g, '/'),
+ ]),
+ );
+
+ return {
+ params: params as AppParams<Key>,
+ pathname: match.url,
+ pathnameBase: match.url,
+ pattern: { path: pattern, caseSensitive: false, end },
+ };
+}
diff --git a/frontend/src/lib/router/navigation.ts b/frontend/src/lib/router/navigation.ts
new file mode 100644
index 0000000000..3619e127e8
--- /dev/null
+++ b/frontend/src/lib/router/navigation.ts
@@ -0,0 +1,85 @@
+import history from 'lib/history';
+
+import type {
+ AppLocation,
+ NavigateOptions,
+ NavigationAction,
+ NavigationBlocker,
+ To,
+} from './types';
+import { applyNavigate, retryTransition, toAppLocation } from './utils';
+
+let entryKeys: Array<string | undefined> = [history.location.key];
+let currentKey = history.location.key;
+
+// history@4 reports a blocked POP's target but not how far away it is, and the
+// POP is already reverted by the time `retry` runs. Mirroring its entry keys
+// gives the distance back. Like history@4, an entry it never saw (one from
+// before a reload) counts as the first one, so a POP whose ends both land on
+// index 0 is not reverted.
+history.listen((location, action) => {
+ const index = entryKeys.indexOf(currentKey);
+ currentKey = location.key;
+ if (action === 'PUSH') {
+ entryKeys = [...entryKeys.slice(0, index + 1), location.key];
+ } else if (action === 'REPLACE' && index !== -1) {
+ entryKeys[index] = location.key;
+ }
+});
+
+function entryIndex(key: string | undefined): number {
+ return Math.max(0, entryKeys.indexOf(key));
+}
+
+/**
+ * Imperative navigation on the app's history singleton, usable from any code.
+ * `useAppNavigate` navigates on the nearest router instead. Unlike
+ * `useSafeNavigate` it does not suppress same-URL navigation and has no new-tab
+ * branch, because it cannot see the current render.
+ *
+ * Callers pass and receive basename-free app paths.
+ */
+export function navigate(to: To, options?: NavigateOptions): void {
+ applyNavigate(history, to, options);
+}
+
+export function back(): void {
+ history.goBack();
+}
+
+export function getCurrentLocation(): AppLocation {
+ return toAppLocation(history.location);
+}
+
+export function blockNavigation(blocker: NavigationBlocker): () => void {
+ return history.block((location, action) => {
+ const appLocation = toAppLocation(location);
+ const navigationAction = action as NavigationAction;
+ const delta = entryIndex(location.key) - entryIndex(currentKey);
+ const popDelta = delta === 0 ? null : delta;
+ let deciding = true;
+ let allowed = false;
+
+ blocker({
+ location: appLocation,
+ action: navigationAction,
+ retry: () => {
+ if (deciding) {
+ allowed = true;
+ return;
+ }
+ retryTransition(history, appLocation, navigationAction, popDelta);
+ },
+ });
+ deciding = false;
+
+ // history@4 cancels the transition when the prompt returns `false`;
+ // history@5 cancels whenever a blocker is registered and hands control to
+ // `retry()`. A `retry()` inside the blocker means "let it through", and
+ // history@4 does that by not cancelling: re-issuing a POP would walk the
+ // stack twice.
+ return allowed ? undefined : false;
+ });
+}
+
+export { hasInAppHistory } from 'lib/history';
diff --git a/frontend/src/lib/router/types.ts b/frontend/src/lib/router/types.ts
new file mode 100644
index 0000000000..fca7552778
--- /dev/null
+++ b/frontend/src/lib/router/types.ts
@@ -0,0 +1,72 @@
+/**
+ * Facade contracts for the router. Every shape here is defined the way
+ * react-router v6+ / history@5 behaves; the v5-backed implementations adapt up
+ * to it.
+ */
+
+export type NavigationAction = 'PUSH' | 'REPLACE' | 'POP';
+
+export interface AppLocation<S = unknown> {
+ pathname: string;
+ search: string;
+ hash: string;
+ state: S;
+ /** history@4 leaves this undefined on the initial entry; v6 always sets it. */
+ key?: string;
+}
+
+export type To =
+ | string
+ | Partial<Pick<AppLocation, 'pathname' | 'search' | 'hash'>>;
+
+export type AppParams<Key extends string = string> = {
+ readonly [K in Key]: string | undefined;
+};
+
+/**
+ * Mirrors v6's `useParams` return type so both call shapes keep working:
+ * a union of param names (`useAppParams<'dashboardId'>()`) or a record
+ * (`useAppParams<{ dashboardId: string }>()`).
+ */
+export type AppParamsResult<
+ ParamsOrKey extends string | Record<string, string | undefined>,
+> = Readonly<
+ [ParamsOrKey] extends [string] ? AppParams<ParamsOrKey> : Partial<ParamsOrKey>
+>;
+
+export interface RoutePattern {
+ path: string;
+ caseSensitive: boolean;
+ end: boolean;
+}
+
+export interface RouteMatch<Key extends string = string> {
+ params: AppParams<Key>;
+ pathname: string;
+ /**
+ * The matched portion minus any trailing splat. Equal to `pathname` for every
+ * pattern in `constants/routes.ts`, none of which use a splat.
+ */
+ pathnameBase: string;
+ pattern: RoutePattern;
+}
+
+export interface NavigateOptions {
+ replace?: boolean;
+ state?: unknown;
+}
+
+export type NavigateFn = (to: To, options?: NavigateOptions) => void;
+
+export interface BlockedTransition {
+ location: AppLocation;
+ action: NavigationAction;
+ /**
+ * Called inside the blocker, lets this navigation through and leaves the
+ * blocker registered. Called later, replays the navigation, so unblock first
+ * or the blocker catches the replay too.
+ */
+ retry: () => void;
+}
+
+export type NavigationBlocker = (transition: BlockedTransition) => void;
diff --git a/frontend/src/lib/router/useAppLocation.ts b/frontend/src/lib/router/useAppLocation.ts
new file mode 100644
index 0000000000..f892fdfbce
--- /dev/null
+++ b/frontend/src/lib/router/useAppLocation.ts
@@ -0,0 +1,7 @@
+import { useLocation } from 'react-router-dom';
+
+import type { AppLocation } from './types';
+
+export function useAppLocation<S = unknown>(): AppLocation<S> {
+ return useLocation<S>();
+}
diff --git a/frontend/src/lib/router/useAppNavigate.ts b/frontend/src/lib/router/useAppNavigate.ts
new file mode 100644
index 0000000000..82858f6251
--- /dev/null
+++ b/frontend/src/lib/router/useAppNavigate.ts
@@ -0,0 +1,21 @@
+import { useCallback } from 'react';
+import { useHistory } from 'react-router-dom';
+
+import type { NavigateFn, NavigateOptions, To } from './types';
+import { applyNavigate } from './utils';
+
+/**
+ * Hook-context imperative navigation, for `useHistory()` call sites that only
+ * push or replace. Prefer `useSafeNavigate` when the call site wants same-URL
+ * suppression or new-tab handling.
+ */
+export function useAppNavigate(): NavigateFn {
+ const history = useHistory();
+
+ return useCallback(
+ (to: To, options?: NavigateOptions): void => {
+ applyNavigate(history, to, options);
+ },
+ [history],
+ );
+}
diff --git a/frontend/src/lib/router/useAppNavigationType.ts b/frontend/src/lib/router/useAppNavigationType.ts
new file mode 100644
index 0000000000..8b36006336
--- /dev/null
+++ b/frontend/src/lib/router/useAppNavigationType.ts
@@ -0,0 +1,11 @@
+import { useNavigationType } from 'react-router-dom-v5-compat';
+
+import type { NavigationAction } from './types';
+
+/**
+ * The action that produced the current location (`POP` for browser back and
+ * forward). v6 only; v5 exposes this as `history.action`.
+ */
+export function useAppNavigationType(): NavigationAction {
+ return useNavigationType();
+}
diff --git a/frontend/src/lib/router/useAppParams.ts b/frontend/src/lib/router/useAppParams.ts
new file mode 100644
index 0000000000..ee14a5f4c4
--- /dev/null
+++ b/frontend/src/lib/router/useAppParams.ts
@@ -0,0 +1,13 @@
+import { useParams } from 'react-router-dom';
+
+import type { AppParamsResult } from './types';
+
+/**
+ * Types every param `string | undefined`, as v6 does. v5 types them as required
+ * strings.
+ */
+export function useAppParams<
+ ParamsOrKey extends string | Record<string, string | undefined> = string,
+>(): AppParamsResult<ParamsOrKey> {
+ return useParams() as AppParamsResult<ParamsOrKey>;
+}
diff --git a/frontend/src/lib/router/useAppSearchParams.ts b/frontend/src/lib/router/useAppSearchParams.ts
new file mode 100644
index 0000000000..b2605f34b5
--- /dev/null
+++ b/frontend/src/lib/router/useAppSearchParams.ts
@@ -0,0 +1,9 @@
+import { useSearchParams } from 'react-router-dom-v5-compat';
+
+/**
+ * v6's `useSearchParams`, which has no v5 equivalent. Its setter navigates
+ * through the router.
+ */
+export function useAppSearchParams(): ReturnType<typeof useSearchParams> {
+ return useSearchParams();
+}
diff --git a/frontend/src/lib/router/utils.ts b/frontend/src/lib/router/utils.ts
new file mode 100644
index 0000000000..9184c51fbf
--- /dev/null
+++ b/frontend/src/lib/router/utils.ts
@@ -0,0 +1,98 @@
+import type { History, Location, LocationDescriptor } from 'history';
+import { parsePath } from 'history';
+
+import type {
+ AppLocation,
+ NavigateOptions,
+ NavigationAction,
+ To,
+} from './types';
+
+export function toAppLocation<S = unknown>(
+ location: Location<S>,
+): AppLocation<S> {
+ return {
+ pathname: location.pathname,
+ search: location.search,
+ hash: location.hash,
+ state: location.state,
+ key: location.key,
+ };
+}
+
+/**
+ * v5 carries state inside `to`. The string form is parsed first, or search and
+ * hash would land in `pathname`. Pass `currentLocation` where the target
+ * renders an href, so a search-only or hash-only string keeps the current
+ * pathname as it does without state; `history.push` resolves it on its own.
+ * Not `createLocation`: its `decodeURI` runs again when the link is followed.
+ */
+export function withState(
+ to: To,
+ state: unknown,
+ currentLocation?: AppLocation,
+): LocationDescriptor {
+ if (state === undefined) {
+ return to;
+ }
+ if (typeof to === 'string') {
+ const parsed = parsePath(to);
+ return {
+ ...parsed,
+ pathname: parsed.pathname || currentLocation?.pathname || '',
+ state,
+ };
+ }
+ return { ...to, state };
+}
+
+/**
+ * `state` always travels as the second argument, which history@4 and history@5
+ * both honour for string and object targets. It is omitted rather than passed
+ * as `undefined`, so a stateless `navigate(path)` reaches the history as the
+ * bare `push(path)` the call sites used before the facade.
+ */
+export function applyNavigate(
+ history: History,
+ to: To,
+ options?: NavigateOptions,
+): void {
+ const { replace = false, state } = options ?? {};
+
+ const args: Parameters<History['push']> =
+ state === undefined ? [to] : [to, state];
+
+ if (replace) {
+ history.replace(...args);
+ } else {
+ history.push(...args);
+ }
+}
+
+/**
+ * Replays a transition that a blocker cancelled. history@4 discards the
+ * transition on cancel, so it has to be re-issued from the location it carried.
+ * `popDelta` walks the browser from where history@4 reverted the blocked POP
+ * back to its target. It is `null` when history@4 did not revert, so the
+ * browser is already on the target and only the router has to catch up.
+ */
+export function retryTransition(
+ history: History,
+ location: AppLocation,
+ action: NavigationAction,
+ popDelta: number | null,
+): void {
+ if (action === 'POP') {
+ if (popDelta === null) {
+ history.replace(location);
+ } else if (popDelta !== 0) {
+ history.go(popDelta);
+ }
+ return;
+ }
+ if (action === 'REPLACE') {
+ history.replace(location);
+ return;
+ }
+ history.push(location);
+}
diff --git a/frontend/src/modules/Servicemap/ServiceMap.tsx b/frontend/src/modules/Servicemap/ServiceMap.tsx
index 32494aadc6..57445daaf6 100644
--- a/frontend/src/modules/Servicemap/ServiceMap.tsx
+++ b/frontend/src/modules/Servicemap/ServiceMap.tsx
@@ -3,7 +3,6 @@
import { useEffect, useMemo, useRef } from 'react';
// eslint-disable-next-line no-restricted-imports
import { connect } from 'react-redux';
-import { RouteComponentProps, withRouter } from 'react-router-dom';
import { Card } from 'antd';
import Spinner from 'components/Spinner';
import TextToolTip from 'components/TextToolTip';
@@ -39,7 +38,7 @@ const Container = styled.div`
}
`;
-interface ServiceMapProps extends RouteComponentProps<any> {
+interface ServiceMapProps {
serviceMap: ServiceMapStore;
globalTime: GlobalTime;
getDetailedServiceMapItems: (
@@ -129,8 +128,6 @@ const mapStateToProps = (
globalTime: state.globalTime,
});
-export default withRouter(
- connect(mapStateToProps, {
- getDetailedServiceMapItems,
- })(ServiceMap),
-);
+export default connect(mapStateToProps, {
+ getDetailedServiceMapItems,
+})(ServiceMap);
diff --git a/frontend/src/modules/Usage/UsageExplorer.tsx b/frontend/src/modules/Usage/UsageExplorer.tsx
index 5802b3c9ec..4a56e5a987 100644
--- a/frontend/src/modules/Usage/UsageExplorer.tsx
+++ b/frontend/src/modules/Usage/UsageExplorer.tsx
@@ -3,7 +3,6 @@
import { useEffect, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { connect, useSelector } from 'react-redux';
-import { withRouter } from 'react-router-dom';
import { Select, Space } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import Graph from 'components/Graph';
@@ -32,7 +31,6 @@ interface UsageExplorerProps {
selectedTimeInterval: GlobalReducer['selectedTime'];
}) => void;
globalTime: GlobalTime;
- servicesList: servicesListItem[];
totalCount: number;
}
const timeDaysOptions = [
@@ -213,9 +211,7 @@ const mapStateToProps = (
};
};
-export const UsageExplorer = withRouter(
- connect(mapStateToProps, {
- getUsageData,
- getServicesList: GetService,
- })(_UsageExplorer),
-);
+export const UsageExplorer = connect(mapStateToProps, {
+ getUsageData,
+ getServicesList: GetService,
+})(_UsageExplorer);
diff --git a/frontend/src/pages/AIAssistantPage/AIAssistantPage.tsx b/frontend/src/pages/AIAssistantPage/AIAssistantPage.tsx
index 595897a3f4..3406e3b248 100644
--- a/frontend/src/pages/AIAssistantPage/AIAssistantPage.tsx
+++ b/frontend/src/pages/AIAssistantPage/AIAssistantPage.tsx
@@ -1,7 +1,9 @@
import { useCallback, useEffect, useRef } from 'react';
-import { useHistory, useLocation, useParams } from 'react-router-dom';
import logEvent from 'api/common/logEvent';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppParams } from 'lib/router/useAppParams';
+import { navigate } from 'lib/router/navigation';
import ROUTES from 'constants/routes';
import ConversationView from 'container/AIAssistant/ConversationView';
@@ -16,15 +18,10 @@ import { useAIAssistantStripInfo } from './useAIAssistantStripInfo';
import styles from './AIAssistantPage.module.scss';
import ConversationsList from 'container/AIAssistant/components/ConversationsList';
-interface RouteParams {
- conversationId: string;
-}
-
export default function AIAssistantPage(): JSX.Element {
- const history = useHistory();
- const location = useLocation<{ fromInApp?: boolean } | undefined>();
+ const location = useAppLocation<{ fromInApp?: boolean } | undefined>();
const { pathname } = location;
- const { conversationId } = useParams<RouteParams>();
+ const { conversationId } = useAppParams<'conversationId'>();
// Skip the mount-time Opened fire when the user expanded an already-open
// drawer/modal — that surface already emitted Opened with the right source.
@@ -83,7 +80,9 @@ export default function AIAssistantPage(): JSX.Element {
activeId && conversationsRef.current[activeId]
? activeId
: startNewConversation();
- history.replace(ROUTES.AI_ASSISTANT.replace(':conversationId', resumeId));
+ navigate(ROUTES.AI_ASSISTANT.replace(':conversationId', resumeId), {
+ replace: true,
+ });
// Only re-run when the URL param changes, not when conversations mutates.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [conversationId]);
@@ -98,19 +97,17 @@ export default function AIAssistantPage(): JSX.Element {
activeConversationId !== conversationId &&
conversations[activeConversationId]
) {
- history.replace(
+ navigate(
ROUTES.AI_ASSISTANT.replace(':conversationId', activeConversationId),
+ { replace: true },
);
}
- }, [activeConversationId, conversationId, conversations, history]);
+ }, [activeConversationId, conversationId, conversations]);
// When conversations sidebar selects a thread, navigate to it
- const handleHistorySelect = useCallback(
- (id: string) => {
- history.push(ROUTES.AI_ASSISTANT.replace(':conversationId', id));
- },
- [history],
- );
+ const handleHistorySelect = useCallback((id: string) => {
+ navigate(ROUTES.AI_ASSISTANT.replace(':conversationId', id));
+ }, []);
const handleNewConversation = useCallback(() => {
void logEvent(AIAssistantEvents.NewChatClicked, {
@@ -119,14 +116,14 @@ export default function AIAssistantPage(): JSX.Element {
source: 'history_list',
});
const newId = startNewConversation();
- history.push(ROUTES.AI_ASSISTANT.replace(':conversationId', newId));
- }, [startNewConversation, history, pathname]);
+ navigate(ROUTES.AI_ASSISTANT.replace(':conversationId', newId));
+ }, [startNewConversation, pathname]);
// Prefer the URL param, but fall back to the store's `activeConversationId`
// for the brief render after a re-key (client UUID → backend threadId), so
// the chat doesn't unmount while the URL sync effect catches up.
let activeId: string | null = null;
- if (conversations[conversationId]) {
+ if (conversationId && conversations[conversationId]) {
activeId = conversationId;
} else if (activeConversationId && conversations[activeConversationId]) {
activeId = activeConversationId;
diff --git a/frontend/src/pages/AIAssistantPage/__tests__/AIAssistantPage.test.tsx b/frontend/src/pages/AIAssistantPage/__tests__/AIAssistantPage.test.tsx
index 4ecf59441c..b34db344cb 100644
--- a/frontend/src/pages/AIAssistantPage/__tests__/AIAssistantPage.test.tsx
+++ b/frontend/src/pages/AIAssistantPage/__tests__/AIAssistantPage.test.tsx
@@ -1,8 +1,8 @@
-import { MemoryRouter, Route } from 'react-router-dom';
// eslint-disable-next-line no-restricted-imports
import { render } from '@testing-library/react';
import ROUTES from 'constants/routes';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
+import { TestRouter } from 'tests/router';
jest.mock('api/common/logEvent', () => ({
__esModule: true,
@@ -34,13 +34,12 @@ import AIAssistantPage from '../AIAssistantPage';
function renderAt(entry: string): { unmount: () => void } {
return render(
- <MemoryRouter initialEntries={[entry]}>
- <Route
- exact
- path={[ROUTES.AI_ASSISTANT_BASE, ROUTES.AI_ASSISTANT]}
- component={AIAssistantPage}
- />
- </MemoryRouter>,
+ <TestRouter
+ initialRoute={entry}
+ routePath={[ROUTES.AI_ASSISTANT_BASE, ROUTES.AI_ASSISTANT]}
+ >
+ <AIAssistantPage />
+ </TestRouter>,
);
}
diff --git a/frontend/src/pages/AIAssistantPage/stories/AIAssistantPage.stories.tsx b/frontend/src/pages/AIAssistantPage/stories/AIAssistantPage.stories.tsx
index e882a54033..114b226a84 100644
--- a/frontend/src/pages/AIAssistantPage/stories/AIAssistantPage.stories.tsx
+++ b/frontend/src/pages/AIAssistantPage/stories/AIAssistantPage.stories.tsx
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -34,11 +34,9 @@ const meta = {
component: AIAssistantPage,
// The conversation id is in the pathname, so the page renders under its own
// route rather than being mounted on its own.
- render: (): JSX.Element => (
- <Route
- path={[ROUTES.AI_ASSISTANT_BASE, ROUTES.AI_ASSISTANT]}
- component={AIAssistantPage}
- />
+ render: renderAtRoute(
+ [ROUTES.AI_ASSISTANT_BASE, ROUTES.AI_ASSISTANT],
+ AIAssistantPage,
),
...pageStory,
parameters: { ...pageStory.parameters },
diff --git a/frontend/src/pages/AlertDetails/AlertDetails.tsx b/frontend/src/pages/AlertDetails/AlertDetails.tsx
index 2415f9534a..fba635f077 100644
--- a/frontend/src/pages/AlertDetails/AlertDetails.tsx
+++ b/frontend/src/pages/AlertDetails/AlertDetails.tsx
@@ -1,5 +1,4 @@
import React, { useEffect, useMemo } from 'react';
-import { useLocation } from 'react-router-dom';
import { Divider } from '@signozhq/ui/divider';
import logEvent from 'api/common/logEvent';
import classNames from 'classnames';
@@ -15,7 +14,7 @@ import {
getCreateAlertLocalStateFromAlertDef,
} from 'container/CreateAlertV2/utils';
import useUrlQuery from 'hooks/useUrlQuery';
-import history from 'lib/history';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { useAlertRule } from 'providers/Alert';
import { NEW_ALERT_SCHEMA_VERSION } from 'types/api/alerts/alertTypesV2';
import { fromRuleDTOToPostableRuleV2 } from 'types/api/alerts/convert';
@@ -27,7 +26,7 @@ import { useGetAlertRuleDetails, useRouteTabUtils } from './hooks';
import './AlertDetails.styles.scss';
function AlertDetails(): JSX.Element {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const { routes } = useRouteTabUtils();
const params = useUrlQuery();
const { alertRuleName } = useAlertRule();
@@ -113,7 +112,6 @@ function AlertDetails(): JSX.Element {
<RouteTab
routes={routes}
activeKey={pathname}
- history={history}
onChangeHandler={handleTabChange}
tabBarExtraContent={<Filters />}
/>
diff --git a/frontend/src/pages/AlertDetails/__tests__/AlertNotFound.test.tsx b/frontend/src/pages/AlertDetails/__tests__/AlertNotFound.test.tsx
index bd4ef81a96..401983db12 100644
--- a/frontend/src/pages/AlertDetails/__tests__/AlertNotFound.test.tsx
+++ b/frontend/src/pages/AlertDetails/__tests__/AlertNotFound.test.tsx
@@ -6,14 +6,11 @@ import { userEvent } from 'tests/test-utils';
import AlertNotFound from '../AlertNotFound';
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: jest.fn(),
- },
+jest.mock('lib/router/navigation', () => ({
+ navigate: jest.fn(),
}));
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
const mockSafeNavigate = jest.fn();
const useGetTenantLicenseSpy = jest.spyOn(
@@ -82,7 +79,7 @@ describe('AlertNotFound', () => {
render(<AlertNotFound isTestAlert={false} />);
await user.click(screen.getByText('Contact Support'));
- expect(history.push).toHaveBeenCalledWith('/support');
+ expect(navigate).toHaveBeenCalledWith('/support');
});
it('should navigate to the support page for self-hosted users when the contact support button is clicked', async () => {
diff --git a/frontend/src/pages/AlertDetails/hooks.tsx b/frontend/src/pages/AlertDetails/hooks.tsx
index 82281f79d7..bd44568ac9 100644
--- a/frontend/src/pages/AlertDetails/hooks.tsx
+++ b/frontend/src/pages/AlertDetails/hooks.tsx
@@ -1,6 +1,5 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useMutation, useQueryClient, useQuery } from 'react-query';
-import { generatePath } from 'react-router-dom';
import { TablePaginationConfig, TableProps } from 'antd';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import { patchRulePartial } from 'api/alerts/patchRulePartial';
@@ -46,7 +45,8 @@ import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constan
import { useNotifications } from 'hooks/useNotifications';
import useUrlQuery from 'hooks/useUrlQuery';
import GetMinMax from 'lib/getMinMax';
-import history from 'lib/history';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
+import { navigate } from 'lib/router/navigation';
import { History, Table } from '@signozhq/icons';
import EditRules from 'pages/EditRules';
import BetaTag from 'periscope/components/BetaTag/BetaTag';
@@ -119,7 +119,7 @@ export const useRouteTabUtils = (): { routes: TabRoutes[] } => {
return '';
}
- return `${generatePath(route)}?${params}`;
+ return `${buildRoutePath(route)}?${params}`;
};
const routes = [
@@ -502,7 +502,7 @@ export const useAlertRuleClone = ({
await invalidateListRules(queryClient);
params.set(QueryParams.ruleId, response.data.id);
- history.push(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`);
+ navigate(`${ROUTES.ALERT_OVERVIEW}?${params.toString()}`);
},
onError: (error) =>
showErrorModal(
@@ -591,7 +591,7 @@ export const useAlertRuleDelete = ({
message: `Success`,
});
- history.push(ROUTES.LIST_ALL_ALERT);
+ navigate(ROUTES.LIST_ALL_ALERT);
},
onError: (error) =>
showErrorModal(
diff --git a/frontend/src/pages/AlertList/NotificationChannels/components/ChannelActionsMenu/ChannelActionsMenu.tsx b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelActionsMenu/ChannelActionsMenu.tsx
index e877812f56..aaf8973647 100644
--- a/frontend/src/pages/AlertList/NotificationChannels/components/ChannelActionsMenu/ChannelActionsMenu.tsx
+++ b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelActionsMenu/ChannelActionsMenu.tsx
@@ -1,5 +1,4 @@
import { useCallback, useMemo, useState } from 'react';
-import { generatePath } from 'react-router-dom';
import { useCopyToClipboard } from 'react-use';
import {
Braces,
@@ -15,6 +14,7 @@ import ROUTES from 'constants/routes';
import { useNotificationChannelPermissions } from 'hooks/notificationChannels/useNotificationChannelPermissions';
import AuthZDropdown from 'lib/authz/components/AuthZDropdown/AuthZDropdown';
import type { AuthZDropdownItemType } from 'lib/authz/components/AuthZDropdown/types';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { getAbsoluteUrl } from 'utils/basePath';
import type { Channel } from '../../types';
@@ -66,7 +66,7 @@ function ChannelActionsMenu({
onClick: (): void => {
setCopy(
getAbsoluteUrl(
- generatePath(ROUTES.CHANNELS_EDIT, { channelId: channel.id }),
+ buildRoutePath(ROUTES.CHANNELS_EDIT, { channelId: channel.id }),
),
);
toast.success('Link copied to clipboard');
diff --git a/frontend/src/pages/AlertList/NotificationChannels/hooks/useChannelFormView.ts b/frontend/src/pages/AlertList/NotificationChannels/hooks/useChannelFormView.ts
index a62c4b43ed..6f8ec42457 100644
--- a/frontend/src/pages/AlertList/NotificationChannels/hooks/useChannelFormView.ts
+++ b/frontend/src/pages/AlertList/NotificationChannels/hooks/useChannelFormView.ts
@@ -1,6 +1,6 @@
-import { generatePath } from 'react-router-dom';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
+import { navigate } from 'lib/router/navigation';
import { openInNewTab } from 'utils/navigation';
export interface ChannelFormView {
@@ -11,21 +11,19 @@ export interface ChannelFormView {
/** Create and edit both render on their own route. */
export function useChannelFormView(): ChannelFormView {
const openEdit = (channelId: string, options?: { newTab?: boolean }): void => {
- const path = generatePath(ROUTES.CHANNELS_EDIT, { channelId });
+ const path = buildRoutePath(ROUTES.CHANNELS_EDIT, { channelId });
if (options?.newTab) {
openInNewTab(path);
return;
}
- history.push(path);
+ navigate(path);
};
return {
openCreate: (kind?: string): void =>
- history.push(
- kind ? `${ROUTES.CHANNELS_NEW}?kind=${kind}` : ROUTES.CHANNELS_NEW,
- ),
+ navigate(kind ? `${ROUTES.CHANNELS_NEW}?kind=${kind}` : ROUTES.CHANNELS_NEW),
openEdit,
};
}
diff --git a/frontend/src/pages/AlertList/__tests__/AlertList.test.tsx b/frontend/src/pages/AlertList/__tests__/AlertList.test.tsx
index 520eb9aaa6..5b7182769b 100644
--- a/frontend/src/pages/AlertList/__tests__/AlertList.test.tsx
+++ b/frontend/src/pages/AlertList/__tests__/AlertList.test.tsx
@@ -1,4 +1,5 @@
import { fireEvent, render, screen } from '@testing-library/react';
+import { mockAppLocation } from 'tests/router-mocks';
import AlertList from '../index';
@@ -15,12 +16,6 @@ const CHANNELS_SUB_TAB = 'channels';
const PLANNED_DOWNTIME_SUB_TAB = 'planned-downtime';
const ROUTING_POLICIES_SUB_TAB = 'routing-policies';
-const mockUseLocation = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): unknown => mockUseLocation(),
-}));
-
let mockUrlQuery: URLSearchParams;
jest.mock('hooks/useUrlQuery', () => ({
__esModule: true,
@@ -78,9 +73,7 @@ jest.mock('container/ListAlertRules', () => ({
}));
const mockLocation = (pathname: string): void => {
- mockUseLocation.mockReturnValue({
- pathname,
- });
+ mockAppLocation({ pathname });
};
const mockQueryParams = (params: Record<string, string | null>): void => {
diff --git a/frontend/src/pages/AlertList/index.tsx b/frontend/src/pages/AlertList/index.tsx
index 6d8774410c..fafdf9ba69 100644
--- a/frontend/src/pages/AlertList/index.tsx
+++ b/frontend/src/pages/AlertList/index.tsx
@@ -1,6 +1,6 @@
import { useCallback, useMemo } from 'react';
-import { useLocation } from 'react-router-dom';
import { Tabs, TabsProps } from 'antd';
+import { useAppLocation } from 'lib/router/useAppLocation';
import ConfigureIcon from 'assets/AlertHistory/ConfigureIcon';
import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
import ROUTES from 'constants/routes';
@@ -48,7 +48,7 @@ const CONFIGURATION_SIDEBAR_ITEMS: ConfigurationSidebarItem[] = [
function AllAlertList(): JSX.Element {
const urlQuery = useUrlQuery();
- const location = useLocation();
+ const location = useAppLocation();
const { safeNavigate } = useSafeNavigate();
const tab = urlQuery.get('tab');
diff --git a/frontend/src/pages/AllErrors/index.tsx b/frontend/src/pages/AllErrors/index.tsx
index b296a2079a..871230cca8 100644
--- a/frontend/src/pages/AllErrors/index.tsx
+++ b/frontend/src/pages/AllErrors/index.tsx
@@ -1,6 +1,5 @@
import { useCallback, useState } from 'react';
import { useQueryClient } from 'react-query';
-import { useLocation } from 'react-router-dom';
import { Filter } from '@signozhq/icons';
import { Button, Tooltip } from 'antd';
import getLocalStorageKey from 'api/browser/localstorage/get';
@@ -15,7 +14,7 @@ import RightToolbarActions from 'container/QueryBuilder/components/ToolbarAction
import ResourceAttributesFilterV2 from 'container/ResourceAttributeFilterV2/ResourceAttributesFilterV2';
import Toolbar from 'container/Toolbar/Toolbar';
import { useRunQueryWithFilterItems } from 'hooks/queryBuilder/useRunQueryWithFilterItems';
-import history from 'lib/history';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { isNull } from 'lodash-es';
import { routes } from './config';
@@ -24,7 +23,7 @@ import { useAllErrorsQueryState } from './QueryStateContext';
import './AllErrors.styles.scss';
function AllErrors(): JSX.Element {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const handleRunQuery = useRunQueryWithFilterItems();
const queryClient = useQueryClient();
@@ -95,12 +94,7 @@ function AllErrors(): JSX.Element {
}
/>
<ResourceAttributesFilterV2 />
- <RouteTab
- routes={routes}
- activeKey={pathname}
- history={history}
- showRightSection={false}
- />
+ <RouteTab routes={routes} activeKey={pathname} showRightSection={false} />
</QuickFiltersLayout>
);
}
diff --git a/frontend/src/pages/ApiMonitoring/ApiMonitoringPage.test.tsx b/frontend/src/pages/ApiMonitoring/ApiMonitoringPage.test.tsx
index 23bbf43219..0034dee1d5 100644
--- a/frontend/src/pages/ApiMonitoring/ApiMonitoringPage.test.tsx
+++ b/frontend/src/pages/ApiMonitoring/ApiMonitoringPage.test.tsx
@@ -1,5 +1,5 @@
-import { MemoryRouter } from 'react-router-dom';
import { render, screen } from '@testing-library/react';
+import { TestRouter } from 'tests/router';
import ApiMonitoringPage from './ApiMonitoringPage';
@@ -28,20 +28,12 @@ jest.mock('components/RouteTab', () => ({
),
}));
-// Mock useLocation hook to properly return the path we're testing
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: '/api-monitoring/explorer',
- }),
-}));
-
describe('ApiMonitoringPage', () => {
it('should render the RouteTab with the Explorer tab', () => {
render(
- <MemoryRouter initialEntries={['/api-monitoring/explorer']}>
+ <TestRouter initialRoute="/api-monitoring/explorer">
<ApiMonitoringPage />
- </MemoryRouter>,
+ </TestRouter>,
);
// Check if the mock RouteTab is rendered
diff --git a/frontend/src/pages/ApiMonitoring/ApiMonitoringPage.tsx b/frontend/src/pages/ApiMonitoring/ApiMonitoringPage.tsx
index d79e4ad30c..0ba9879b97 100644
--- a/frontend/src/pages/ApiMonitoring/ApiMonitoringPage.tsx
+++ b/frontend/src/pages/ApiMonitoring/ApiMonitoringPage.tsx
@@ -1,7 +1,6 @@
import { useLocation } from 'react-use';
import RouteTab from 'components/RouteTab';
import { TabRoutes } from 'components/RouteTab/types';
-import history from 'lib/history';
import { Explorer } from './constants';
@@ -17,7 +16,6 @@ function ApiMonitoringPage(): JSX.Element {
className="api-monitoring-page"
routes={routes}
activeKey={pathname}
- history={history}
/>
);
}
diff --git a/frontend/src/pages/Celery/CeleryOverview/CeleryOverviewDetail/OverviewRightPanelGraph.tsx b/frontend/src/pages/Celery/CeleryOverview/CeleryOverviewDetail/OverviewRightPanelGraph.tsx
index 340235741c..cd8ecad4cf 100644
--- a/frontend/src/pages/Celery/CeleryOverview/CeleryOverviewDetail/OverviewRightPanelGraph.tsx
+++ b/frontend/src/pages/Celery/CeleryOverview/CeleryOverviewDetail/OverviewRightPanelGraph.tsx
@@ -1,8 +1,9 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
import { Color } from '@signozhq/design-tokens';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { navigate } from 'lib/router/navigation';
import { Card } from 'antd';
import logEvent from 'api/common/logEvent';
import { useGetGraphCustomSeries } from 'components/CeleryTask/useGetGraphCustomSeries';
@@ -35,8 +36,7 @@ export default function OverviewRightPanelGraph({
groupByFilter?: BaseAutocompleteData;
filters?: TagFilterItem[];
}): JSX.Element {
- const history = useHistory();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const dispatch = useDispatch();
const urlQuery = useUrlQuery();
@@ -48,13 +48,13 @@ export default function OverviewRightPanelGraph({
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
}
},
- [dispatch, history, pathname, urlQuery],
+ [dispatch, pathname, urlQuery],
);
const { minTime, maxTime } = useSelector<AppState, GlobalReducer>(
diff --git a/frontend/src/pages/ChannelsEdit/ChannelsEditPage.tsx b/frontend/src/pages/ChannelsEdit/ChannelsEditPage.tsx
index 27d618a7b2..acf3901b9a 100644
--- a/frontend/src/pages/ChannelsEdit/ChannelsEditPage.tsx
+++ b/frontend/src/pages/ChannelsEdit/ChannelsEditPage.tsx
@@ -3,7 +3,7 @@ import { toast } from '@signozhq/ui/sonner';
import { useGetNotificationChannel } from 'api/generated/services/channels';
import BackHeader from 'components/BackHeader/BackHeader';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import ChannelForm from 'pages/AlertList/NotificationChannels/components/ChannelForm/ChannelForm';
import CopyButton from 'periscope/components/CopyButton/CopyButton';
@@ -49,7 +49,7 @@ function ChannelsEditPage({ channelId }: ChannelsEditPageProps): JSX.Element {
<ChannelForm
channelId={channelId}
onDone={(): void => {
- history.replace(ROUTES.ALL_CHANNELS);
+ navigate(ROUTES.ALL_CHANNELS, { replace: true });
}}
/>
</div>
diff --git a/frontend/src/pages/ChannelsEdit/index.tsx b/frontend/src/pages/ChannelsEdit/index.tsx
index c7978cbce8..5f42d51b9f 100644
--- a/frontend/src/pages/ChannelsEdit/index.tsx
+++ b/frontend/src/pages/ChannelsEdit/index.tsx
@@ -1,6 +1,8 @@
-import { matchPath, Redirect, useLocation } from 'react-router-dom';
import { Skeleton } from 'antd';
import ROUTES from 'constants/routes';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { matchRoute } from 'lib/router/matchRoute';
+import { Redirect } from 'lib/router/Redirect';
import { withAuthZPage } from 'lib/authz/components/withAuthZ/withAuthZPage';
import {
buildNotificationChannelReadPermission,
@@ -11,10 +13,9 @@ import ChannelsEditPage from './ChannelsEditPage';
import styles from './ChannelsEdit.module.scss';
function ChannelsEdit(): JSX.Element {
- const { pathname } = useLocation();
- const channelId = matchPath<{ channelId: string }>(pathname, {
- path: ROUTES.CHANNELS_EDIT,
- })?.params?.channelId;
+ const { pathname } = useAppLocation();
+ const channelId = matchRoute<'channelId'>(pathname, ROUTES.CHANNELS_EDIT)
+ ?.params?.channelId;
if (!channelId) {
return <Redirect to={ROUTES.ALL_CHANNELS} />;
diff --git a/frontend/src/pages/ChannelsNew/index.tsx b/frontend/src/pages/ChannelsNew/index.tsx
index 1c5c97d25b..43ecd8798d 100644
--- a/frontend/src/pages/ChannelsNew/index.tsx
+++ b/frontend/src/pages/ChannelsNew/index.tsx
@@ -1,8 +1,8 @@
-import { useLocation } from 'react-router-dom';
import { Skeleton } from 'antd';
import BackHeader from 'components/BackHeader/BackHeader';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { withAuthZPage } from 'lib/authz/components/withAuthZ/withAuthZPage';
import { NotificationChannelCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
import { ChannelKind } from 'container/CreateAlertChannels/types';
@@ -12,7 +12,7 @@ import { KIND_KEY } from 'pages/AlertList/NotificationChannels/constants';
import styles from './styles.module.scss';
function ChannelsNew(): JSX.Element {
- const requested = new URLSearchParams(useLocation().search).get('kind');
+ const requested = new URLSearchParams(useAppLocation().search).get('kind');
// an unknown kind in the URL falls back to the form's own default
const initialKind = (Object.values(ChannelKind) as string[]).includes(
requested ?? '',
@@ -37,7 +37,7 @@ function ChannelsNew(): JSX.Element {
<ChannelForm
initialKind={initialKind}
onDone={(): void => {
- history.replace(listRoute);
+ navigate(listRoute, { replace: true });
}}
/>
</div>
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/DashboardActions.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/DashboardActions.tsx
index 50a1102ceb..36d1150788 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/DashboardActions.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/DashboardActions.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { FullScreenHandle } from 'react-full-screen';
-import { generatePath } from 'react-router-dom';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import {
Braces,
Configure,
@@ -130,7 +130,7 @@ function DashboardActions({
source: 'detail',
});
safeNavigate(
- generatePath(ROUTES.DASHBOARD, { dashboardId: response.data.id }),
+ buildRoutePath(ROUTES.DASHBOARD, { dashboardId: response.data.id }),
);
} catch (error) {
showErrorModal(error as APIError);
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/useDeleteDashboardAction.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/useDeleteDashboardAction.tsx
index cb1051505a..d16d3e28da 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/useDeleteDashboardAction.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/useDeleteDashboardAction.tsx
@@ -10,7 +10,7 @@ import {
import { useDeleteConfirm } from 'components/DeleteConfirmModal/useDeleteConfirm';
import ROUTES from 'constants/routes';
import { useDashboardPreferencesStore } from 'hooks/dashboard/useDashboardPreference';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { DashboardDetailEvents } from 'pages/DashboardPage/constants/events';
import { useErrorModal } from 'providers/ErrorModalProvider';
import APIError from 'types/api/error';
@@ -53,7 +53,7 @@ export function useDeleteDashboardAction({
removePreferences(dashboardId);
await invalidateListDashboardsForUserV2(queryClient);
toast.success('Dashboard deleted successfully');
- history.replace(ROUTES.ALL_DASHBOARD);
+ navigate(ROUTES.ALL_DASHBOARD, { replace: true });
},
onError: (error: unknown): void => {
showErrorModal(error as APIError);
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/__tests__/Header.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/__tests__/Header.test.tsx
index 6e134a1fa1..bdfa023244 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/__tests__/Header.test.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/Header/__tests__/Header.test.tsx
@@ -1,7 +1,7 @@
import type { ComponentProps } from 'react';
-import { MemoryRouter } from 'react-router-dom';
import { render, screen } from 'tests/test-utils';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
+import { TestRouter } from 'tests/router';
import Header from '../Header';
@@ -27,7 +27,7 @@ function renderHeader(
props: Partial<ComponentProps<typeof Header>> = {},
): void {
render(
- <MemoryRouter>
+ <TestRouter>
<Header
isDirty={false}
isSaving={false}
@@ -35,7 +35,7 @@ function renderHeader(
onClose={jest.fn()}
{...props}
/>
- </MemoryRouter>,
+ </TestRouter>,
);
}
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/__tests__/panelEditorUrlQuery.promql.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/__tests__/panelEditorUrlQuery.promql.test.tsx
index 0faef877ca..f644f364c3 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/__tests__/panelEditorUrlQuery.promql.test.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/__tests__/panelEditorUrlQuery.promql.test.tsx
@@ -4,8 +4,9 @@ import { useRef, useState } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider as ReduxProvider } from 'react-redux';
-import { MemoryRouter, Route, useHistory, useParams } from 'react-router-dom';
-import { CompatRouter } from 'react-router-dom-v5-compat';
+import { matchRoute } from 'lib/router/matchRoute';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useSafeNavigate } from 'hooks/useSafeNavigate';
import {
type DashboardtypesPanelDTO,
TelemetrytypesSignalDTO,
@@ -14,6 +15,7 @@ import { PANEL_TYPES } from 'constants/queryBuilder';
import { QueryBuilderProvider } from 'providers/QueryBuilder';
import configureStore from 'redux-mock-store';
import appStore from 'store';
+import { TestRouter } from 'tests/router';
import { useOpenPanelEditor } from '../../hooks/useOpenPanelEditor';
import { usePanelEditorQuerySync } from '../hooks/usePanelEditorQuerySync';
@@ -25,15 +27,11 @@ import type { BuildersByVariant } from 'types/api/queryBuilder/queryBuilderData'
// jest.config maps the real hook to a no-op mock; this suite needs real navigation.
jest.mock('hooks/useSafeNavigate', () => {
- const { useHistory: useRouterHistory } =
- jest.requireActual('react-router-dom');
+ const { navigate } = jest.requireActual('lib/router/navigation');
return {
- useSafeNavigate: (): unknown => {
- const history = useRouterHistory();
- return {
- safeNavigate: (to: string): void => history.push(to),
- };
- },
+ useSafeNavigate: (): unknown => ({
+ safeNavigate: (to: string): void => navigate(to),
+ }),
};
});
@@ -71,8 +69,7 @@ const PANELS: Record<string, DashboardtypesPanelDTO> = {
const noop = (): void => {};
/** Stands in for the editor route: the same draft + builder sync `PanelEditorContainer` runs. */
-function EditorRoute(): JSX.Element {
- const { panelId } = useParams<{ panelId: string }>();
+function EditorRoute({ panelId }: { panelId: string }): JSX.Element {
const [panel] = useState(PANELS[panelId]);
usePanelEditorQuerySync({
@@ -102,9 +99,20 @@ function EditorRoute(): JSX.Element {
);
}
+/** Mounts the editor only while the URL is on the editor route, as `<Route>` did. */
+function EditorRouteOutlet(): JSX.Element | null {
+ const { pathname } = useAppLocation();
+ const panelId = matchRoute<'panelId'>(
+ pathname,
+ '/dashboard/:dashboardId/panel/:panelId',
+ )?.params.panelId;
+
+ return panelId ? <EditorRoute panelId={panelId} /> : null;
+}
+
function Harness(): JSX.Element {
const openPanelEditor = useOpenPanelEditor();
- const history = useHistory();
+ const { safeNavigate } = useSafeNavigate();
return (
<>
@@ -125,31 +133,26 @@ function Harness(): JSX.Element {
<button
type="button"
data-testid="back"
- onClick={(): void => history.push('/dashboard/dash-1')}
+ onClick={(): void => safeNavigate('/dashboard/dash-1')}
>
back
</button>
- <Route
- path="/dashboard/:dashboardId/panel/:panelId"
- component={EditorRoute}
- />
+ <EditorRouteOutlet />
</>
);
}
const renderHarness = (): void => {
render(
- <MemoryRouter initialEntries={['/dashboard/dash-1']}>
- <CompatRouter>
- <QueryClientProvider client={new QueryClient()}>
- <ReduxProvider store={configureStore([])(appStore.getState())}>
- <QueryBuilderProvider>
- <Harness />
- </QueryBuilderProvider>
- </ReduxProvider>
- </QueryClientProvider>
- </CompatRouter>
- </MemoryRouter>,
+ <TestRouter initialRoute="/dashboard/dash-1">
+ <QueryClientProvider client={new QueryClient()}>
+ <ReduxProvider store={configureStore([])(appStore.getState())}>
+ <QueryBuilderProvider>
+ <Harness />
+ </QueryBuilderProvider>
+ </ReduxProvider>
+ </QueryClientProvider>
+ </TestRouter>,
);
};
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/hooks/useSwitchToViewMode.ts b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/hooks/useSwitchToViewMode.ts
index 96099832ec..b3f7d4fad2 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/hooks/useSwitchToViewMode.ts
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/hooks/useSwitchToViewMode.ts
@@ -1,5 +1,5 @@
import { useCallback } from 'react';
-import { generatePath } from 'react-router-dom';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import type { DashboardtypesPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import type { PANEL_TYPES } from 'constants/queryBuilder';
@@ -49,7 +49,7 @@ export function useSwitchToViewMode({
encodeURIComponent(JSON.stringify(query)),
);
safeNavigate(
- `${generatePath(ROUTES.DASHBOARD, { dashboardId })}?${params.toString()}`,
+ `${buildRoutePath(ROUTES.DASHBOARD, { dashboardId })}?${params.toString()}`,
);
}, [safeNavigate, urlQuery, dashboardId, panelId, panelType, query, spec]);
}
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/newPanelRoute.ts b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/newPanelRoute.ts
index 423d5389ca..b2a6e6fc44 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/newPanelRoute.ts
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/newPanelRoute.ts
@@ -1,4 +1,4 @@
-import { generatePath } from 'react-router-dom';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { QueryParams } from 'constants/query';
import type { PANEL_TYPES } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
@@ -73,7 +73,7 @@ export function buildExportPanelLink({
if (!kind) {
return null;
}
- const path = generatePath(ROUTES.DASHBOARD_PANEL_EDITOR, {
+ const path = buildRoutePath(ROUTES.DASHBOARD_PANEL_EDITOR, {
dashboardId,
panelId: NEW_PANEL_ID,
});
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/Panels/components/NoData/__tests__/useExtendTimeWindow.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/Panels/components/NoData/__tests__/useExtendTimeWindow.test.tsx
index ad63acb8f0..f8c0aeea00 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/Panels/components/NoData/__tests__/useExtendTimeWindow.test.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/Panels/components/NoData/__tests__/useExtendTimeWindow.test.tsx
@@ -2,11 +2,11 @@ import { act, renderHook } from '@testing-library/react';
import { ReactNode } from 'react';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { UPDATE_TIME_INTERVAL } from 'types/actions/globalTime';
import { GlobalReducer } from 'types/reducer/globalTime';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
+import { TestRouter } from 'tests/router';
import { useExtendTimeWindow } from '../useExtendTimeWindow';
@@ -46,7 +46,7 @@ function setup(globalTime: GlobalReducer): {
const { result } = renderHook(() => useExtendTimeWindow(), {
wrapper: ({ children }: { children: ReactNode }): JSX.Element => (
<Provider store={store}>
- <MemoryRouter>{children}</MemoryRouter>
+ <TestRouter>{children}</TestRouter>
</Provider>
),
});
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/Panels/kinds/ListPanel/useListRowInteraction.ts b/frontend/src/pages/DashboardPage/DashboardContainer/Panels/kinds/ListPanel/useListRowInteraction.ts
index eddbec7d6a..b947f793b3 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/Panels/kinds/ListPanel/useListRowInteraction.ts
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/Panels/kinds/ListPanel/useListRowInteraction.ts
@@ -3,7 +3,7 @@ import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
import { VIEW_TYPES, type VIEWS } from 'components/LogDetail/constants';
import { getTraceLink } from 'container/TracesExplorer/ListView/utils';
import useLogDetailHandlers from 'hooks/logs/useLogDetailHandlers';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import type { RowData } from 'lib/query/createTableColumnsFromQuery';
import type { ILog } from 'types/api/logs/log';
import { openInNewTab } from 'utils/navigation';
@@ -64,7 +64,7 @@ export function useListRowInteraction({
if (event.metaKey || event.ctrlKey) {
openInNewTab(link);
} else {
- history.push(link);
+ navigate(link);
}
return;
}
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.addons.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.addons.test.tsx
index c107363809..26b1de798d 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.addons.test.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.addons.test.tsx
@@ -4,12 +4,11 @@ import type { ReactElement } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider as ReduxProvider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { CompatRouter } from 'react-router-dom-v5-compat';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryBuilderProvider } from 'providers/QueryBuilder';
import configureStore from 'redux-mock-store';
import appStore from 'store';
+import { TestRouter } from 'tests/router';
import ViewPanelModal from '../ViewPanelModal/ViewPanelModal';
import { useViewPanel } from '../hooks/useViewPanel';
@@ -45,11 +44,16 @@ beforeAll(() => {
});
// jest.config maps the real hook to a no-op mock; this suite needs real navigation.
-jest.mock('hooks/useSafeNavigate', () =>
- jest
- .requireActual('tests/browser-history-safe-navigate')
- .createBrowserHistorySafeNavigateMock(),
-);
+jest.mock('hooks/useSafeNavigate', () => {
+ const { navigate } = jest.requireActual('lib/router/navigation');
+ return {
+ useSafeNavigate: (): unknown => ({
+ safeNavigate: (to: string, opts?: { replace?: boolean }): void => {
+ navigate(to, { replace: opts?.replace });
+ },
+ }),
+ };
+});
jest.mock('api/querySuggestions/getFieldKeySuggestions', () => ({
getFieldKeySuggestions: jest.fn().mockResolvedValue({
@@ -203,17 +207,15 @@ const INITIAL_ROUTE = '/dashboard/dash-1';
const renderHarness = (): void => {
window.history.replaceState(null, '', INITIAL_ROUTE);
render(
- <MemoryRouter initialEntries={[INITIAL_ROUTE]}>
- <CompatRouter>
- <QueryClientProvider client={new QueryClient()}>
- <ReduxProvider store={configureStore([])(appStore.getState())}>
- <QueryBuilderProvider>
- <Harness />
- </QueryBuilderProvider>
- </ReduxProvider>
- </QueryClientProvider>
- </CompatRouter>
- </MemoryRouter>,
+ <TestRouter initialRoute="/dashboard/dash-1">
+ <QueryClientProvider client={new QueryClient()}>
+ <ReduxProvider store={configureStore([])(appStore.getState())}>
+ <QueryBuilderProvider>
+ <Harness />
+ </QueryBuilderProvider>
+ </ReduxProvider>
+ </QueryClientProvider>
+ </TestRouter>,
);
};
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.promql.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.promql.test.tsx
index 8ea39be98b..481fc3754d 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.promql.test.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.promql.test.tsx
@@ -4,22 +4,26 @@ import type { ReactElement } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider as ReduxProvider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
-import { CompatRouter } from 'react-router-dom-v5-compat';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryBuilderProvider } from 'providers/QueryBuilder';
import configureStore from 'redux-mock-store';
import appStore from 'store';
+import { TestRouter } from 'tests/router';
import ViewPanelModal from '../ViewPanelModal/ViewPanelModal';
import { useViewPanel } from '../hooks/useViewPanel';
// jest.config maps the real hook to a no-op mock; this suite needs real navigation.
-jest.mock('hooks/useSafeNavigate', () =>
- jest
- .requireActual('tests/browser-history-safe-navigate')
- .createBrowserHistorySafeNavigateMock(),
-);
+jest.mock('hooks/useSafeNavigate', () => {
+ const { navigate } = jest.requireActual('lib/router/navigation');
+ return {
+ useSafeNavigate: (): unknown => ({
+ safeNavigate: (to: string, opts?: { replace?: boolean }): void => {
+ navigate(to, { replace: opts?.replace });
+ },
+ }),
+ };
+});
jest.mock('pages/DashboardPage/DashboardContainer/hooks/usePanelQuery', () => ({
usePanelQuery: (): unknown => ({
@@ -139,17 +143,15 @@ const INITIAL_ROUTE = '/dashboard/dash-1';
const renderHarness = (): void => {
window.history.replaceState(null, '', INITIAL_ROUTE);
render(
- <MemoryRouter initialEntries={[INITIAL_ROUTE]}>
- <CompatRouter>
- <QueryClientProvider client={new QueryClient()}>
- <ReduxProvider store={configureStore([])(appStore.getState())}>
- <QueryBuilderProvider>
- <Harness />
- </QueryBuilderProvider>
- </ReduxProvider>
- </QueryClientProvider>
- </CompatRouter>
- </MemoryRouter>,
+ <TestRouter initialRoute="/dashboard/dash-1">
+ <QueryClientProvider client={new QueryClient()}>
+ <ReduxProvider store={configureStore([])(appStore.getState())}>
+ <QueryBuilderProvider>
+ <Harness />
+ </QueryBuilderProvider>
+ </ReduxProvider>
+ </QueryClientProvider>
+ </TestRouter>,
);
};
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.test.tsx
index 80843c1eff..fda1ae60c7 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.test.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/__tests__/useViewPanel.test.tsx
@@ -1,7 +1,6 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import { MemoryRouter, useLocation } from 'react-router-dom';
-import { CompatRouter } from 'react-router-dom-v5-compat';
+import { useAppLocation } from 'lib/router/useAppLocation';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
@@ -9,6 +8,7 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { fromPerses } from 'pages/DashboardPage/DashboardContainer/queryV5/persesQueryAdapters';
import { QueryBuilderProvider } from 'providers/QueryBuilder';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
+import { TestRouter } from 'tests/router';
import { usePanelEditorDraft } from 'pages/DashboardPage/DashboardContainer/PanelEditor/hooks/usePanelEditorDraft';
@@ -16,11 +16,16 @@ import { useViewPanelMode } from '../ViewPanelModal/useViewPanelMode';
import { useViewPanel } from '../hooks/useViewPanel';
// jest.config maps the real hook to a no-op mock; this suite needs real navigation.
-jest.mock('hooks/useSafeNavigate', () =>
- jest
- .requireActual('tests/browser-history-safe-navigate')
- .createBrowserHistorySafeNavigateMock(),
-);
+jest.mock('hooks/useSafeNavigate', () => {
+ const { navigate } = jest.requireActual('lib/router/navigation');
+ return {
+ useSafeNavigate: (): unknown => ({
+ safeNavigate: (to: string, opts?: { replace?: boolean }): void => {
+ navigate(to, { replace: opts?.replace });
+ },
+ }),
+ };
+});
jest.mock('pages/DashboardPage/DashboardContainer/hooks/usePanelQuery', () => ({
usePanelQuery: (): unknown => ({
@@ -117,7 +122,7 @@ function ModalBody({ panelId }: { panelId: string }): JSX.Element {
}
function SearchProbe(): JSX.Element {
- return <div data-testid="search">{useLocation().search}</div>;
+ return <div data-testid="search">{useAppLocation().search}</div>;
}
function StagedQueryProbe(): null {
@@ -199,13 +204,11 @@ const INITIAL_ROUTE = '/dashboard/dash-1';
const renderHarness = (): void => {
window.history.replaceState(null, '', INITIAL_ROUTE);
render(
- <MemoryRouter initialEntries={[INITIAL_ROUTE]}>
- <CompatRouter>
- <QueryBuilderProvider>
- <Harness />
- </QueryBuilderProvider>
- </CompatRouter>
- </MemoryRouter>,
+ <TestRouter initialRoute="/dashboard/dash-1">
+ <QueryBuilderProvider>
+ <Harness />
+ </QueryBuilderProvider>
+ </TestRouter>,
);
};
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/usePanelInteractions.ts b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/usePanelInteractions.ts
index 99542494fb..6e4c0e11b4 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/usePanelInteractions.ts
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/usePanelInteractions.ts
@@ -1,7 +1,8 @@
import { useCallback, useMemo } from 'react';
// eslint-disable-next-line no-restricted-imports -- TODO: migrate global time dispatch off redux
import { useDispatch } from 'react-redux';
-import { useLocation, useParams } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppParams } from 'lib/router/useAppParams';
import { QueryParams } from 'constants/query';
import { PanelMode } from 'lib/visualization/panels/types';
import type { DashboardPreference } from 'pages/DashboardPage/DashboardContainer/Panels/types/rendererProps';
@@ -26,10 +27,10 @@ export interface PanelInteractions {
*/
export function usePanelInteractions(): PanelInteractions {
const dispatch = useDispatch();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const { safeNavigate } = useSafeNavigate();
const urlQuery = useUrlQuery();
- const { dashboardId } = useParams<{ dashboardId: string }>();
+ const { dashboardId } = useAppParams<{ dashboardId: string }>();
const [syncMode] = useDashboardCursorSyncMode(
dashboardId,
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useViewPanel.ts b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useViewPanel.ts
index b68fe0cfe3..07f8ba63eb 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useViewPanel.ts
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useViewPanel.ts
@@ -1,5 +1,5 @@
import { useCallback } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import logEvent from 'api/common/logEvent';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
@@ -38,7 +38,7 @@ export interface UseViewPanelApi {
*/
export function useViewPanel(): UseViewPanelApi {
const { safeNavigate } = useSafeNavigate();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const urlQuery = useUrlQuery();
const { resetQuery } = useQueryBuilder();
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useOpenPanelEditor.ts b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useOpenPanelEditor.ts
index 1bdb2f192d..e8b1d8bfd8 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useOpenPanelEditor.ts
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/hooks/useOpenPanelEditor.ts
@@ -1,5 +1,5 @@
import { useCallback } from 'react';
-import { generatePath } from 'react-router-dom';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
@@ -38,7 +38,7 @@ export function useOpenPanelEditor(): (
panelId,
dashboardId,
});
- const path = generatePath(ROUTES.DASHBOARD_PANEL_EDITOR, {
+ const path = buildRoutePath(ROUTES.DASHBOARD_PANEL_EDITOR, {
dashboardId,
panelId,
});
diff --git a/frontend/src/pages/DashboardPage/DashboardPage.tsx b/frontend/src/pages/DashboardPage/DashboardPage.tsx
index cc3cc06590..2fcd647ba7 100644
--- a/frontend/src/pages/DashboardPage/DashboardPage.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardPage.tsx
@@ -1,6 +1,5 @@
import { useEffect, useRef } from 'react';
-import { useParams } from 'react-router-dom';
-
+import { useAppParams } from 'lib/router/useAppParams';
import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
import Spinner from 'components/Spinner';
@@ -17,10 +16,11 @@ import { useDashboardFetch } from './DashboardContainer/hooks/useDashboardFetch'
import styles from './DashboardPage.module.scss';
function DashboardPage(): JSX.Element {
- const { dashboardId } = useParams<{ dashboardId: string }>();
+ const { dashboardId } = useAppParams<'dashboardId'>();
- const { dashboard, isLoading, isError, error, refetch } =
- useDashboardFetch(dashboardId);
+ const { dashboard, isLoading, isError, error, refetch } = useDashboardFetch(
+ dashboardId || '',
+ );
// Fire once per dashboard load (re-fires on navigating to a different id).
const openedRef = useRef<string | null>(null);
diff --git a/frontend/src/pages/DashboardPage/PanelEditorPage/PanelEditorPage.tsx b/frontend/src/pages/DashboardPage/PanelEditorPage/PanelEditorPage.tsx
index 3f544a41cf..8068ff5077 100644
--- a/frontend/src/pages/DashboardPage/PanelEditorPage/PanelEditorPage.tsx
+++ b/frontend/src/pages/DashboardPage/PanelEditorPage/PanelEditorPage.tsx
@@ -1,10 +1,8 @@
import { useCallback, useMemo, useRef } from 'react';
-import {
- generatePath,
- Redirect,
- useLocation,
- useParams,
-} from 'react-router-dom';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
+import { Redirect } from 'lib/router/Redirect';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { useAppParams } from 'lib/router/useAppParams';
import { Typography } from '@signozhq/ui/typography';
import Spinner from 'components/Spinner';
import ROUTES from 'constants/routes';
@@ -38,11 +36,8 @@ import styles from './PanelEditorPage.module.scss';
* fetched dashboard spec and wires up navigate-back callbacks.
*/
function PanelEditorPage(): JSX.Element {
- const { dashboardId, panelId } = useParams<{
- dashboardId: string;
- panelId: string;
- }>();
- const { search, state } = useLocation();
+ const { dashboardId, panelId } = useAppParams<'dashboardId' | 'panelId'>();
+ const { search, state } = useAppLocation();
const { safeNavigate } = useSafeNavigate();
const timeSearch = useTimeSearchParams();
@@ -50,8 +45,9 @@ function PanelEditorPage(): JSX.Element {
// instead of the saved panel. Lost on refresh/new-tab, which falls back to saved.
const handoffSpec = (state as PanelEditorHandoffState | null)?.editSpec;
- const { dashboard, isLoading, isError, error, refetch } =
- useDashboardFetch(dashboardId);
+ const { dashboard, isLoading, isError, error, refetch } = useDashboardFetch(
+ dashboardId || '',
+ );
// On a refresh/direct URL this route is the only mount, so seed the edit
// context the way DashboardContainer does — during render, so the subtree's
// first render already sees the id (useDashboardFetchRequired throws without it).
@@ -78,8 +74,8 @@ function PanelEditorPage(): JSX.Element {
// A `panel/new?panelKind=…` route means "create": seed a default panel of that
// kind rather than looking one up (seeded from the exported query when present).
// Persisted (with a real id) only on save.
- const newKind = parseNewPanelKind(panelId, search);
- const existingPanel = dashboard?.spec.panels[panelId];
+ const newKind = parseNewPanelKind(panelId || '', search);
+ const existingPanel = panelId ? dashboard?.spec.panels[panelId] : undefined;
const panel = useMemo(() => {
if (newKind) {
// A `compositeQuery` at mount means the explorer routed an export here.
@@ -104,7 +100,9 @@ function PanelEditorPage(): JSX.Element {
const backToDashboard = useCallback((): void => {
// Drop editor-only URL state (variables come from the persisted store), but carry
// time so a custom range picked in the editor isn't reset to the dashboard default.
- const path = generatePath(ROUTES.DASHBOARD, { dashboardId });
+ const path = buildRoutePath(ROUTES.DASHBOARD, {
+ dashboardId: dashboardId || '',
+ });
safeNavigate(timeSearch ? `${path}?${timeSearch}` : path);
}, [safeNavigate, dashboardId, timeSearch]);
@@ -125,15 +123,15 @@ function PanelEditorPage(): JSX.Element {
if (!panel) {
return (
<Redirect
- to={`${generatePath(ROUTES.DASHBOARD, { dashboardId })}${search}`}
+ to={`${buildRoutePath(ROUTES.DASHBOARD, { dashboardId: dashboardId || '' })}${search}`}
/>
);
}
return (
<PanelEditorContainer
- dashboardId={dashboardId}
- panelId={panelId}
+ dashboardId={dashboardId || ''}
+ panelId={panelId || ''}
panel={panel}
savedPanel={existingPanel}
isNew={!!newKind}
diff --git a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.mocks.tsx b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.mocks.tsx
index 0377a7de9a..0e73a46f8a 100644
--- a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.mocks.tsx
+++ b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.mocks.tsx
@@ -4,8 +4,8 @@
*/
import { rest } from 'msw';
-import { generatePath } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
@@ -61,7 +61,7 @@ const PANEL_OPTIONS = [...PANEL_IDS, NEW_PANEL_ID] as const;
type PanelOption = (typeof PANEL_OPTIONS)[number];
const editorRoute = (panel: PanelOption, kind: NewPanelKind): string => {
- const path = generatePath(ROUTES.DASHBOARD_PANEL_EDITOR, {
+ const path = buildRoutePath(ROUTES.DASHBOARD_PANEL_EDITOR, {
dashboardId: STORY_DASHBOARD_ID,
panelId: panel,
});
diff --git a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.tsx b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.tsx
index 6d77ed28e7..72eff5e775 100644
--- a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.tsx
+++ b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.tsx
@@ -1,7 +1,7 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -29,9 +29,7 @@ const meta = {
component: PanelEditorPage as ComponentType<PanelEditorArgs>,
// The dashboard and panel ids come out of the pathname, so the editor renders
// under its own route rather than being mounted on its own.
- render: (): JSX.Element => (
- <Route path={ROUTES.DASHBOARD_PANEL_EDITOR} component={PanelEditorPage} />
- ),
+ render: renderAtRoute(ROUTES.DASHBOARD_PANEL_EDITOR, PanelEditorPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<PanelEditorArgs>;
diff --git a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/sections/ChartOptions.stories.tsx b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/sections/ChartOptions.stories.tsx
index 0471a8bb25..b169afaab1 100644
--- a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/sections/ChartOptions.stories.tsx
+++ b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/sections/ChartOptions.stories.tsx
@@ -1,7 +1,7 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { expect, screen, userEvent, waitFor } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -31,9 +31,7 @@ const meta = {
title: 'Pages/Dashboards/Panel Editor/Chart Options',
tags: ['authz', 'play'],
component: PanelEditorPage as ComponentType<PanelEditorArgs>,
- render: (): JSX.Element => (
- <Route path={ROUTES.DASHBOARD_PANEL_EDITOR} component={PanelEditorPage} />
- ),
+ render: renderAtRoute(ROUTES.DASHBOARD_PANEL_EDITOR, PanelEditorPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<PanelEditorArgs>;
diff --git a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/sections/ThresholdsAndLinks.stories.tsx b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/sections/ThresholdsAndLinks.stories.tsx
index 69d21b9799..89bb0c9d35 100644
--- a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/sections/ThresholdsAndLinks.stories.tsx
+++ b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/sections/ThresholdsAndLinks.stories.tsx
@@ -1,7 +1,7 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { expect, screen, userEvent, waitFor } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -31,9 +31,7 @@ const meta = {
title: 'Pages/Dashboards/Panel Editor/Thresholds and Links',
tags: ['authz', 'play'],
component: PanelEditorPage as ComponentType<PanelEditorArgs>,
- render: (): JSX.Element => (
- <Route path={ROUTES.DASHBOARD_PANEL_EDITOR} component={PanelEditorPage} />
- ),
+ render: renderAtRoute(ROUTES.DASHBOARD_PANEL_EDITOR, PanelEditorPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<PanelEditorArgs>;
diff --git a/frontend/src/pages/DashboardPage/__tests__/DashboardPage.authz.test.tsx b/frontend/src/pages/DashboardPage/__tests__/DashboardPage.authz.test.tsx
index 5c5646e2c1..37b64ba642 100644
--- a/frontend/src/pages/DashboardPage/__tests__/DashboardPage.authz.test.tsx
+++ b/frontend/src/pages/DashboardPage/__tests__/DashboardPage.authz.test.tsx
@@ -6,19 +6,16 @@ import {
setupAuthzAdmin,
setupAuthzDenyAll,
} from 'lib/authz/utils/authz-test-utils';
+import { mockAppParams } from 'tests/router-mocks';
import DashboardPage from '../DashboardPage';
const DASHBOARD_ID = 'dash-1';
const DASHBOARD_URL = `http://localhost/api/v2/dashboards/${DASHBOARD_ID}`;
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useParams: (): { dashboardId: string } => ({ dashboardId: DASHBOARD_ID }),
-}));
-
describe('DashboardPage - AuthZ', () => {
beforeEach(() => {
+ mockAppParams({ dashboardId: DASHBOARD_ID });
server.use(setupAuthzAdmin());
});
diff --git a/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsx b/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsx
index 38c4a6942f..1e58b1b437 100644
--- a/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsx
+++ b/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsx
@@ -4,8 +4,8 @@
*/
import { rest } from 'msw';
-import { generatePath } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import type { GetPublicDashboard200 } from 'api/generated/services/sigNoz.schemas';
import { useDashboardPreferencesStore } from 'hooks/dashboard/useDashboardPreference';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
@@ -62,7 +62,7 @@ const SHARING = 'Dashboard · sharing';
const REQUESTS = 'Dashboard · requests';
export const dashboardRoute = (): string =>
- generatePath(ROUTES.DASHBOARD, { dashboardId: STORY_DASHBOARD_ID });
+ buildRoutePath(ROUTES.DASHBOARD, { dashboardId: STORY_DASHBOARD_ID });
export const tooltipRoute = (): string =>
`${dashboardRoute()}?variables=${encodeURIComponent(
diff --git a/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.tsx b/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.tsx
index 8883cf4d28..9a29a5b6d3 100644
--- a/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.tsx
+++ b/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.tsx
@@ -1,8 +1,8 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import * as monaco from 'monaco-editor';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -44,9 +44,7 @@ const meta = {
component: DashboardPage as ComponentType<DashboardArgs>,
// The page reads the dashboard id out of the pathname, so it renders under
// its own route rather than being mounted on its own.
- render: (): JSX.Element => (
- <Route path={ROUTES.DASHBOARD} component={DashboardPage} />
- ),
+ render: renderAtRoute(ROUTES.DASHBOARD, DashboardPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<DashboardArgs>;
diff --git a/frontend/src/pages/DashboardPage/stories/authz/DashboardPage.authz.stories.tsx b/frontend/src/pages/DashboardPage/stories/authz/DashboardPage.authz.stories.tsx
index 08cef976c8..884888ca63 100644
--- a/frontend/src/pages/DashboardPage/stories/authz/DashboardPage.authz.stories.tsx
+++ b/frontend/src/pages/DashboardPage/stories/authz/DashboardPage.authz.stories.tsx
@@ -1,7 +1,7 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -33,9 +33,7 @@ const meta = {
title: 'Pages/Dashboards/Detail/Authz',
tags: ['authz', 'play'],
component: DashboardPage as ComponentType<DashboardArgs>,
- render: (): JSX.Element => (
- <Route path={ROUTES.DASHBOARD} component={DashboardPage} />
- ),
+ render: renderAtRoute(ROUTES.DASHBOARD, DashboardPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<DashboardArgs>;
diff --git a/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.mocks.tsx b/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.mocks.tsx
index 28312b8f40..160ff35356 100644
--- a/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.mocks.tsx
+++ b/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.mocks.tsx
@@ -4,8 +4,8 @@
*/
import { rest } from 'msw';
-import { generatePath } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import {
DashboardtypesHeatmapPaletteDTO as HeatmapPalette,
DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
@@ -266,7 +266,7 @@ export const panelsMocks = defineStoryMocks({
];
},
config: () => ({
- route: generatePath(ROUTES.DASHBOARD, { dashboardId: PANELS_DASHBOARD_ID }),
+ route: buildRoutePath(ROUTES.DASHBOARD, { dashboardId: PANELS_DASHBOARD_ID }),
}),
effect: (values) => {
seedPanelsDocument(values);
diff --git a/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.tsx b/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.tsx
index dc61a76584..496fbde3e8 100644
--- a/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.tsx
+++ b/frontend/src/pages/DashboardPage/stories/panels/Panels.stories.tsx
@@ -1,6 +1,5 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import {
DashboardtypesHeatmapYScaleDTO as HeatmapYScale,
DashboardtypesLegendPositionDTO as LegendPosition,
@@ -10,6 +9,7 @@ import {
import ROUTES from 'constants/routes';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import DashboardPage from '../../DashboardPage';
@@ -39,9 +39,7 @@ const meta = {
// signature; the story's args are what the controls resolve to.
component: DashboardPage as ComponentType<PanelsArgs>,
// The page reads the dashboard id out of the pathname.
- render: (): JSX.Element => (
- <Route path={ROUTES.DASHBOARD} component={DashboardPage} />
- ),
+ render: renderAtRoute(ROUTES.DASHBOARD, DashboardPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<PanelsArgs>;
diff --git a/frontend/src/pages/DashboardPage/stories/settings/EditVariable.stories.tsx b/frontend/src/pages/DashboardPage/stories/settings/EditVariable.stories.tsx
index fa7c696459..b952ba1ac7 100644
--- a/frontend/src/pages/DashboardPage/stories/settings/EditVariable.stories.tsx
+++ b/frontend/src/pages/DashboardPage/stories/settings/EditVariable.stories.tsx
@@ -1,7 +1,7 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { expect, screen, userEvent, waitFor } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -32,9 +32,7 @@ const meta = {
title: 'Pages/Dashboards/Detail/Edit Variable',
tags: ['authz', 'play'],
component: DashboardPage as ComponentType<DashboardArgs>,
- render: (): JSX.Element => (
- <Route path={ROUTES.DASHBOARD} component={DashboardPage} />
- ),
+ render: renderAtRoute(ROUTES.DASHBOARD, DashboardPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<DashboardArgs>;
diff --git a/frontend/src/pages/DashboardPage/stories/settings/NewVariable.stories.tsx b/frontend/src/pages/DashboardPage/stories/settings/NewVariable.stories.tsx
index 7880d8f93d..64ea6629be 100644
--- a/frontend/src/pages/DashboardPage/stories/settings/NewVariable.stories.tsx
+++ b/frontend/src/pages/DashboardPage/stories/settings/NewVariable.stories.tsx
@@ -1,7 +1,7 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -33,9 +33,7 @@ const meta = {
title: 'Pages/Dashboards/Detail/New Variable',
tags: ['authz', 'play'],
component: DashboardPage as ComponentType<DashboardArgs>,
- render: (): JSX.Element => (
- <Route path={ROUTES.DASHBOARD} component={DashboardPage} />
- ),
+ render: renderAtRoute(ROUTES.DASHBOARD, DashboardPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<DashboardArgs>;
diff --git a/frontend/src/pages/DashboardPage/stories/settings/Settings.stories.tsx b/frontend/src/pages/DashboardPage/stories/settings/Settings.stories.tsx
index 9b8f50e056..889b74ffa4 100644
--- a/frontend/src/pages/DashboardPage/stories/settings/Settings.stories.tsx
+++ b/frontend/src/pages/DashboardPage/stories/settings/Settings.stories.tsx
@@ -1,7 +1,7 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -26,9 +26,7 @@ const meta = {
title: 'Pages/Dashboards/Detail/Settings',
tags: ['authz', 'play'],
component: DashboardPage as ComponentType<DashboardArgs>,
- render: (): JSX.Element => (
- <Route path={ROUTES.DASHBOARD} component={DashboardPage} />
- ),
+ render: renderAtRoute(ROUTES.DASHBOARD, DashboardPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<DashboardArgs>;
diff --git a/frontend/src/pages/DashboardPage/stories/settings/Variables.stories.tsx b/frontend/src/pages/DashboardPage/stories/settings/Variables.stories.tsx
index 42d12869bc..38e95c5b8a 100644
--- a/frontend/src/pages/DashboardPage/stories/settings/Variables.stories.tsx
+++ b/frontend/src/pages/DashboardPage/stories/settings/Variables.stories.tsx
@@ -1,7 +1,7 @@
import type { ComponentType } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -35,9 +35,7 @@ const meta = {
title: 'Pages/Dashboards/Detail/Variables',
tags: ['authz', 'play'],
component: DashboardPage as ComponentType<DashboardArgs>,
- render: (): JSX.Element => (
- <Route path={ROUTES.DASHBOARD} component={DashboardPage} />
- ),
+ render: renderAtRoute(ROUTES.DASHBOARD, DashboardPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<DashboardArgs>;
diff --git a/frontend/src/pages/DashboardsListPage/components/ActionsPopover/useCloneDashboardAction.ts b/frontend/src/pages/DashboardsListPage/components/ActionsPopover/useCloneDashboardAction.ts
index fa19c9b1e1..f2e4dfeaa5 100644
--- a/frontend/src/pages/DashboardsListPage/components/ActionsPopover/useCloneDashboardAction.ts
+++ b/frontend/src/pages/DashboardsListPage/components/ActionsPopover/useCloneDashboardAction.ts
@@ -1,9 +1,9 @@
import { useMutation } from 'react-query';
-import { generatePath } from 'react-router-dom';
import { toast } from '@signozhq/ui/sonner';
import logEvent from 'api/common/logEvent';
import { cloneDashboardV2 } from 'api/generated/services/dashboard';
import ROUTES from 'constants/routes';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { DashboardListEvents } from 'pages/DashboardsListPage/constants/events';
import { useErrorModal } from 'providers/ErrorModalProvider';
@@ -32,7 +32,7 @@ export function useCloneDashboardAction({
dashboardId,
});
safeNavigate(
- generatePath(ROUTES.DASHBOARD, { dashboardId: response.data.id }),
+ buildRoutePath(ROUTES.DASHBOARD, { dashboardId: response.data.id }),
);
},
onError: (error: APIError) => {
diff --git a/frontend/src/pages/DashboardsListPage/components/DashboardRow/DashboardRow.tsx b/frontend/src/pages/DashboardsListPage/components/DashboardRow/DashboardRow.tsx
index fe8fd0a94f..335e541e1b 100644
--- a/frontend/src/pages/DashboardsListPage/components/DashboardRow/DashboardRow.tsx
+++ b/frontend/src/pages/DashboardsListPage/components/DashboardRow/DashboardRow.tsx
@@ -6,7 +6,7 @@ import { Typography } from '@signozhq/ui/typography';
import { CalendarClock, LockKeyhole, Pin, PinOff } from '@signozhq/icons';
import cx from 'classnames';
import logEvent from 'api/common/logEvent';
-import { generatePath } from 'react-router-dom';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { resolveDashboardImage } from 'pages/DashboardPage/DashboardContainer/dashboardIcons';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import ROUTES from 'constants/routes';
@@ -60,7 +60,7 @@ function DashboardRow({
const isLocked = !!dashboard.locked;
const tags = tagsToStrings(dashboard.tags);
- const link = generatePath(ROUTES.DASHBOARD, { dashboardId: id });
+ const link = buildRoutePath(ROUTES.DASHBOARD, { dashboardId: id });
const formattedCreatedAt = formatTimezoneAdjustedTimestamp(
createdAt,
DATE_TIME_FORMATS.DASH_DATETIME_UTC,
diff --git a/frontend/src/pages/DashboardsListPage/components/NewDashboardModal/BlankDashboardPanel.tsx b/frontend/src/pages/DashboardsListPage/components/NewDashboardModal/BlankDashboardPanel.tsx
index 576bb8d64a..8c60086d5c 100644
--- a/frontend/src/pages/DashboardsListPage/components/NewDashboardModal/BlankDashboardPanel.tsx
+++ b/frontend/src/pages/DashboardsListPage/components/NewDashboardModal/BlankDashboardPanel.tsx
@@ -6,7 +6,7 @@ import { Input } from '@signozhq/ui/input';
import { Typography } from '@signozhq/ui/typography';
import { toast } from '@signozhq/ui/sonner';
import { AxiosError } from 'axios';
-import { generatePath } from 'react-router-dom';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import logEvent from 'api/common/logEvent';
import { createDashboardV2 } from 'api/generated/services/dashboard';
import ROUTES from 'constants/routes';
@@ -72,7 +72,7 @@ function BlankDashboardPanel({ onClose }: Props): JSX.Element {
});
onClose();
safeNavigate(
- generatePath(ROUTES.DASHBOARD, { dashboardId: created.data.id }),
+ buildRoutePath(ROUTES.DASHBOARD, { dashboardId: created.data.id }),
);
} catch (e) {
showErrorModal(e as APIError);
diff --git a/frontend/src/pages/DashboardsListPage/components/NewDashboardModal/ImportJsonPanel.tsx b/frontend/src/pages/DashboardsListPage/components/NewDashboardModal/ImportJsonPanel.tsx
index d70a13ee8f..95204ea1f9 100644
--- a/frontend/src/pages/DashboardsListPage/components/NewDashboardModal/ImportJsonPanel.tsx
+++ b/frontend/src/pages/DashboardsListPage/components/NewDashboardModal/ImportJsonPanel.tsx
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { generatePath } from 'react-router-dom';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { red } from '@ant-design/colors';
// eslint-disable-next-line signoz/no-antd-components -- Upload has no @signozhq/ui equivalent yet
import { Upload, UploadProps } from 'antd';
@@ -82,7 +82,7 @@ function ImportJsonPanel({ onClose }: Props): JSX.Element {
void logEvent(DashboardListEvents.DashboardCreated, { method: 'import' });
onClose();
safeNavigate(
- generatePath(ROUTES.DASHBOARD, { dashboardId: response.data.id }),
+ buildRoutePath(ROUTES.DASHBOARD, { dashboardId: response.data.id }),
);
} catch (error) {
showErrorModal(error as APIError);
diff --git a/frontend/src/pages/EditRules/index.tsx b/frontend/src/pages/EditRules/index.tsx
index 34208165be..b13579443e 100644
--- a/frontend/src/pages/EditRules/index.tsx
+++ b/frontend/src/pages/EditRules/index.tsx
@@ -15,7 +15,7 @@ import EditRulesContainer from 'container/EditRules';
import { useNotifications } from 'hooks/useNotifications';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import {
NEW_ALERT_SCHEMA_VERSION,
PostableAlertRuleV2,
@@ -53,7 +53,7 @@ function EditRules(): JSX.Element {
params.delete(QueryParams.panelTypes);
params.delete(QueryParams.ruleId);
params.delete(QueryParams.relativeTime);
- history.push(`${ROUTES.LIST_ALL_ALERT}?${params.toString()}`);
+ navigate(`${ROUTES.LIST_ALL_ALERT}?${params.toString()}`);
};
useEffect(() => {
diff --git a/frontend/src/pages/ErrorDetails/index.tsx b/frontend/src/pages/ErrorDetails/index.tsx
index efb7ece35e..c9b5c220e0 100644
--- a/frontend/src/pages/ErrorDetails/index.tsx
+++ b/frontend/src/pages/ErrorDetails/index.tsx
@@ -3,8 +3,9 @@ import { useTranslation } from 'react-i18next';
import { useQuery } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { Redirect, useLocation } from 'react-router-dom';
import { Typography } from '@signozhq/ui/typography';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { Redirect } from 'lib/router/Redirect';
import getByErrorType from 'api/errors/getByErrorTypeAndService';
import getById from 'api/errors/getById';
import Spinner from 'components/Spinner';
@@ -21,7 +22,7 @@ function ErrorDetails(): JSX.Element {
const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
- const { search } = useLocation();
+ const { search } = useAppLocation();
const params = useMemo(() => new URLSearchParams(search), [search]);
const groupId = params.get(urlKey.groupId);
diff --git a/frontend/src/pages/ForgotPassword/__tests__/ForgotPassword.test.tsx b/frontend/src/pages/ForgotPassword/__tests__/ForgotPassword.test.tsx
index 46531c0991..a5a111df36 100644
--- a/frontend/src/pages/ForgotPassword/__tests__/ForgotPassword.test.tsx
+++ b/frontend/src/pages/ForgotPassword/__tests__/ForgotPassword.test.tsx
@@ -1,23 +1,16 @@
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { render, waitFor } from 'tests/test-utils';
import ForgotPassword from '../index';
// Mock dependencies
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: jest.fn(),
- location: {
- search: '',
- },
- },
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: jest.fn(),
}));
-const mockHistoryPush = history.push as jest.MockedFunction<
- typeof history.push
->;
+const mockNavigate = navigate as jest.MockedFunction<typeof navigate>;
describe('ForgotPassword Page', () => {
beforeEach(() => {
@@ -31,7 +24,7 @@ describe('ForgotPassword Page', () => {
});
await waitFor(() => {
- expect(mockHistoryPush).toHaveBeenCalledWith(ROUTES.LOGIN);
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.LOGIN);
});
});
diff --git a/frontend/src/pages/ForgotPassword/index.tsx b/frontend/src/pages/ForgotPassword/index.tsx
index 472622e13d..0eb35827ed 100644
--- a/frontend/src/pages/ForgotPassword/index.tsx
+++ b/frontend/src/pages/ForgotPassword/index.tsx
@@ -1,21 +1,21 @@
import { useEffect } from 'react';
-import { useLocation } from 'react-router-dom';
import AuthPageContainer from 'components/AuthPageContainer';
import ROUTES from 'constants/routes';
import ForgotPasswordContainer, {
ForgotPasswordRouteState,
} from 'container/ForgotPassword';
-import history from 'lib/history';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { navigate } from 'lib/router/navigation';
import '../Login/Login.styles.scss';
function ForgotPassword(): JSX.Element | null {
- const location = useLocation<ForgotPasswordRouteState | undefined>();
+ const location = useAppLocation<ForgotPasswordRouteState | undefined>();
const routeState = location.state;
useEffect(() => {
if (!routeState?.email) {
- history.push(ROUTES.LOGIN);
+ navigate(ROUTES.LOGIN);
}
}, [routeState]);
diff --git a/frontend/src/pages/InfrastructureMonitoring/InfrastructureMonitoringPage.tsx b/frontend/src/pages/InfrastructureMonitoring/InfrastructureMonitoringPage.tsx
index 128fc15f89..4fcd118ee1 100644
--- a/frontend/src/pages/InfrastructureMonitoring/InfrastructureMonitoringPage.tsx
+++ b/frontend/src/pages/InfrastructureMonitoring/InfrastructureMonitoringPage.tsx
@@ -1,7 +1,6 @@
import { useLocation } from 'react-use';
import RouteTab from 'components/RouteTab';
import { TabRoutes } from 'components/RouteTab/types';
-import history from 'lib/history';
import { Hosts, Kubernetes } from './constants';
@@ -17,7 +16,6 @@ export default function InfrastructureMonitoringPage(): JSX.Element {
className="infra-monitoring-module-container"
routes={routes}
activeKey={pathname}
- history={history}
/>
);
}
diff --git a/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/CloudIntegration.stories.tsx b/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/CloudIntegration.stories.tsx
index 58c9df9f03..6d59be3dea 100644
--- a/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/CloudIntegration.stories.tsx
+++ b/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/CloudIntegration.stories.tsx
@@ -1,8 +1,8 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import { screen, userEvent, within } from 'storybook/test';
import { CloudintegrationtypesGCPConnectionMethodDTO } from 'api/generated/services/sigNoz.schemas';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -42,12 +42,7 @@ const meta = {
// `aws`, `azure` and `gcp` are integration ids like any other, and the detail
// page renders the cloud page instead of the built-in one for those three, so
// the story runs on the detail route and its `route` picks the provider.
- render: (): JSX.Element => (
- <Route
- path={ROUTES.INTEGRATIONS_DETAIL}
- component={IntegrationsDetailsPage}
- />
- ),
+ render: renderAtRoute(ROUTES.INTEGRATIONS_DETAIL, IntegrationsDetailsPage),
...pageStory,
// The built-in-integration lookup is expected to 404 for a cloud provider.
parameters: { ...pageStory.parameters, allowConsoleErrors: true },
diff --git a/frontend/src/pages/IntegrationsDetailsPage/stories/IntegrationsDetailsPage.stories.tsx b/frontend/src/pages/IntegrationsDetailsPage/stories/IntegrationsDetailsPage.stories.tsx
index 8a2d2c6b1d..9b4ba51a4d 100644
--- a/frontend/src/pages/IntegrationsDetailsPage/stories/IntegrationsDetailsPage.stories.tsx
+++ b/frontend/src/pages/IntegrationsDetailsPage/stories/IntegrationsDetailsPage.stories.tsx
@@ -1,7 +1,7 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import { screen, userEvent, within } from 'storybook/test';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -25,12 +25,7 @@ const meta = {
component: IntegrationsDetailsPage,
// The page reads the integration id out of the pathname, so it renders under
// its own route rather than being mounted on its own.
- render: (): JSX.Element => (
- <Route
- path={ROUTES.INTEGRATIONS_DETAIL}
- component={IntegrationsDetailsPage}
- />
- ),
+ render: renderAtRoute(ROUTES.INTEGRATIONS_DETAIL, IntegrationsDetailsPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<IntegrationDetailArgs>;
diff --git a/frontend/src/pages/LLMObservability/__tests__/LLMObservability.test.tsx b/frontend/src/pages/LLMObservability/__tests__/LLMObservability.test.tsx
index e03074cce1..f3a84825ef 100644
--- a/frontend/src/pages/LLMObservability/__tests__/LLMObservability.test.tsx
+++ b/frontend/src/pages/LLMObservability/__tests__/LLMObservability.test.tsx
@@ -4,7 +4,7 @@ import {
makeListResponse,
mockRules,
} from 'container/LLMObservability/Settings/ModelPricing/__tests__/fixtures';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
@@ -24,15 +24,12 @@ jest.mock('container/LLMObservability/Explorer/Explorer', () => ({
default: (): JSX.Element => <div data-testid="llm-observability-explorer" />,
}));
-jest.mock('lib/history', () => ({
- push: jest.fn(),
- listen: jest.fn(() => jest.fn()),
- location: { pathname: '/ai-observability/overview', search: '' },
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: jest.fn(),
}));
-const mockHistoryPush = history.push as jest.MockedFunction<
- typeof history.push
->;
+const mockNavigate = navigate as jest.MockedFunction<typeof navigate>;
const SYSTEM_DASHBOARD_ENDPOINT = '*/api/v2/dashboards/system/ai-o11y-overview';
@@ -74,7 +71,7 @@ function setupList(items = mockRules): void {
describe('LLMObservability (integration)', () => {
beforeEach(() => {
window.history.pushState(null, '', '/');
- mockHistoryPush.mockClear();
+ mockNavigate.mockClear();
});
afterEach(() => {
@@ -110,7 +107,7 @@ describe('LLMObservability (integration)', () => {
await user.click(screen.getByRole('tab', { name: /Model pricing/ }));
- expect(mockHistoryPush).toHaveBeenCalledWith(
+ expect(mockNavigate).toHaveBeenCalledWith(
ROUTES.AI_OBSERVABILITY_CONFIGURATION,
);
});
@@ -123,7 +120,7 @@ describe('LLMObservability (integration)', () => {
await user.click(screen.getByRole('tab', { name: /Attribute Mapping/ }));
- expect(mockHistoryPush).toHaveBeenCalledWith(
+ expect(mockNavigate).toHaveBeenCalledWith(
ROUTES.AI_OBSERVABILITY_ATTRIBUTE_MAPPING,
);
});
@@ -136,9 +133,7 @@ describe('LLMObservability (integration)', () => {
await user.click(screen.getByRole('tab', { name: /Explorer/ }));
- expect(mockHistoryPush).toHaveBeenCalledWith(
- ROUTES.AI_OBSERVABILITY_EXPLORER,
- );
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.AI_OBSERVABILITY_EXPLORER);
});
it('renders the explorer panel on the explorer route', () => {
diff --git a/frontend/src/pages/LLMObservability/index.tsx b/frontend/src/pages/LLMObservability/index.tsx
index e928285686..f6cb6fea12 100644
--- a/frontend/src/pages/LLMObservability/index.tsx
+++ b/frontend/src/pages/LLMObservability/index.tsx
@@ -1,7 +1,6 @@
-import { useLocation } from 'react-router-dom';
import RouteTab from 'components/RouteTab';
import { TabRoutes } from 'components/RouteTab/types';
-import history from 'lib/history';
+import { useAppLocation } from 'lib/router/useAppLocation';
import {
AttributeMapping,
@@ -20,14 +19,14 @@ const routes: TabRoutes[] = [
];
function LLMObservabilityPage(): JSX.Element {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
return (
<div
className="ai-observability-module-container"
data-testid="llm-observability-page"
>
- <RouteTab routes={routes} activeKey={pathname} history={history} />
+ <RouteTab routes={routes} activeKey={pathname} />
</div>
);
}
diff --git a/frontend/src/pages/LogsExplorer/__tests__/LogsExplorer.liveLogs.test.tsx b/frontend/src/pages/LogsExplorer/__tests__/LogsExplorer.liveLogs.test.tsx
index 6840a6ee2f..e0f3511f75 100644
--- a/frontend/src/pages/LogsExplorer/__tests__/LogsExplorer.liveLogs.test.tsx
+++ b/frontend/src/pages/LogsExplorer/__tests__/LogsExplorer.liveLogs.test.tsx
@@ -1,4 +1,3 @@
-import { MemoryRouter } from 'react-router-dom-v5-compat';
import * as panelTypesQueryParamHooks from 'hooks/queryBuilder/useGetPanelTypesQueryParam';
import { PANEL_TYPES } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
@@ -7,13 +6,6 @@ import { fireEvent, render, screen } from 'tests/test-utils';
import LogsExplorer from '../index';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${ROUTES.LOGS_EXPLORER}`,
- }),
-}));
-
jest.mock(
'container/Toolbar/Toolbar',
() =>
@@ -85,16 +77,14 @@ jest.mock('providers/preferences/sync/usePreferenceSync', () => ({
function page(): JSX.Element {
return (
- <MemoryRouter initialEntries={[ROUTES.LOGS_EXPLORER]}>
- <PreferenceContextProvider>
- <LogsExplorer />
- </PreferenceContextProvider>
- </MemoryRouter>
+ <PreferenceContextProvider>
+ <LogsExplorer />
+ </PreferenceContextProvider>
);
}
describe('Logs Explorer live mode', () => {
- // useLocation is mocked without a search string, so the tab is driven
+ // The route carries no search string, so the tab is driven
// through the hook that reads it from the url.
const panelTypeSpy = jest.spyOn(
panelTypesQueryParamHooks,
@@ -107,7 +97,9 @@ describe('Logs Explorer live mode', () => {
it('ends when the url moves off the list tab, whatever moved it', () => {
panelTypeSpy.mockReturnValue(PANEL_TYPES.LIST);
- const { rerender } = render(page());
+ const { rerender } = render(page(), undefined, {
+ initialRoute: ROUTES.LOGS_EXPLORER,
+ });
fireEvent.click(screen.getByTestId('go-live'));
expect(screen.getByTestId('live-state')).toHaveTextContent('live');
@@ -120,7 +112,9 @@ describe('Logs Explorer live mode', () => {
it('stays on while the url keeps the list tab', () => {
panelTypeSpy.mockReturnValue(PANEL_TYPES.LIST);
- const { rerender } = render(page());
+ const { rerender } = render(page(), undefined, {
+ initialRoute: ROUTES.LOGS_EXPLORER,
+ });
fireEvent.click(screen.getByTestId('go-live'));
rerender(page());
diff --git a/frontend/src/pages/LogsExplorer/__tests__/LogsExplorer.test.tsx b/frontend/src/pages/LogsExplorer/__tests__/LogsExplorer.test.tsx
index 01db045a4d..e7d6a829eb 100644
--- a/frontend/src/pages/LogsExplorer/__tests__/LogsExplorer.test.tsx
+++ b/frontend/src/pages/LogsExplorer/__tests__/LogsExplorer.test.tsx
@@ -1,5 +1,3 @@
-import { MemoryRouter } from 'react-router-dom-v5-compat';
-import * as panelTypesQueryParamHooks from 'hooks/queryBuilder/useGetPanelTypesQueryParam';
// https://virtuoso.dev/mocking-in-tests/
import { VirtuosoMockContext } from 'react-virtuoso';
import {
@@ -7,7 +5,6 @@ import {
initialQueryBuilderFormValues,
PANEL_TYPES,
} from 'constants/queryBuilder';
-import ROUTES from 'constants/routes';
import { noop } from 'lodash-es';
import { logsQueryRangeSuccessResponse } from 'mocks-server/__mockdata__/logs_query_range';
import { server } from 'mocks-server/server';
@@ -21,13 +18,6 @@ import LogsExplorer from '../index';
const queryRangeURL = 'http://localhost/api/v3/query_range';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): { pathname: string } => ({
- pathname: `${ROUTES.LOGS_EXPLORER}`,
- }),
-}));
-
// mocking the graph components in this test as this should be handled separately
jest.mock(
'container/TimeSeriesView/TimeSeriesView',
@@ -92,15 +82,13 @@ describe('Logs Explorer Tests', () => {
it('Logs Explorer default view test without data', async () => {
const { getByRole, queryByText, getByTestId, queryByTestId, container } =
render(
- <MemoryRouter
- initialEntries={[
- '/logs-explorer/?panelType=list&selectedExplorerView=list',
- ]}
- >
- <PreferenceContextProvider>
- <LogsExplorer />
- </PreferenceContextProvider>
- </MemoryRouter>,
+ <PreferenceContextProvider>
+ <LogsExplorer />
+ </PreferenceContextProvider>,
+ undefined,
+ {
+ initialRoute: '/logs-explorer/?panelType=list&selectedExplorerView=list',
+ },
);
// by default is hidden, toggle the chart and check it's visibility
@@ -132,18 +120,12 @@ describe('Logs Explorer Tests', () => {
});
it('renders the tab the url panelTypes param names', () => {
- // useLocation is mocked without a search string in this file, so drive
- // the param through the hook that reads it.
- const panelTypeSpy = jest
- .spyOn(panelTypesQueryParamHooks, 'useGetPanelTypesQueryParam')
- .mockReturnValue(PANEL_TYPES.TIME_SERIES);
-
const { container } = render(
- <MemoryRouter initialEntries={['/logs-explorer/?panelTypes=%22graph%22']}>
- <PreferenceContextProvider>
- <LogsExplorer />
- </PreferenceContextProvider>
- </MemoryRouter>,
+ <PreferenceContextProvider>
+ <LogsExplorer />
+ </PreferenceContextProvider>,
+ undefined,
+ { initialRoute: '/logs-explorer/?panelTypes=%22graph%22' },
);
expect(container.querySelector('.timeseries-view-tab')).toHaveClass(
@@ -152,7 +134,6 @@ describe('Logs Explorer Tests', () => {
expect(container.querySelector('.list-view-tab')).not.toHaveClass(
'active-tab',
);
- panelTypeSpy.mockRestore();
});
// update this test properly
@@ -160,19 +141,17 @@ describe('Logs Explorer Tests', () => {
// mocking the query range API to return the logs
logsQueryServerRequest();
const { queryByText, queryByTestId } = render(
- <MemoryRouter
- initialEntries={[
- '/logs-explorer/?panelType=list&selectedExplorerView=list',
- ]}
- >
- <PreferenceContextProvider>
- <VirtuosoMockContext.Provider
- value={{ viewportHeight: 300, itemHeight: 100 }}
- >
- <LogsExplorer />
- </VirtuosoMockContext.Provider>
- </PreferenceContextProvider>
- </MemoryRouter>,
+ <PreferenceContextProvider>
+ <VirtuosoMockContext.Provider
+ value={{ viewportHeight: 300, itemHeight: 100 }}
+ >
+ <LogsExplorer />
+ </VirtuosoMockContext.Provider>
+ </PreferenceContextProvider>,
+ undefined,
+ {
+ initialRoute: '/logs-explorer/?panelType=list&selectedExplorerView=list',
+ },
);
// check for loading state to be not present
@@ -195,65 +174,63 @@ describe('Logs Explorer Tests', () => {
// mocking the query range API to return the logs
logsQueryServerRequest();
const { queryAllByText } = render(
- <MemoryRouter
- initialEntries={[
- '/logs-explorer/?panelType=list&selectedExplorerView=list',
- ]}
- >
- <QueryBuilderContext.Provider
- value={{
- isDefaultQuery: (): boolean => false,
- currentQuery: {
- ...initialQueriesMap.metrics,
- builder: {
- ...initialQueriesMap.metrics.builder,
- queryData: [
- initialQueryBuilderFormValues,
- initialQueryBuilderFormValues,
- ],
- queryTraceOperator: [],
- },
+ <QueryBuilderContext.Provider
+ value={{
+ isDefaultQuery: (): boolean => false,
+ currentQuery: {
+ ...initialQueriesMap.metrics,
+ builder: {
+ ...initialQueriesMap.metrics.builder,
+ queryData: [
+ initialQueryBuilderFormValues,
+ initialQueryBuilderFormValues,
+ ],
+ queryTraceOperator: [],
},
- setSupersetQuery: jest.fn(),
- supersetQuery: initialQueriesMap.metrics,
- stagedQuery: initialQueriesMap.metrics,
- initialDataSource: null,
- panelType: PANEL_TYPES.TIME_SERIES,
- isEnabledQuery: false,
- lastUsedQuery: 0,
- handleSetTraceOperatorData: noop,
- removeAllQueryBuilderEntities: noop,
- removeTraceOperator: noop,
- addTraceOperator: noop,
- setLastUsedQuery: noop,
- handleSetQueryData: noop,
- handleSetFormulaData: noop,
- handleSetQueryItemData: noop,
- handleSetConfig: noop,
- removeQueryBuilderEntityByIndex: noop,
- removeQueryTypeItemByIndex: noop,
- addNewBuilderQuery: noop,
- cloneQuery: noop,
- addNewFormula: noop,
- addNewQueryItem: noop,
- redirectWithQueryBuilderData: noop,
- handleRunQuery: noop,
- resetQuery: noop,
- updateAllQueriesOperators: (): Query => initialQueriesMap.metrics,
- updateQueriesData: (): Query => initialQueriesMap.metrics,
- initQueryBuilderData: noop,
- handleOnUnitsChange: noop,
- }}
- >
- <PreferenceContextProvider>
- <VirtuosoMockContext.Provider
- value={{ viewportHeight: 300, itemHeight: 100 }}
- >
- <LogsExplorer />
- </VirtuosoMockContext.Provider>
- </PreferenceContextProvider>
- </QueryBuilderContext.Provider>
- </MemoryRouter>,
+ },
+ setSupersetQuery: jest.fn(),
+ supersetQuery: initialQueriesMap.metrics,
+ stagedQuery: initialQueriesMap.metrics,
+ initialDataSource: null,
+ panelType: PANEL_TYPES.TIME_SERIES,
+ isEnabledQuery: false,
+ lastUsedQuery: 0,
+ handleSetTraceOperatorData: noop,
+ removeAllQueryBuilderEntities: noop,
+ removeTraceOperator: noop,
+ addTraceOperator: noop,
+ setLastUsedQuery: noop,
+ handleSetQueryData: noop,
+ handleSetFormulaData: noop,
+ handleSetQueryItemData: noop,
+ handleSetConfig: noop,
+ removeQueryBuilderEntityByIndex: noop,
+ removeQueryTypeItemByIndex: noop,
+ addNewBuilderQuery: noop,
+ cloneQuery: noop,
+ addNewFormula: noop,
+ addNewQueryItem: noop,
+ redirectWithQueryBuilderData: noop,
+ handleRunQuery: noop,
+ resetQuery: noop,
+ updateAllQueriesOperators: (): Query => initialQueriesMap.metrics,
+ updateQueriesData: (): Query => initialQueriesMap.metrics,
+ initQueryBuilderData: noop,
+ handleOnUnitsChange: noop,
+ }}
+ >
+ <PreferenceContextProvider>
+ <VirtuosoMockContext.Provider
+ value={{ viewportHeight: 300, itemHeight: 100 }}
+ >
+ <LogsExplorer />
+ </VirtuosoMockContext.Provider>
+ </PreferenceContextProvider>
+ </QueryBuilderContext.Provider>,
+ undefined,
+ {
+ initialRoute: '/logs-explorer/?panelType=list&selectedExplorerView=list',
+ },
);
const queries = queryAllByText(
@@ -264,15 +241,13 @@ describe('Logs Explorer Tests', () => {
it('frequency chart visibility and switch toggle', async () => {
const { getByRole, queryByText } = render(
- <MemoryRouter
- initialEntries={[
- '/logs-explorer/?panelType=list&selectedExplorerView=list',
- ]}
- >
- <PreferenceContextProvider>
- <LogsExplorer />
- </PreferenceContextProvider>
- </MemoryRouter>,
+ <PreferenceContextProvider>
+ <LogsExplorer />
+ </PreferenceContextProvider>,
+ undefined,
+ {
+ initialRoute: '/logs-explorer/?panelType=list&selectedExplorerView=list',
+ },
);
// check the presence of Frequency Chart
diff --git a/frontend/src/pages/LogsModulePage/LogsModulePage.tsx b/frontend/src/pages/LogsModulePage/LogsModulePage.tsx
index 4c07705ef6..4777a3dfad 100644
--- a/frontend/src/pages/LogsModulePage/LogsModulePage.tsx
+++ b/frontend/src/pages/LogsModulePage/LogsModulePage.tsx
@@ -1,7 +1,6 @@
import { useLocation } from 'react-use';
import RouteTab from 'components/RouteTab';
import { TabRoutes } from 'components/RouteTab/types';
-import history from 'lib/history';
import { logsExplorer, logsPipelines } from './constants';
@@ -17,7 +16,6 @@ export default function LogsModulePage(): JSX.Element {
className="logs-module-container"
routes={routes}
activeKey={pathname}
- history={history}
/>
);
}
diff --git a/frontend/src/pages/LogsSettings/components/TabLabel.tsx b/frontend/src/pages/LogsSettings/components/TabLabel.tsx
index 28bf071b6e..d315cdb4ec 100644
--- a/frontend/src/pages/LogsSettings/components/TabLabel.tsx
+++ b/frontend/src/pages/LogsSettings/components/TabLabel.tsx
@@ -1,10 +1,10 @@
-import { useLocation } from 'react-router-dom';
import { Typography } from '@signozhq/ui/typography';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { TableLabel } from '../types';
function TabLabel({ routeKey, label }: TableLabel): JSX.Element {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
if (pathname === routeKey) {
return <Typography.Link>{label}</Typography.Link>;
diff --git a/frontend/src/pages/LogsSettings/index.tsx b/frontend/src/pages/LogsSettings/index.tsx
index 37db811174..701130b084 100644
--- a/frontend/src/pages/LogsSettings/index.tsx
+++ b/frontend/src/pages/LogsSettings/index.tsx
@@ -1,18 +1,17 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useLocation } from 'react-router-dom';
import RouteTab from 'components/RouteTab';
-import history from 'lib/history';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { getLogsSettingsRoute } from './config';
function LogsSettings(): JSX.Element {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const { t } = useTranslation();
const routes = useMemo(() => getLogsSettingsRoute(t), [t]);
- return <RouteTab activeKey={pathname} routes={routes} history={history} />;
+ return <RouteTab activeKey={pathname} routes={routes} />;
}
export default LogsSettings;
diff --git a/frontend/src/pages/MessagingQueues/MQDetailPage/MQDetailPage.tsx b/frontend/src/pages/MessagingQueues/MQDetailPage/MQDetailPage.tsx
index 5ab38b7cc3..a3027e828e 100644
--- a/frontend/src/pages/MessagingQueues/MQDetailPage/MQDetailPage.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetailPage/MQDetailPage.tsx
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
-import { useHistory } from 'react-router-dom';
import { Select } from 'antd';
+import { getCurrentLocation, navigate } from 'lib/router/navigation';
import logEvent from 'api/common/logEvent';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
@@ -24,7 +24,6 @@ import MessagingQueuesGraph from '../MQGraph/MQGraph';
import '../MessagingQueues.styles.scss';
function MQDetailPage(): JSX.Element {
- const history = useHistory();
const [selectedView, setSelectedView] =
useState<MessagingQueuesViewTypeOptions>(
MessagingQueuesViewType.consumerLag.value,
@@ -48,11 +47,11 @@ function MQDetailPage(): JSX.Element {
}, [mqServiceView]);
const updateUrlQuery = (query: Record<string, string | number>): void => {
- const searchParams = new URLSearchParams(history.location.search);
+ const searchParams = new URLSearchParams(getCurrentLocation().search);
Object.keys(query).forEach((key) => {
searchParams.set(key, query[key].toString());
});
- history.push({
+ navigate({
search: searchParams.toString(),
});
};
@@ -67,7 +66,7 @@ function MQDetailPage(): JSX.Element {
if (event && isModifierKeyPressed(event as React.MouseEvent)) {
openInNewTab(ROUTES.MESSAGING_QUEUES_KAFKA);
} else {
- history.push(ROUTES.MESSAGING_QUEUES_KAFKA);
+ navigate(ROUTES.MESSAGING_QUEUES_KAFKA);
}
};
diff --git a/frontend/src/pages/MessagingQueues/MQDetails/DropRateView/DropRateView.tsx b/frontend/src/pages/MessagingQueues/MQDetails/DropRateView/DropRateView.tsx
index 17ea398b2b..7bb916e809 100644
--- a/frontend/src/pages/MessagingQueues/MQDetails/DropRateView/DropRateView.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetails/DropRateView/DropRateView.tsx
@@ -1,6 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useMutation } from 'react-query';
-import { generatePath } from 'react-router-dom';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { Table } from 'antd';
@@ -12,6 +11,7 @@ import axios from 'axios';
import cx from 'classnames';
import { SOMETHING_WENT_WRONG } from 'constants/api';
import ROUTES from 'constants/routes';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { useNotifications } from 'hooks/useNotifications';
import { isNumber } from 'lodash-es';
import {
@@ -94,7 +94,7 @@ export function getColumns(
key={item}
className="traceid-text"
onClick={(): void => {
- openInNewTab(generatePath(ROUTES.TRACE_DETAIL, { id: item }));
+ openInNewTab(buildRoutePath(ROUTES.TRACE_DETAIL, { id: item }));
logEvent(`MQ Kafka: Drop Rate - traceid navigation`, {
item,
});
diff --git a/frontend/src/pages/MessagingQueues/MQDetails/MQTables/MQTables.tsx b/frontend/src/pages/MessagingQueues/MQDetails/MQTables/MQTables.tsx
index f3377f5091..2b92cb2a7b 100644
--- a/frontend/src/pages/MessagingQueues/MQDetails/MQTables/MQTables.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetails/MQTables/MQTables.tsx
@@ -1,6 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useMutation } from 'react-query';
-import { useHistory, useLocation } from 'react-router-dom';
import { Skeleton, Table } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
@@ -13,7 +12,8 @@ import cx from 'classnames';
import { ColumnTypeRender } from 'components/Logs/TableView/types';
import { SOMETHING_WENT_WRONG } from 'constants/api';
import { QueryParams } from 'constants/query';
-import { History } from 'history';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { useNotifications } from 'hooks/useNotifications';
import useUrlQuery from 'hooks/useUrlQuery';
import { isEmpty } from 'lodash-es';
@@ -42,7 +42,6 @@ const INITIAL_PAGE_SIZE = 10;
// eslint-disable-next-line sonarjs/cognitive-complexity
export function getColumns(
data: MessagingQueuesPayloadProps['payload'],
- history: History<unknown>,
isProducerOverview?: boolean,
): RowData[] {
if (data?.result?.length === 0) {
@@ -85,7 +84,7 @@ export function getColumns(
if (isModifierKeyPressed(e as React.MouseEvent)) {
openInNewTab(path);
} else {
- history.push(path);
+ navigate(path);
}
}}
>
@@ -151,7 +150,6 @@ function MessagingQueuesTable({
const [tableData, setTableData] = useState<any[]>([]);
const { notifications } = useNotifications();
const urlQuery = useUrlQuery();
- const history = useHistory();
const timelineQuery = decodeURIComponent(
urlQuery.get(QueryParams.selectedTimelineQuery) || '',
);
@@ -205,7 +203,7 @@ function MessagingQueuesTable({
} = useMutation(tableApi, {
onSuccess: (data) => {
if (data.payload) {
- setColumns(getColumns(data?.payload, history, isProducerOverview));
+ setColumns(getColumns(data?.payload, isProducerOverview));
setTableData(
isProducerOverview
? getTableDataForProducerLatencyOverview(data?.payload)
@@ -228,7 +226,7 @@ function MessagingQueuesTable({
const [selectedRowKey, setSelectedRowKey] = useState<React.Key>();
const [, setSelectedRows] = useState<any>();
- const location = useLocation();
+ const location = useAppLocation();
const selectedRowKeyGenerator = (record: {
[key: string]: string;
@@ -250,13 +248,13 @@ function MessagingQueuesTable({
if (selectedRowKeyGenerator(record) === selectedRowKey) {
setSelectedRowKey(undefined);
setSelectedRows({});
- setConfigDetail(urlQuery, location, history, {});
+ setConfigDetail(urlQuery, location, {});
} else {
setSelectedRowKey(selectedRowKeyGenerator(record));
setSelectedRows(record);
if (!isEmpty(record)) {
- setConfigDetail(urlQuery, location, history, record);
+ setConfigDetail(urlQuery, location, record);
}
}
};
diff --git a/frontend/src/pages/MessagingQueues/MQDetails/MessagingQueueOverview.tsx b/frontend/src/pages/MessagingQueues/MQDetails/MessagingQueueOverview.tsx
index 9ca082814f..b0ebd06cb9 100644
--- a/frontend/src/pages/MessagingQueues/MQDetails/MessagingQueueOverview.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetails/MessagingQueueOverview.tsx
@@ -1,7 +1,7 @@
import { Dispatch, SetStateAction, useMemo } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { ToggleGroup } from '@signozhq/ui/toggle-group';
import { MessagingQueueServicePayload } from 'api/messagingQueues/getConsumerLagDetails';
import { getKafkaSpanEval } from 'api/messagingQueues/getKafkaSpanEval';
@@ -31,8 +31,7 @@ function ProducerLatencyTabs({
setOption: Dispatch<SetStateAction<ProducerLatencyOptions>>;
}): JSX.Element {
const urlQuery = useUrlQuery();
- const location = useLocation();
- const history = useHistory();
+ const location = useAppLocation();
return (
<ToggleGroup
@@ -41,7 +40,7 @@ function ProducerLatencyTabs({
size="sm"
type="single"
onChange={(value: string): void => {
- setConfigDetail(urlQuery, location, history, {});
+ setConfigDetail(urlQuery, location, {});
setOption(value as ProducerLatencyOptions);
}}
value={option}
diff --git a/frontend/src/pages/MessagingQueues/MQDetails/MetricPage/MetricPageGraph.tsx b/frontend/src/pages/MessagingQueues/MQDetails/MetricPage/MetricPageGraph.tsx
index c15cd3792d..311eadfedf 100644
--- a/frontend/src/pages/MessagingQueues/MQDetails/MetricPage/MetricPageGraph.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetails/MetricPage/MetricPageGraph.tsx
@@ -1,7 +1,8 @@
import { useCallback } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { ViewMenuAction } from 'container/WidgetCard/config';
@@ -21,8 +22,7 @@ function MetricPageGridGraph({
widgetData: Widgets;
checkIfDataExists?: (isDataAvailable: boolean) => void;
}): JSX.Element {
- const history = useHistory();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const dispatch = useDispatch();
const urlQuery = useUrlQuery();
const isDarkMode = useIsDarkMode();
@@ -35,13 +35,13 @@ function MetricPageGridGraph({
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
}
},
- [dispatch, history, pathname, urlQuery],
+ [dispatch, pathname, urlQuery],
);
return (
diff --git a/frontend/src/pages/MessagingQueues/MQGraph/MQConfigOptions.tsx b/frontend/src/pages/MessagingQueues/MQGraph/MQConfigOptions.tsx
index 2558dc3c40..5733a56772 100644
--- a/frontend/src/pages/MessagingQueues/MQGraph/MQConfigOptions.tsx
+++ b/frontend/src/pages/MessagingQueues/MQGraph/MQConfigOptions.tsx
@@ -1,12 +1,13 @@
import { useState } from 'react';
-import { useHistory, useLocation } from 'react-router-dom';
import { useCopyToClipboard } from 'react-use';
import { Color } from '@signozhq/design-tokens';
import { Button, Select, Spin, Tooltip } from 'antd';
import type { DefaultOptionType } from 'antd/es/select';
import { SelectMaxTagPlaceholder } from 'components/MessagingQueues/MQCommon/MQCommon';
import { QueryParams } from 'constants/query';
-import { History, Location } from 'history';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import type { AppLocation } from 'lib/router/types';
import useDebouncedFn from 'hooks/useDebouncedFunction';
import useUrlQuery from 'hooks/useUrlQuery';
import { Check, Share2 } from '@signozhq/icons';
@@ -57,13 +58,12 @@ const useConfigOptions = (
function setQueryParamsForConfigOptions(
value: string[],
urlQuery: URLSearchParams,
- history: History<unknown>,
- location: Location<unknown>,
+ location: AppLocation,
queryParams: QueryParams,
): void {
urlQuery.set(queryParams, value.join(','));
const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
- history.replace(generatedUrl);
+ navigate(generatedUrl, { replace: true });
}
function getConfigValuesFromQueryParams(
@@ -76,13 +76,12 @@ function getConfigValuesFromQueryParams(
function MessagingQueuesConfigOptions(): JSX.Element {
const urlQuery = useUrlQuery();
- const location = useLocation();
- const history = useHistory();
+ const location = useAppLocation();
const resetTabularConfigDetailsOnChange = (): void => {
urlQuery.delete(QueryParams.selectedTimelineQuery);
const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
- history.replace(generatedUrl);
+ navigate(generatedUrl, { replace: true });
};
const {
@@ -135,7 +134,6 @@ function MessagingQueuesConfigOptions(): JSX.Element {
setQueryParamsForConfigOptions(
value,
urlQuery,
- history,
location,
QueryParams.consumerGrp,
);
@@ -167,7 +165,6 @@ function MessagingQueuesConfigOptions(): JSX.Element {
setQueryParamsForConfigOptions(
value,
urlQuery,
- history,
location,
QueryParams.topic,
);
@@ -201,7 +198,6 @@ function MessagingQueuesConfigOptions(): JSX.Element {
setQueryParamsForConfigOptions(
value,
urlQuery,
- history,
location,
QueryParams.partition,
);
diff --git a/frontend/src/pages/MessagingQueues/MQGraph/MQGraph.tsx b/frontend/src/pages/MessagingQueues/MQGraph/MQGraph.tsx
index e3ee48b14a..3964499e49 100644
--- a/frontend/src/pages/MessagingQueues/MQGraph/MQGraph.tsx
+++ b/frontend/src/pages/MessagingQueues/MQGraph/MQGraph.tsx
@@ -1,7 +1,8 @@
import { useCallback, useMemo, useRef } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import logEvent from 'api/common/logEvent';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
@@ -37,8 +38,7 @@ function MessagingQueuesGraph(): JSX.Element {
[filterItems],
);
- const history = useHistory();
- const location = useLocation();
+ const location = useAppLocation();
const isLogEventCalled = useRef<boolean>(false);
const messagingQueueCustomTooltipText = (): HTMLDivElement => {
@@ -50,7 +50,7 @@ function MessagingQueuesGraph(): JSX.Element {
return customText;
};
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const dispatch = useDispatch();
const onDragSelect = useCallback(
@@ -61,13 +61,13 @@ function MessagingQueuesGraph(): JSX.Element {
urlQuery.set(QueryParams.startTime, startTimestamp.toString());
urlQuery.set(QueryParams.endTime, endTimestamp.toString());
const generatedUrl = `${pathname}?${urlQuery.toString()}`;
- history.push(generatedUrl);
+ navigate(generatedUrl);
if (startTimestamp !== endTimestamp) {
dispatch(UpdateTimeInterval('custom', [startTimestamp, endTimestamp]));
}
},
- [dispatch, history, pathname, urlQuery],
+ [dispatch, pathname, urlQuery],
);
const checkIfDataExists = (isDataAvailable: boolean): void => {
@@ -88,7 +88,7 @@ function MessagingQueuesGraph(): JSX.Element {
widget={widgetData}
headerMenuList={[...ViewMenuAction]}
onClickHandler={(xValue, _yValue, _mouseX, _mouseY, data): void => {
- setSelectedTimelineQuery(urlQuery, xValue, location, history, data);
+ setSelectedTimelineQuery(urlQuery, xValue, location, data);
}}
onDragSelect={onDragSelect}
customTooltipElement={messagingQueueCustomTooltipText()}
diff --git a/frontend/src/pages/MessagingQueues/MessagingQueues.tsx b/frontend/src/pages/MessagingQueues/MessagingQueues.tsx
index 42f8cf35ae..6b68297ad5 100644
--- a/frontend/src/pages/MessagingQueues/MessagingQueues.tsx
+++ b/frontend/src/pages/MessagingQueues/MessagingQueues.tsx
@@ -1,7 +1,7 @@
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
-import { useHistory } from 'react-router-dom';
import { Button } from 'antd';
+import { navigate } from 'lib/router/navigation';
import logEvent from 'api/common/logEvent';
import cx from 'classnames';
import MessagingQueueHealthCheck from 'components/MessagingQueueHealthCheck/MessagingQueueHealthCheck';
@@ -21,7 +21,6 @@ import {
import './MessagingQueues.styles.scss';
function MessagingQueues(): JSX.Element {
- const history = useHistory();
const { t } = useTranslation('messagingQueuesKafkaOverview');
const redirectToDetailsPage = (
@@ -37,7 +36,7 @@ function MessagingQueues(): JSX.Element {
if (event && isModifierKeyPressed(event)) {
openInNewTab(path);
} else {
- history.push(path);
+ navigate(path);
}
};
@@ -56,7 +55,7 @@ function MessagingQueues(): JSX.Element {
if (event && isModifierKeyPressed(event)) {
openInNewTab(link);
} else {
- history.push(link);
+ navigate(link);
}
} else {
openInNewTab(KAFKA_SETUP_DOC_LINK);
diff --git a/frontend/src/pages/MessagingQueues/MessagingQueuesMainPage.tsx b/frontend/src/pages/MessagingQueues/MessagingQueuesMainPage.tsx
index ebc21e0a98..537a5521e0 100644
--- a/frontend/src/pages/MessagingQueues/MessagingQueuesMainPage.tsx
+++ b/frontend/src/pages/MessagingQueues/MessagingQueuesMainPage.tsx
@@ -1,8 +1,7 @@
-import { useLocation } from 'react-router-dom';
import RouteTab from 'components/RouteTab';
import { TabRoutes } from 'components/RouteTab/types';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { ListMinus, Rows3 } from '@signozhq/icons';
import CeleryOverview from 'pages/Celery/CeleryOverview/CeleryOverview';
@@ -57,7 +56,7 @@ export const Overview: TabRoutes = {
};
export default function MessagingQueuesMainPage(): JSX.Element {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const isKafkaDetail = pathname === ROUTES.MESSAGING_QUEUES_KAFKA_DETAIL;
@@ -72,7 +71,6 @@ export default function MessagingQueuesMainPage(): JSX.Element {
className="messaging-queues-module-container"
routes={routes}
activeKey={pathname}
- history={history}
/>
);
}
diff --git a/frontend/src/pages/MessagingQueues/MessagingQueuesUtils.ts b/frontend/src/pages/MessagingQueues/MessagingQueuesUtils.ts
index 5433084812..9b1e56e1c1 100644
--- a/frontend/src/pages/MessagingQueues/MessagingQueuesUtils.ts
+++ b/frontend/src/pages/MessagingQueues/MessagingQueuesUtils.ts
@@ -9,7 +9,8 @@ import { OnboardingStatusResponse } from 'api/messagingQueues/onboarding/getOnbo
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetWidgetQueryBuilderProps } from 'container/MetricsApplication/types';
-import { History, Location } from 'history';
+import { navigate } from 'lib/router/navigation';
+import type { AppLocation } from 'lib/router/types';
import { isEmpty } from 'lodash-es';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
@@ -207,8 +208,7 @@ export interface SelectedTimelineQuery {
export function setSelectedTimelineQuery(
urlQuery: URLSearchParams,
timestamp: number,
- location: Location<unknown>,
- history: History<unknown>,
+ location: AppLocation,
data?: {
[key: string]: string;
},
@@ -224,7 +224,7 @@ export function setSelectedTimelineQuery(
encodeURIComponent(JSON.stringify(selectedTimelineQuery)),
);
const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
- history.replace(generatedUrl);
+ navigate(generatedUrl, { replace: true });
}
export enum MessagingQueuesViewTypeOptions {
@@ -260,8 +260,7 @@ export const MessagingQueuesViewType = {
export function setConfigDetail(
urlQuery: URLSearchParams,
- location: Location<unknown>,
- history: History<unknown>,
+ location: AppLocation,
paramsToSet?: {
[key: string]: string;
},
@@ -281,7 +280,7 @@ export function setConfigDetail(
urlQuery.delete(QueryParams.configDetail);
}
const generatedUrl = `${location.pathname}?${urlQuery.toString()}`;
- history.replace(generatedUrl);
+ navigate(generatedUrl, { replace: true });
}
export enum ProducerLatencyOptions {
diff --git a/frontend/src/pages/MeterExplorer/MeterExplorerPage.tsx b/frontend/src/pages/MeterExplorer/MeterExplorerPage.tsx
index 094af1704e..fc03617b21 100644
--- a/frontend/src/pages/MeterExplorer/MeterExplorerPage.tsx
+++ b/frontend/src/pages/MeterExplorer/MeterExplorerPage.tsx
@@ -2,7 +2,6 @@ import { useLocation } from 'react-use';
import RouteTab from 'components/RouteTab';
import { TabRoutes } from 'components/RouteTab/types';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
import { Explorer, Meter } from './constants';
@@ -18,7 +17,6 @@ function MeterExplorerPage(): JSX.Element {
className="meter-explorer-page"
routes={routes}
activeKey={pathname}
- history={history}
defaultActiveKey={ROUTES.METER}
/>
);
diff --git a/frontend/src/pages/MetricsApplication/ApDex/ApDexApplication.test.tsx b/frontend/src/pages/MetricsApplication/ApDex/ApDexApplication.test.tsx
index 515dde41c9..e1ccb7f296 100644
--- a/frontend/src/pages/MetricsApplication/ApDex/ApDexApplication.test.tsx
+++ b/frontend/src/pages/MetricsApplication/ApDex/ApDexApplication.test.tsx
@@ -1,15 +1,11 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { mockAppParams } from 'tests/router-mocks';
import { APPLICATION_SETTINGS } from '../constants';
import { thresholdMockData } from './__mock__/thresholdMockData';
import ApDexApplication from './ApDexApplication';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useParams: (): {
- servicename: string;
- } => ({ servicename: 'mockServiceName' }),
-}));
+mockAppParams({ servicename: 'mockServiceName' });
jest.mock('hooks/apDex/useGetApDexSettings', () => ({
__esModule: true,
diff --git a/frontend/src/pages/MetricsApplication/ApDex/ApDexApplication.tsx b/frontend/src/pages/MetricsApplication/ApDex/ApDexApplication.tsx
index 9a706569d1..ba3208ba34 100644
--- a/frontend/src/pages/MetricsApplication/ApDex/ApDexApplication.tsx
+++ b/frontend/src/pages/MetricsApplication/ApDex/ApDexApplication.tsx
@@ -1,7 +1,6 @@
import { useEffect, useState } from 'react';
-import { useParams } from 'react-router-dom';
import { Popover } from 'antd';
-import { IServiceName } from 'container/MetricsApplication/Tabs/types';
+import { useAppParams } from 'lib/router/useAppParams';
import { useGetApDexSettings } from 'hooks/apDex/useGetApDexSettings';
import { useNotifications } from 'hooks/useNotifications';
@@ -10,8 +9,8 @@ import ApDexSettings from './ApDexSettings';
import { Settings } from '@signozhq/icons';
function ApDexApplication(): JSX.Element {
- const { servicename: encodedServiceName } = useParams<IServiceName>();
- const servicename = decodeURIComponent(encodedServiceName);
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
+ const servicename = decodeURIComponent(encodedServiceName || '');
const {
data,
diff --git a/frontend/src/pages/MetricsApplication/MetricsApplication.tsx b/frontend/src/pages/MetricsApplication/MetricsApplication.tsx
index b94654840d..a67c21b5ae 100644
--- a/frontend/src/pages/MetricsApplication/MetricsApplication.tsx
+++ b/frontend/src/pages/MetricsApplication/MetricsApplication.tsx
@@ -1,5 +1,5 @@
-import { useParams } from 'react-router-dom';
import { Tabs, TabsProps } from 'antd';
+import { useAppParams } from 'lib/router/useAppParams';
import { QueryParams } from 'constants/query';
import DBCall from 'container/MetricsApplication/Tabs/DBCall';
import External from 'container/MetricsApplication/Tabs/External';
@@ -15,7 +15,7 @@ import useMetricsApplicationTabKey from './useMetricsApplicationTabKey';
import './MetricsApplication.styles.scss';
function MetricsApplication(): JSX.Element {
- const { servicename: encodedServiceName } = useParams<{
+ const { servicename: encodedServiceName } = useAppParams<{
servicename: string;
}>();
diff --git a/frontend/src/pages/MetricsApplication/stories/MetricsApplication.stories.tsx b/frontend/src/pages/MetricsApplication/stories/MetricsApplication.stories.tsx
index e13f306d25..6e4396564e 100644
--- a/frontend/src/pages/MetricsApplication/stories/MetricsApplication.stories.tsx
+++ b/frontend/src/pages/MetricsApplication/stories/MetricsApplication.stories.tsx
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -25,9 +25,7 @@ const meta = {
component: MetricsApplication,
// The page reads the service out of the pathname, so it renders under its own
// route rather than being mounted on its own.
- render: (): JSX.Element => (
- <Route path={ROUTES.SERVICE_METRICS} component={MetricsApplication} />
- ),
+ render: renderAtRoute(ROUTES.SERVICE_METRICS, MetricsApplication),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<MetricsApplicationArgs>;
diff --git a/frontend/src/pages/MetricsExplorer/MetricsExplorerPage.tsx b/frontend/src/pages/MetricsExplorer/MetricsExplorerPage.tsx
index e6e37af41c..07c3eb543b 100644
--- a/frontend/src/pages/MetricsExplorer/MetricsExplorerPage.tsx
+++ b/frontend/src/pages/MetricsExplorer/MetricsExplorerPage.tsx
@@ -8,7 +8,6 @@ import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { useVolumeControlFeatureGate } from 'hooks/metricsExplorer/useVolumeControlFeatureGate';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
-import history from 'lib/history';
import { DataSource } from 'types/common/queryBuilder';
import { Explorer, Summary, VolumeControl } from './constants';
@@ -45,7 +44,6 @@ function MetricsExplorerPage(): JSX.Element {
})}
routes={routes}
activeKey={pathname}
- history={history}
/>
);
}
diff --git a/frontend/src/pages/PublicDashboard/__tests__/PublicDashboardPage.test.tsx b/frontend/src/pages/PublicDashboard/__tests__/PublicDashboardPage.test.tsx
index 154a8ac0fe..c938240020 100644
--- a/frontend/src/pages/PublicDashboard/__tests__/PublicDashboardPage.test.tsx
+++ b/frontend/src/pages/PublicDashboard/__tests__/PublicDashboardPage.test.tsx
@@ -3,12 +3,11 @@ import {
PublicDashboardSchema,
useGetResolvedPublicDashboard,
} from 'hooks/dashboard/useGetResolvedPublicDashboard';
+import { mockAppParams } from 'tests/router-mocks';
import PublicDashboardPage from '..';
-jest.mock('react-router-dom', () => ({
- useParams: (): { dashboardId: string } => ({ dashboardId: 'dash-1' }),
-}));
+mockAppParams({ dashboardId: 'dash-1' });
jest.mock('hooks/dashboard/useGetResolvedPublicDashboard', () => ({
PublicDashboardSchema: { Legacy: 'legacy', V2: 'v2' },
diff --git a/frontend/src/pages/PublicDashboard/index.tsx b/frontend/src/pages/PublicDashboard/index.tsx
index dd677507af..c769309afc 100644
--- a/frontend/src/pages/PublicDashboard/index.tsx
+++ b/frontend/src/pages/PublicDashboard/index.tsx
@@ -1,4 +1,4 @@
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import {
PublicDashboardSchema,
useGetResolvedPublicDashboard,
@@ -12,20 +12,20 @@ import './PublicDashboard.styles.scss';
function PublicDashboardPage(): JSX.Element {
// read the dashboard id from the url
- const { dashboardId } = useParams<{ dashboardId: string }>();
+ const { dashboardId } = useAppParams<'dashboardId'>();
const {
data: resolved,
isLoading,
isFetching,
isError,
- } = useGetResolvedPublicDashboard(dashboardId || '');
+ } = useGetResolvedPublicDashboard(dashboardId ?? '');
const isBusy = isLoading || isFetching;
return (
<div className="public-dashboard-page">
- {resolved?.schema === PublicDashboardSchema.V2 && (
+ {resolved?.schema === PublicDashboardSchema.V2 && dashboardId && (
<PublicDashboardView publicDashboardId={dashboardId} data={resolved.data} />
)}
diff --git a/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.mocks.tsx b/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.mocks.tsx
index 4e4816966d..4bce11db8e 100644
--- a/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.mocks.tsx
+++ b/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.mocks.tsx
@@ -4,8 +4,8 @@
*/
import { rest } from 'msw';
-import { generatePath } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import {
choiceControl,
@@ -37,7 +37,7 @@ const VIEWER = 'Public dashboard · viewer';
const DATA = 'Public dashboard · panels';
export const publicDashboardRoute = (): string =>
- generatePath(ROUTES.PUBLIC_DASHBOARD, { dashboardId: STORY_DASHBOARD_ID });
+ buildRoutePath(ROUTES.PUBLIC_DASHBOARD, { dashboardId: STORY_DASHBOARD_ID });
export const publicDashboardMocks = defineStoryMocks({
controls: {
diff --git a/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.tsx b/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.tsx
index cd2e305ed6..bc748f934a 100644
--- a/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.tsx
+++ b/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.tsx
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -27,9 +27,7 @@ const meta = {
// The published id comes out of the pathname, so the viewer renders under its
// own route rather than being mounted on its own. The layout drops the app
// chrome on this path, which is what a signed-out viewer sees.
- render: (): JSX.Element => (
- <Route path={ROUTES.PUBLIC_DASHBOARD} component={PublicDashboardPage} />
- ),
+ render: renderAtRoute(ROUTES.PUBLIC_DASHBOARD, PublicDashboardPage),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<PublicDashboardArgs>;
diff --git a/frontend/src/pages/ResetPassword/__tests__/ResetPasswordPage.test.tsx b/frontend/src/pages/ResetPassword/__tests__/ResetPasswordPage.test.tsx
index a471d9f7db..90a947f56c 100644
--- a/frontend/src/pages/ResetPassword/__tests__/ResetPasswordPage.test.tsx
+++ b/frontend/src/pages/ResetPassword/__tests__/ResetPasswordPage.test.tsx
@@ -1,17 +1,14 @@
import { Logout } from 'api/utils';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { createErrorResponse, rest, server } from 'mocks-server/server';
import { render, screen, waitFor, fireEvent } from 'tests/test-utils';
import ResetPassword from '../index';
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: jest.fn(),
- location: { search: '' },
- },
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ navigate: jest.fn(),
}));
jest.mock('api/utils', () => ({
@@ -21,9 +18,7 @@ jest.mock('api/utils', () => ({
const VERIFY_TOKEN_ENDPOINT = '*/api/v2/reset_password_tokens/verify';
const VERSION_ENDPOINT = '*/version';
-const mockHistoryPush = history.push as jest.MockedFunction<
- typeof history.push
->;
+const mockNavigate = navigate as jest.MockedFunction<typeof navigate>;
const successVerifyResponse = {
data: { id: 'token-id', token: 'valid-token' },
@@ -136,7 +131,7 @@ describe('ResetPassword Page', () => {
screen.getByText(/reset password token has expired/i),
).toBeInTheDocument();
// 401 from this endpoint must NOT trigger logout/redirect
- expect(mockHistoryPush).not.toHaveBeenCalledWith(ROUTES.LOGIN);
+ expect(mockNavigate).not.toHaveBeenCalledWith(ROUTES.LOGIN);
expect(Logout).not.toHaveBeenCalled();
expect(screen.getByTestId('back-to-login')).toBeInTheDocument();
});
@@ -163,7 +158,7 @@ describe('ResetPassword Page', () => {
});
fireEvent.click(screen.getByTestId('back-to-login'));
- expect(mockHistoryPush).toHaveBeenCalledWith(ROUTES.LOGIN);
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.LOGIN);
});
it('redirects to login when no token is in the URL', async () => {
@@ -173,7 +168,7 @@ describe('ResetPassword Page', () => {
});
await waitFor(() => {
- expect(mockHistoryPush).toHaveBeenCalledWith(ROUTES.LOGIN);
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.LOGIN);
});
expect(Logout).toHaveBeenCalled();
diff --git a/frontend/src/pages/ResetPassword/index.tsx b/frontend/src/pages/ResetPassword/index.tsx
index 84aa5eb194..cbf2864c30 100644
--- a/frontend/src/pages/ResetPassword/index.tsx
+++ b/frontend/src/pages/ResetPassword/index.tsx
@@ -11,7 +11,7 @@ import Spinner from 'components/Spinner';
import ResetPasswordContainer from 'container/ResetPassword';
import TokenError from 'container/ResetPassword/TokenError';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { useAppContext } from 'providers/App/App';
import { useErrorModal } from 'providers/ErrorModalProvider';
import APIError from 'types/api/error';
@@ -26,7 +26,7 @@ function ResetPassword(): JSX.Element {
useEffect(() => {
if (!token) {
void Logout();
- history.push(ROUTES.LOGIN);
+ navigate(ROUTES.LOGIN);
}
}, [token]);
diff --git a/frontend/src/pages/ServiceTopLevelOperations/index.tsx b/frontend/src/pages/ServiceTopLevelOperations/index.tsx
index 468c2d5ccd..91cf50be11 100644
--- a/frontend/src/pages/ServiceTopLevelOperations/index.tsx
+++ b/frontend/src/pages/ServiceTopLevelOperations/index.tsx
@@ -1,12 +1,12 @@
import { ReactNode, useEffect, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
-import { Link, useParams } from 'react-router-dom';
import { Histogram, RefreshCw } from '@signozhq/icons';
+import { AppLink } from 'lib/router/AppLink';
+import { useAppParams } from 'lib/router/useAppParams';
import { Alert, Table } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import ROUTES from 'constants/routes';
-import { IServiceName } from 'container/MetricsApplication/Tabs/types';
import useErrorNotification from 'hooks/useErrorNotification';
import { useQueryService } from 'hooks/useQueryService';
import useResourceAttribute from 'hooks/useResourceAttribute';
@@ -18,12 +18,12 @@ import { Tags } from 'hooks/useResourceAttribute/types';
import './ServiceTopLevelOperations.styles.scss';
export default function ServiceTopLevelOperations(): JSX.Element {
- const { servicename: encodedServiceName } = useParams<IServiceName>();
+ const { servicename: encodedServiceName } = useAppParams<'servicename'>();
const { maxTime, minTime, selectedTime } = useSelector<
AppState,
GlobalReducer
>((state) => state.globalTime);
- const servicename = decodeURIComponent(encodedServiceName);
+ const servicename = decodeURIComponent(encodedServiceName || '');
const { queries } = useResourceAttribute();
const selectedTags = useMemo(
() => (convertRawQueriesToTraceSelectedTags(queries) as Tags[]) || [],
@@ -94,16 +94,16 @@ export default function ServiceTopLevelOperations(): JSX.Element {
return (
<div className="container">
<Typography.Title level={5} className="top-level-operations-header">
- <Link to={ROUTES.APPLICATION}>
+ <AppLink to={ROUTES.APPLICATION}>
<span className="breadcrumb">
{' '}
<Histogram size={12} /> services{' '}
</span>
- </Link>
+ </AppLink>
<div className="divider">/</div>
- <Link to={`${ROUTES.APPLICATION}/${servicename}`}>
+ <AppLink to={`${ROUTES.APPLICATION}/${servicename}`}>
<span className="breadcrumb">{servicename} </span>
- </Link>
+ </AppLink>
</Typography.Title>
<div className="info-alert">
diff --git a/frontend/src/pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.tsx b/frontend/src/pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.tsx
index 33f498e5db..561a95076b 100644
--- a/frontend/src/pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.tsx
+++ b/frontend/src/pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.tsx
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -24,11 +24,9 @@ const meta = {
component: ServiceTopLevelOperations,
// The page reads the service out of the pathname, so it renders under its own
// route rather than being mounted on its own.
- render: (): JSX.Element => (
- <Route
- path={ROUTES.SERVICE_TOP_LEVEL_OPERATIONS}
- component={ServiceTopLevelOperations}
- />
+ render: renderAtRoute(
+ ROUTES.SERVICE_TOP_LEVEL_OPERATIONS,
+ ServiceTopLevelOperations,
),
...pageStory,
parameters: { ...pageStory.parameters },
diff --git a/frontend/src/pages/Settings/Settings.tsx b/frontend/src/pages/Settings/Settings.tsx
index 09c3cb23ab..2b1f88cba2 100644
--- a/frontend/src/pages/Settings/Settings.tsx
+++ b/frontend/src/pages/Settings/Settings.tsx
@@ -1,6 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useLocation } from 'react-router-dom';
import logEvent from 'api/common/logEvent';
import RouteTab from 'components/RouteTab';
import { FeatureKeys } from 'constants/features';
@@ -12,7 +11,8 @@ import NavItem from 'container/SideNav/NavItem/NavItem';
import { SidebarItem } from 'container/SideNav/sideNav.types';
import useComponentPermission from 'hooks/useComponentPermission';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
-import history from 'lib/history';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { navigate } from 'lib/router/navigation';
import { Cog } from '@signozhq/icons';
import { useAppContext } from 'providers/App/App';
import { USER_ROLES } from 'types/roles';
@@ -24,7 +24,7 @@ import { getRoutes } from './utils';
import './Settings.styles.scss';
function SettingsPage(): JSX.Element {
- const { pathname, search } = useLocation();
+ const { pathname, search } = useAppLocation();
const { user, featureFlags, trialInfo, isFetchingActiveLicense } =
useAppContext();
@@ -253,8 +253,8 @@ function SettingsPage(): JSX.Element {
if (event && isModifierKeyPressed(event)) {
openInNewTab(url);
} else {
- history.push(url, {
- from: pathname,
+ navigate(url, {
+ state: { from: pathname },
});
}
}
@@ -336,7 +336,6 @@ function SettingsPage(): JSX.Element {
<RouteTab
routes={routes}
activeKey={pathname}
- history={history}
tabBarStyle={{ display: 'none' }}
/>
</div>
diff --git a/frontend/src/pages/Settings/__tests__/Settings.test.tsx b/frontend/src/pages/Settings/__tests__/Settings.test.tsx
index f64b0ee21c..8c6df780ed 100644
--- a/frontend/src/pages/Settings/__tests__/Settings.test.tsx
+++ b/frontend/src/pages/Settings/__tests__/Settings.test.tsx
@@ -10,12 +10,6 @@ jest.mock('components/MarkdownRenderer/MarkdownRenderer', () => ({
children,
}));
-jest.mock('lib/history', () => ({
- push: jest.fn(),
- listen: jest.fn(() => jest.fn()),
- location: { pathname: '/settings', search: '' },
-}));
-
const getCloudAdminOverrides = (): any => ({
activeLicense: {
key: 'test-key',
diff --git a/frontend/src/pages/SignUp/__tests__/SignUp.test.tsx b/frontend/src/pages/SignUp/__tests__/SignUp.test.tsx
index 6a65b45d65..8465bb441e 100644
--- a/frontend/src/pages/SignUp/__tests__/SignUp.test.tsx
+++ b/frontend/src/pages/SignUp/__tests__/SignUp.test.tsx
@@ -14,16 +14,6 @@ jest.mock('AppRoutes/utils', () => ({
const mockAfterLogin = jest.mocked(afterLogin);
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- push: jest.fn(),
- location: {
- search: '',
- },
- },
-}));
-
const REGISTER_ENDPOINT = '*/api/v1/register';
const EMAIL_PASSWORD_ENDPOINT = '*/api/v2/sessions/email_password';
diff --git a/frontend/src/pages/Support/Support.tsx b/frontend/src/pages/Support/Support.tsx
index 8eec76eb8d..3f0426beb0 100644
--- a/frontend/src/pages/Support/Support.tsx
+++ b/frontend/src/pages/Support/Support.tsx
@@ -1,7 +1,8 @@
import { useEffect, useState } from 'react';
import { useMutation } from 'react-query';
-import { useHistory, useLocation } from 'react-router-dom';
import { Button, Card, Modal } from 'antd';
+import { useAppLocation } from 'lib/router/useAppLocation';
+import { getCurrentLocation } from 'lib/router/navigation';
import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
import { createSubscription } from 'api/generated/services/subscriptions';
@@ -87,23 +88,23 @@ const supportChannels = [
];
export default function Support(): JSX.Element {
- const history = useHistory();
const { notifications } = useNotifications();
const { trialInfo, featureFlags } = useAppContext();
const [isAddCreditCardModalOpen, setIsAddCreditCardModalOpen] =
useState(false);
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const handleChannelWithRedirects = (url: string): void => {
openInNewTab(url);
};
useEffect(() => {
- if (history?.location?.state) {
- const histroyState = history?.location?.state as any;
+ const currentLocation = getCurrentLocation();
+ if (currentLocation?.state) {
+ const locationState = currentLocation.state as any;
- if (histroyState && histroyState?.from) {
- logEvent(`Support : From URL : ${histroyState.from}`, {});
+ if (locationState && locationState?.from) {
+ logEvent(`Support : From URL : ${locationState.from}`, {});
}
}
diff --git a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel.tsx b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel.tsx
index 3ca5e92993..22b5bfd507 100644
--- a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel.tsx
+++ b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel.tsx
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import { Tabs } from '@signozhq/ui/tabs';
import { DetailsHeader } from 'components/DetailsPanel';
import { useIsDarkMode } from 'hooks/useDarkMode';
@@ -10,7 +10,6 @@ import {
SpantypesSpanAggregationDTO,
TelemetrytypesTelemetryFieldKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
-import { TraceDetailV3URLProps } from 'types/api/trace/getTraceV3';
import { useTraceStore } from '../../stores/traceStore';
import {
@@ -37,7 +36,7 @@ function AnalyticsPanel({
onClose,
onTabChange,
}: AnalyticsPanelProps): JSX.Element | null {
- const { id: traceId } = useParams<TraceDetailV3URLProps>();
+ const { id: traceId } = useAppParams<'id'>();
const colorByField = useTraceStore((s) => s.colorByField);
const colorByFieldName = colorByField.name;
const isDarkMode = useIsDarkMode();
diff --git a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/__tests__/AnalyticsPanel.test.tsx b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/__tests__/AnalyticsPanel.test.tsx
index 1187eca828..f8a1ec7734 100644
--- a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/__tests__/AnalyticsPanel.test.tsx
+++ b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/__tests__/AnalyticsPanel.test.tsx
@@ -1,15 +1,13 @@
import { screen } from '@testing-library/react';
import useGetTraceAggregations from 'hooks/trace/useGetTraceAggregations';
+import { mockAppParams } from 'tests/router-mocks';
import { render } from 'tests/test-utils';
import { DEFAULT_COLOR_BY_FIELD } from '../../../constants';
import { useTraceStore } from '../../../stores/traceStore';
import AnalyticsPanel from '../AnalyticsPanel';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useParams: (): { id: string } => ({ id: 'trace-123' }),
-}));
+mockAppParams({ id: 'trace-123' });
jest.mock('hooks/trace/useGetTraceAggregations', () => ({
__esModule: true,
diff --git a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/LinkedSpans/LinkedSpans.tsx b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/LinkedSpans/LinkedSpans.tsx
index 18445b43fd..9f63988095 100644
--- a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/LinkedSpans/LinkedSpans.tsx
+++ b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/LinkedSpans/LinkedSpans.tsx
@@ -1,5 +1,6 @@
import { useCallback, useMemo, useState } from 'react';
-import { generatePath, Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { ChevronDown, ChevronRight } from '@signozhq/icons';
import { Badge } from '@signozhq/ui/badge';
import ROUTES from 'constants/routes';
@@ -78,7 +79,7 @@ export function LinkedSpansPanel({
}): JSX.Element | null {
const getLink = useCallback(
(item: SpanReference): string =>
- `${generatePath(ROUTES.TRACE_DETAIL, { id: item.traceId })}?spanId=${item.spanId}`,
+ `${buildRoutePath(ROUTES.TRACE_DETAIL, { id: item.traceId })}?spanId=${item.spanId}`,
[],
);
@@ -93,11 +94,11 @@ export function LinkedSpansPanel({
key={item.spanId}
badgeKey="Linked Span ID"
badgeValue={
- <Link to={getLink(item)}>
+ <AppLink to={getLink(item)}>
<Badge textTransform="none" variant="solid" color="secondary">
{item.spanId}
</Badge>
- </Link>
+ </AppLink>
}
direction="column"
/>
diff --git a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/TraceIdField.tsx b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/TraceIdField.tsx
index d0a3d8c65d..963b3b9c48 100644
--- a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/TraceIdField.tsx
+++ b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/TraceIdField.tsx
@@ -1,8 +1,10 @@
-import { Link, useRouteMatch } from 'react-router-dom';
import { useCopyToClipboard } from 'react-use';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import { toast } from '@signozhq/ui/sonner';
+import { AppLink } from 'lib/router/AppLink';
+import { matchRoute } from 'lib/router/matchRoute';
+import { useAppLocation } from 'lib/router/useAppLocation';
import ROUTES from 'constants/routes';
import { SpanV3 } from 'types/api/trace/getTraceV3';
@@ -19,10 +21,8 @@ interface TraceIdFieldProps {
* existing link to the trace detail page.
*/
export function TraceIdField({ span }: TraceIdFieldProps): JSX.Element {
- const match = useRouteMatch<{ id: string }>({
- path: ROUTES.TRACE_DETAIL,
- exact: true,
- });
+ const { pathname } = useAppLocation();
+ const match = matchRoute<'id'>(pathname, ROUTES.TRACE_DETAIL, { exact: true });
const [, setCopy] = useCopyToClipboard();
const isCurrentTrace = match?.params.id === span.trace_id;
@@ -51,7 +51,7 @@ export function TraceIdField({ span }: TraceIdFieldProps): JSX.Element {
}
return (
- <Link
+ <AppLink
to={{
pathname: `/trace/${span.trace_id}`,
search: window.location.search,
@@ -59,6 +59,6 @@ export function TraceIdField({ span }: TraceIdFieldProps): JSX.Element {
className={styles.traceId}
>
{span.trace_id}
- </Link>
+ </AppLink>
);
}
diff --git a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/NozButton.tsx b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/NozButton.tsx
index d6f4d56388..6e09995689 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/NozButton.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/NozButton.tsx
@@ -1,5 +1,5 @@
import { useCallback } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import logEvent from 'api/common/logEvent';
@@ -14,7 +14,7 @@ import { openAIAssistant } from 'container/AIAssistant/store/useAIAssistantStore
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
export default function NozButton(): JSX.Element | null {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const handleOpenNoz = useCallback((): void => {
diff --git a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.tsx b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.tsx
index f731392d78..09149d75bd 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.tsx
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useState } from 'react';
-import { useParams } from 'react-router-dom';
import { Button } from '@signozhq/ui/button';
import { Tooltip } from '@signozhq/ui/tooltip';
import { Skeleton } from 'antd';
@@ -7,10 +6,10 @@ import cx from 'classnames';
import FieldsSelector from 'components/FieldsSelector';
import ROUTES from 'constants/routes';
import dayjs from 'dayjs';
-import history, { hasInAppHistory } from 'lib/history';
+import { navigate, back, hasInAppHistory } from 'lib/router/navigation';
+import { useAppParams } from 'lib/router/useAppParams';
import { ArrowLeft, ChartPie } from '@signozhq/icons';
import KeyValueLabel from 'periscope/components/KeyValueLabel';
-import { TraceDetailV3URLProps } from 'types/api/trace/getTraceV3';
import { DataSource } from 'types/common/queryBuilder';
import { TraceDetailsTab } from '../constants';
@@ -58,7 +57,7 @@ function TraceDetailsHeader({
onFilteredSpansChange,
showTraceDetailsHeaderOptions,
}: TraceDetailsHeaderProps): JSX.Element {
- const { id: traceID } = useParams<TraceDetailV3URLProps>();
+ const { id: traceID = '' } = useAppParams<'id'>();
const [showTraceDetails, setShowTraceDetails] = useState(true);
const [isFilterExpanded, setIsFilterExpanded] = useState(false);
const [isPreviewFieldsOpen, setIsPreviewFieldsOpen] = useState(false);
@@ -98,11 +97,11 @@ function TraceDetailsHeader({
const handlePreviousBtnClick = useCallback((): void => {
if (hasInAppHistory()) {
- history.goBack();
+ back();
} else if (!isOverview) {
- history.push(ROUTES.AI_OBSERVABILITY_EXPLORER);
+ navigate(ROUTES.AI_OBSERVABILITY_EXPLORER);
} else {
- history.push(ROUTES.TRACES_EXPLORER);
+ navigate(ROUTES.TRACES_EXPLORER);
}
}, [isOverview]);
diff --git a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/__tests__/TraceDetailsHeader.test.tsx b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/__tests__/TraceDetailsHeader.test.tsx
index ace70a0384..2e53e4abdf 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/__tests__/TraceDetailsHeader.test.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/__tests__/TraceDetailsHeader.test.tsx
@@ -11,26 +11,19 @@ jest.mock('../useTraceSummary', () => ({
useTraceSummary: jest.fn(() => ({ data: undefined, isLoading: false })),
}));
-const mockGoBack = jest.fn();
-const mockPush = jest.fn();
-const mockReplace = jest.fn();
+const mockBack = jest.fn();
+const mockNavigate = jest.fn();
const mockHasInAppHistory = jest.fn();
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- goBack: (): void => mockGoBack(),
- push: (path: string): void => mockPush(path),
- replace: (path: string): void => mockReplace(path),
- location: { pathname: '/', search: '' },
- listen: (): (() => void) => (): void => undefined,
- },
+jest.mock('lib/router/navigation', () => ({
+ ...jest.requireActual('lib/router/navigation'),
+ back: (): void => mockBack(),
+ navigate: (path: string): void => mockNavigate(path),
hasInAppHistory: (): boolean => mockHasInAppHistory(),
}));
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useParams: (): { id: string } => ({ id: 'trace-123' }),
+jest.mock('lib/router/useAppParams', () => ({
+ useAppParams: (): { id: string } => ({ id: 'trace-123' }),
}));
jest.mock(
@@ -73,19 +66,19 @@ const SUMMARY = {
describe('TraceDetailsHeader – back button', () => {
beforeEach(() => {
- mockGoBack.mockClear();
- mockPush.mockClear();
+ mockBack.mockClear();
+ mockNavigate.mockClear();
mockHasInAppHistory.mockReset();
});
- it('calls history.goBack() when there is in-app SPA history', () => {
+ it('goes back when there is in-app SPA history', () => {
mockHasInAppHistory.mockReturnValue(true);
render(<TraceDetailsHeader {...baseProps} />);
fireEvent.click(screen.getByRole('button', { name: /back/i }));
- expect(mockGoBack).toHaveBeenCalledTimes(1);
- expect(mockPush).not.toHaveBeenCalled();
+ expect(mockBack).toHaveBeenCalledTimes(1);
+ expect(mockNavigate).not.toHaveBeenCalled();
});
it('pushes to the traces explorer route when there is no in-app SPA history', () => {
@@ -94,9 +87,9 @@ describe('TraceDetailsHeader – back button', () => {
fireEvent.click(screen.getByRole('button', { name: /back/i }));
- expect(mockPush).toHaveBeenCalledTimes(1);
- expect(mockPush).toHaveBeenCalledWith(ROUTES.TRACES_EXPLORER);
- expect(mockGoBack).not.toHaveBeenCalled();
+ expect(mockNavigate).toHaveBeenCalledTimes(1);
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.TRACES_EXPLORER);
+ expect(mockBack).not.toHaveBeenCalled();
});
it('pushes to the AI observability explorer when opened directly on another tab', async () => {
@@ -110,15 +103,14 @@ describe('TraceDetailsHeader – back button', () => {
await user.click(screen.getByRole('button', { name: /back/i }));
- expect(mockPush).toHaveBeenCalledTimes(1);
- expect(mockPush).toHaveBeenCalledWith(ROUTES.AI_OBSERVABILITY_EXPLORER);
- expect(mockGoBack).not.toHaveBeenCalled();
+ expect(mockNavigate).toHaveBeenCalledTimes(1);
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.AI_OBSERVABILITY_EXPLORER);
+ expect(mockBack).not.toHaveBeenCalled();
});
});
describe('TraceDetailsHeader – action cluster', () => {
beforeEach(() => {
- mockReplace.mockClear();
jest
.mocked(useTraceSummary)
.mockReturnValue({ data: SUMMARY, isLoading: false });
diff --git a/frontend/src/pages/TraceDetailsV3/TraceDetailsOverview/TraceDetailsOverview.tsx b/frontend/src/pages/TraceDetailsV3/TraceDetailsOverview/TraceDetailsOverview.tsx
index d8598a5c4b..68a194a0b7 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceDetailsOverview/TraceDetailsOverview.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceDetailsOverview/TraceDetailsOverview.tsx
@@ -7,7 +7,7 @@ import {
useRef,
useState,
} from 'react';
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import {
ChartNoAxesGantt,
ChevronDown,
@@ -25,7 +25,7 @@ import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import { ResizableBox } from 'periscope/components/ResizableBox';
-import { SpanV3, TraceDetailV3URLProps } from 'types/api/trace/getTraceV3';
+import { SpanV3 } from 'types/api/trace/getTraceV3';
import { TraceDetailEventKeys, TraceDetailEvents } from '../events';
import { useSpanDetailVariant } from '../hooks/useSpanDetailVariant';
@@ -74,7 +74,7 @@ function TraceDetailsOverview({
onHasTraceDataChange,
dataLoadedFiredForRef,
}: TraceDetailsOverviewProps): JSX.Element {
- const { id: traceId } = useParams<TraceDetailV3URLProps>();
+ const { id: traceId } = useAppParams<'id'>();
const urlQuery = useUrlQuery();
const [interestedSpanId, setInterestedSpanId] = useState<IInterestedSpan>(
() => ({
@@ -147,7 +147,7 @@ function TraceDetailsOverview({
isFetching: isFetchingTraceData,
error: errorFetchingTraceData,
} = useGetTraceV4({
- traceId,
+ traceId: traceId || '',
uncollapsedSpans: queryParams.uncollapsedSpans,
selectedSpanId: queryParams.selectedSpanId,
isSelectedSpanIDUnCollapsed: queryParams.isSelectedSpanIDUnCollapsed,
diff --git a/frontend/src/pages/TraceDetailsV3/TraceDetailsThread/ThreadSpanDetails.tsx b/frontend/src/pages/TraceDetailsV3/TraceDetailsThread/ThreadSpanDetails.tsx
index 0b3857c5a4..5b69d910ca 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceDetailsThread/ThreadSpanDetails.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceDetailsThread/ThreadSpanDetails.tsx
@@ -1,8 +1,7 @@
import { useState } from 'react';
-import { useParams } from 'react-router-dom';
import { DetailsPanelState } from 'components/DetailsPanel/types';
+import { useAppParams } from 'lib/router/useAppParams';
import { ResizableBox } from 'periscope/components/ResizableBox';
-import { TraceDetailV3URLProps } from 'types/api/trace/getTraceV3';
import SpanDetailsPanel from '../SpanDetailsPanel/SpanDetailsPanel';
import {
@@ -34,7 +33,7 @@ function ThreadSpanDetails({
}: ThreadSpanDetailsProps): JSX.Element {
const [width, setWidth] = useState(RIGHT_DOCK_MIN);
const [height, setHeight] = useState(BOTTOM_DOCK_DEFAULT);
- const { id: traceId } = useParams<TraceDetailV3URLProps>();
+ const { id: traceId = '' } = useAppParams<'id'>();
const { data: traceSummary } = useTraceSummary(traceId);
const panel = (
diff --git a/frontend/src/pages/TraceDetailsV3/TraceDetailsThread/TraceDetailsThread.tsx b/frontend/src/pages/TraceDetailsV3/TraceDetailsThread/TraceDetailsThread.tsx
index 4c24e8ad31..2a6e727ae9 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceDetailsThread/TraceDetailsThread.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceDetailsThread/TraceDetailsThread.tsx
@@ -1,7 +1,6 @@
-import { useParams } from 'react-router-dom';
import { Callout } from '@signozhq/ui/callout';
-import history, { hasInAppHistory } from 'lib/history';
-import { TraceDetailV3URLProps } from 'types/api/trace/getTraceV3';
+import { back, hasInAppHistory } from 'lib/router/navigation';
+import { useAppParams } from 'lib/router/useAppParams';
import { TraceDetailsTab } from '../constants';
import { useSpanDetailVariant } from '../hooks/useSpanDetailVariant';
@@ -25,7 +24,7 @@ import styles from './TraceDetailsThread.module.scss';
const INITIAL_LOADER_COUNT = 4;
function TraceDetailsThread(): JSX.Element {
- const { id: traceId } = useParams<TraceDetailV3URLProps>();
+ const { id: traceId } = useAppParams<'id'>();
const [, setTab] = useTraceDetailsTab();
const [view, setView] = useThreadView();
const {
@@ -93,7 +92,7 @@ function TraceDetailsThread(): JSX.Element {
onGoBack={(): void => {
// go back to the previous page
if (hasInAppHistory()) {
- history.goBack();
+ back();
} else {
void setTab(TraceDetailsTab.Overview);
}
diff --git a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph.tsx b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph.tsx
index 0f139ee294..a24ef7f971 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph.tsx
@@ -1,10 +1,10 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useHistory, useParams } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
+import { useAppParams } from 'lib/router/useAppParams';
import { Skeleton } from 'antd';
import useGetTraceFlamegraphV3 from 'hooks/trace/useGetTraceFlamegraphV3';
import useUrlQuery from 'hooks/useUrlQuery';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
-import { TraceDetailFlamegraphURLProps } from 'types/api/trace/getTraceFlamegraph';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import { COLOR_BY_FIELDS } from '../constants';
@@ -28,9 +28,8 @@ function TraceFlamegraph({
selectedSpan,
totalSpansCount,
}: TraceFlamegraphProps): JSX.Element {
- const { id: traceId } = useParams<TraceDetailFlamegraphURLProps>();
+ const { id: traceId } = useAppParams<'id'>();
const urlQuery = useUrlQuery();
- const history = useHistory();
const [firstSpanAtFetchLevel, setFirstSpanAtFetchLevel] = useState<string>(
urlQuery.get('spanId') || '',
);
@@ -39,18 +38,15 @@ function TraceFlamegraph({
setFirstSpanAtFetchLevel(urlQuery.get('spanId') || '');
}, [urlQuery]);
- const handleSpanClick = useCallback(
- (spanId: string): void => {
- setFirstSpanAtFetchLevel(spanId);
- const searchParams = getUnstableCurrentSearchParams();
- //tood: use from query params constants
- if (searchParams.get('spanId') !== spanId) {
- searchParams.set('spanId', spanId);
- history.replace({ search: searchParams.toString() });
- }
- },
- [history],
- );
+ const handleSpanClick = useCallback((spanId: string): void => {
+ setFirstSpanAtFetchLevel(spanId);
+ const searchParams = getUnstableCurrentSearchParams();
+ //tood: use from query params constants
+ if (searchParams.get('spanId') !== spanId) {
+ searchParams.set('spanId', spanId);
+ navigate({ search: searchParams.toString() }, { replace: true });
+ }
+ }, []);
const previewFields = useTraceStore((s) => s.previewFields);
// Gate the fetch until prefs load, else selectFields (in the query key)
@@ -74,7 +70,7 @@ function TraceFlamegraph({
isFetching,
error: fetchError,
} = useGetTraceFlamegraphV3({
- traceId,
+ traceId: traceId || '',
selectedSpanId: selectedSpanIdForFetch,
selectFields: flamegraphSelectFields,
enabled: !!traceId && userPrefsReady,
diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/SpanLineActionButtons/__tests__/SpanLineActionButtons.test.tsx b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/SpanLineActionButtons/__tests__/SpanLineActionButtons.test.tsx
index d50479a1df..d711716dab 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/SpanLineActionButtons/__tests__/SpanLineActionButtons.test.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/SpanLineActionButtons/__tests__/SpanLineActionButtons.test.tsx
@@ -88,8 +88,14 @@ describe('SpanLineActionButtons', () => {
toString: jest.fn().mockReturnValue('spanId=test-span-id'),
};
const mockPathname = '/test-path';
+ // history@5 re-reads `window.location` on every access, so the stub has
+ // to carry the fields the router reads, not just the one under test.
const mockLocation = {
origin: 'http://localhost:3000',
+ href: 'http://localhost:3000/',
+ pathname: '/',
+ search: '',
+ hash: '',
};
// Mock window.location
diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx
index 550a175a38..14d30968d2 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx
@@ -1,5 +1,5 @@
import { useCallback, useMemo, useRef, useState } from 'react';
-import { useHistory } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
import { ArrowRightFromLine, Search, X } from '@signozhq/icons';
import { Switch } from '@signozhq/ui/switch';
import { ToggleGroup } from '@signozhq/ui/toggle-group';
@@ -164,8 +164,6 @@ function Filters({
const { selectedCategory, categories, handleCategoryChange } =
useSpanCategoryFilter(filterProps);
- const history = useHistory();
-
const handlePrevNext = useCallback(
(index: number, spanId?: string): void => {
const searchParams = getUnstableCurrentSearchParams();
@@ -175,9 +173,9 @@ function Filters({
searchParams.set('spanId', filteredSpanIds[index]);
}
- history.replace({ search: searchParams.toString() });
+ navigate({ search: searchParams.toString() }, { replace: true });
},
- [filteredSpanIds, history],
+ [filteredSpanIds],
);
const isFilterActive = committedExpression.trim().length > 0;
diff --git a/frontend/src/pages/TraceDetailsV3/stories/TraceDetailsV3.stories.tsx b/frontend/src/pages/TraceDetailsV3/stories/TraceDetailsV3.stories.tsx
index cd21408386..75f6e797b1 100644
--- a/frontend/src/pages/TraceDetailsV3/stories/TraceDetailsV3.stories.tsx
+++ b/frontend/src/pages/TraceDetailsV3/stories/TraceDetailsV3.stories.tsx
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import {
expect,
fireEvent,
@@ -44,9 +44,7 @@ const meta = {
component: TraceDetailsV3,
// The page reads the trace id out of the pathname, so it renders under its
// own route rather than being mounted on its own.
- render: (): JSX.Element => (
- <Route path={ROUTES.TRACE_DETAIL} component={TraceDetailsV3} />
- ),
+ render: renderAtRoute(ROUTES.TRACE_DETAIL, TraceDetailsV3),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<TraceDetailsArgs>;
diff --git a/frontend/src/pages/TracesExplorer/__test__/TracesExplorer.test.tsx b/frontend/src/pages/TracesExplorer/__test__/TracesExplorer.test.tsx
index a9ae42be90..9ca221822b 100644
--- a/frontend/src/pages/TracesExplorer/__test__/TracesExplorer.test.tsx
+++ b/frontend/src/pages/TracesExplorer/__test__/TracesExplorer.test.tsx
@@ -1,5 +1,6 @@
import { ENVIRONMENT } from 'constants/env';
import ROUTES from 'constants/routes';
+import { getCurrentLocation } from 'lib/router/navigation';
import { quickFiltersListResponse } from 'mocks-server/__mockdata__/customQuickFilters';
import {
queryRangeForListView,
@@ -25,9 +26,9 @@ import { optionMenuReturn, qbProviderValue } from './testUtils';
const currentTestUrl =
'/traces-explorer/?panelType=list&selectedExplorerView=list';
-jest.mock('react-router-dom-v5-compat', () => ({
- ...jest.requireActual('react-router-dom-v5-compat'),
- useSearchParams: jest.fn(() => {
+jest.mock('lib/router/useAppSearchParams', () => ({
+ ...jest.requireActual('lib/router/useAppSearchParams'),
+ useAppSearchParams: jest.fn(() => {
const searchParams = new URLSearchParams();
// Parse the current test URL
@@ -51,30 +52,9 @@ jest.mock('hooks/queryBuilder/useGetPanelTypesQueryParam', () => ({
}),
}));
-const historyPush = jest.fn();
-
const BASE_URL = ENVIRONMENT.baseURL;
const FILTER_SERVICE_NAME = 'Service Name';
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useLocation: (): {
- pathname: string;
- search: string;
- hash: string;
- state: any;
- } => ({
- pathname: `${process.env.FRONTEND_API_ENDPOINT}${ROUTES.TRACES_EXPLORER}/`,
- search: '',
- hash: '',
- state: null,
- }),
- useHistory: (): any => ({
- ...jest.requireActual('react-router-dom').useHistory(),
- push: historyPush,
- }),
-}));
-
jest.mock(
'components/Uplot/Uplot',
() =>
@@ -354,8 +334,6 @@ describe('TracesExplorer -', () => {
);
fireEvent.click(createAlertBtn);
- expect(historyPush).toHaveBeenCalledWith(
- expect.stringContaining(`${ROUTES.ALERTS_NEW}`),
- );
+ expect(getCurrentLocation().pathname).toBe(ROUTES.ALERTS_NEW);
});
});
diff --git a/frontend/src/pages/TracesExplorer/index.tsx b/frontend/src/pages/TracesExplorer/index.tsx
index bc05e0c040..02bc14afc4 100644
--- a/frontend/src/pages/TracesExplorer/index.tsx
+++ b/frontend/src/pages/TracesExplorer/index.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useQueryClient } from 'react-query';
-import { useSearchParams } from 'react-router-dom-v5-compat';
+import { useAppSearchParams } from 'lib/router/useAppSearchParams';
import * as Sentry from '@sentry/react';
import logEvent from 'api/common/logEvent';
import QueryCancelledPlaceholder from 'components/QueryCancelledPlaceholder';
@@ -80,7 +80,7 @@ function TracesExplorer(): JSX.Element {
},
});
- const [searchParams] = useSearchParams();
+ const [searchParams] = useAppSearchParams();
const queryClient = useQueryClient();
const listQueryKeyRef = useRef<any>();
diff --git a/frontend/src/pages/TracesFunnelDetails/TracesFunnelDetails.tsx b/frontend/src/pages/TracesFunnelDetails/TracesFunnelDetails.tsx
index a58e60285d..ec8651432c 100644
--- a/frontend/src/pages/TracesFunnelDetails/TracesFunnelDetails.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/TracesFunnelDetails.tsx
@@ -1,4 +1,4 @@
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import { Typography } from '@signozhq/ui/typography';
import Spinner from 'components/Spinner';
import { NotFoundContainer } from 'container/WidgetCard/Card/FullView/styles';
@@ -11,8 +11,10 @@ import FunnelResults from './components/FunnelResults/FunnelResults';
import './TracesFunnelDetails.styles.scss';
function TracesFunnelDetails(): JSX.Element {
- const { funnelId } = useParams<{ funnelId: string }>();
- const { data, isLoading, isError } = useFunnelDetails({ funnelId });
+ const { funnelId } = useAppParams<'funnelId'>();
+ const { data, isLoading, isError } = useFunnelDetails({
+ funnelId: funnelId || '',
+ });
if (isLoading || !data?.payload) {
return <Spinner size="large" tip="Loading..." />;
@@ -27,7 +29,7 @@ function TracesFunnelDetails(): JSX.Element {
}
return (
- <FunnelProvider funnelId={funnelId}>
+ <FunnelProvider funnelId={funnelId || ''}>
<div className="traces-funnel-details">
<div className="traces-funnel-details__steps-config">
<FunnelConfiguration funnel={data.payload} />
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelBreadcrumb.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelBreadcrumb.tsx
index 7476084349..9efba819ee 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelBreadcrumb.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelBreadcrumb.tsx
@@ -1,4 +1,4 @@
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import { Breadcrumb } from 'antd';
import ROUTES from 'constants/routes';
@@ -12,11 +12,11 @@ function FunnelBreadcrumb({ funnelName }: FunnelBreadcrumbProps): JSX.Element {
const breadcrumbItems = [
{
title: (
- <Link to={ROUTES.TRACES_FUNNELS}>
+ <AppLink to={ROUTES.TRACES_FUNNELS}>
<span className="funnel-breadcrumb__link">
<span className="funnel-breadcrumb__title">All funnels</span>
</span>
- </Link>
+ </AppLink>
),
},
{
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/OverallMetrics.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/OverallMetrics.tsx
index 5349c8bf29..3f9e787e21 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/OverallMetrics.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/OverallMetrics.tsx
@@ -1,12 +1,12 @@
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import { useFunnelMetrics } from 'hooks/TracesFunnels/useFunnelMetrics';
import FunnelMetricsTable from './FunnelMetricsTable';
function OverallMetrics(): JSX.Element {
- const { funnelId } = useParams<{ funnelId: string }>();
+ const { funnelId } = useAppParams<'funnelId'>();
const { isLoading, metricsData, conversionRate, isError } = useFunnelMetrics({
- funnelId,
+ funnelId: funnelId || '',
});
return (
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/StepsTransitionMetrics.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/StepsTransitionMetrics.tsx
index c5992efb3a..1b98f0e852 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/StepsTransitionMetrics.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/StepsTransitionMetrics.tsx
@@ -1,4 +1,4 @@
-import { useParams } from 'react-router-dom';
+import { useAppParams } from 'lib/router/useAppParams';
import { useFunnelStepsMetrics } from 'hooks/TracesFunnels/useFunnelMetrics';
import FunnelMetricsTable from './FunnelMetricsTable';
@@ -17,7 +17,7 @@ function StepsTransitionMetrics({
startStep,
endStep,
}: StepsTransitionMetricsProps): JSX.Element {
- const { funnelId } = useParams<{ funnelId: string }>();
+ const { funnelId } = useAppParams<'funnelId'>();
const currentTransition = transitions.find(
(transition) => transition.value === selectedTransition,
);
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/utils.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/utils.tsx
index 1946f1a797..2cb2d26535 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/utils.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/utils.tsx
@@ -1,4 +1,4 @@
-import { Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
export const topTracesTableColumns = [
@@ -7,14 +7,14 @@ export const topTracesTableColumns = [
dataIndex: 'trace_id',
key: 'trace_id',
render: (traceId: string): JSX.Element => (
- <Link
+ <AppLink
to={`/trace/${traceId}`}
className="trace-id-cell"
target="_blank"
rel="noopener noreferrer"
>
{traceId}
- </Link>
+ </AppLink>
),
},
{
diff --git a/frontend/src/pages/TracesFunnelDetails/stories/TracesFunnelDetails.stories.tsx b/frontend/src/pages/TracesFunnelDetails/stories/TracesFunnelDetails.stories.tsx
index b4757bb5ae..b300b3c523 100644
--- a/frontend/src/pages/TracesFunnelDetails/stories/TracesFunnelDetails.stories.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/stories/TracesFunnelDetails.stories.tsx
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { Route } from 'react-router-dom';
import ROUTES from 'constants/routes';
+import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
@@ -25,9 +25,7 @@ const meta = {
component: TracesFunnelDetails,
// The funnel id is in the pathname, so the page renders under its own route
// rather than being mounted on its own.
- render: (): JSX.Element => (
- <Route path={ROUTES.TRACES_FUNNELS_DETAIL} component={TracesFunnelDetails} />
- ),
+ render: renderAtRoute(ROUTES.TRACES_FUNNELS_DETAIL, TracesFunnelDetails),
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<TracesFunnelDetailsArgs>;
diff --git a/frontend/src/pages/TracesFunnels/components/CreateFunnel/CreateFunnel.tsx b/frontend/src/pages/TracesFunnels/components/CreateFunnel/CreateFunnel.tsx
index 9039a42f1e..b0c03d4929 100644
--- a/frontend/src/pages/TracesFunnels/components/CreateFunnel/CreateFunnel.tsx
+++ b/frontend/src/pages/TracesFunnels/components/CreateFunnel/CreateFunnel.tsx
@@ -1,6 +1,8 @@
import { useState } from 'react';
import { useQueryClient } from 'react-query';
-import { generatePath, matchPath, useLocation } from 'react-router-dom';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
+import { matchRoute } from 'lib/router/matchRoute';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { Input } from '@signozhq/ui/input';
import logEvent from 'api/common/logEvent';
import axios from 'axios';
@@ -31,7 +33,7 @@ function CreateFunnel({
const { notifications } = useNotifications();
const queryClient = useQueryClient();
const { safeNavigate } = useSafeNavigate();
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const handleCreate = (): void => {
createFunnelMutation.mutate(
@@ -45,7 +47,7 @@ function CreateFunnel({
message: 'Funnel created successfully',
});
- const eventMessage = matchPath(pathname, ROUTES.TRACE_DETAIL)
+ const eventMessage = matchRoute(pathname, ROUTES.TRACE_DETAIL)
? 'Trace Funnels: Funnel created from trace details page'
: 'Trace Funnels: Funnel created from trace funnels list page';
@@ -60,7 +62,7 @@ function CreateFunnel({
onClose(funnelId);
if (funnelId && redirectToDetails) {
safeNavigate(
- generatePath(ROUTES.TRACES_FUNNELS_DETAIL, {
+ buildRoutePath(ROUTES.TRACES_FUNNELS_DETAIL, {
funnelId,
}),
);
diff --git a/frontend/src/pages/TracesFunnels/components/DeleteFunnel/DeleteFunnel.tsx b/frontend/src/pages/TracesFunnels/components/DeleteFunnel/DeleteFunnel.tsx
index ffcb4dae1f..86462a0a69 100644
--- a/frontend/src/pages/TracesFunnels/components/DeleteFunnel/DeleteFunnel.tsx
+++ b/frontend/src/pages/TracesFunnels/components/DeleteFunnel/DeleteFunnel.tsx
@@ -1,5 +1,6 @@
import { useQueryClient } from 'react-query';
-import { useHistory } from 'react-router-dom';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
import SignozModal from 'components/SignozModal/SignozModal';
import { LOCALSTORAGE } from 'constants/localStorage';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
@@ -30,8 +31,7 @@ function DeleteFunnel({
const { notifications } = useNotifications();
const queryClient = useQueryClient();
- const history = useHistory();
- const { pathname } = history.location;
+ const { pathname } = useAppLocation();
// localStorage hook for funnel steps
const localStorageKey = `${LOCALSTORAGE.FUNNEL_STEPS}_${funnelId}`;
@@ -56,7 +56,7 @@ function DeleteFunnel({
pathname !== ROUTES.TRACES_FUNNELS &&
shouldRedirectToTracesListOnDeleteSuccess
) {
- history.push(ROUTES.TRACES_FUNNELS);
+ navigate(ROUTES.TRACES_FUNNELS);
return;
}
queryClient.invalidateQueries([REACT_QUERY_KEY.GET_FUNNELS_LIST]);
diff --git a/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelsList.tsx b/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelsList.tsx
index 346d6f2c72..7b39899be4 100644
--- a/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelsList.tsx
+++ b/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelsList.tsx
@@ -1,5 +1,6 @@
import { useState } from 'react';
-import { generatePath, Link } from 'react-router-dom';
+import { AppLink } from 'lib/router/AppLink';
+import { buildRoutePath } from 'lib/router/buildRoutePath';
import { Button } from 'antd';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import ROUTES from 'constants/routes';
@@ -25,7 +26,7 @@ export function FunnelListItem({
isSpanDetailsPage,
}: FunnelListItemProps): JSX.Element {
const [isPopoverOpen, setIsPopoverOpen] = useState<boolean>(false);
- const funnelDetailsLink = generatePath(ROUTES.TRACES_FUNNELS_DETAIL, {
+ const funnelDetailsLink = buildRoutePath(ROUTES.TRACES_FUNNELS_DETAIL, {
funnelId: funnel.funnel_id,
});
@@ -85,9 +86,9 @@ export function FunnelListItem({
{content}
</button>
) : (
- <Link to={funnelDetailsLink} className="funnel-item">
+ <AppLink to={funnelDetailsLink} className="funnel-item">
{content}
- </Link>
+ </AppLink>
);
}
diff --git a/frontend/src/pages/TracesModulePage/TracesModulePage.tsx b/frontend/src/pages/TracesModulePage/TracesModulePage.tsx
index e1f484243a..8bc14a203d 100644
--- a/frontend/src/pages/TracesModulePage/TracesModulePage.tsx
+++ b/frontend/src/pages/TracesModulePage/TracesModulePage.tsx
@@ -1,16 +1,15 @@
-import { useLocation } from 'react-router-dom';
import logEvent from 'api/common/logEvent';
import RouteTab from 'components/RouteTab';
import { TabRoutes } from 'components/RouteTab/types';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { tracesExplorer, tracesFunnel } from './constants';
import './TracesModulePage.styles.scss';
function TracesModulePage(): JSX.Element {
- const { pathname } = useLocation();
+ const { pathname } = useAppLocation();
const routes: TabRoutes[] = [tracesExplorer, tracesFunnel(pathname)];
@@ -27,7 +26,6 @@ function TracesModulePage(): JSX.Element {
activeKey={
pathname.includes(ROUTES.TRACES_FUNNELS) ? ROUTES.TRACES_FUNNELS : pathname
}
- history={history}
onChangeHandler={handleTabChange}
/>
);
diff --git a/frontend/src/pages/TracesModulePage/constants.tsx b/frontend/src/pages/TracesModulePage/constants.tsx
index f7b1bbaa60..791c2e3bfa 100644
--- a/frontend/src/pages/TracesModulePage/constants.tsx
+++ b/frontend/src/pages/TracesModulePage/constants.tsx
@@ -1,5 +1,5 @@
-import { matchPath } from 'react-router-dom';
import { TabRoutes } from 'components/RouteTab/types';
+import { matchRoute } from 'lib/router/matchRoute';
import ROUTES from 'constants/routes';
import { Compass, Cone } from '@signozhq/icons';
import TracesExplorer from 'pages/TracesExplorer';
@@ -19,7 +19,7 @@ export const tracesExplorer: TabRoutes = {
export const tracesFunnel = (pathname: string): TabRoutes => ({
Component: (): JSX.Element => {
- const isFunnelDetails = matchPath(pathname, ROUTES.TRACES_FUNNELS_DETAIL);
+ const isFunnelDetails = matchRoute(pathname, ROUTES.TRACES_FUNNELS_DETAIL);
return isFunnelDetails ? <TracesFunnelDetails /> : <TracesFunnels />;
},
diff --git a/frontend/src/pages/WorkspaceAccessRestricted/WorkspaceAccessRestricted.tsx b/frontend/src/pages/WorkspaceAccessRestricted/WorkspaceAccessRestricted.tsx
index aec2dcf4e5..cde35a2bb1 100644
--- a/frontend/src/pages/WorkspaceAccessRestricted/WorkspaceAccessRestricted.tsx
+++ b/frontend/src/pages/WorkspaceAccessRestricted/WorkspaceAccessRestricted.tsx
@@ -2,7 +2,7 @@ import { useEffect } from 'react';
import { Button, Col, Modal, Row, Skeleton, Space } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import ROUTES from 'constants/routes';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { useAppContext } from 'providers/App/App';
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
@@ -25,7 +25,7 @@ function WorkspaceAccessRestricted(): JSX.Element {
!isWorkspaceAccessRestricted ||
activeLicense.platform === LicensePlatform.SELF_HOSTED
) {
- history.push(ROUTES.HOME);
+ navigate(ROUTES.HOME);
}
}
}, [isFetchingActiveLicense, activeLicense]);
diff --git a/frontend/src/pages/WorkspaceLocked/WorkspaceLocked.tsx b/frontend/src/pages/WorkspaceLocked/WorkspaceLocked.tsx
index e87bc688c8..1d60a26190 100644
--- a/frontend/src/pages/WorkspaceLocked/WorkspaceLocked.tsx
+++ b/frontend/src/pages/WorkspaceLocked/WorkspaceLocked.tsx
@@ -24,7 +24,7 @@ import { useNotifications } from 'hooks/useNotifications';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import { SubscriptionCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/subscription.permissions';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { CircleArrowRight } from '@signozhq/icons';
import { useAppContext } from 'providers/App/App';
import APIError from 'types/api/error';
@@ -78,7 +78,7 @@ export default function WorkspaceBlocked(): JSX.Element {
!shouldBlockWorkspace ||
activeLicense?.platform === LicensePlatform.SELF_HOSTED
) {
- history.push(ROUTES.HOME);
+ navigate(ROUTES.HOME);
}
}
}, [
diff --git a/frontend/src/pages/WorkspaceSuspended/WorkspaceSuspended.tsx b/frontend/src/pages/WorkspaceSuspended/WorkspaceSuspended.tsx
index c2570474d8..be1be97186 100644
--- a/frontend/src/pages/WorkspaceSuspended/WorkspaceSuspended.tsx
+++ b/frontend/src/pages/WorkspaceSuspended/WorkspaceSuspended.tsx
@@ -9,7 +9,7 @@ import ROUTES from 'constants/routes';
import { useNotifications } from 'hooks/useNotifications';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import { SubscriptionManagePermissions } from 'lib/authz/hooks/useAuthZ/permissions/subscription.permissions';
-import history from 'lib/history';
+import { navigate } from 'lib/router/navigation';
import { useAppContext } from 'providers/App/App';
import APIError from 'types/api/error';
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
@@ -60,7 +60,7 @@ function WorkspaceSuspended(): JSX.Element {
!shouldSuspendWorkspace ||
activeLicense?.platform === LicensePlatform.SELF_HOSTED
) {
- history.push(ROUTES.HOME);
+ navigate(ROUTES.HOME);
}
}
}, [isFetchingActiveLicense, activeLicense]);
diff --git a/frontend/src/providers/QueryBuilder.tsx b/frontend/src/providers/QueryBuilder.tsx
index 616f5345c5..4bc55c3c19 100644
--- a/frontend/src/providers/QueryBuilder.tsx
+++ b/frontend/src/providers/QueryBuilder.tsx
@@ -8,7 +8,7 @@ import {
useRef,
useState,
} from 'react';
-import { useLocation } from 'react-router-dom';
+import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
import {
alphabet,
@@ -101,7 +101,7 @@ export const QueryBuilderContext = createContext<QueryBuilderContextType>({
export function QueryBuilderProvider({
children,
}: PropsWithChildren): JSX.Element {
- const location = useLocation();
+ const location = useAppLocation();
const currentPathnameRef = useRef<string | null>(location.pathname);
diff --git a/frontend/src/providers/__tests__/QueryBuilder.compositeQueryNormalize.test.tsx b/frontend/src/providers/__tests__/QueryBuilder.compositeQueryNormalize.test.tsx
index e39df2d6dc..cbeab6c908 100644
--- a/frontend/src/providers/__tests__/QueryBuilder.compositeQueryNormalize.test.tsx
+++ b/frontend/src/providers/__tests__/QueryBuilder.compositeQueryNormalize.test.tsx
@@ -15,11 +15,16 @@ import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import { DataSource, QueryBuilderContextType } from 'types/common/queryBuilder';
-jest.mock('hooks/useSafeNavigate', () =>
- jest
- .requireActual('tests/browser-history-safe-navigate')
- .createBrowserHistorySafeNavigateMock(),
-);
+jest.mock('hooks/useSafeNavigate', () => {
+ const { navigate } = jest.requireActual('lib/router/navigation');
+ return {
+ useSafeNavigate: (): unknown => ({
+ safeNavigate: (to: string, opts?: { replace?: boolean }): void => {
+ navigate(to, { replace: opts?.replace });
+ },
+ }),
+ };
+});
const builderlessUrlQuery = {
queryType: 'clickhouse_sql',
diff --git a/frontend/src/storybook/renderAtRoute.tsx b/frontend/src/storybook/renderAtRoute.tsx
new file mode 100644
index 0000000000..6c0f24ab8c
--- /dev/null
+++ b/frontend/src/storybook/renderAtRoute.tsx
@@ -0,0 +1,18 @@
+import type { ComponentType } from 'react';
+import { Route } from 'react-router-dom';
+
+/**
+ * A page that reads its params out of the pathname renders under its own route
+ * rather than being mounted bare. Stories declare the pattern here instead of
+ * mounting a router `<Route>` themselves.
+ */
+export const renderAtRoute = (
+ path: string | string[],
+ Component: ComponentType,
+): (() => JSX.Element) => {
+ function StoryAtRoute(): JSX.Element {
+ return <Route exact path={path} component={Component} />;
+ }
+
+ return StoryAtRoute;
+};
diff --git a/frontend/src/tests/README.md b/frontend/src/tests/README.md
index e759b3045f..b571ca48b2 100644
--- a/frontend/src/tests/README.md
+++ b/frontend/src/tests/README.md
@@ -86,6 +86,25 @@ fireEvent.scroll(scroller);
Routing-dependent behavior:
```ts
render(<Page />, undefined, { initialRoute: '/logs-explorer?panelType=list' });
+
+// Pattern params: mount under the route the page reads them from.
+render(<Page />, undefined, {
+ initialRoute: '/dashboard/abc',
+ routePath: ROUTES.DASHBOARD,
+});
+
+// Where the component navigated to.
+expect(getCurrentLocation().pathname).toBe(ROUTES.HOME);
+```
+
+Never mock the router packages (`react-router`, `react-router-dom`) or `lib/history`;
+`signoz/no-direct-react-router-import` rejects it. When a test cannot render at a route,
+or asserts the call itself, spy on the `lib/router` facade with `tests/router-mocks`:
+```ts
+mockAppLocation({ pathname: ROUTES.LOGS_EXPLORER });
+mockAppParams({ dashboardId: 'abc' });
+const navigate = mockAppNavigate(); // what useAppNavigate() returns
+const navigateSpy = mockNavigate(); // module-level navigate()
```
#### Notes
diff --git a/frontend/src/tests/browser-history-safe-navigate.ts b/frontend/src/tests/browser-history-safe-navigate.ts
deleted file mode 100644
index 2bc1ccfe3e..0000000000
--- a/frontend/src/tests/browser-history-safe-navigate.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-// Mock factory for suites that need `useSafeNavigate` to navigate for real.
-//
-// `jest.config.ts` maps every `hooks/useSafeNavigate` import to the no-op
-// `__tests__/safeNavigateMock.ts`, so a suite that drives navigation has to opt
-// out with its own `jest.mock`.
-//
-// In production `safeNavigate` goes through `createBrowserHistory`, which writes
-// `window.location` as well as notifying the router. `MemoryRouter` never touches
-// `window`, so anything reading `getUnstableCurrentSearchParams()` sees an empty
-// search and drops the params the test just navigated with. This mock writes both.
-//
-// The `jest.mock` factory is hoisted above imports, so require it inside:
-//
-// jest.mock('hooks/useSafeNavigate', () =>
-// jest
-// .requireActual('tests/browser-history-safe-navigate')
-// .createBrowserHistorySafeNavigateMock(),
-// );
-
-import type { History } from 'history';
-
-interface SafeNavigateOptions {
- replace?: boolean;
-}
-
-interface UseSafeNavigateModule {
- useSafeNavigate: () => {
- safeNavigate: (to: string, options?: SafeNavigateOptions) => void;
- };
-}
-
-export function createBrowserHistorySafeNavigateMock(): UseSafeNavigateModule {
- const { useHistory } = jest.requireActual<{ useHistory: () => History }>(
- 'react-router-dom',
- );
-
- return {
- useSafeNavigate: () => {
- const history = useHistory();
-
- return {
- safeNavigate: (to: string, options?: SafeNavigateOptions): void => {
- if (options?.replace) {
- window.history.replaceState(null, '', to);
- history.replace(to);
- } else {
- window.history.pushState(null, '', to);
- history.push(to);
- }
- },
- };
- },
- };
-}
diff --git a/frontend/src/tests/router-mocks.ts b/frontend/src/tests/router-mocks.ts
new file mode 100644
index 0000000000..dfd55d9890
--- /dev/null
+++ b/frontend/src/tests/router-mocks.ts
@@ -0,0 +1,45 @@
+// Spies on the `lib/router` facade, for tests that cannot render at a route or
+// assert the navigation call itself. Tests never mock the router packages or
+// `lib/history`: those change at a router upgrade, the facade does not.
+// Spies last for the rest of the file unless restored.
+
+import * as navigation from 'lib/router/navigation';
+import type { AppLocation, AppParams, NavigateFn } from 'lib/router/types';
+import * as useAppLocationModule from 'lib/router/useAppLocation';
+import * as useAppNavigateModule from 'lib/router/useAppNavigate';
+import * as useAppParamsModule from 'lib/router/useAppParams';
+
+export function mockAppLocation(
+ location: Partial<AppLocation> = {},
+): jest.SpyInstance {
+ return jest.spyOn(useAppLocationModule, 'useAppLocation').mockReturnValue({
+ pathname: '/',
+ search: '',
+ hash: '',
+ state: undefined,
+ ...location,
+ });
+}
+
+export function mockAppParams(params: AppParams): jest.SpyInstance {
+ return jest
+ .spyOn(useAppParamsModule, 'useAppParams')
+ .mockReturnValue(
+ params as ReturnType<typeof useAppParamsModule.useAppParams>,
+ );
+}
+
+/** Replaces the function `useAppNavigate()` returns, and returns it. */
+export function mockAppNavigate(): jest.MockedFunction<NavigateFn> {
+ const navigate = jest.fn() as jest.MockedFunction<NavigateFn>;
+ jest.spyOn(useAppNavigateModule, 'useAppNavigate').mockReturnValue(navigate);
+ return navigate;
+}
+
+/** Stubs the module-level `navigate()`, so the call is recorded and the URL stays put. */
+export function mockNavigate(): jest.SpyInstance<
+ ReturnType<typeof navigation.navigate>,
+ Parameters<typeof navigation.navigate>
+> {
+ return jest.spyOn(navigation, 'navigate').mockImplementation(() => {});
+}
diff --git a/frontend/src/tests/router-utils.ts b/frontend/src/tests/router-utils.ts
new file mode 100644
index 0000000000..176c8e9ea8
--- /dev/null
+++ b/frontend/src/tests/router-utils.ts
@@ -0,0 +1,6 @@
+import { navigate } from 'lib/router/navigation';
+
+/** Returns the history singleton to the state a suite should start each test in. */
+export function resetTestRoute(): void {
+ navigate('/', { replace: true });
+}
diff --git a/frontend/src/tests/router.isolation.test.tsx b/frontend/src/tests/router.isolation.test.tsx
new file mode 100644
index 0000000000..d27da7afa2
--- /dev/null
+++ b/frontend/src/tests/router.isolation.test.tsx
@@ -0,0 +1,34 @@
+import { render, screen } from '@testing-library/react';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
+
+import { TestRouter } from './router';
+
+function Pathname(): JSX.Element {
+ const { pathname } = useAppLocation();
+ return <span data-testid="pathname">{pathname}</span>;
+}
+
+describe('TestRouter isolation', () => {
+ it('lets a test navigate away from the start', () => {
+ render(
+ <TestRouter>
+ <Pathname />
+ </TestRouter>,
+ );
+ navigate('/logs');
+
+ expect(window.location.pathname).toBe('/logs');
+ });
+
+ it('starts the next test at /', () => {
+ render(
+ <TestRouter>
+ <Pathname />
+ </TestRouter>,
+ );
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/');
+ expect(window.location.pathname).toBe('/');
+ });
+});
diff --git a/frontend/src/tests/router.test.tsx b/frontend/src/tests/router.test.tsx
new file mode 100644
index 0000000000..026d006363
--- /dev/null
+++ b/frontend/src/tests/router.test.tsx
@@ -0,0 +1,69 @@
+import { render, screen } from '@testing-library/react';
+import { navigate } from 'lib/router/navigation';
+import { useAppLocation } from 'lib/router/useAppLocation';
+
+import { TestRouter } from './router';
+import { resetTestRoute } from './router-utils';
+
+function Pathname(): JSX.Element {
+ const { pathname } = useAppLocation();
+ return <span data-testid="pathname">{pathname}</span>;
+}
+
+describe('TestRouter', () => {
+ beforeEach(() => {
+ resetTestRoute();
+ });
+
+ it('mounts at initialRoute', () => {
+ render(
+ <TestRouter initialRoute="/logs">
+ <Pathname />
+ </TestRouter>,
+ );
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/logs');
+ });
+
+ it('keeps the existing URL when initialRoute is omitted', () => {
+ navigate('/existing');
+
+ render(
+ <TestRouter>
+ <Pathname />
+ </TestRouter>,
+ );
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/existing');
+ });
+
+ it('rejects an initialRoute on a nested TestRouter', () => {
+ const consoleError = jest
+ .spyOn(console, 'error')
+ .mockImplementation(() => undefined);
+
+ expect(() =>
+ render(
+ <TestRouter initialRoute="/outer">
+ <TestRouter initialRoute="/inner">
+ <Pathname />
+ </TestRouter>
+ </TestRouter>,
+ ),
+ ).toThrow('A nested TestRouter cannot take initialRoute');
+
+ consoleError.mockRestore();
+ });
+
+ it('keeps the outer route when the nested TestRouter has no initialRoute', () => {
+ render(
+ <TestRouter initialRoute="/outer">
+ <TestRouter>
+ <Pathname />
+ </TestRouter>
+ </TestRouter>,
+ );
+
+ expect(screen.getByTestId('pathname')).toHaveTextContent('/outer');
+ });
+});
diff --git a/frontend/src/tests/router.tsx b/frontend/src/tests/router.tsx
new file mode 100644
index 0000000000..5f8d6e9427
--- /dev/null
+++ b/frontend/src/tests/router.tsx
@@ -0,0 +1,80 @@
+import { ReactElement, ReactNode, useRef } from 'react';
+import { Route, Router } from 'react-router-dom';
+import { CompatRouter, useInRouterContext } from 'react-router-dom-v5-compat';
+import history from 'lib/history';
+
+import { resetTestRoute } from './router-utils';
+
+// Mounts on the `lib/history` singleton like `src/AppRoutes/index.tsx`, so
+// imperative `navigate()` calls move the router. `CompatRouter` is always
+// present for the v6-only facade hooks. A `TestRouter` inside another renders
+// its children on the outer router and cannot take an `initialRoute`: the outer
+// `CompatRouter` has already read the location, so v6-backed hooks would keep
+// the outer route.
+
+interface TestRouterProps {
+ children: ReactNode;
+ /**
+ * Seeded onto the history singleton before the router reads it. Omit to mount
+ * at whatever URL the test has already set up. `render()` defaults it to `/`.
+ */
+ initialRoute?: string;
+ /**
+ * Route pattern(s) to mount the children under, for a component that reads
+ * `useParams`. Matching is exact.
+ */
+ routePath?: string | string[];
+}
+
+export function TestRouter({
+ children,
+ initialRoute,
+ routePath,
+}: TestRouterProps): ReactElement {
+ const nested = useInRouterContext();
+ if (nested && initialRoute) {
+ throw new Error(
+ 'A nested TestRouter cannot take initialRoute. Pass it to the outermost TestRouter or to render().',
+ );
+ }
+
+ // The seed has to land before `<Router>` reads `history.location`, hence the
+ // render body rather than an effect. The ref keeps it to the first render, so
+ // a navigation made by the component under test is not undone.
+ const seeded = useRef(false);
+ if (!seeded.current) {
+ seeded.current = true;
+ if (initialRoute) {
+ history.replace(initialRoute);
+ }
+ }
+
+ const tree = routePath ? (
+ <Route exact path={routePath}>
+ {children}
+ </Route>
+ ) : (
+ children
+ );
+
+ if (nested) {
+ return <>{tree}</>;
+ }
+
+ return (
+ <Router history={history}>
+ <CompatRouter>{tree}</CompatRouter>
+ </Router>
+ );
+}
+
+TestRouter.defaultProps = {
+ initialRoute: undefined,
+ routePath: undefined,
+};
+
+// Registered here rather than in `test-utils` so a suite that mounts
+// `TestRouter` without importing the harness starts every test at `/` too.
+beforeEach(() => {
+ resetTestRoute();
+});
diff --git a/frontend/src/tests/test-utils.tsx b/frontend/src/tests/test-utils.tsx
index c7d3e15a99..f445a6bcbf 100644
--- a/frontend/src/tests/test-utils.tsx
+++ b/frontend/src/tests/test-utils.tsx
@@ -2,7 +2,6 @@ import React, { ReactElement } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { render, RenderOptions, RenderResult } from '@testing-library/react';
import { ResourceProvider } from 'hooks/useResourceAttribute';
import { NuqsAdapter } from 'nuqs/adapters/react';
@@ -20,7 +19,8 @@ import { createAppContextMock } from 'tests/fixtures/appContextMock';
import thunk from 'redux-thunk';
import store from 'store';
import { QueryBuilderContextType } from 'types/common/queryBuilder';
-// import { MemoryRouter as V5MemoryRouter } from 'react-router-dom-v5-compat';
+
+import { TestRouter } from './router';
// Mock ResizeObserver
class ResizeObserverMock {
@@ -112,17 +112,18 @@ export function AllTheProviders({
appContextOverrides,
queryBuilderOverrides,
initialRoute,
+ routePath,
}: {
children: React.ReactNode;
role?: string;
appContextOverrides?: Partial<IAppContext>;
queryBuilderOverrides?: Partial<QueryBuilderContextType>;
initialRoute?: string;
+ routePath?: string | string[];
}): ReactElement {
// Set default values
const roleValue = role || 'ADMIN';
const appContextOverridesValue = appContextOverrides || {};
- const initialRouteValue = initialRoute || '/';
const queryBuilderContent = queryBuilderOverrides ? (
<QueryBuilderContext.Provider
@@ -137,7 +138,7 @@ export function AllTheProviders({
const appContextValue = getAppContextMock(roleValue, appContextOverridesValue);
return (
- <MemoryRouter initialEntries={[initialRouteValue]}>
+ <TestRouter initialRoute={initialRoute} routePath={routePath}>
<NuqsAdapter>
<QueryClientProvider client={queryClient}>
<Provider store={mockStored(roleValue)}>
@@ -155,7 +156,7 @@ export function AllTheProviders({
</Provider>
</QueryClientProvider>
</NuqsAdapter>
- </MemoryRouter>
+ </TestRouter>
);
}
@@ -163,7 +164,8 @@ AllTheProviders.defaultProps = {
role: 'ADMIN',
appContextOverrides: {},
queryBuilderOverrides: undefined,
- initialRoute: '/',
+ initialRoute: undefined,
+ routePath: undefined,
};
interface ProviderProps {
@@ -171,6 +173,7 @@ interface ProviderProps {
appContextOverrides?: Partial<IAppContext>;
queryBuilderOverrides?: Partial<QueryBuilderContextType>;
initialRoute?: string;
+ routePath?: string | string[];
}
const customRender = (
@@ -183,6 +186,7 @@ const customRender = (
appContextOverrides = {},
queryBuilderOverrides,
initialRoute = '/',
+ routePath,
} = providerProps;
return render(ui, {
@@ -192,6 +196,7 @@ const customRender = (
appContextOverrides={appContextOverrides}
queryBuilderOverrides={queryBuilderOverrides}
initialRoute={initialRoute}
+ routePath={routePath}
>
{ui}
</AllTheProviders>
diff --git a/frontend/src/types/api/trace/getTraceFlamegraph.ts b/frontend/src/types/api/trace/getTraceFlamegraph.ts
index 9661e59a49..5dc37d6eb5 100644
--- a/frontend/src/types/api/trace/getTraceFlamegraph.ts
+++ b/frontend/src/types/api/trace/getTraceFlamegraph.ts
@@ -1,9 +1,5 @@
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
-export interface TraceDetailFlamegraphURLProps {
- id: string;
-}
-
export interface GetTraceFlamegraphPayloadProps {
traceId: string;
selectedSpanId?: string;
diff --git a/frontend/src/types/api/trace/getTraceV3.ts b/frontend/src/types/api/trace/getTraceV3.ts
index 5a9660995a..ee9ca22434 100644
--- a/frontend/src/types/api/trace/getTraceV3.ts
+++ b/frontend/src/types/api/trace/getTraceV3.ts
@@ -6,10 +6,6 @@ export interface GetTraceV4PayloadProps {
limit?: number; // Optional limit for number of spans to fetch, default can be set in API
}
-export interface TraceDetailV3URLProps {
- id: string;
-}
-
// Event shape — same in V2 and V3 (already camelCase from backend)
export interface EventV3 {
name: string;
diff --git a/frontend/src/utils/__tests__/app.test.ts b/frontend/src/utils/__tests__/app.test.ts
index ec9073c88f..873594dd27 100644
--- a/frontend/src/utils/__tests__/app.test.ts
+++ b/frontend/src/utils/__tests__/app.test.ts
@@ -1,23 +1,20 @@
import { buildAbsolutePath } from '../app';
-// buildAbsolutePath reads history.location.pathname (basename-relative) rather than
-// window.location.pathname, so we mock lib/history instead of utils/getLocation.
-jest.mock('lib/history', () => ({
- __esModule: true,
- default: {
- location: { pathname: '/' },
- },
+// buildAbsolutePath reads getCurrentLocation().pathname (basename-relative) rather than
+// window.location.pathname, so we mock lib/router/navigation instead of utils/getLocation.
+jest.mock('lib/router/navigation', () => ({
+ getCurrentLocation: jest.fn(() => ({ pathname: '/' })),
}));
// oxlint-disable-next-line typescript-eslint/no-require-imports, typescript-eslint/no-var-requires
-const mockHistory = require('lib/history').default as {
- location: { pathname: string };
+const { getCurrentLocation } = require('lib/router/navigation') as {
+ getCurrentLocation: jest.Mock<{ pathname: string }>;
};
const BASE_PATH = '/some-base-path';
const mockLocation = (pathname: string): void => {
- mockHistory.location.pathname = pathname;
+ getCurrentLocation.mockReturnValue({ pathname });
};
describe('buildAbsolutePath', () => {
diff --git a/frontend/src/utils/app.ts b/frontend/src/utils/app.ts
index 926fddf879..43d3cf03bd 100644
--- a/frontend/src/utils/app.ts
+++ b/frontend/src/utils/app.ts
@@ -2,7 +2,7 @@ import getLocalStorage from 'api/browser/localstorage/get';
import { FeatureKeys } from 'constants/features';
import { SKIP_ONBOARDING } from 'constants/onboarding';
import dayjs from 'dayjs';
-import history from 'lib/history';
+import { getCurrentLocation } from 'lib/router/navigation';
import { get } from 'lodash-es';
export const isOnboardingSkipped = (): boolean =>
@@ -61,7 +61,7 @@ export function buildAbsolutePath({
relativePath: string;
urlQueryString?: string;
}): string {
- const currentPathname = history.location.pathname;
+ const currentPathname = getCurrentLocation().pathname;
if (!relativePath) {
return urlQueryString