You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ms...@apache.org on 2026/06/11 12:39:15 UTC
(superset) branch tanstack-router created (now 4c233d92a32)
This is an automated email from the ASF dual-hosted git repository.
msyavuz pushed a change to branch tanstack-router
in repository https://gitbox.apache.org/repos/asf/superset.git
at 4c233d92a32 feat(frontend): migrate react-router v5 to TanStack Router with intent-based preloading
This branch includes the following new commits:
new 4c233d92a32 feat(frontend): migrate react-router v5 to TanStack Router with intent-based preloading
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(superset) 01/01: feat(frontend): migrate react-router v5 to TanStack Router with intent-based preloading
Posted by ms...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
msyavuz pushed a commit to branch tanstack-router
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 4c233d92a32234671d97c990482ac06d6d091a12
Author: Mehmet Salih Yavuz <sa...@proton.me>
AuthorDate: Wed Jun 10 23:25:23 2026 +0300
feat(frontend): migrate react-router v5 to TanStack Router with intent-based preloading
- Replace BrowserRouter/Switch/Route with a TanStack route tree built
from the existing routes.tsx table; route chunks preload on link
hover/focus (defaultPreload: 'intent') via fire-and-forget loaders
- Custom raw-string search param codec so rison payloads round-trip
through the router untouched
- TanstackRouterAdapter replaces ReactRouter5Adapter for use-query-params
- StandaloneRouter (RouterContextProvider-based, synchronous mount) hosts
the menu entry on Flask pages and component tests
- pushAppHref/replaceAppHref helpers restore v5's basename-prefixing
semantics for raw href navigation
- useUnsavedChangesPrompt now uses useBlocker
- Migrate all 92 importing files; drop react-router-dom dependency
---
superset-frontend/package-lock.json | 183 +++++++++---
superset-frontend/package.json | 3 +-
superset-frontend/spec/helpers/ProviderWrapper.tsx | 10 +-
superset-frontend/spec/helpers/testing-library.tsx | 17 +-
.../src/SqlLab/components/App/index.tsx | 10 +-
.../components/PopEditorTab/PopEditorTab.test.tsx | 6 +-
.../src/SqlLab/components/ResultSet/index.tsx | 7 +-
.../src/components/Chart/DrillBy/DrillByModal.tsx | 16 +-
.../Chart/DrillDetail/DrillDetailModal.test.tsx | 10 +-
.../Chart/DrillDetail/DrillDetailModal.tsx | 9 +-
.../src/components/GenericLink/index.tsx | 39 ++-
.../src/components/ListView/CrossLinks.tsx | 2 +-
.../src/components/ListView/CrossLinksTooltip.tsx | 2 +-
.../src/components/ListView/ListView.test.tsx | 10 +-
superset-frontend/src/components/Tag/index.tsx | 5 +-
superset-frontend/src/dashboard/actions/hydrate.ts | 11 +-
.../dashboard/components/Header/Header.test.tsx | 28 +-
.../Header/useHeaderActionsDropdownMenu.tsx | 11 +-
.../components/SliceHeader/SliceHeader.test.tsx | 36 ++-
.../src/dashboard/components/SliceHeader/index.tsx | 8 +-
.../ViewResultsModalTrigger.tsx | 8 +-
.../components/SliceHeaderControls/index.tsx | 11 +-
.../nativeFilters/FilterBar/Horizontal.tsx | 12 +-
.../FilterBar/UrlFilters/Vertical.test.tsx | 23 +-
.../FilterBar/UrlFilters/Vertical.tsx | 12 +-
.../components/nativeFilters/FilterBar/index.tsx | 37 ++-
.../src/dashboard/containers/DashboardPage.tsx | 10 +-
.../src/dashboard/util/risonFilters.test.ts | 22 +-
.../src/dashboard/util/risonFilters.ts | 15 +-
superset-frontend/src/embedded/index.tsx | 38 ++-
.../components/ExploreChartHeader/index.tsx | 10 +-
.../ExploreViewContainer.test.tsx | 36 ++-
.../components/ExploreViewContainer/index.tsx | 8 +-
.../src/explore/components/SaveModal.tsx | 20 +-
.../DatasourceControl/DatasourceControl.test.tsx | 29 +-
.../controls/DatasourceControl/index.tsx | 14 +-
.../explore/components/controls/ViewQuery.test.tsx | 21 +-
.../src/explore/components/controls/ViewQuery.tsx | 9 +-
.../components/controls/ViewQueryModalFooter.tsx | 12 +-
.../DashboardsSubMenu.tsx | 12 +-
.../src/features/charts/ChartCard.tsx | 25 +-
.../src/features/dashboards/DashboardCard.test.tsx | 7 +-
.../src/features/dashboards/DashboardCard.tsx | 26 +-
.../databases/DatabaseModal/index.test.tsx | 10 +-
.../src/features/databases/DatabaseModal/index.tsx | 11 +-
.../AddDataset/DatasetPanel/MessageContent.tsx | 2 +-
.../datasets/AddDataset/Footer/Footer.test.tsx | 18 +-
.../features/datasets/AddDataset/Footer/index.tsx | 15 +-
.../datasets/DatasetLayout/DatasetLayout.test.tsx | 8 -
.../src/features/home/ActivityTable.tsx | 10 +-
superset-frontend/src/features/home/ChartTable.tsx | 7 +-
.../src/features/home/DashboardTable.test.tsx | 40 ++-
.../src/features/home/DashboardTable.tsx | 7 +-
superset-frontend/src/features/home/Menu.tsx | 26 +-
superset-frontend/src/features/home/RightMenu.tsx | 38 ++-
.../src/features/home/SavedQueries.tsx | 11 +-
.../src/features/home/SubMenu.test.tsx | 6 +-
superset-frontend/src/features/home/SubMenu.tsx | 19 +-
superset-frontend/src/features/tags/TagCard.tsx | 2 +-
.../src/hooks/useUnsavedChangesPrompt/index.ts | 112 ++++----
.../useUnsavedChangesPrompt.test.tsx | 177 ++++++------
.../pages/AlertReportList/AlertReportList.test.tsx | 16 +-
.../src/pages/AlertReportList/index.tsx | 8 +-
.../AnnotationLayerList.test.tsx | 10 +-
.../src/pages/AnnotationLayerList/index.tsx | 14 +-
.../src/pages/AnnotationList/index.tsx | 16 +-
superset-frontend/src/pages/Chart/Chart.test.tsx | 18 +-
superset-frontend/src/pages/Chart/index.tsx | 42 +--
.../src/pages/ChartCreation/index.tsx | 14 +-
.../pages/ChartList/ChartList.permissions.test.tsx | 10 +-
.../src/pages/ChartList/ChartList.testHelpers.tsx | 12 +-
superset-frontend/src/pages/ChartList/index.tsx | 48 ++--
.../pages/CssTemplateList/CssTemplateList.test.tsx | 10 +-
superset-frontend/src/pages/Dashboard/index.tsx | 4 +-
.../DashboardList.permissions.test.tsx | 10 +-
.../DashboardList/DashboardList.testHelpers.tsx | 10 +-
.../src/pages/DashboardList/index.tsx | 38 ++-
.../pages/DatasetCreation/DatasetCreation.test.tsx | 10 +-
.../src/pages/DatasetCreation/index.tsx | 6 +-
.../pages/DatasetList/DatasetList.testHelpers.tsx | 10 +-
superset-frontend/src/pages/DatasetList/index.tsx | 17 +-
.../ExecutionLogList/ExecutionLogList.test.tsx | 4 +-
.../src/pages/ExecutionLogList/index.tsx | 4 +-
.../src/pages/FileHandler/index.test.tsx | 112 +++-----
superset-frontend/src/pages/FileHandler/index.tsx | 16 +-
.../src/pages/GroupsList/GroupsList.test.tsx | 16 +-
.../src/pages/QueryHistoryList/index.tsx | 11 +-
.../src/pages/Register/Register.test.tsx | 6 +-
superset-frontend/src/pages/Register/index.tsx | 6 +-
.../src/pages/RolesList/RolesList.test.tsx | 21 +-
.../RowLevelSecurityList.test.tsx | 10 +-
.../pages/SavedQueryList/SavedQueryList.test.tsx | 36 ++-
.../src/pages/SavedQueryList/index.tsx | 19 +-
.../src/pages/SqlLab/LocationContext.tsx | 13 +-
superset-frontend/src/pages/Tags/index.tsx | 6 +-
.../src/pages/TaskList/TaskList.test.tsx | 10 +-
.../src/pages/UserInfo/UserInfo.test.tsx | 16 +-
.../src/pages/UsersList/UsersList.test.tsx | 16 +-
superset-frontend/src/router/StandaloneRouter.tsx | 88 ++++++
superset-frontend/src/router/index.tsx | 164 +++++++++++
superset-frontend/src/router/navigation.ts | 61 ++++
superset-frontend/src/router/queryParamAdapter.tsx | 62 +++++
superset-frontend/src/router/searchParams.ts | 95 +++++++
.../tanstack-history.d.ts} | 20 +-
superset-frontend/src/views/App.tsx | 85 +-----
.../src/views/RootContextProviders.tsx | 4 +-
superset-frontend/src/views/ScrollToTop.tsx | 4 +-
superset-frontend/src/views/menu.tsx | 10 +-
superset-frontend/src/views/routes.tsx | 310 ++++++++++-----------
109 files changed, 1794 insertions(+), 1113 deletions(-)
diff --git a/superset-frontend/package-lock.json b/superset-frontend/package-lock.json
index a2e16c3302a..c22a2159d73 100644
--- a/superset-frontend/package-lock.json
+++ b/superset-frontend/package-lock.json
@@ -71,6 +71,7 @@
"@superset-ui/plugin-chart-word-cloud": "file:./plugins/plugin-chart-word-cloud",
"@superset-ui/preset-chart-deckgl": "file:./plugins/preset-chart-deckgl",
"@superset-ui/switchboard": "file:./packages/superset-ui-switchboard",
+ "@tanstack/react-router": "^1.170.15",
"@types/d3-format": "^3.0.1",
"@types/d3-selection": "^3.0.11",
"@types/d3-time-format": "^4.0.3",
@@ -135,7 +136,6 @@
"react-redux": "^7.2.9",
"react-resize-detector": "^9.1.1",
"react-reverse-portal": "^2.3.0",
- "react-router-dom": "^5.3.4",
"react-search-input": "^0.11.3",
"react-split": "^2.0.9",
"react-table": "^7.8.0",
@@ -206,7 +206,6 @@
"@types/react-dom": "^18.2.0",
"@types/react-loadable": "^5.5.11",
"@types/react-redux": "^7.1.10",
- "@types/react-router-dom": "^5.3.3",
"@types/react-transition-group": "^4.4.12",
"@types/react-window": "^1.8.8",
"@types/redux-localstorage": "^1.0.8",
@@ -10754,6 +10753,89 @@
"@swc/counter": "^0.1.3"
}
},
+ "node_modules/@tanstack/history": {
+ "version": "1.162.0",
+ "resolved": "https://registry.npmjs.org/@tanstack/history/-/history-1.162.0.tgz",
+ "integrity": "sha512-79pf/RkhteYZTRgcR4F9kbk84P2N8rugQJswxfIqovlbRiT3yI7eBE+5QorIrZaOKktsgzRlXh1l/du/xpl4iA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ }
+ },
+ "node_modules/@tanstack/react-router": {
+ "version": "1.170.15",
+ "resolved": "https://registry.npmjs.org/@tanstack/react-router/-/react-router-1.170.15.tgz",
+ "integrity": "sha512-GawYz7HEjj8rTUUDoT/SemDEVm63pZUO+2mOcXHY9Jl3EwMS5gFBnPu/2UvcrwRm1jN1k79fokc0d4aFmrLatg==",
+ "license": "MIT",
+ "dependencies": {
+ "@tanstack/history": "1.162.0",
+ "@tanstack/react-store": "^0.9.3",
+ "@tanstack/router-core": "1.171.13",
+ "isbot": "^5.1.22"
+ },
+ "engines": {
+ "node": ">=20.19"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "peerDependencies": {
+ "react": ">=18.0.0 || >=19.0.0",
+ "react-dom": ">=18.0.0 || >=19.0.0"
+ }
+ },
+ "node_modules/@tanstack/react-store": {
+ "version": "0.9.3",
+ "resolved": "https://registry.npmjs.org/@tanstack/react-store/-/react-store-0.9.3.tgz",
+ "integrity": "sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg==",
+ "license": "MIT",
+ "dependencies": {
+ "@tanstack/store": "0.9.3",
+ "use-sync-external-store": "^1.6.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
+ "node_modules/@tanstack/router-core": {
+ "version": "1.171.13",
+ "resolved": "https://registry.npmjs.org/@tanstack/router-core/-/router-core-1.171.13.tgz",
+ "integrity": "sha512-+NOwEj1kO/6IGmpHRIZHasYxYWpyBQGNIZAST9aNrk9Q3YlU9SgqVnl1pbLa9qAKfeNdXQIRve0RQb/0kyDeDA==",
+ "license": "MIT",
+ "dependencies": {
+ "@tanstack/history": "1.162.0",
+ "cookie-es": "^3.0.0",
+ "seroval": "^1.5.4",
+ "seroval-plugins": "^1.5.4"
+ },
+ "engines": {
+ "node": ">=20.19"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ }
+ },
+ "node_modules/@tanstack/store": {
+ "version": "0.9.3",
+ "resolved": "https://registry.npmjs.org/@tanstack/store/-/store-0.9.3.tgz",
+ "integrity": "sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ }
+ },
"node_modules/@testing-library/dom": {
"version": "9.3.4",
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-9.3.4.tgz",
@@ -11407,13 +11489,6 @@
"@types/unist": "^2"
}
},
- "node_modules/@types/history": {
- "version": "4.7.11",
- "resolved": "https://registry.npmjs.org/@types/history/-/history-4.7.11.tgz",
- "integrity": "sha512-qjDJRrmvBMiTx+jyLxvLfJU7UznFuokDv4f3WRuriHKERccVpFU+8XMQUAbDzoiJCsmexxRExQeMwwCdamSKDA==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@types/hoist-non-react-statics": {
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.6.tgz",
@@ -11812,29 +11887,6 @@
"redux": "^4.0.0"
}
},
- "node_modules/@types/react-router": {
- "version": "5.1.20",
- "resolved": "https://registry.npmjs.org/@types/react-router/-/react-router-5.1.20.tgz",
- "integrity": "sha512-jGjmu/ZqS7FjSH6owMcD5qpq19+1RS9DeVRqfl1FeBMxTDQAGwlMWOcs52NDoXaNKyG3d1cYQFMs9rCrb88o9Q==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/history": "^4.7.11",
- "@types/react": "*"
- }
- },
- "node_modules/@types/react-router-dom": {
- "version": "5.3.3",
- "resolved": "https://registry.npmjs.org/@types/react-router-dom/-/react-router-dom-5.3.3.tgz",
- "integrity": "sha512-kpqnYK4wcdm5UaWI3fLcELopqLrHgLqNsdpHauzlQktfkHL3npOSwtj1Uz9oKBAzs7lFtVkV8j83voAz2D8fhw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/history": "^4.7.11",
- "@types/react": "*",
- "@types/react-router": "*"
- }
- },
"node_modules/@types/react-syntax-highlighter": {
"version": "15.5.13",
"resolved": "https://registry.npmjs.org/@types/react-syntax-highlighter/-/react-syntax-highlighter-15.5.13.tgz",
@@ -16439,6 +16491,12 @@
"node": ">= 0.6"
}
},
+ "node_modules/cookie-es": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-3.1.1.tgz",
+ "integrity": "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==",
+ "license": "MIT"
+ },
"node_modules/cookie-signature": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
@@ -24131,6 +24189,15 @@
"url": "https://github.com/sponsors/gjtorikian/"
}
},
+ "node_modules/isbot": {
+ "version": "5.1.42",
+ "resolved": "https://registry.npmjs.org/isbot/-/isbot-5.1.42.tgz",
+ "integrity": "sha512-/SXsVh7KpPRISrD4ffrGSxnTLlUBzEQUfWIusaJPrpJ93FW1P0YEZri5vAUkFsA0m2HRUhQRQadk2wJ+EeKowQ==",
+ "license": "Unlicense",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
@@ -35981,6 +36048,8 @@
"resolved": "https://registry.npmjs.org/react-router/-/react-router-5.3.4.tgz",
"integrity": "sha512-Ys9K+ppnJah3QuaRiLxk+jDWOR1MekYQrlytiXxC1RyfbdsZkS5pvKAzCCr031xHixZwpnsYNT5xysdFHQaYsA==",
"license": "MIT",
+ "optional": true,
+ "peer": true,
"dependencies": {
"@babel/runtime": "^7.12.13",
"history": "^4.9.0",
@@ -36001,6 +36070,8 @@
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-5.3.4.tgz",
"integrity": "sha512-m4EqFMHv/Ih4kpcBCONHbkT68KoAeHN4p3lAGoNryfHi0dMy0kCzEZakiKRsvg5wHZ/JLrLW8o8KomWiz/qbYQ==",
"license": "MIT",
+ "optional": true,
+ "peer": true,
"dependencies": {
"@babel/runtime": "^7.12.13",
"history": "^4.9.0",
@@ -36019,6 +36090,8 @@
"resolved": "https://registry.npmjs.org/history/-/history-4.10.1.tgz",
"integrity": "sha512-36nwAD620w12kuzPAsyINPWJqlNbij+hpK1k9XRloDtym8mxzGYl2c17LnV6IAGB2Dmg4tEa7G7DlawS0+qjew==",
"license": "MIT",
+ "optional": true,
+ "peer": true,
"dependencies": {
"@babel/runtime": "^7.1.2",
"loose-envify": "^1.2.0",
@@ -36033,6 +36106,8 @@
"resolved": "https://registry.npmjs.org/history/-/history-4.10.1.tgz",
"integrity": "sha512-36nwAD620w12kuzPAsyINPWJqlNbij+hpK1k9XRloDtym8mxzGYl2c17LnV6IAGB2Dmg4tEa7G7DlawS0+qjew==",
"license": "MIT",
+ "optional": true,
+ "peer": true,
"dependencies": {
"@babel/runtime": "^7.1.2",
"loose-envify": "^1.2.0",
@@ -36046,13 +36121,17 @@
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
"integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==",
- "license": "MIT"
+ "license": "MIT",
+ "optional": true,
+ "peer": true
},
"node_modules/react-router/node_modules/path-to-regexp": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.9.0.tgz",
"integrity": "sha512-xIp7/apCFJuUHdDLWe8O1HIkb0kQrOMb/0u6FXQjemHn/ii5LrIzU6bdECnsiTF/GjZkMEKg1xdiZwNqDYlZ6g==",
"license": "MIT",
+ "optional": true,
+ "peer": true,
"dependencies": {
"isarray": "0.0.1"
}
@@ -36061,7 +36140,9 @@
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
- "license": "MIT"
+ "license": "MIT",
+ "optional": true,
+ "peer": true
},
"node_modules/react-search-input": {
"version": "0.11.3",
@@ -37362,7 +37443,9 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/resolve-pathname/-/resolve-pathname-3.0.0.tgz",
"integrity": "sha512-C7rARubxI8bXFNB/hqcp/4iUeIXJhJZvFPFPiSPRnhU5UPxzMFIl+2E6yY6c4k9giDJAhtV+enfA+G89N6Csng==",
- "license": "MIT"
+ "license": "MIT",
+ "optional": true,
+ "peer": true
},
"node_modules/resolve-pkg-maps": {
"version": "1.0.0",
@@ -37798,6 +37881,27 @@
"integrity": "sha512-y9WzzDj3BsGgKLCh0ugiinufS//YqOfao/yVJjkXA4VLuyNCfHOLU/cbulGPxs3aeCqhvROw7qPL04JSZnCo0w==",
"license": "ISC"
},
+ "node_modules/seroval": {
+ "version": "1.5.4",
+ "resolved": "https://registry.npmjs.org/seroval/-/seroval-1.5.4.tgz",
+ "integrity": "sha512-46uFvgrXTVxZcUorgSSRZ4y+ieqLLQRMlG4bnCZKW3qI6BZm7Rg4ntMW4p1mILEEBZWrFlcpp0AyIIlM6jD9iw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/seroval-plugins": {
+ "version": "1.5.4",
+ "resolved": "https://registry.npmjs.org/seroval-plugins/-/seroval-plugins-1.5.4.tgz",
+ "integrity": "sha512-S0xQPhUTefAhNvNWFg0c1J8qJArHt5KdtJ/cFAofo06KD1MVSeFWyl4iiu+ApDIuw0WhjpOfCdgConOfAnLgkw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "peerDependencies": {
+ "seroval": "^1.0"
+ }
+ },
"node_modules/serve-index": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz",
@@ -40082,13 +40186,16 @@
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
"integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
+ "devOptional": true,
"license": "MIT"
},
"node_modules/tiny-warning": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-warning/-/tiny-warning-1.0.3.tgz",
"integrity": "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA==",
- "license": "MIT"
+ "license": "MIT",
+ "optional": true,
+ "peer": true
},
"node_modules/tinycolor2": {
"version": "1.6.0",
@@ -42091,7 +42198,9 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/value-equal/-/value-equal-1.0.1.tgz",
"integrity": "sha512-NOJ6JZCAWr0zlxZt+xqCHNTEKOsrks2HQd4MqhP1qy4z1SkbEP467eNx6TgDKXMvUOb+OENfJCZwM+16n7fRfw==",
- "license": "MIT"
+ "license": "MIT",
+ "optional": true,
+ "peer": true
},
"node_modules/vary": {
"version": "1.1.2",
diff --git a/superset-frontend/package.json b/superset-frontend/package.json
index b96f3b67732..3e280c9a368 100644
--- a/superset-frontend/package.json
+++ b/superset-frontend/package.json
@@ -154,6 +154,7 @@
"@superset-ui/plugin-chart-word-cloud": "file:./plugins/plugin-chart-word-cloud",
"@superset-ui/preset-chart-deckgl": "file:./plugins/preset-chart-deckgl",
"@superset-ui/switchboard": "file:./packages/superset-ui-switchboard",
+ "@tanstack/react-router": "^1.170.15",
"@types/d3-format": "^3.0.1",
"@types/d3-selection": "^3.0.11",
"@types/d3-time-format": "^4.0.3",
@@ -218,7 +219,6 @@
"react-redux": "^7.2.9",
"react-resize-detector": "^9.1.1",
"react-reverse-portal": "^2.3.0",
- "react-router-dom": "^5.3.4",
"react-search-input": "^0.11.3",
"react-split": "^2.0.9",
"react-table": "^7.8.0",
@@ -289,7 +289,6 @@
"@types/react-dom": "^18.2.0",
"@types/react-loadable": "^5.5.11",
"@types/react-redux": "^7.1.10",
- "@types/react-router-dom": "^5.3.3",
"@types/react-transition-group": "^4.4.12",
"@types/react-window": "^1.8.8",
"@types/redux-localstorage": "^1.0.8",
diff --git a/superset-frontend/spec/helpers/ProviderWrapper.tsx b/superset-frontend/spec/helpers/ProviderWrapper.tsx
index 74a90252363..dcdd3f49f73 100644
--- a/superset-frontend/spec/helpers/ProviderWrapper.tsx
+++ b/superset-frontend/spec/helpers/ProviderWrapper.tsx
@@ -19,18 +19,18 @@
import { ThemeProvider } from '@apache-superset/core/theme';
import querystring from 'query-string';
-import { BrowserRouter as Router } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
export function ProviderWrapper(props: any) {
const { children, theme } = props;
return (
<ThemeProvider theme={theme}>
- <Router>
+ <StandaloneRouter>
<QueryParamProvider
- adapter={ReactRouter5Adapter}
+ adapter={TanstackRouterAdapter}
options={{
searchStringToObject: querystring.parse,
objectToSearchString: (object: Record<string, any>) =>
@@ -39,7 +39,7 @@ export function ProviderWrapper(props: any) {
>
{children}
</QueryParamProvider>
- </Router>
+ </StandaloneRouter>
</ThemeProvider>
);
}
diff --git a/superset-frontend/spec/helpers/testing-library.tsx b/superset-frontend/spec/helpers/testing-library.tsx
index 71a77857cb4..c7ba73abded 100644
--- a/superset-frontend/spec/helpers/testing-library.tsx
+++ b/superset-frontend/spec/helpers/testing-library.tsx
@@ -33,14 +33,14 @@ import {
} from '@apache-superset/core/theme';
import { SupersetThemeProvider } from 'src/theme/ThemeProvider';
import { ThemeController } from 'src/theme/ThemeController';
-import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DndContext } from '@dnd-kit/core';
import reducerIndex from 'spec/helpers/reducerIndex';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import { configureStore, Store } from '@reduxjs/toolkit';
import { api } from 'src/hooks/apiResources/queryApi';
import userEvent from '@testing-library/user-event';
@@ -55,6 +55,8 @@ type Options = Omit<RenderOptions, 'queries'> & {
initialState?: {};
reducers?: {};
store?: Store;
+ /** Starting history entries for the test router (memory history). */
+ initialEntries?: string[];
};
const themeController = new ThemeController({ themeObject });
@@ -84,6 +86,7 @@ export function createWrapper(options?: Options) {
initialState,
reducers,
store,
+ initialEntries,
} = options || {};
return ({ children }: { children?: ReactNode }) => {
@@ -116,14 +119,18 @@ export function createWrapper(options?: Options) {
if (useQueryParams) {
result = (
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
{result}
</QueryParamProvider>
);
}
- if (useRouter) {
- result = <BrowserRouter>{result}</BrowserRouter>;
+ if (useRouter || useQueryParams || initialEntries) {
+ result = (
+ <StandaloneRouter initialEntries={initialEntries}>
+ {result}
+ </StandaloneRouter>
+ );
}
return result;
diff --git a/superset-frontend/src/SqlLab/components/App/index.tsx b/superset-frontend/src/SqlLab/components/App/index.tsx
index cec0c515666..eaa5062a2c2 100644
--- a/superset-frontend/src/SqlLab/components/App/index.tsx
+++ b/superset-frontend/src/SqlLab/components/App/index.tsx
@@ -18,7 +18,7 @@
*/
import { PureComponent } from 'react';
import { connect } from 'react-redux';
-import { Redirect } from 'react-router-dom';
+import { Navigate } from '@tanstack/react-router';
import Mousetrap from 'mousetrap';
import { t } from '@apache-superset/core/translation';
import { css, styled } from '@apache-superset/core/theme';
@@ -208,13 +208,7 @@ class App extends PureComponent<AppProps, AppState> {
render() {
const { queries, queriesLastUpdate } = this.props;
if (this.state.hash && this.state.hash === '#search') {
- return (
- <Redirect
- to={{
- pathname: '/sqllab/history/',
- }}
- />
- );
+ return <Navigate to="/sqllab/history/" replace />;
}
return (
<SqlLabStyles data-test="SqlLabApp" className="App SqlLab">
diff --git a/superset-frontend/src/SqlLab/components/PopEditorTab/PopEditorTab.test.tsx b/superset-frontend/src/SqlLab/components/PopEditorTab/PopEditorTab.test.tsx
index 1e94927fef5..49894ecece9 100644
--- a/superset-frontend/src/SqlLab/components/PopEditorTab/PopEditorTab.test.tsx
+++ b/superset-frontend/src/SqlLab/components/PopEditorTab/PopEditorTab.test.tsx
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { MemoryRouter } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import { render, waitFor } from 'spec/helpers/testing-library';
import fetchMock from 'fetch-mock';
import { initialState } from 'src/SqlLab/fixtures';
@@ -32,11 +32,11 @@ const setup = (
overridesInitialState?: RootState,
) =>
render(
- <MemoryRouter initialEntries={[url]}>
+ <StandaloneRouter initialEntries={[url]}>
<LocationProvider>
<PopEditorTab />
</LocationProvider>
- </MemoryRouter>,
+ </StandaloneRouter>,
{
useRedux: true,
initialState: overridesInitialState || initialState,
diff --git a/superset-frontend/src/SqlLab/components/ResultSet/index.tsx b/superset-frontend/src/SqlLab/components/ResultSet/index.tsx
index 310b8af58e7..8d2667eb69b 100644
--- a/superset-frontend/src/SqlLab/components/ResultSet/index.tsx
+++ b/superset-frontend/src/SqlLab/components/ResultSet/index.tsx
@@ -30,7 +30,8 @@ import {
import AutoSizer from 'react-virtualized-auto-sizer';
import { shallowEqual, useSelector } from 'react-redux';
import { useAppDispatch } from 'src/SqlLab/hooks/useAppDispatch';
-import { useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import { pick } from 'lodash';
import {
Button,
@@ -232,7 +233,7 @@ const ResultSet = ({
canExportDataSqlLab: canExportData,
canCopyClipboardSqlLab: canCopyClipboard,
} = usePermissions();
- const history = useHistory();
+ const router = useRouter();
const dispatch = useAppDispatch();
const logAction = useLogAction({ queryId, sqlEditorId: query.sqlEditorId });
const { showConfirm, ConfirmModal } = useConfirmModal();
@@ -314,7 +315,7 @@ const ResultSet = ({
if (openInNewWindow) {
window.open(url, '_blank', 'noreferrer');
} else {
- history.push(url);
+ pushAppHref(router, url);
}
} else {
addDangerToast(t('Unable to create chart without a query id.'));
diff --git a/superset-frontend/src/components/Chart/DrillBy/DrillByModal.tsx b/superset-frontend/src/components/Chart/DrillBy/DrillByModal.tsx
index 57149ee55e0..4f27e997391 100644
--- a/superset-frontend/src/components/Chart/DrillBy/DrillByModal.tsx
+++ b/superset-frontend/src/components/Chart/DrillBy/DrillByModal.tsx
@@ -32,7 +32,7 @@ import {
import { Alert } from '@apache-superset/core/components';
import { css, useTheme } from '@apache-superset/core/theme';
import { useDispatch, useSelector } from 'react-redux';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
import {
Button,
Modal,
@@ -78,7 +78,7 @@ const ModalFooter = ({ formData, closeModal }: ModalFooterProps) => {
const dispatch = useDispatch();
const { addDangerToast } = useToasts();
const theme = useTheme();
- const [url, setUrl] = useState('');
+ const [formDataKey, setFormDataKey] = useState('');
const dashboardPageId = useContext(DashboardPageIdContext);
const onEditChartClick = useCallback(() => {
dispatch(
@@ -97,9 +97,7 @@ const ModalFooter = ({ formData, closeModal }: ModalFooterProps) => {
if (isEmbedded()) return;
postFormData(Number(datasource_id), datasource_type, formData, 0)
.then(key => {
- setUrl(
- `/explore/?form_data_key=${key}&dashboard_page_id=${dashboardPageId}`,
- );
+ setFormDataKey(key);
})
.catch(() => {
addDangerToast(t('Failed to generate chart edit URL'));
@@ -111,7 +109,7 @@ const ModalFooter = ({ formData, closeModal }: ModalFooterProps) => {
datasource_type,
formData,
]);
- const isEditDisabled = !url || !canExplore;
+ const isEditDisabled = !formDataKey || !canExplore;
return (
<>
@@ -133,7 +131,11 @@ const ModalFooter = ({ formData, closeModal }: ModalFooterProps) => {
text-decoration: none;
}
`}
- to={url}
+ to="/explore/"
+ search={{
+ form_data_key: formDataKey,
+ dashboard_page_id: dashboardPageId,
+ }}
>
{t('Edit chart')}
</Link>
diff --git a/superset-frontend/src/components/Chart/DrillDetail/DrillDetailModal.test.tsx b/superset-frontend/src/components/Chart/DrillDetail/DrillDetailModal.test.tsx
index b63c7c2c866..800a10a20bc 100644
--- a/superset-frontend/src/components/Chart/DrillDetail/DrillDetailModal.test.tsx
+++ b/superset-frontend/src/components/Chart/DrillDetail/DrillDetailModal.test.tsx
@@ -25,10 +25,12 @@ import DrillDetailModal from './DrillDetailModal';
jest.mock('./DrillDetailPane', () => () => null);
const mockHistoryPush = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: () => ({
- push: mockHistoryPush,
+jest.mock('@tanstack/react-router', () => ({
+ ...jest.requireActual('@tanstack/react-router'),
+ useRouter: () => ({
+ history: {
+ push: mockHistoryPush,
+ },
}),
}));
diff --git a/superset-frontend/src/components/Chart/DrillDetail/DrillDetailModal.tsx b/superset-frontend/src/components/Chart/DrillDetail/DrillDetailModal.tsx
index fcf3d96f9df..6b340eb84ac 100644
--- a/superset-frontend/src/components/Chart/DrillDetail/DrillDetailModal.tsx
+++ b/superset-frontend/src/components/Chart/DrillDetail/DrillDetailModal.tsx
@@ -18,7 +18,8 @@
*/
import { useCallback, useContext, useMemo } from 'react';
-import { useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import { t } from '@apache-superset/core/translation';
import {
BinaryQueryObjectFilterClause,
@@ -98,7 +99,7 @@ export default function DrillDetailModal({
dataset,
}: DrillDetailModalProps) {
const theme = useTheme();
- const history = useHistory();
+ const router = useRouter();
const dashboardPageId = useContext(DashboardPageIdContext);
const { slice_name: chartName } = useSelector(
(state: { sliceEntities: { slices: Record<number, Slice> } }) =>
@@ -114,8 +115,8 @@ export default function DrillDetailModal({
);
const exploreChart = useCallback(() => {
- history.push(exploreUrl);
- }, [exploreUrl, history]);
+ pushAppHref(router, exploreUrl);
+ }, [exploreUrl, router]);
return (
<Modal
diff --git a/superset-frontend/src/components/GenericLink/index.tsx b/superset-frontend/src/components/GenericLink/index.tsx
index 474b174bfd5..70f5f27736e 100644
--- a/superset-frontend/src/components/GenericLink/index.tsx
+++ b/superset-frontend/src/components/GenericLink/index.tsx
@@ -17,32 +17,49 @@
* under the License.
*/
import { sanitizeUrl } from '@braintree/sanitize-url';
-import { PropsWithoutRef, RefAttributes } from 'react';
-import { Link, LinkProps } from 'react-router-dom';
+import { AnchorHTMLAttributes } from 'react';
+import { Link } from '@tanstack/react-router';
+import { parseSearch } from 'src/router/searchParams';
import { isUrlExternal, parseUrl } from 'src/utils/urlUtils';
-export const GenericLink = <S,>({
- to,
- component,
+export type GenericLinkProps = Omit<
+ AnchorHTMLAttributes<HTMLAnchorElement>,
+ 'href'
+> & {
+ to: string;
+ replace?: boolean;
+};
+
+export const GenericLink = ({
+ to: rawTo,
replace,
- innerRef,
children,
...rest
-}: PropsWithoutRef<LinkProps<S>> & RefAttributes<HTMLAnchorElement>) => {
- if (typeof to === 'string' && isUrlExternal(to)) {
+}: GenericLinkProps) => {
+ // Callers may pass undefined at runtime (e.g. backend rows without a URL).
+ const to = typeof rawTo === 'string' ? rawTo : '';
+ if (to && isUrlExternal(to)) {
return (
<a data-test="external-link" href={sanitizeUrl(parseUrl(to))} {...rest}>
{children}
</a>
);
}
+ const hashIndex = to.indexOf('#');
+ const hash = hashIndex === -1 ? undefined : to.slice(hashIndex + 1);
+ const withoutHash = hashIndex === -1 ? to : to.slice(0, hashIndex);
+ const searchIndex = withoutHash.indexOf('?');
+ const pathname =
+ searchIndex === -1 ? withoutHash : withoutHash.slice(0, searchIndex);
+ const searchStr =
+ searchIndex === -1 ? '' : withoutHash.slice(searchIndex + 1);
return (
<Link
data-test="internal-link"
- to={to}
- component={component}
+ to={pathname}
+ search={searchStr ? parseSearch(searchStr) : undefined}
+ hash={hash}
replace={replace}
- innerRef={innerRef}
{...rest}
>
{children}
diff --git a/superset-frontend/src/components/ListView/CrossLinks.tsx b/superset-frontend/src/components/ListView/CrossLinks.tsx
index 6f4cd6d262b..25d59a2753d 100644
--- a/superset-frontend/src/components/ListView/CrossLinks.tsx
+++ b/superset-frontend/src/components/ListView/CrossLinks.tsx
@@ -19,7 +19,7 @@
import { memo, useMemo } from 'react';
import { useTruncation } from '@superset-ui/core';
import { styled } from '@apache-superset/core/theme';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
import CrossLinksTooltip from './CrossLinksTooltip';
export type CrossLinkProps = {
diff --git a/superset-frontend/src/components/ListView/CrossLinksTooltip.tsx b/superset-frontend/src/components/ListView/CrossLinksTooltip.tsx
index 2f8517ca2fb..23adb0ddf20 100644
--- a/superset-frontend/src/components/ListView/CrossLinksTooltip.tsx
+++ b/superset-frontend/src/components/ListView/CrossLinksTooltip.tsx
@@ -19,7 +19,7 @@
import { ReactNode } from 'react';
import { t } from '@apache-superset/core/translation';
import { styled } from '@apache-superset/core/theme';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
import { Tooltip } from '@superset-ui/core/components';
export type CrossLinksTooltipProps = {
diff --git a/superset-frontend/src/components/ListView/ListView.test.tsx b/superset-frontend/src/components/ListView/ListView.test.tsx
index e2d0dec4bfc..159a3a97daf 100644
--- a/superset-frontend/src/components/ListView/ListView.test.tsx
+++ b/superset-frontend/src/components/ListView/ListView.test.tsx
@@ -19,8 +19,8 @@
import { render, screen, within, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
-import { MemoryRouter } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import { ReactNode } from 'react';
@@ -206,11 +206,11 @@ test('redirects to first page when page index is invalid', async () => {
const factory = (overrides?: Partial<ListViewProps>) => {
const props = { ...mockedPropsComprehensive, ...overrides };
return render(
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter initialEntries={['/']}>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<ListView {...props} />
</QueryParamProvider>
- </MemoryRouter>,
+ </StandaloneRouter>,
{ store: mockStore() },
);
};
diff --git a/superset-frontend/src/components/Tag/index.tsx b/superset-frontend/src/components/Tag/index.tsx
index d09334e175b..d09c06364be 100644
--- a/superset-frontend/src/components/Tag/index.tsx
+++ b/superset-frontend/src/components/Tag/index.tsx
@@ -18,7 +18,7 @@
*/
import { styled } from '@apache-superset/core/theme';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
import type { TagType } from 'src/types/TagType';
import { Tag as AntdTag } from '@superset-ui/core/components/Tag';
import { Tooltip } from '@superset-ui/core/components/Tooltip';
@@ -82,7 +82,8 @@ const SupersetTag = ({
{' '}
{id ? (
<Link
- to={`/superset/all_entities/?id=${id}`}
+ to="/superset/all_entities/"
+ search={{ id: String(id) }}
target="_blank"
rel="noreferrer"
>
diff --git a/superset-frontend/src/dashboard/actions/hydrate.ts b/superset-frontend/src/dashboard/actions/hydrate.ts
index f28803a0dec..2369639cecf 100644
--- a/superset-frontend/src/dashboard/actions/hydrate.ts
+++ b/superset-frontend/src/dashboard/actions/hydrate.ts
@@ -21,7 +21,7 @@ import { DataMaskStateWithId, JsonObject } from '@superset-ui/core';
import type { AnyAction } from 'redux';
import type { ThunkDispatch } from 'redux-thunk';
// eslint-disable-next-line import/no-extraneous-dependencies
-import type { History } from 'history';
+import type { RouterHistory } from '@tanstack/react-router';
import { chart } from 'src/components/Chart/chartReducer';
import { initSliceEntities } from 'src/dashboard/reducers/sliceEntities';
import { getInitialState as getInitialNativeFilterState } from 'src/dashboard/reducers/nativeFilters';
@@ -92,7 +92,7 @@ interface HydrateDashboardData extends Dashboard {
}
interface HydrateDashboardParams {
- history: History;
+ history: RouterHistory;
dashboard: HydrateDashboardData;
charts: HydrateChartData[];
dataMask: DataMaskStateWithId;
@@ -278,9 +278,10 @@ export const hydrateDashboard =
// Removes the focused_chart parameter from the URL
const params = new URLSearchParams(window.location.search);
params.delete(URL_PARAMS.dashboardFocusedChart.name);
- history.replace({
- search: params.toString(),
- });
+ const paramString = params.toString();
+ history.replace(
+ `${history.location.pathname}${paramString ? `?${paramString}` : ''}`,
+ );
}
// find direct link component and path from root
diff --git a/superset-frontend/src/dashboard/components/Header/Header.test.tsx b/superset-frontend/src/dashboard/components/Header/Header.test.tsx
index df0a4bc8799..8c150557e6c 100644
--- a/superset-frontend/src/dashboard/components/Header/Header.test.tsx
+++ b/superset-frontend/src/dashboard/components/Header/Header.test.tsx
@@ -32,14 +32,16 @@ import { UPDATE_COMPONENTS } from '../../actions/dashboardLayout';
import { AutoRefreshStatus } from '../../types/autoRefresh';
const mockHistoryReplace = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: () => ({
- replace: mockHistoryReplace,
+jest.mock('@tanstack/react-router', () => ({
+ ...jest.requireActual('@tanstack/react-router'),
+ useRouter: () => ({
+ history: {
+ replace: mockHistoryReplace,
+ },
}),
useLocation: jest.fn(() => ({
pathname: '/dashboard',
- search: '?standalone=1',
+ searchStr: 'standalone=1',
hash: '',
state: undefined,
})),
@@ -237,10 +239,10 @@ beforeAll(() => {
beforeEach(() => {
jest.clearAllMocks();
- const { useLocation } = jest.requireMock('react-router-dom');
+ const { useLocation } = jest.requireMock('@tanstack/react-router');
useLocation.mockReturnValue({
pathname: '/dashboard',
- search: '?standalone=1',
+ searchStr: 'standalone=1',
hash: '',
state: undefined,
});
@@ -1051,11 +1053,11 @@ test('should sync theme ref when navigating between dashboards', async () => {
});
test('should not duplicate subdirectory prefix when toggling fullscreen', async () => {
- const { useLocation } = jest.requireMock('react-router-dom');
+ const { useLocation } = jest.requireMock('@tanstack/react-router');
// Simulate React Router with basename=/pcs: useLocation returns path relative to basename
useLocation.mockReturnValue({
pathname: '/dashboard',
- search: '?standalone=1',
+ searchStr: 'standalone=1',
hash: '',
state: undefined,
});
@@ -1078,10 +1080,10 @@ test('should not duplicate subdirectory prefix when toggling fullscreen', async
});
test('should not duplicate subdirectory prefix when entering fullscreen', async () => {
- const { useLocation } = jest.requireMock('react-router-dom');
+ const { useLocation } = jest.requireMock('@tanstack/react-router');
useLocation.mockReturnValue({
pathname: '/dashboard',
- search: '',
+ searchStr: '',
hash: '',
state: undefined,
});
@@ -1100,11 +1102,11 @@ test('should not duplicate subdirectory prefix when entering fullscreen', async
});
test('share URL should use browser-absolute pathname to preserve subdirectory prefix', () => {
- const { useLocation } = jest.requireMock('react-router-dom');
+ const { useLocation } = jest.requireMock('@tanstack/react-router');
// Router returns path without the subdirectory prefix
useLocation.mockReturnValue({
pathname: '/dashboard',
- search: '',
+ searchStr: '',
hash: '',
state: undefined,
});
diff --git a/superset-frontend/src/dashboard/components/Header/useHeaderActionsDropdownMenu.tsx b/superset-frontend/src/dashboard/components/Header/useHeaderActionsDropdownMenu.tsx
index 102a0a70581..25b4b55e2c8 100644
--- a/superset-frontend/src/dashboard/components/Header/useHeaderActionsDropdownMenu.tsx
+++ b/superset-frontend/src/dashboard/components/Header/useHeaderActionsDropdownMenu.tsx
@@ -19,7 +19,8 @@
import type { Dispatch, ReactElement, SetStateAction } from 'react';
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useSelector } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
+import { useLocation, useRouter } from '@tanstack/react-router';
+import { replaceAppHref } from 'src/router/navigation';
import { Menu, MenuItem } from '@superset-ui/core/components/Menu';
import { t } from '@apache-superset/core/translation';
import { isEmpty } from 'lodash';
@@ -74,7 +75,7 @@ export const useHeaderActionsMenu = ({
] => {
const [isDropdownVisible, setIsDropdownVisible] = useState(false);
const { canExportImage } = usePermissions();
- const history = useHistory();
+ const router = useRouter();
const location = useLocation();
const directPathToChild = useSelector(
(state: RootState) => state.dashboardState.directPathToChild,
@@ -102,7 +103,7 @@ export const useHeaderActionsMenu = ({
case MenuKeys.ToggleFullscreen: {
const isCurrentlyStandalone =
Number(getUrlParam(URL_PARAMS.standalone)) === 1;
- // Use location.pathname from React Router (relative to basename) rather than
+ // Use location.pathname from the router (relative to basepath) rather than
// window.location.pathname to avoid duplicating the subdirectory prefix when
// history.replace prepends it again.
const url = getDashboardUrl({
@@ -111,7 +112,7 @@ export const useHeaderActionsMenu = ({
hash: window.location.hash,
standalone: isCurrentlyStandalone ? null : 1,
});
- history.replace(url);
+ replaceAppHref(router, url);
break;
}
case MenuKeys.ManageEmbedded:
@@ -128,7 +129,7 @@ export const useHeaderActionsMenu = ({
showPropertiesModal,
showRefreshModal,
manageEmbedded,
- history,
+ router,
location,
],
);
diff --git a/superset-frontend/src/dashboard/components/SliceHeader/SliceHeader.test.tsx b/superset-frontend/src/dashboard/components/SliceHeader/SliceHeader.test.tsx
index 58150a2c48b..d48cda58efa 100644
--- a/superset-frontend/src/dashboard/components/SliceHeader/SliceHeader.test.tsx
+++ b/superset-frontend/src/dashboard/components/SliceHeader/SliceHeader.test.tsx
@@ -16,10 +16,15 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { Router } from 'react-router-dom';
-import { createMemoryHistory } from 'history';
+import { createMemoryHistory } from '@tanstack/react-router';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import { getExtensionsRegistry, VizType } from '@superset-ui/core';
-import { render, screen, userEvent } from 'spec/helpers/testing-library';
+import {
+ render,
+ screen,
+ userEvent,
+ waitFor,
+} from 'spec/helpers/testing-library';
import { isEmbedded } from 'src/dashboard/util/isEmbedded';
import { useUiConfig } from 'src/components/UiConfigContext';
import SliceHeader from '.';
@@ -283,12 +288,12 @@ test('Should render click to edit prompt and run onExploreChart on click', async
initialEntries: ['/superset/dashboard/1/'],
});
render(
- <Router history={history}>
+ <StandaloneRouter history={history}>
<SliceHeader {...props} />
- </Router>,
+ </StandaloneRouter>,
{ useRedux: true, initialState },
);
- userEvent.hover(screen.getByText('Vaccine Candidates per Phase'));
+ userEvent.hover(await screen.findByText('Vaccine Candidates per Phase'));
expect(
await screen.findByText('Click to edit Vaccine Candidates per Phase.'),
).toBeInTheDocument();
@@ -297,7 +302,8 @@ test('Should render click to edit prompt and run onExploreChart on click', async
).toBeInTheDocument();
userEvent.click(screen.getByText('Vaccine Candidates per Phase'));
- expect(history.location.pathname).toMatch('/explore');
+ // TanStack router commits navigation asynchronously.
+ await waitFor(() => expect(history.location.pathname).toMatch('/explore'));
});
test('Display cmd button in tooltip if running on MacOS', async () => {
@@ -317,18 +323,18 @@ test('Display cmd button in tooltip if running on MacOS', async () => {
).toBeInTheDocument();
});
-test('Should not render click to edit prompt and run onExploreChart on click if supersetCanExplore=false', () => {
+test('Should not render click to edit prompt and run onExploreChart on click if supersetCanExplore=false', async () => {
const props = createProps({ supersetCanExplore: false });
const history = createMemoryHistory({
initialEntries: ['/superset/dashboard/1/'],
});
render(
- <Router history={history}>
+ <StandaloneRouter history={history}>
<SliceHeader {...props} />
- </Router>,
+ </StandaloneRouter>,
{ useRedux: true, initialState },
);
- userEvent.hover(screen.getByText('Vaccine Candidates per Phase'));
+ userEvent.hover(await screen.findByText('Vaccine Candidates per Phase'));
expect(
screen.queryByText(
'Click to edit Vaccine Candidates per Phase in a new tab',
@@ -339,18 +345,18 @@ test('Should not render click to edit prompt and run onExploreChart on click if
expect(history.location.pathname).toMatch('/superset/dashboard');
});
-test('Should not render click to edit prompt and run onExploreChart on click if in edit mode', () => {
+test('Should not render click to edit prompt and run onExploreChart on click if in edit mode', async () => {
const props = createProps({ editMode: true });
const history = createMemoryHistory({
initialEntries: ['/superset/dashboard/1/'],
});
render(
- <Router history={history}>
+ <StandaloneRouter history={history}>
<SliceHeader {...props} />
- </Router>,
+ </StandaloneRouter>,
{ useRedux: true, initialState },
);
- userEvent.hover(screen.getByText('Vaccine Candidates per Phase'));
+ userEvent.hover(await screen.findByText('Vaccine Candidates per Phase'));
expect(
screen.queryByText(
'Click to edit Vaccine Candidates per Phase in a new tab',
diff --git a/superset-frontend/src/dashboard/components/SliceHeader/index.tsx b/superset-frontend/src/dashboard/components/SliceHeader/index.tsx
index fe06ca461f1..b840577266f 100644
--- a/superset-frontend/src/dashboard/components/SliceHeader/index.tsx
+++ b/superset-frontend/src/dashboard/components/SliceHeader/index.tsx
@@ -45,7 +45,7 @@ import { RootState } from 'src/dashboard/types';
import { getSliceHeaderTooltip } from 'src/dashboard/util/getSliceHeaderTooltip';
import { DashboardPageIdContext } from 'src/dashboard/containers/DashboardPage';
import RowCountLabel from 'src/components/RowCountLabel';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
const extensionsRegistry = getExtensionsRegistry();
@@ -245,7 +245,11 @@ const SliceHeader = forwardRef<HTMLDivElement, SliceHeaderProps>(
const renderExploreLink = (title: string) => (
<Link
- to={exploreUrl}
+ to="/explore/"
+ search={{
+ dashboard_page_id: dashboardPageId,
+ slice_id: String(slice.slice_id),
+ }}
css={(theme: SupersetTheme) => css`
color: ${theme.colorText};
text-decoration: none;
diff --git a/superset-frontend/src/dashboard/components/SliceHeaderControls/ViewResultsModalTrigger.tsx b/superset-frontend/src/dashboard/components/SliceHeaderControls/ViewResultsModalTrigger.tsx
index c9c9845cc5a..252e4462ad0 100644
--- a/superset-frontend/src/dashboard/components/SliceHeaderControls/ViewResultsModalTrigger.tsx
+++ b/superset-frontend/src/dashboard/components/SliceHeaderControls/ViewResultsModalTrigger.tsx
@@ -17,7 +17,8 @@
* under the License.
*/
import { ReactChild, RefObject, useCallback } from 'react';
-import { useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import { t } from '@apache-superset/core/translation';
import { css, useTheme } from '@apache-superset/core/theme';
import { Button, ModalTrigger } from '@superset-ui/core/components';
@@ -37,8 +38,9 @@ export const ViewResultsModalTrigger = ({
modalBody: ReactChild;
modalRef?: RefObject<any>;
}) => {
- const history = useHistory();
- const exploreChart = () => history.push(exploreUrl);
+ const router = useRouter();
+ // exploreUrl carries a query string; raw history push preserves it.
+ const exploreChart = () => pushAppHref(router, exploreUrl);
const theme = useTheme();
const handleCloseModal = useCallback(() => {
modalRef?.current?.close();
diff --git a/superset-frontend/src/dashboard/components/SliceHeaderControls/index.tsx b/superset-frontend/src/dashboard/components/SliceHeaderControls/index.tsx
index 508b83c0bc1..0f9967bc2aa 100644
--- a/superset-frontend/src/dashboard/components/SliceHeaderControls/index.tsx
+++ b/superset-frontend/src/dashboard/components/SliceHeaderControls/index.tsx
@@ -26,7 +26,8 @@ import {
RefObject,
} from 'react';
-import { RouteComponentProps, useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import { extendedDayjs } from '@superset-ui/core/utils/dates';
import { t } from '@apache-superset/core/translation';
import {
@@ -144,8 +145,7 @@ export interface SliceHeaderControlsProps {
crossFiltersEnabled?: boolean;
}
-type SliceHeaderControlsPropsWithRouter = SliceHeaderControlsProps &
- RouteComponentProps;
+type SliceHeaderControlsPropsWithRouter = SliceHeaderControlsProps;
const dropdownIconsStyles = css`
&&.anticon > .anticon:first-of-type {
@@ -169,7 +169,7 @@ const SliceHeaderControls = (
const [openScopingModal, scopingModal] = useCrossFiltersScopingModal(
props.slice.slice_id,
);
- const history = useHistory();
+ const router = useRouter();
const queryMenuRef: RefObject<any> = useRef(null);
const resultsMenuRef: RefObject<any> = useRef(null);
@@ -265,7 +265,8 @@ const SliceHeaderControls = (
domEvent.preventDefault();
window.open(props.exploreUrl, '_blank');
} else {
- history.push(props.exploreUrl);
+ // exploreUrl carries a query string; raw history push preserves it.
+ pushAppHref(router, props.exploreUrl);
}
break;
case MenuKeys.ExportCsv:
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/Horizontal.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/Horizontal.tsx
index 0d4d4edf9ee..af607182ba2 100644
--- a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/Horizontal.tsx
+++ b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/Horizontal.tsx
@@ -30,7 +30,7 @@ import { FilterBarOrientation, RootState } from 'src/dashboard/types';
import { useChartLayoutItems } from 'src/dashboard/util/useChartLayoutItems';
import { useChartIds } from 'src/dashboard/util/charts/useChartIds';
import { useDispatch, useSelector } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
+import { useLocation, useRouter } from '@tanstack/react-router';
import { removeDataMask, updateDataMask } from 'src/dataMask/actions';
import {
getRisonFilterParam,
@@ -121,8 +121,8 @@ const HorizontalFilterBar: FC<HorizontalBarProps> = ({
state => state.dataMask,
);
const dispatch = useDispatch();
- const history = useHistory();
- const location = useLocation();
+ const router = useRouter();
+ const searchStr = useLocation({ select: location => location.searchStr });
const chartIds = useChartIds();
const chartLayoutItems = useChartLayoutItems();
const verboseMaps = useChartsVerboseMaps();
@@ -146,7 +146,7 @@ const HorizontalFilterBar: FC<HorizontalBarProps> = ({
// programmatic history.replace).
useEffect(() => {
setActiveUrlFilters(getUrlFilterIndicators());
- }, [location.search]);
+ }, [searchStr]);
const handleRemoveUrlFilter = useCallback(
(filterToRemove: UrlFilterIndicator) => {
@@ -158,7 +158,7 @@ const HorizontalFilterBar: FC<HorizontalBarProps> = ({
const remaining = currentFilters.filter(
f => getUrlFilterIdentity(f) !== removeId,
);
- updateUrlWithUnmatchedFilters(remaining, history);
+ updateUrlWithUnmatchedFilters(remaining, router.history);
setActiveUrlFilters(prev =>
prev.filter(f => getUrlFilterIdentity(f.filter) !== removeId),
);
@@ -175,7 +175,7 @@ const HorizontalFilterBar: FC<HorizontalBarProps> = ({
);
}
},
- [dispatch, history],
+ [dispatch, router],
);
const urlFiltersComponent = useMemo(() => {
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/UrlFilters/Vertical.test.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/UrlFilters/Vertical.test.tsx
index 6e75d7c5090..bc75a95df4f 100644
--- a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/UrlFilters/Vertical.test.tsx
+++ b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/UrlFilters/Vertical.test.tsx
@@ -24,9 +24,15 @@
* - the chip list must react to URL changes (back/forward navigation or
* a programmatic history.replace), not snapshot the URL at mount.
*/
-import { createMemoryHistory } from 'history';
-import { Router } from 'react-router-dom';
-import { act, render, screen, userEvent } from 'spec/helpers/testing-library';
+import { createMemoryHistory } from '@tanstack/react-router';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import {
+ act,
+ render,
+ screen,
+ userEvent,
+ waitFor,
+} from 'spec/helpers/testing-library';
import { REMOVE_DATA_MASK, UPDATE_DATA_MASK } from 'src/dataMask/actions';
import { RISON_UNMATCHED_DATAMASK_ID } from 'src/dashboard/util/risonFilters';
import UrlFiltersVertical from './Vertical';
@@ -39,7 +45,7 @@ jest.mock('react-redux', () => ({
const seedUrl = (search: string) => {
// jsdom doesn't navigate, so set both window.location (read by
- // getRisonFilterParam) and react-router's in-memory history.
+ // getRisonFilterParam) and the router's in-memory history.
window.history.replaceState({}, '', `/superset/dashboard/1/${search}`);
};
@@ -49,9 +55,9 @@ const renderAt = (search: string) => {
initialEntries: [`/superset/dashboard/1/${search}`],
});
const utils = render(
- <Router history={history}>
+ <StandaloneRouter history={history}>
<UrlFiltersVertical />
- </Router>,
+ </StandaloneRouter>,
{ useRedux: true },
);
return { ...utils, history };
@@ -120,7 +126,7 @@ test('removing the last chip dispatches removeDataMask, not an empty update', as
expect(updateCalls).toHaveLength(0);
});
-test('chip list re-renders when the URL changes (popstate/programmatic nav)', () => {
+test('chip list re-renders when the URL changes (popstate/programmatic nav)', async () => {
const { history } = renderAt('?f=(region:EMEA)');
expect(screen.getByText('region')).toBeInTheDocument();
@@ -133,7 +139,8 @@ test('chip list re-renders when the URL changes (popstate/programmatic nav)', ()
history.replace('/superset/dashboard/1/?f=(priority:high)');
});
- expect(screen.getByText('priority')).toBeInTheDocument();
+ // The router commits location updates asynchronously.
+ await waitFor(() => expect(screen.getByText('priority')).toBeInTheDocument());
expect(screen.getByText('high')).toBeInTheDocument();
expect(screen.queryByText('region')).not.toBeInTheDocument();
});
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/UrlFilters/Vertical.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/UrlFilters/Vertical.tsx
index 1c62b1cbb48..c28101c527a 100644
--- a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/UrlFilters/Vertical.tsx
+++ b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/UrlFilters/Vertical.tsx
@@ -19,7 +19,7 @@
import { useCallback, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
-import { useHistory, useLocation } from 'react-router-dom';
+import { useLocation, useRouter } from '@tanstack/react-router';
import { QueryObjectFilterClause } from '@superset-ui/core';
import { removeDataMask, updateDataMask } from 'src/dataMask/actions';
import {
@@ -38,8 +38,8 @@ import UrlFiltersVerticalCollapse from './VerticalCollapse';
const UrlFiltersVertical = () => {
const dispatch = useDispatch();
- const history = useHistory();
- const location = useLocation();
+ const router = useRouter();
+ const searchStr = useLocation({ select: location => location.searchStr });
const [urlFilters, setUrlFilters] = useState<UrlFilterIndicator[]>(() =>
getUrlFilterIndicators(),
);
@@ -48,7 +48,7 @@ const UrlFiltersVertical = () => {
// programmatic history.replace).
useEffect(() => {
setUrlFilters(getUrlFilterIndicators());
- }, [location.search]);
+ }, [searchStr]);
const handleRemoveFilter = useCallback(
(filterToRemove: UrlFilterIndicator) => {
@@ -61,7 +61,7 @@ const UrlFiltersVertical = () => {
f => getUrlFilterIdentity(f) !== removeId,
);
- updateUrlWithUnmatchedFilters(remaining, history);
+ updateUrlWithUnmatchedFilters(remaining, router.history);
setUrlFilters(prev =>
prev.filter(f => getUrlFilterIdentity(f.filter) !== removeId),
);
@@ -78,7 +78,7 @@ const UrlFiltersVertical = () => {
);
}
},
- [dispatch, history],
+ [dispatch, router],
);
if (!urlFilters.length) {
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/index.tsx b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/index.tsx
index 9fb1b004d82..eeb1a6732dc 100644
--- a/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/index.tsx
+++ b/superset-frontend/src/dashboard/components/nativeFilters/FilterBar/index.tsx
@@ -43,7 +43,7 @@ import {
} from '@superset-ui/core';
import { styled } from '@apache-superset/core/theme';
import { Constants } from '@superset-ui/core/components';
-import { useHistory } from 'react-router-dom';
+import { useRouter, type RouterHistory } from '@tanstack/react-router';
import { updateDataMask, removeDataMask } from 'src/dataMask/actions';
import {
saveChartCustomization,
@@ -55,7 +55,6 @@ import { useImmer } from 'use-immer';
import { isEmpty, isEqual, debounce } from 'lodash';
import { getInitialDataMask } from 'src/dataMask/reducer';
import { URL_PARAMS } from 'src/constants';
-import { applicationRoot } from 'src/utils/getBootstrapData';
import { getUrlParam } from 'src/utils/urlUtils';
import { useTabId } from 'src/hooks/useTabId';
import { logEvent } from 'src/logger/actions';
@@ -96,7 +95,7 @@ const EMPTY_DATA_MASK_RECORD: Record<string, DataMask> = {};
const publishDataMask = debounce(
async (
- history,
+ history: RouterHistory,
dashboardId,
updateKey,
dataMaskSelected: DataMaskStateWithId,
@@ -145,15 +144,10 @@ const publishDataMask = debounce(
// replace params only when current page is /superset/dashboard
// this prevents a race condition between updating filters and navigating to Explore
if (window.location.pathname.includes('/superset/dashboard')) {
- // The history API is part of React router and understands that a basename may exist.
- // Internally it treats all paths as if they are relative to the root and appends
- // it when necessary. We strip any prefix so that history.replace adds it back and doesn't
- // double it up.
- const appRoot = applicationRoot();
- let replacementPathname = window.location.pathname;
- if (appRoot !== '/' && replacementPathname.startsWith(appRoot)) {
- replacementPathname = replacementPathname.substring(appRoot.length);
- }
+ // The router's history is the raw browser history (no basepath
+ // handling), so the full window pathname — application root
+ // included — is replaced verbatim.
+ const replacementPathname = window.location.pathname;
// Manually reconstruct the search string to preserve Rison filter encoding
let searchString = newParams.toString();
if (rawRisonFilterValue) {
@@ -161,10 +155,9 @@ const publishDataMask = debounce(
searchString = `${searchString}${separator}f=${rawRisonFilterValue}`;
}
- history.replace({
- pathname: replacementPathname,
- search: searchString,
- });
+ history.replace(
+ `${replacementPathname}${searchString ? `?${searchString}` : ''}`,
+ );
}
},
Constants.SLOW_DEBOUNCE,
@@ -175,7 +168,7 @@ const FilterBar: FC<FiltersBarProps> = ({
verticalConfig,
hidden = false,
}) => {
- const history = useHistory();
+ const router = useRouter();
const dataMaskApplied: DataMaskStateWithId = useAllAppliedDataMask();
const [dataMaskSelected, setDataMaskSelected] =
@@ -406,10 +399,16 @@ const FilterBar: FC<FiltersBarProps> = ({
useEffect(() => {
// embedded users can't persist filter combinations
if (user?.userId) {
- publishDataMask(history, dashboardId, updateKey, dataMaskApplied, tabId);
+ publishDataMask(
+ router.history,
+ dashboardId,
+ updateKey,
+ dataMaskApplied,
+ tabId,
+ );
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [dashboardId, dataMaskAppliedText, history, updateKey, tabId]);
+ }, [dashboardId, dataMaskAppliedText, router, updateKey, tabId]);
const pendingChartCustomizations = useSelector<
RootState,
diff --git a/superset-frontend/src/dashboard/containers/DashboardPage.tsx b/superset-frontend/src/dashboard/containers/DashboardPage.tsx
index ae86ec63c0a..7b3bf892b3c 100644
--- a/superset-frontend/src/dashboard/containers/DashboardPage.tsx
+++ b/superset-frontend/src/dashboard/containers/DashboardPage.tsx
@@ -18,7 +18,7 @@
*/
import { createContext, lazy, FC, useEffect, useMemo, useRef } from 'react';
import { Global } from '@emotion/react';
-import { useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
import { t } from '@apache-superset/core/translation';
import { useTheme } from '@apache-superset/core/theme';
import { useDispatch, useSelector } from 'react-redux';
@@ -128,7 +128,7 @@ const selectActiveFilters = createSelector(
export const DashboardPage: FC<PageProps> = ({ idOrSlug }: PageProps) => {
const theme = useTheme();
const dispatch = useDispatch();
- const history = useHistory();
+ const router = useRouter();
const dashboardPageId = useMemo(() => nanoid(), []);
const hasDashboardInfoInitiated = useSelector<RootState, boolean>(
({ dashboardInfo }) =>
@@ -267,14 +267,14 @@ export const DashboardPage: FC<PageProps> = ({ idOrSlug }: PageProps) => {
// Rewrite the URL to drop matched filters in a single step, keeping
// only unmatched ones (and prettifying their encoding). Going
- // through react-router's history keeps `history.location.search` in
+ // through the router's history keeps its location.search in
// sync so `publishDataMask` doesn't re-emit the original `f=`.
const matchedCount =
risonFilters.length - injectionResult.unmatchedFilters.length;
if (matchedCount > 0) {
updateUrlWithUnmatchedFilters(
injectionResult.unmatchedFilters,
- history,
+ router.history,
);
}
if (injectionResult.unmatchedFilters.length > 0) {
@@ -289,7 +289,7 @@ export const DashboardPage: FC<PageProps> = ({ idOrSlug }: PageProps) => {
}
dispatch(
hydrateDashboard({
- history,
+ history: router.history,
dashboard: dashboard!,
charts: charts!,
activeTabs: activeTabs ?? null,
diff --git a/superset-frontend/src/dashboard/util/risonFilters.test.ts b/superset-frontend/src/dashboard/util/risonFilters.test.ts
index 258069a00ab..8440f272a2c 100644
--- a/superset-frontend/src/dashboard/util/risonFilters.test.ts
+++ b/superset-frontend/src/dashboard/util/risonFilters.test.ts
@@ -353,10 +353,10 @@ test('updateUrlWithUnmatchedFilters goes through history when supplied', () => {
);
expect(replace).toHaveBeenCalledTimes(1);
- const call = replace.mock.calls[0][0];
- expect(call.pathname).toBe('/superset/dashboard/1/');
- expect(call.search).toContain('f=');
- expect(call.search).toContain('region');
+ const href = replace.mock.calls[0][0];
+ expect(href).toMatch(/^\/superset\/dashboard\/1\/\?/);
+ expect(href).toContain('f=');
+ expect(href).toContain('region');
// Restore.
window.history.replaceState({}, '', originalLocation);
@@ -370,7 +370,7 @@ test('updateUrlWithUnmatchedFilters drops f= when no unmatched remain', () => {
updateUrlWithUnmatchedFilters([], { replace });
expect(replace).toHaveBeenCalledTimes(1);
- expect(replace.mock.calls[0][0].search).toBe('');
+ expect(replace.mock.calls[0][0]).toBe('/superset/dashboard/1/');
window.history.replaceState({}, '', originalLocation);
});
@@ -382,16 +382,20 @@ test('updateUrlWithUnmatchedFilters cleanup is observable by history readers', (
// history.location.search stale, causing publishDataMask to re-append
// the original f= on the next interaction.
//
- // Stand in for react-router's history with a fake whose `.location`
+ // Stand in for the router's history with a fake whose `.location`
// updates synchronously when .replace is called — same contract as
- // react-router-dom's history.replace.
+ // the router history's replace.
const fakeHistory = {
location: {
pathname: '/superset/dashboard/1/',
search: '?f=(country:USA)',
},
- replace(next: { pathname: string; search: string }) {
- this.location = next;
+ replace(href: string) {
+ const [pathname, search = ''] = href.split('?');
+ this.location = {
+ pathname,
+ search: search ? `?${search}` : '',
+ };
},
};
const originalLocation = window.location.href;
diff --git a/superset-frontend/src/dashboard/util/risonFilters.ts b/superset-frontend/src/dashboard/util/risonFilters.ts
index d9b4ead12a0..d4ca8551512 100644
--- a/superset-frontend/src/dashboard/util/risonFilters.ts
+++ b/superset-frontend/src/dashboard/util/risonFilters.ts
@@ -318,15 +318,15 @@ export function risonFiltersToString(filters: RisonFilter[]): string {
}
interface ReplaceHistory {
- replace(location: { pathname: string; search: string }): void;
+ replace(href: string): void;
}
/**
* Update the URL to remove successfully matched filters, keeping only unmatched ones.
- * When a react-router history is supplied, the update goes through it so that
- * components reading from `history.location` (e.g. `publishDataMask` in the
- * filter bar) see the new search string. Otherwise falls back to a raw
- * `window.history.replaceState`.
+ * When a router history is supplied (e.g. `useRouter().history`), the update
+ * goes through it so that components reading the router location (e.g.
+ * `publishDataMask` in the filter bar) see the new search string. Otherwise
+ * falls back to a raw `window.history.replaceState`.
*/
export function updateUrlWithUnmatchedFilters(
unmatchedFilters: RisonFilter[],
@@ -358,10 +358,7 @@ export function updateUrlWithUnmatchedFilters(
currentUrl.toString(),
);
if (history) {
- history.replace({
- pathname: currentUrl.pathname,
- search: currentUrl.search,
- });
+ history.replace(`${currentUrl.pathname}${currentUrl.search}`);
}
} catch (error) {
console.warn('Failed to update URL with unmatched filters:', error);
diff --git a/superset-frontend/src/embedded/index.tsx b/superset-frontend/src/embedded/index.tsx
index b0a09f81645..16a0579e19c 100644
--- a/superset-frontend/src/embedded/index.tsx
+++ b/superset-frontend/src/embedded/index.tsx
@@ -20,7 +20,13 @@ import 'src/public-path';
import { lazy, Suspense, useEffect } from 'react';
import { createRoot, type Root } from 'react-dom/client';
-import { BrowserRouter as Router, Route } from 'react-router-dom';
+import {
+ createRootRoute,
+ createRoute,
+ createRouter,
+ RouterProvider,
+} from '@tanstack/react-router';
+import { parseSearch, stringifySearch } from 'src/router/searchParams';
import { Global } from '@emotion/react';
import { t } from '@apache-superset/core/translation';
import { makeApi } from '@superset-ui/core';
@@ -116,13 +122,29 @@ const EmbeddedRoute = () => (
</EmbeddedContextProviders>
);
-const EmbeddedApp = () => (
- <Router basename={applicationRoot()}>
- {/* todo (embedded) remove this line after uuids are deployed */}
- <Route path="/dashboard/:idOrSlug/embedded/" component={EmbeddedRoute} />
- <Route path="/embedded/:uuid/" component={EmbeddedRoute} />
- </Router>
-);
+const embeddedRootRoute = createRootRoute();
+const embeddedRouter = createRouter({
+ routeTree: embeddedRootRoute.addChildren([
+ // todo (embedded) remove this route after uuids are deployed
+ createRoute({
+ getParentRoute: () => embeddedRootRoute,
+ path: '/dashboard/$idOrSlug/embedded',
+ component: EmbeddedRoute,
+ }),
+ createRoute({
+ getParentRoute: () => embeddedRootRoute,
+ path: '/embedded/$uuid',
+ component: EmbeddedRoute,
+ }),
+ ]),
+ basepath: applicationRoot() || undefined,
+ parseSearch,
+ stringifySearch,
+ trailingSlash: 'preserve',
+ defaultPreload: false,
+});
+
+const EmbeddedApp = () => <RouterProvider router={embeddedRouter} />;
const appMountPoint = document.getElementById('app')!;
diff --git a/superset-frontend/src/explore/components/ExploreChartHeader/index.tsx b/superset-frontend/src/explore/components/ExploreChartHeader/index.tsx
index 78e4d01af22..ee6a1044a2b 100644
--- a/superset-frontend/src/explore/components/ExploreChartHeader/index.tsx
+++ b/superset-frontend/src/explore/components/ExploreChartHeader/index.tsx
@@ -17,7 +17,7 @@
* under the License.
*/
import { FC, memo, useCallback, useEffect, useMemo, useState } from 'react';
-import { useHistory } from 'react-router-dom';
+import { useRouter, type RouterHistory } from '@tanstack/react-router';
import { useDispatch } from 'react-redux';
import { QueryFormData, JsonObject } from '@superset-ui/core';
import {
@@ -60,7 +60,7 @@ interface ExploreActions {
saveFaveStar: (sliceId: number, isStarred: boolean) => void;
redirectSQLLab: (
formData: QueryFormData,
- history?: ReturnType<typeof useHistory> | false,
+ history?: RouterHistory | false,
) => void;
}
@@ -187,14 +187,14 @@ const ExploreChartHeader: FC<ExploreChartHeaderProps> = ({
setCurrentReportDeleting(null);
};
- const history = useHistory();
+ const router = useRouter();
const { redirectSQLLab } = actions;
const redirectToSQLLab = useCallback(
(redirectFormData: QueryFormData, openNewWindow = false) => {
- redirectSQLLab(redirectFormData, !openNewWindow && history);
+ redirectSQLLab(redirectFormData, !openNewWindow && router.history);
},
- [redirectSQLLab, history],
+ [redirectSQLLab, router],
);
const [menu, isDropdownVisible, setIsDropdownVisible, streamingExportState] =
diff --git a/superset-frontend/src/explore/components/ExploreViewContainer/ExploreViewContainer.test.tsx b/superset-frontend/src/explore/components/ExploreViewContainer/ExploreViewContainer.test.tsx
index 349b085dba1..8def1eb76a9 100644
--- a/superset-frontend/src/explore/components/ExploreViewContainer/ExploreViewContainer.test.tsx
+++ b/superset-frontend/src/explore/components/ExploreViewContainer/ExploreViewContainer.test.tsx
@@ -26,8 +26,10 @@ import {
VizType,
} from '@superset-ui/core';
import { QUERY_MODE_REQUISITES } from 'src/explore/constants';
-import { Router, Route } from 'react-router-dom';
-import { createMemoryHistory } from 'history';
+import {
+ createMemoryHistory,
+ type RouterHistory,
+} from '@tanstack/react-router';
import {
render,
screen,
@@ -40,6 +42,17 @@ import reducerIndex from 'spec/helpers/reducerIndex';
import * as exploreActions from 'src/explore/actions/exploreActions';
import ExploreViewContainer from '.';
+// The component syncs the explore URL through `useRouter().history`;
+// back it with a spy-able in-memory history per test.
+let mockRouterHistory: RouterHistory | undefined;
+
+jest.mock('@tanstack/react-router', () => ({
+ ...jest.requireActual('@tanstack/react-router'),
+ useRouter: () => ({
+ history: mockRouterHistory,
+ }),
+}));
+
jest.doMock('@superset-ui/core', () => ({
__esModule: true,
...jest.requireActual('@superset-ui/core'),
@@ -136,7 +149,7 @@ const renderWithRouter = ({
overridePathname?: string;
initialState?: object;
store?: Store;
- history?: ReturnType<typeof createMemoryHistory>;
+ history?: RouterHistory;
} = {}) => {
const path = overridePathname ?? defaultPath;
jest.spyOn(window, 'location', 'get').mockReturnValue({
@@ -146,14 +159,15 @@ const renderWithRouter = ({
const history =
existingHistory ??
createMemoryHistory({ initialEntries: [`${path}${search}`] });
- const result = render(
- <Router history={history}>
- <Route path={path}>
- <ExploreViewContainer />
- </Route>
- </Router>,
- { useRedux: true, useDnd: true, initialState, store },
- );
+ mockRouterHistory = history;
+ const result = render(<ExploreViewContainer />, {
+ useRedux: true,
+ useDnd: true,
+ initialState,
+ store,
+ useRouter: true,
+ initialEntries: [`${path}${search}`],
+ });
return { ...result, history };
};
diff --git a/superset-frontend/src/explore/components/ExploreViewContainer/index.tsx b/superset-frontend/src/explore/components/ExploreViewContainer/index.tsx
index baa5b947314..a375885be6e 100644
--- a/superset-frontend/src/explore/components/ExploreViewContainer/index.tsx
+++ b/superset-frontend/src/explore/components/ExploreViewContainer/index.tsx
@@ -47,7 +47,7 @@ import { t } from '@apache-superset/core/translation';
import { logging } from '@apache-superset/core/utils';
import { debounce, isEqual, isObjectLike, omit, pick } from 'lodash';
import { Resizable } from 're-resizable';
-import { useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
import { Tooltip } from '@superset-ui/core/components';
import { usePluginContext } from 'src/components';
import { Global } from '@emotion/react';
@@ -387,7 +387,7 @@ function ExploreViewContainer(props: ExploreViewContainerProps) {
getSidebarWidths(LocalStorageKeys.DatasourceWidth),
);
const tabId = useTabId();
- const history = useHistory();
+ const router = useRouter();
const theme = useTheme();
@@ -477,7 +477,7 @@ function ExploreViewContainer(props: ExploreViewContainerProps) {
props.force,
title,
tabId,
- history,
+ router.history,
);
},
[
@@ -488,7 +488,7 @@ function ExploreViewContainer(props: ExploreViewContainerProps) {
props.standalone,
props.force,
tabId,
- history,
+ router,
],
);
diff --git a/superset-frontend/src/explore/components/SaveModal.tsx b/superset-frontend/src/explore/components/SaveModal.tsx
index ec169671271..1467f034974 100755
--- a/superset-frontend/src/explore/components/SaveModal.tsx
+++ b/superset-frontend/src/explore/components/SaveModal.tsx
@@ -17,12 +17,12 @@
* under the License.
*/
/* eslint camelcase: 0 */
-import { ChangeEvent, FormEvent, Component } from 'react';
+import { ChangeEvent, ComponentProps, FormEvent, Component } from 'react';
import { Dispatch } from 'redux';
import { nanoid } from 'nanoid';
import rison from 'rison';
import { connect } from 'react-redux';
-import { withRouter, RouteComponentProps } from 'react-router-dom';
+import { useRouter, type RouterHistory } from '@tanstack/react-router';
import {
InfoTooltip,
Button,
@@ -64,7 +64,8 @@ import { CHART_WIDTH, CHART_HEIGHT } from 'src/dashboard/constants';
// Session storage key for recent dashboard
const SK_DASHBOARD_ID = 'save_chart_recent_dashboard';
-interface SaveModalProps extends RouteComponentProps {
+interface SaveModalProps {
+ history: RouterHistory;
addDangerToast: (msg: string) => void;
actions: Record<string, any>;
form_data?: Record<string, any>;
@@ -836,7 +837,18 @@ function mapStateToProps({
};
}
-export default withRouter(connect(mapStateToProps)(withTheme(SaveModal)));
+const ConnectedSaveModal = connect(mapStateToProps)(withTheme(SaveModal));
+
+// Function wrapper replacing react-router's withRouter HOC: injects the
+// router history into the class component as an explicit prop.
+function SaveModalWithRouter(
+ props: Omit<ComponentProps<typeof ConnectedSaveModal>, 'history'>,
+) {
+ const router = useRouter();
+ return <ConnectedSaveModal {...props} history={router.history} />;
+}
+
+export default SaveModalWithRouter;
// User for testing purposes need to revisit once we convert this to functional component
export { SaveModal as PureSaveModal };
diff --git a/superset-frontend/src/explore/components/controls/DatasourceControl/DatasourceControl.test.tsx b/superset-frontend/src/explore/components/controls/DatasourceControl/DatasourceControl.test.tsx
index d2680b8effd..0ca1ca5db61 100644
--- a/superset-frontend/src/explore/components/controls/DatasourceControl/DatasourceControl.test.tsx
+++ b/superset-frontend/src/explore/components/controls/DatasourceControl/DatasourceControl.test.tsx
@@ -18,7 +18,7 @@
*/
import type React from 'react';
-import { Route } from 'react-router-dom';
+import { useLocation } from '@tanstack/react-router';
import fetchMock from 'fetch-mock';
import { DatasourceType, JsonObject, SupersetClient } from '@superset-ui/core';
import {
@@ -315,16 +315,19 @@ test('Edit dataset should be disabled when user is not admin', async () => {
test('Click on View in SQL Lab', async () => {
const props = createProps();
- const { queryByTestId, getByTestId } = render(
+ // Renders the current location state once the router navigates to /sqllab,
+ // mimicking the former react-router <Route path="/sqllab" render={...} />.
+ const MockSqlLabRoute = () => {
+ const location = useLocation();
+ if (location.pathname !== '/sqllab') return null;
+ return (
+ <div data-test="mock-sqllab-route">{JSON.stringify(location.state)}</div>
+ );
+ };
+
+ const { queryByTestId, findByTestId, getByTestId } = render(
<>
- <Route
- path="/sqllab"
- render={({ location }) => (
- <div data-test="mock-sqllab-route">
- {JSON.stringify(location.state)}
- </div>
- )}
- />
+ <MockSqlLabRoute />
<DatasourceControl {...props} />
</>,
{
@@ -338,14 +341,14 @@ test('Click on View in SQL Lab', async () => {
await userEvent.click(screen.getByText('View in SQL Lab'));
- expect(getByTestId('mock-sqllab-route')).toBeInTheDocument();
+ expect(await findByTestId('mock-sqllab-route')).toBeInTheDocument();
expect(JSON.parse(`${getByTestId('mock-sqllab-route').textContent}`)).toEqual(
- {
+ expect.objectContaining({
requestedQuery: {
datasourceKey: `${mockDatasource.id}__${mockDatasource.type}`,
sql: mockDatasource.sql,
},
- },
+ }),
);
});
diff --git a/superset-frontend/src/explore/components/controls/DatasourceControl/index.tsx b/superset-frontend/src/explore/components/controls/DatasourceControl/index.tsx
index e9e36d72d5c..59a77ca5b2e 100644
--- a/superset-frontend/src/explore/components/controls/DatasourceControl/index.tsx
+++ b/superset-frontend/src/explore/components/controls/DatasourceControl/index.tsx
@@ -56,7 +56,7 @@ import ViewQueryModalFooter from 'src/explore/components/controls/ViewQueryModal
import ViewQuery from 'src/explore/components/controls/ViewQuery';
import { SaveDatasetModal } from 'src/SqlLab/components/SaveDatasetModal';
import { safeStringify } from 'src/utils/safeStringify';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
// Extended Datasource interface with all properties used in this component
interface ExtendedDatasource extends Datasource {
@@ -415,10 +415,8 @@ class DatasourceControl extends PureComponent<
key: VIEW_IN_SQL_LAB,
label: (
<Link
- to={{
- pathname: '/sqllab',
- state: { requestedQuery },
- }}
+ to="/sqllab"
+ state={{ requestedQuery }}
onClick={preventRouterLinkWhileMetaClicked}
>
{t('View in SQL Lab')}
@@ -472,10 +470,8 @@ class DatasourceControl extends PureComponent<
key: VIEW_IN_SQL_LAB,
label: (
<Link
- to={{
- pathname: '/sqllab',
- state: { requestedQuery },
- }}
+ to="/sqllab"
+ state={{ requestedQuery }}
onClick={preventRouterLinkWhileMetaClicked}
>
{t('View in SQL Lab')}
diff --git a/superset-frontend/src/explore/components/controls/ViewQuery.test.tsx b/superset-frontend/src/explore/components/controls/ViewQuery.test.tsx
index 5fd67dafa07..30d2ca8bbf1 100644
--- a/superset-frontend/src/explore/components/controls/ViewQuery.test.tsx
+++ b/superset-frontend/src/explore/components/controls/ViewQuery.test.tsx
@@ -29,10 +29,12 @@ import { RootState } from 'src/dashboard/types';
import ViewQuery, { ViewQueryProps } from './ViewQuery';
const mockHistoryPush = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: () => ({
- push: mockHistoryPush,
+jest.mock('@tanstack/react-router', () => ({
+ ...jest.requireActual('@tanstack/react-router'),
+ useRouter: () => ({
+ history: {
+ push: mockHistoryPush,
+ },
}),
}));
@@ -162,13 +164,10 @@ test('navigates to SQL Lab when View in SQL Lab button is clicked', () => {
const viewInSQLLabButton = screen.getByText('View in SQL Lab');
fireEvent.click(viewInSQLLabButton);
- expect(mockHistoryPush).toHaveBeenCalledWith({
- pathname: '/sqllab',
- state: {
- requestedQuery: {
- datasourceKey: mockProps.datasource,
- sql: mockProps.sql,
- },
+ expect(mockHistoryPush).toHaveBeenCalledWith('/sqllab', {
+ requestedQuery: {
+ datasourceKey: mockProps.datasource,
+ sql: mockProps.sql,
},
});
});
diff --git a/superset-frontend/src/explore/components/controls/ViewQuery.tsx b/superset-frontend/src/explore/components/controls/ViewQuery.tsx
index 1d321d766e3..db6bbf75b16 100644
--- a/superset-frontend/src/explore/components/controls/ViewQuery.tsx
+++ b/superset-frontend/src/explore/components/controls/ViewQuery.tsx
@@ -45,7 +45,8 @@ import CodeSyntaxHighlighter, {
SupportedLanguage,
preloadLanguages,
} from '@superset-ui/core/components/CodeSyntaxHighlighter';
-import { useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import { ExplorePageState } from 'src/explore/types';
export interface ViewQueryProps {
@@ -86,7 +87,7 @@ const ViewQuery: FC<ViewQueryProps> = props => {
);
const [formattedSQL, setFormattedSQL] = useState<string>();
const [showFormatSQL, setShowFormatSQL] = useState(true);
- const history = useHistory();
+ const router = useRouter();
const currentSQL = (showFormatSQL ? formattedSQL : sql) ?? sql;
const canAccessSQLLab = useSelector((state: RootState) =>
findPermission('menu_access', 'SQL Lab', state.user?.roles),
@@ -147,10 +148,10 @@ const ViewQuery: FC<ViewQueryProps> = props => {
'_blank',
);
} else {
- history.push({ pathname: '/sqllab', state: { requestedQuery } });
+ pushAppHref(router, '/sqllab', { requestedQuery });
}
},
- [history, datasource, currentSQL],
+ [router, datasource, currentSQL],
);
useEffect(() => {
diff --git a/superset-frontend/src/explore/components/controls/ViewQueryModalFooter.tsx b/superset-frontend/src/explore/components/controls/ViewQueryModalFooter.tsx
index fc8c7c948b2..6003710862c 100644
--- a/superset-frontend/src/explore/components/controls/ViewQueryModalFooter.tsx
+++ b/superset-frontend/src/explore/components/controls/ViewQueryModalFooter.tsx
@@ -21,7 +21,8 @@ import { isObject } from 'lodash';
import { t } from '@apache-superset/core/translation';
import { SupersetClient } from '@superset-ui/core';
import { Button } from '@superset-ui/core/components';
-import { useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
interface SimpleDataSource {
id: string;
@@ -44,7 +45,7 @@ const ViewQueryModalFooter: FC<ViewQueryModalFooterProps> = (props: {
changeDatasource: () => void;
datasource: SimpleDataSource;
}) => {
- const history = useHistory();
+ const router = useRouter();
const viewInSQLLab = (
openInNewWindow: boolean,
id: string,
@@ -58,11 +59,8 @@ const ViewQueryModalFooter: FC<ViewQueryModalFooterProps> = (props: {
if (openInNewWindow) {
SupersetClient.postForm('/sqllab/', payload);
} else {
- history.push({
- pathname: '/sqllab',
- state: {
- requestedQuery: payload,
- },
+ pushAppHref(router, '/sqllab', {
+ requestedQuery: payload,
});
}
};
diff --git a/superset-frontend/src/explore/components/useExploreAdditionalActionsMenu/DashboardsSubMenu.tsx b/superset-frontend/src/explore/components/useExploreAdditionalActionsMenu/DashboardsSubMenu.tsx
index fcd2454615c..d71efcca457 100644
--- a/superset-frontend/src/explore/components/useExploreAdditionalActionsMenu/DashboardsSubMenu.tsx
+++ b/superset-frontend/src/explore/components/useExploreAdditionalActionsMenu/DashboardsSubMenu.tsx
@@ -21,7 +21,7 @@ import { t } from '@apache-superset/core/translation';
import { css, useTheme } from '@apache-superset/core/theme';
import { MenuItem } from '@superset-ui/core/components/Menu';
import { Icons } from '@superset-ui/core/components/Icons';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
export interface DashboardsMenuProps {
chartId?: number;
@@ -45,7 +45,10 @@ export const useDashboardsMenuItems = ({
);
}, [dashboards, searchTerm]);
- const urlQueryString = chartId ? `?focused_chart=${chartId}` : '';
+ const urlSearch = useMemo(
+ () => (chartId ? { focused_chart: String(chartId) } : undefined),
+ [chartId],
+ );
const noResults = dashboards.length === 0;
const noResultsFound = searchTerm && filteredDashboards.length === 0;
@@ -72,7 +75,8 @@ export const useDashboardsMenuItems = ({
<Link
target="_blank"
rel="noreferer noopener"
- to={`/superset/dashboard/${dashboard.id}${urlQueryString}`}
+ to={`/superset/dashboard/${dashboard.id}`}
+ search={urlSearch}
css={css`
display: flex;
flex-direction: row;
@@ -102,7 +106,7 @@ export const useDashboardsMenuItems = ({
return items;
}, [
filteredDashboards,
- urlQueryString,
+ urlSearch,
noResults,
noResultsFound,
theme.sizeUnit,
diff --git a/superset-frontend/src/features/charts/ChartCard.tsx b/superset-frontend/src/features/charts/ChartCard.tsx
index 47562c84450..2b604500606 100644
--- a/superset-frontend/src/features/charts/ChartCard.tsx
+++ b/superset-frontend/src/features/charts/ChartCard.tsx
@@ -16,10 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
+import type { ReactNode } from 'react';
import { t } from '@apache-superset/core/translation';
import { isFeatureEnabled, FeatureFlag } from '@superset-ui/core';
import { css } from '@apache-superset/core/theme';
-import { Link, useHistory } from 'react-router-dom';
+import { Link, useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
+import { parseSearch } from 'src/router/searchParams';
import {
ConfirmStatusChange,
Button,
@@ -55,6 +58,20 @@ interface ChartCardProps {
getData?: (tab: TableTab) => void;
}
+// Backend-provided chart URLs may carry a query string; split it out so
+// the router preserves it via the raw search codec.
+function CardLink({ to, children }: { to: string; children?: ReactNode }) {
+ const [pathname, queryString] = to.split('?');
+ return (
+ <Link
+ to={pathname}
+ {...(queryString ? { search: parseSearch(queryString) } : {})}
+ >
+ {children}
+ </Link>
+ );
+}
+
export default function ChartCard({
chart,
hasPerm,
@@ -72,7 +89,7 @@ export default function ChartCard({
handleBulkChartExport,
getData,
}: ChartCardProps) {
- const history = useHistory();
+ const router = useRouter();
const canEdit = hasPerm('can_write');
const canDelete = hasPerm('can_write');
const canExport = hasPerm('can_export');
@@ -170,7 +187,7 @@ export default function ChartCard({
<CardStyles
onClick={() => {
if (!bulkSelectEnabled && chart.url) {
- history.push(chart.url);
+ pushAppHref(router, chart.url);
}
}}
>
@@ -192,7 +209,7 @@ export default function ChartCard({
description={t('Modified %s', chart.changed_on_delta_humanized)}
coverLeft={<FacePile users={chart.owners || []} />}
coverRight={<Label>{chart.datasource_name_text}</Label>}
- linkComponent={Link}
+ linkComponent={CardLink}
actions={
<ListViewCard.Actions
onClick={e => {
diff --git a/superset-frontend/src/features/dashboards/DashboardCard.test.tsx b/superset-frontend/src/features/dashboards/DashboardCard.test.tsx
index 0d944234030..0dec35ebe71 100644
--- a/superset-frontend/src/features/dashboards/DashboardCard.test.tsx
+++ b/superset-frontend/src/features/dashboards/DashboardCard.test.tsx
@@ -17,7 +17,7 @@
* under the License.
*/
-import { MemoryRouter } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import {
JsonResponse,
SupersetClient,
@@ -68,7 +68,7 @@ afterAll(() => {
beforeEach(() => {
render(
- <MemoryRouter>
+ <StandaloneRouter>
<DashboardCard
dashboard={mockDashboard}
hasPerm={mockHasPerm}
@@ -80,7 +80,7 @@ beforeEach(() => {
handleBulkDashboardExport={mockHandleBulkDashboardExport}
onDelete={mockOnDelete}
/>
- </MemoryRouter>,
+ </StandaloneRouter>,
);
});
@@ -129,6 +129,7 @@ test('should fetch thumbnail when dashboard has no thumbnail URL and feature fla
handleBulkDashboardExport={() => {}}
onDelete={() => {}}
/>,
+ { useRouter: true },
);
await waitFor(() => {
expect(mockGet).toHaveBeenCalledWith({
diff --git a/superset-frontend/src/features/dashboards/DashboardCard.tsx b/superset-frontend/src/features/dashboards/DashboardCard.tsx
index 5793e0e1bc0..06ad3b4ef3a 100644
--- a/superset-frontend/src/features/dashboards/DashboardCard.tsx
+++ b/superset-frontend/src/features/dashboards/DashboardCard.tsx
@@ -16,8 +16,10 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { useEffect, useState } from 'react';
-import { Link, useHistory } from 'react-router-dom';
+import { useEffect, useState, type ReactNode } from 'react';
+import { Link, useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
+import { parseSearch } from 'src/router/searchParams';
import { t } from '@apache-superset/core/translation';
import {
isFeatureEnabled,
@@ -53,6 +55,20 @@ interface DashboardCardProps {
onDelete: (dashboard: Dashboard) => void;
}
+// Backend-provided dashboard URLs may carry a query string; split it out
+// so the router preserves it via the raw search codec.
+function CardLink({ to, children }: { to: string; children?: ReactNode }) {
+ const [pathname, queryString] = to.split('?');
+ return (
+ <Link
+ to={pathname}
+ {...(queryString ? { search: parseSearch(queryString) } : {})}
+ >
+ {children}
+ </Link>
+ );
+}
+
function DashboardCard({
dashboard,
hasPerm,
@@ -65,7 +81,7 @@ function DashboardCard({
handleBulkDashboardExport,
onDelete,
}: DashboardCardProps) {
- const history = useHistory();
+ const router = useRouter();
const canEdit = hasPerm('can_write');
const canDelete = hasPerm('can_write');
const canExport = hasPerm('can_export');
@@ -154,7 +170,7 @@ function DashboardCard({
<CardStyles
onClick={() => {
if (!bulkSelectEnabled) {
- history.push(dashboard.url);
+ pushAppHref(router, dashboard.url);
}
}}
>
@@ -170,7 +186,7 @@ function DashboardCard({
) : null
}
url={bulkSelectEnabled ? undefined : dashboard.url}
- linkComponent={Link}
+ linkComponent={CardLink}
imgURL={thumbnailUrl}
imgFallbackURL={assetUrl(
'/static/assets/images/dashboard-card-fallback.svg',
diff --git a/superset-frontend/src/features/databases/DatabaseModal/index.test.tsx b/superset-frontend/src/features/databases/DatabaseModal/index.test.tsx
index 0cfd11eede3..66130a232f9 100644
--- a/superset-frontend/src/features/databases/DatabaseModal/index.test.tsx
+++ b/superset-frontend/src/features/databases/DatabaseModal/index.test.tsx
@@ -45,10 +45,12 @@ jest.mock('@superset-ui/core', () => ({
}));
const mockHistoryPush = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: () => ({
- push: mockHistoryPush,
+jest.mock('@tanstack/react-router', () => ({
+ ...jest.requireActual('@tanstack/react-router'),
+ useRouter: () => ({
+ history: {
+ push: mockHistoryPush,
+ },
}),
}));
diff --git a/superset-frontend/src/features/databases/DatabaseModal/index.tsx b/superset-frontend/src/features/databases/DatabaseModal/index.tsx
index 27fbe97c4b4..992eb22596b 100644
--- a/superset-frontend/src/features/databases/DatabaseModal/index.tsx
+++ b/superset-frontend/src/features/databases/DatabaseModal/index.tsx
@@ -33,7 +33,8 @@ import {
} from 'react';
import { CheckboxChangeEvent } from '@superset-ui/core/components/Checkbox/types';
-import { useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import { setItem, LocalStorageKeys } from 'src/utils/localStorageHelpers';
import Tabs from '@superset-ui/core/components/Tabs';
import {
@@ -751,7 +752,7 @@ const DatabaseModal: FunctionComponent<DatabaseModalProps> = ({
(DB: DatabaseObject) => DB.backend === engine || DB.engine === engine,
)?.parameters !== undefined;
const showDBError = validationErrors || dbErrors;
- const history = useHistory();
+ const router = useRouter();
const dbModel: DatabaseForm =
// TODO: we need a centralized engine in one place
@@ -887,7 +888,7 @@ const DatabaseModal: FunctionComponent<DatabaseModalProps> = ({
};
const redirectURL = (url: string) => {
- history.push(url);
+ pushAppHref(router, url);
};
// Database import logic
@@ -1875,8 +1876,8 @@ const DatabaseModal: FunctionComponent<DatabaseModalProps> = ({
onClick={() => {
setLoading(true);
fetchAndSetDB();
- // redirectURL() delegates to history.push; React Router's basename
- // already prefixes the application root, so pass a relative path.
+ // redirectURL() prefixes the application root via pushAppHref,
+ // so pass a root-relative path.
redirectURL('/sqllab?db=true');
}}
>
diff --git a/superset-frontend/src/features/datasets/AddDataset/DatasetPanel/MessageContent.tsx b/superset-frontend/src/features/datasets/AddDataset/DatasetPanel/MessageContent.tsx
index 960703408fa..677ae6972a2 100644
--- a/superset-frontend/src/features/datasets/AddDataset/DatasetPanel/MessageContent.tsx
+++ b/superset-frontend/src/features/datasets/AddDataset/DatasetPanel/MessageContent.tsx
@@ -20,7 +20,7 @@
import { t } from '@apache-superset/core/translation';
import { styled } from '@apache-superset/core/theme';
import { EmptyState } from '@superset-ui/core/components';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
const StyledContainer = styled.div`
padding: ${({ theme }) => theme.sizeUnit * 8}px
diff --git a/superset-frontend/src/features/datasets/AddDataset/Footer/Footer.test.tsx b/superset-frontend/src/features/datasets/AddDataset/Footer/Footer.test.tsx
index b0714fc90c5..b1bae5b9bd6 100644
--- a/superset-frontend/src/features/datasets/AddDataset/Footer/Footer.test.tsx
+++ b/superset-frontend/src/features/datasets/AddDataset/Footer/Footer.test.tsx
@@ -24,11 +24,16 @@ import {
} from 'spec/helpers/testing-library';
import Footer from 'src/features/datasets/AddDataset/Footer';
+const mockNavigate = jest.fn();
const mockHistoryPush = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: () => ({
- push: mockHistoryPush,
+jest.mock('@tanstack/react-router', () => ({
+ ...jest.requireActual('@tanstack/react-router'),
+ useNavigate: () => mockNavigate,
+ useRouter: () => ({
+ history: {
+ push: mockHistoryPush,
+ back: jest.fn(),
+ },
}),
}));
@@ -173,7 +178,9 @@ describe('Footer', () => {
schema: 'public',
table_name: 'real_info',
});
- expect(mockHistoryPush).toHaveBeenCalledWith('/tablemodelview/list/');
+ expect(mockNavigate).toHaveBeenCalledWith({
+ to: '/tablemodelview/list/',
+ });
});
});
@@ -192,6 +199,7 @@ describe('Footer', () => {
expect(mockCreateResource).toHaveBeenCalled();
// Should not navigate if creation failed
expect(mockHistoryPush).not.toHaveBeenCalled();
+ expect(mockNavigate).not.toHaveBeenCalled();
});
});
diff --git a/superset-frontend/src/features/datasets/AddDataset/Footer/index.tsx b/superset-frontend/src/features/datasets/AddDataset/Footer/index.tsx
index 2ed2aabbcd2..da2b4b9987d 100644
--- a/superset-frontend/src/features/datasets/AddDataset/Footer/index.tsx
+++ b/superset-frontend/src/features/datasets/AddDataset/Footer/index.tsx
@@ -16,7 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { useHistory } from 'react-router-dom';
+import { useNavigate, useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import {
Button,
DropdownButton,
@@ -61,7 +62,8 @@ function Footer({
hasColumns = false,
datasets,
}: FooterProps) {
- const history = useHistory();
+ const navigate = useNavigate();
+ const router = useRouter();
const theme = useTheme();
const { createResource, state } = useSingleViewResource<
Partial<DatasetObject>
@@ -87,7 +89,7 @@ function Footer({
const logAction = createLogAction(datasetObject);
logEvent(logAction, datasetObject);
}
- history.goBack();
+ router.history.back();
};
const tooltipText = t('Select a database table.');
@@ -108,9 +110,12 @@ function Footer({
logEvent(LOG_ACTIONS_DATASET_CREATION_SUCCESS, datasetObject);
// When a dataset is created the response we get is its ID number
if (createChart) {
- history.push(`/chart/add/?dataset=${datasetObject.table_name}`);
+ pushAppHref(
+ router,
+ `/chart/add/?dataset=${datasetObject.table_name}`,
+ );
} else {
- history.push('/tablemodelview/list/');
+ navigate({ to: '/tablemodelview/list/' });
}
}
});
diff --git a/superset-frontend/src/features/datasets/DatasetLayout/DatasetLayout.test.tsx b/superset-frontend/src/features/datasets/DatasetLayout/DatasetLayout.test.tsx
index 15c6268f2c7..a6712f529bb 100644
--- a/superset-frontend/src/features/datasets/DatasetLayout/DatasetLayout.test.tsx
+++ b/superset-frontend/src/features/datasets/DatasetLayout/DatasetLayout.test.tsx
@@ -25,14 +25,6 @@ import DatasetPanelComponent from 'src/features/datasets/AddDataset/DatasetPanel
import RightPanel from 'src/features/datasets/AddDataset/RightPanel';
import Footer from 'src/features/datasets/AddDataset/Footer';
-const mockHistoryPush = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: () => ({
- push: mockHistoryPush,
- }),
-}));
-
// eslint-disable-next-line no-restricted-globals -- TODO: Migrate from describe blocks
describe('DatasetLayout', () => {
test('renders nothing when no components are passed in', () => {
diff --git a/superset-frontend/src/features/home/ActivityTable.tsx b/superset-frontend/src/features/home/ActivityTable.tsx
index e71006a3adb..042eb4fe061 100644
--- a/superset-frontend/src/features/home/ActivityTable.tsx
+++ b/superset-frontend/src/features/home/ActivityTable.tsx
@@ -21,7 +21,8 @@ import { extendedDayjs } from '@superset-ui/core/utils/dates';
import { t } from '@apache-superset/core/translation';
import { styled } from '@apache-superset/core/theme';
import { setItem, LocalStorageKeys } from 'src/utils/localStorageHelpers';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
+import { parseSearch } from 'src/router/searchParams';
import { ListViewCard } from '@superset-ui/core/components';
import { Dashboard, SavedQueryObject, TableTab } from 'src/views/CRUD/types';
import { ActivityData, LoadingCards } from 'src/pages/Home';
@@ -186,9 +187,14 @@ export default function ActivityTable({
return activities.map((entity: ActivityObject) => {
const url = getEntityUrl(entity);
const lastActionOn = getEntityLastActionOn(entity);
+ // Entity URLs come from backend data and may carry a query string.
+ const [pathname, queryString] = (url || '').split('?');
return (
<CardStyles key={url}>
- <Link to={url}>
+ <Link
+ to={pathname}
+ search={queryString ? parseSearch(queryString) : undefined}
+ >
<ListViewCard
cover={<></>}
url={url}
diff --git a/superset-frontend/src/features/home/ChartTable.tsx b/superset-frontend/src/features/home/ChartTable.tsx
index 37d594c7c50..cfe1227b3c0 100644
--- a/superset-frontend/src/features/home/ChartTable.tsx
+++ b/superset-frontend/src/features/home/ChartTable.tsx
@@ -29,7 +29,8 @@ import {
setItem,
} from 'src/utils/localStorageHelpers';
import withToasts from 'src/components/MessageToasts/withToasts';
-import { useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import { Filter, TableTab } from 'src/views/CRUD/types';
import PropertiesModal from 'src/explore/components/PropertiesModal';
import { User } from 'src/types/bootstrapTypes';
@@ -71,7 +72,7 @@ function ChartTable({
otherTabFilters,
otherTabTitle,
}: ChartTableProps) {
- const history = useHistory();
+ const router = useRouter();
const initialTab = getItem(
LocalStorageKeys.HomepageChartFilter,
TableTab.Other,
@@ -215,7 +216,7 @@ function ChartTable({
'Yes',
)},value:!t))`
: '/chart/list/';
- history.push(target);
+ pushAppHref(router, target);
},
},
]}
diff --git a/superset-frontend/src/features/home/DashboardTable.test.tsx b/superset-frontend/src/features/home/DashboardTable.test.tsx
index ddd6d3521b4..faf14816675 100644
--- a/superset-frontend/src/features/home/DashboardTable.test.tsx
+++ b/superset-frontend/src/features/home/DashboardTable.test.tsx
@@ -23,8 +23,7 @@ import {
waitFor,
} from 'spec/helpers/testing-library';
import { SupersetClient } from '@superset-ui/core';
-import { createMemoryHistory } from 'history';
-import { Router } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import { configureStore } from '@reduxjs/toolkit';
import fetchMock from 'fetch-mock';
import * as hooks from 'src/views/CRUD/hooks';
@@ -105,7 +104,6 @@ const defaultProps = {
otherTabTitle: 'Examples',
};
-const history = createMemoryHistory();
const store = configureStore({
reducer: {
dashboards: (state = { dashboards: [] }) => state,
@@ -156,9 +154,9 @@ beforeEach(() => {
test('renders loading state initially', () => {
render(
- <Router history={history}>
+ <StandaloneRouter initialEntries={['/']}>
<DashboardTable {...defaultProps} />
- </Router>,
+ </StandaloneRouter>,
{ store },
);
expect(screen.getByRole('img', { name: 'empty' })).toBeInTheDocument();
@@ -166,9 +164,9 @@ test('renders loading state initially', () => {
test('renders empty state when no dashboards', async () => {
render(
- <Router history={history}>
+ <StandaloneRouter initialEntries={['/']}>
<DashboardTable {...defaultProps} />
- </Router>,
+ </StandaloneRouter>,
{ store },
);
@@ -194,9 +192,9 @@ test('renders dashboard cards when data is loaded', async () => {
}));
render(
- <Router history={history}>
+ <StandaloneRouter initialEntries={['/']}>
<DashboardTable {...defaultProps} mine={mockDashboards} />
- </Router>,
+ </StandaloneRouter>,
{ store },
);
@@ -214,9 +212,9 @@ test('switches to Mine tab correctly', async () => {
};
render(
- <Router history={history}>
+ <StandaloneRouter initialEntries={['/']}>
<DashboardTable {...props} />
- </Router>,
+ </StandaloneRouter>,
{ store },
);
@@ -235,9 +233,9 @@ test('handles create dashboard button click', async () => {
} as Location);
render(
- <Router history={history}>
+ <StandaloneRouter initialEntries={['/']}>
<DashboardTable {...defaultProps} />
- </Router>,
+ </StandaloneRouter>,
{ store },
);
@@ -255,9 +253,9 @@ test('switches to Other tab when available', async () => {
};
render(
- <Router history={history}>
+ <StandaloneRouter initialEntries={['/']}>
<DashboardTable {...props} />
- </Router>,
+ </StandaloneRouter>,
{ store },
);
@@ -299,9 +297,9 @@ test('handles bulk dashboard export with correct ID and shows spinner', async ()
}));
render(
- <Router history={history}>
+ <StandaloneRouter initialEntries={['/']}>
<DashboardTable {...props} />
- </Router>,
+ </StandaloneRouter>,
{ store },
);
@@ -362,9 +360,9 @@ test('handles dashboard deletion confirmation', async () => {
}));
render(
- <Router history={history}>
+ <StandaloneRouter initialEntries={['/']}>
<DashboardTable {...props} />
- </Router>,
+ </StandaloneRouter>,
{ store },
);
@@ -434,9 +432,9 @@ test('passes correct parameters to handleDashboardDelete for Other tab', async (
};
render(
- <Router history={history}>
+ <StandaloneRouter initialEntries={['/']}>
<DashboardTable {...props} />
- </Router>,
+ </StandaloneRouter>,
{ store },
);
diff --git a/superset-frontend/src/features/home/DashboardTable.tsx b/superset-frontend/src/features/home/DashboardTable.tsx
index 7993900f833..9c835f2e7a3 100644
--- a/superset-frontend/src/features/home/DashboardTable.tsx
+++ b/superset-frontend/src/features/home/DashboardTable.tsx
@@ -22,7 +22,8 @@ import { SupersetClient } from '@superset-ui/core';
import { useFavoriteStatus, useListViewResource } from 'src/views/CRUD/hooks';
import { Dashboard, DashboardTableProps, TableTab } from 'src/views/CRUD/types';
import handleResourceExport from 'src/utils/export';
-import { useHistory } from 'react-router-dom';
+import { useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import {
getItem,
LocalStorageKeys,
@@ -56,7 +57,7 @@ function DashboardTable({
otherTabFilters,
otherTabTitle,
}: DashboardTableProps) {
- const history = useHistory();
+ const router = useRouter();
const defaultTab = getItem(
LocalStorageKeys.HomepageDashboardFilter,
TableTab.Other,
@@ -216,7 +217,7 @@ function DashboardTable({
'Yes',
)},value:!t))`
: '/dashboard/list/';
- history.push(target);
+ pushAppHref(router, target);
},
},
]}
diff --git a/superset-frontend/src/features/home/Menu.tsx b/superset-frontend/src/features/home/Menu.tsx
index 06d606cc6a4..81c3e49aac9 100644
--- a/superset-frontend/src/features/home/Menu.tsx
+++ b/superset-frontend/src/features/home/Menu.tsx
@@ -25,7 +25,8 @@ import { getUrlParam } from 'src/utils/urlUtils';
import { MainNav, MenuItem } from '@superset-ui/core/components/Menu';
import { Tooltip, Grid, Row, Col, Image } from '@superset-ui/core/components';
import { GenericLink } from 'src/components';
-import { NavLink, useLocation } from 'react-router-dom';
+import { Link, useLocation } from '@tanstack/react-router';
+import { parseSearch } from 'src/router/searchParams';
import { Icons } from '@superset-ui/core/components/Icons';
import { Typography } from '@superset-ui/core/components/Typography';
import { useUiConfig } from 'src/components/UiConfigContext';
@@ -244,12 +245,19 @@ export function Menu({
isFrontendRoute,
}: MenuObjectProps): MenuItem => {
if (url && isFrontendRoute) {
+ // Menu URLs come from backend data and may carry a query string.
+ const [pathname, queryString] = url.split('?');
return {
key: label,
label: (
- <NavLink role="button" to={url} activeClassName="is-active">
+ <Link
+ role="button"
+ to={pathname}
+ search={queryString ? parseSearch(queryString) : undefined}
+ activeProps={{ className: 'is-active' }}
+ >
{label}
- </NavLink>
+ </Link>
),
};
}
@@ -266,12 +274,20 @@ export function Menu({
if (typeof child === 'string' && child === '-' && label !== 'Data') {
childItems.push({ type: 'divider', key: `divider-${index1}` });
} else if (typeof child !== 'string') {
+ const [childPathname, childQueryString] = (child.url || '').split('?');
childItems.push({
key: `${child.label}`,
label: child.isFrontendRoute ? (
- <NavLink to={child.url || ''} exact activeClassName="is-active">
+ <Link
+ to={childPathname}
+ search={
+ childQueryString ? parseSearch(childQueryString) : undefined
+ }
+ activeOptions={{ exact: true }}
+ activeProps={{ className: 'is-active' }}
+ >
{child.label}
- </NavLink>
+ </Link>
) : (
<Typography.Link href={child.url}>{child.label}</Typography.Link>
),
diff --git a/superset-frontend/src/features/home/RightMenu.tsx b/superset-frontend/src/features/home/RightMenu.tsx
index 6462c1c588b..59070dc8f6c 100644
--- a/superset-frontend/src/features/home/RightMenu.tsx
+++ b/superset-frontend/src/features/home/RightMenu.tsx
@@ -16,10 +16,18 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { useState, useEffect, FC, PureComponent, useMemo } from 'react';
+import {
+ useState,
+ useEffect,
+ FC,
+ PureComponent,
+ ReactNode,
+ useMemo,
+} from 'react';
import rison from 'rison';
import { useSelector } from 'react-redux';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
+import { parseSearch } from 'src/router/searchParams';
import { useQueryParams, BooleanParam } from 'use-query-params';
import { isEmpty } from 'lodash';
import { t } from '@apache-superset/core/translation';
@@ -102,6 +110,26 @@ const StyledMenuItem = styled.div<{ disabled?: boolean }>`
`}
`;
+// Menu URLs may carry a query string (e.g. /sqllab?new=true); the TanStack
+// <Link> needs the search params passed separately from the pathname.
+const RouterLink = ({
+ url,
+ children,
+}: {
+ url: string;
+ children?: ReactNode;
+}) => {
+ const [pathname, queryString] = url.split('?');
+ return (
+ <Link
+ to={pathname}
+ search={queryString ? parseSearch(queryString) : undefined}
+ >
+ {children}
+ </Link>
+ );
+};
+
const RightMenu = ({
align,
settings,
@@ -409,7 +437,7 @@ const RightMenu = ({
items.push({
key: menu.label,
label: isFrontendRoute(menu.url) ? (
- <Link to={menu.url || ''}>{menu.label}</Link>
+ <RouterLink url={menu.url || ''}>{menu.label}</RouterLink>
) : (
<Typography.Link href={ensureAppRoot(menu.url || '')}>
{menu.label}
@@ -425,7 +453,7 @@ const RightMenu = ({
items.push({
key: menu.label,
label: isFrontendRoute(menu.url) ? (
- <Link to={menu.url || ''}>{menu.label}</Link>
+ <RouterLink url={menu.url || ''}>{menu.label}</RouterLink>
) : (
<Typography.Link href={ensureAppRoot(menu.url || '')}>
{menu.label}
@@ -460,7 +488,7 @@ const RightMenu = ({
sectionItems.push({
key: child.label,
label: isFrontendRoute(child.url) ? (
- <Link to={child.url || ''}>{menuItemDisplay}</Link>
+ <RouterLink url={child.url || ''}>{menuItemDisplay}</RouterLink>
) : (
<Typography.Link
href={child.url || ''}
diff --git a/superset-frontend/src/features/home/SavedQueries.tsx b/superset-frontend/src/features/home/SavedQueries.tsx
index 5e977dd8c7c..d1c476ecd96 100644
--- a/superset-frontend/src/features/home/SavedQueries.tsx
+++ b/superset-frontend/src/features/home/SavedQueries.tsx
@@ -17,7 +17,7 @@
* under the License.
*/
import { useCallback, useState, useEffect } from 'react';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
import { t } from '@apache-superset/core/translation';
import { SupersetClient } from '@superset-ui/core';
import { styled, useTheme, css } from '@apache-superset/core/theme';
@@ -206,7 +206,11 @@ export const SavedQueries = ({
if (canEdit) {
menuItems.push({
key: 'edit',
- label: <Link to={`/sqllab?savedQueryId=${query.id}`}>{t('Edit')}</Link>,
+ label: (
+ <Link to="/sqllab" search={{ savedQueryId: String(query.id) }}>
+ {t('Edit')}
+ </Link>
+ ),
});
}
menuItems.push({
@@ -278,7 +282,8 @@ export const SavedQueries = ({
icon: <Icons.PlusOutlined iconSize="m" />,
name: (
<Link
- to="/sqllab?new=true"
+ to="/sqllab"
+ search={{ new: 'true' }}
css={css`
&:hover {
color: currentColor;
diff --git a/superset-frontend/src/features/home/SubMenu.test.tsx b/superset-frontend/src/features/home/SubMenu.test.tsx
index 2dc716f64ef..91c927928c0 100644
--- a/superset-frontend/src/features/home/SubMenu.test.tsx
+++ b/superset-frontend/src/features/home/SubMenu.test.tsx
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { BrowserRouter } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import { render, screen, userEvent } from 'spec/helpers/testing-library';
import SubMenu, { ButtonProps } from './SubMenu';
@@ -63,9 +63,9 @@ const setup = (overrides: Record<string, any> = {}) => {
...overrides,
};
return render(
- <BrowserRouter>
+ <StandaloneRouter>
<SubMenu {...props} />
- </BrowserRouter>,
+ </StandaloneRouter>,
);
};
diff --git a/superset-frontend/src/features/home/SubMenu.tsx b/superset-frontend/src/features/home/SubMenu.tsx
index 9c2e2c451eb..3c3263f0e41 100644
--- a/superset-frontend/src/features/home/SubMenu.tsx
+++ b/superset-frontend/src/features/home/SubMenu.tsx
@@ -18,7 +18,8 @@
*/
import { ReactNode, useState, useEffect, FunctionComponent } from 'react';
-import { Link, useHistory } from 'react-router-dom';
+import { Link, useRouter } from '@tanstack/react-router';
+import { parseSearch } from 'src/router/searchParams';
import { t } from '@apache-superset/core/translation';
import {
styled,
@@ -172,14 +173,9 @@ const SubMenuComponent: FunctionComponent<SubMenuProps> = props => {
const [navRightStyle, setNavRightStyle] = useState('nav-right');
const theme = useTheme();
- let hasHistory = true;
- // If no parent <Router> component exists, useHistory throws an error
- try {
- useHistory();
- } catch (err) {
- // If error is thrown, we know not to use <Link> in render
- hasHistory = false;
- }
+ // If no parent <RouterProvider> exists, useRouter returns undefined and
+ // we know not to use <Link> in render
+ const hasHistory = !!useRouter({ warn: false });
useEffect(() => {
let isMounted = true;
@@ -223,11 +219,14 @@ const SubMenuComponent: FunctionComponent<SubMenuProps> = props => {
role="tablist"
items={props.tabs?.map(tab => {
if ((props.usesRouter || hasHistory) && !!tab.usesRouter) {
+ // Tab URLs may carry a query string.
+ const [pathname, queryString] = (tab.url || '').split('?');
return {
key: tab.label,
label: (
<Link
- to={tab.url || ''}
+ to={pathname}
+ search={queryString ? parseSearch(queryString) : undefined}
role="tab"
id={tab.id || tab.name}
data-test={tab['data-test']}
diff --git a/superset-frontend/src/features/tags/TagCard.tsx b/superset-frontend/src/features/tags/TagCard.tsx
index 6158acc119c..6b7692bc7e6 100644
--- a/superset-frontend/src/features/tags/TagCard.tsx
+++ b/superset-frontend/src/features/tags/TagCard.tsx
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
import { t } from '@apache-superset/core/translation';
import { isFeatureEnabled, FeatureFlag } from '@superset-ui/core';
import { CardStyles } from 'src/views/CRUD/utils';
diff --git a/superset-frontend/src/hooks/useUnsavedChangesPrompt/index.ts b/superset-frontend/src/hooks/useUnsavedChangesPrompt/index.ts
index 2301b2c515d..99dbaf44ec2 100644
--- a/superset-frontend/src/hooks/useUnsavedChangesPrompt/index.ts
+++ b/superset-frontend/src/hooks/useUnsavedChangesPrompt/index.ts
@@ -18,10 +18,16 @@
*/
import { t } from '@apache-superset/core/translation';
import { getClientErrorObject } from '@superset-ui/core';
-import { useEffect, useRef, useCallback, useState } from 'react';
-import { useHistory } from 'react-router-dom';
+import {
+ useEffect,
+ useRef,
+ useCallback,
+ useState,
+ type Dispatch,
+ type SetStateAction,
+} from 'react';
+import { useBlocker } from '@tanstack/react-router';
import { useBeforeUnload } from 'src/hooks/useBeforeUnload';
-import type { Location, Action } from 'history';
type UseUnsavedChangesPromptProps = {
hasUnsavedChanges: boolean;
@@ -36,16 +42,53 @@ export const useUnsavedChangesPrompt = ({
isSaveModalVisible = false,
manualSaveOnUnsavedChanges = false,
}: UseUnsavedChangesPromptProps) => {
- const history = useHistory();
- const [showModal, setShowModal] = useState(false);
+ const [showModal, setShowModalState] = useState(false);
+ const showModalRef = useRef(showModal);
+ showModalRef.current = showModal;
- const confirmNavigationRef = useRef<(() => void) | null>(null);
- const unblockRef = useRef<() => void>(() => {});
const manualSaveRef = useRef(false); // Track if save was user-initiated (not via navigation)
+ const blocker = useBlocker({
+ shouldBlockFn: ({ action }) => {
+ // REPLACE actions are URL sync (e.g. updating form_data_key), not navigation
+ if (action === 'REPLACE') {
+ return false;
+ }
+
+ if (manualSaveRef.current) {
+ manualSaveRef.current = false;
+ return false;
+ }
+
+ return true;
+ },
+ withResolver: true,
+ disabled: !hasUnsavedChanges,
+ // the manual useBeforeUnload listener below handles the unload prompt
+ enableBeforeUnload: false,
+ });
+ const blockerRef = useRef(blocker);
+ blockerRef.current = blocker;
+
+ useEffect(() => {
+ if (blocker.status === 'blocked') {
+ setShowModalState(true);
+ }
+ }, [blocker.status]);
+
+ // Closing the modal without navigating discards the blocked navigation
+ const setShowModal: Dispatch<SetStateAction<boolean>> = useCallback(value => {
+ const next =
+ typeof value === 'function' ? value(showModalRef.current) : value;
+ if (!next) {
+ blockerRef.current.reset?.();
+ }
+ setShowModalState(next);
+ }, []);
+
const handleConfirmNavigation = useCallback(() => {
- setShowModal(false);
- confirmNavigationRef.current?.();
+ setShowModalState(false);
+ blockerRef.current.proceed?.();
}, []);
const handleSaveAndCloseModal = useCallback(async () => {
@@ -63,66 +106,19 @@ export const useUnsavedChangesPrompt = ({
{ cause: err },
);
}
- }, [manualSaveOnUnsavedChanges, onSave]);
+ }, [manualSaveOnUnsavedChanges, onSave, setShowModal]);
const triggerManualSave = useCallback(() => {
manualSaveRef.current = true;
onSave();
}, [onSave]);
- const blockCallback = useCallback(
- (
- {
- pathname,
- search,
- state,
- }: {
- pathname: Location['pathname'];
- search: Location['search'];
- state: Location['state'];
- },
- action: Action,
- ) => {
- // REPLACE actions are URL sync (e.g. updating form_data_key), not navigation
- if (action === 'REPLACE') {
- return undefined;
- }
-
- if (manualSaveRef.current) {
- manualSaveRef.current = false;
- return undefined;
- }
-
- confirmNavigationRef.current = () => {
- unblockRef.current?.();
- if (action === 'POP') {
- history.go(-1);
- } else {
- history.push({ pathname, search }, state);
- }
- };
-
- setShowModal(true);
- return false;
- },
- [history],
- );
-
- useEffect(() => {
- if (!hasUnsavedChanges) return undefined;
-
- const unblock = history.block(blockCallback);
- unblockRef.current = unblock;
-
- return () => unblock();
- }, [blockCallback, hasUnsavedChanges, history]);
-
useEffect(() => {
if (!isSaveModalVisible && manualSaveRef.current) {
setShowModal(false);
manualSaveRef.current = false;
}
- }, [isSaveModalVisible]);
+ }, [isSaveModalVisible, setShowModal]);
useBeforeUnload(hasUnsavedChanges);
diff --git a/superset-frontend/src/hooks/useUnsavedChangesPrompt/useUnsavedChangesPrompt.test.tsx b/superset-frontend/src/hooks/useUnsavedChangesPrompt/useUnsavedChangesPrompt.test.tsx
index c927bd2ad84..9dd772ca916 100644
--- a/superset-frontend/src/hooks/useUnsavedChangesPrompt/useUnsavedChangesPrompt.test.tsx
+++ b/superset-frontend/src/hooks/useUnsavedChangesPrompt/useUnsavedChangesPrompt.test.tsx
@@ -16,152 +16,143 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { renderHook, act } from '@testing-library/react';
-import { Router } from 'react-router-dom';
-import { createMemoryHistory } from 'history';
+import { ReactNode } from 'react';
+import { renderHook, act, waitFor } from '@testing-library/react';
+import { useRouter } from '@tanstack/react-router';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import { useUnsavedChangesPrompt } from '.';
-let history = createMemoryHistory({
- initialEntries: ['/dashboard'],
-});
-
-beforeEach(() => {
- history = createMemoryHistory({ initialEntries: ['/dashboard'] });
-});
-
-const wrapper = ({ children }: { children: React.ReactNode }) => (
- <Router history={history}>{children}</Router>
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <StandaloneRouter initialEntries={['/dashboard']}>
+ {children}
+ </StandaloneRouter>
);
-test('should not show modal initially', () => {
- const { result } = renderHook(
- () =>
- useUnsavedChangesPrompt({
+const setup = async ({ onSave = jest.fn() }: { onSave?: jest.Mock } = {}) => {
+ const utils = renderHook(
+ () => ({
+ prompt: useUnsavedChangesPrompt({
hasUnsavedChanges: true,
- onSave: jest.fn(),
+ onSave,
}),
+ router: useRouter(),
+ }),
{ wrapper },
);
+ // the router mounts asynchronously before rendering its children
+ await waitFor(() => expect(utils.result.current).toBeTruthy());
+ return utils;
+};
+
+test('should not show modal initially', async () => {
+ const { result } = await setup();
- expect(result.current.showModal).toBe(false);
+ expect(result.current.prompt.showModal).toBe(false);
});
-test('should block navigation and show modal if there are unsaved changes', () => {
- const { result } = renderHook(
- () =>
- useUnsavedChangesPrompt({
- hasUnsavedChanges: true,
- onSave: jest.fn(),
- }),
- { wrapper },
- );
+test('should block navigation and show modal if there are unsaved changes', async () => {
+ const { result } = await setup();
- act(() => {
- history.push('/another-page');
+ await act(async () => {
+ result.current.router.history.push('/another-page');
});
- expect(result.current.showModal).toBe(true);
+ await waitFor(() => expect(result.current.prompt.showModal).toBe(true));
+ expect(result.current.router.state.location.pathname).toBe('/dashboard');
});
test('should trigger onSave and hide modal on handleSaveAndCloseModal', async () => {
const onSave = jest.fn().mockResolvedValue(undefined);
+ const { result } = await setup({ onSave });
- const { result } = renderHook(
- () =>
- useUnsavedChangesPrompt({
- hasUnsavedChanges: true,
- onSave,
- }),
- { wrapper },
- );
-
- await result.current.handleSaveAndCloseModal();
+ await act(async () => {
+ await result.current.prompt.handleSaveAndCloseModal();
+ });
expect(onSave).toHaveBeenCalled();
- expect(result.current.showModal).toBe(false);
+ expect(result.current.prompt.showModal).toBe(false);
});
test('should trigger manual save and not show modal again', async () => {
const onSave = jest.fn().mockResolvedValue(undefined);
+ const { result } = await setup({ onSave });
- const { result } = renderHook(
- () =>
- useUnsavedChangesPrompt({
- hasUnsavedChanges: true,
- onSave,
- }),
- { wrapper },
- );
-
- result.current.triggerManualSave();
+ act(() => {
+ result.current.prompt.triggerManualSave();
+ });
expect(onSave).toHaveBeenCalled();
- expect(result.current.showModal).toBe(false);
+ expect(result.current.prompt.showModal).toBe(false);
});
-test('should close modal when handleConfirmNavigation is called', () => {
- const onSave = jest.fn();
-
- const { result } = renderHook(
- () =>
- useUnsavedChangesPrompt({
- hasUnsavedChanges: true,
- onSave,
- }),
- { wrapper },
- );
+test('should close modal when handleConfirmNavigation is called', async () => {
+ const { result } = await setup();
// First, trigger navigation to show the modal
- act(() => {
- history.push('/another-page');
+ await act(async () => {
+ result.current.router.history.push('/another-page');
});
- expect(result.current.showModal).toBe(true);
+ await waitFor(() => expect(result.current.prompt.showModal).toBe(true));
// Then call handleConfirmNavigation to discard changes
- act(() => {
- result.current.handleConfirmNavigation();
+ await act(async () => {
+ result.current.prompt.handleConfirmNavigation();
});
- expect(result.current.showModal).toBe(false);
+ expect(result.current.prompt.showModal).toBe(false);
});
-test('should preserve pathname, search, and state when confirming navigation', () => {
- const onSave = jest.fn();
- const history = createMemoryHistory();
- const wrapper = ({ children }: any) => (
- <Router history={history}>{children}</Router>
- );
+test('should preserve pathname, search, and state when confirming navigation', async () => {
+ const { result } = await setup();
const locationState = { fromDashboard: true, dashboardId: 123 };
const pathname = '/another-page';
const search = '?slice_id=42&foo=bar';
- const { result } = renderHook(
- () => useUnsavedChangesPrompt({ hasUnsavedChanges: true, onSave }),
- { wrapper },
- );
-
- const pushSpy = jest.spyOn(history, 'push');
-
- // Simulate a blocked navigation (the hook sets up history.block internally)
- act(() => {
- history.push({ pathname, search }, locationState);
+ // Simulate a blocked navigation (the hook sets up a blocker internally)
+ await act(async () => {
+ result.current.router.history.push(`${pathname}${search}`, locationState);
});
// Modal should now be visible
- expect(result.current.showModal).toBe(true);
+ await waitFor(() => expect(result.current.prompt.showModal).toBe(true));
// Confirm navigation
- act(() => {
- result.current.handleConfirmNavigation();
+ await act(async () => {
+ result.current.prompt.handleConfirmNavigation();
});
// Modal should close
- expect(result.current.showModal).toBe(false);
+ expect(result.current.prompt.showModal).toBe(false);
+
+ // Verify the blocked navigation resumed with pathname, search, and state
+ await waitFor(() =>
+ expect(result.current.router.state.location.pathname).toBe(pathname),
+ );
+ expect(result.current.router.state.location.search).toEqual({
+ slice_id: '42',
+ foo: 'bar',
+ });
+ expect(result.current.router.state.location.state).toMatchObject(
+ locationState,
+ );
+});
+
+test('should discard the blocked navigation when modal is dismissed', async () => {
+ const { result } = await setup();
+
+ await act(async () => {
+ result.current.router.history.push('/another-page');
+ });
+
+ await waitFor(() => expect(result.current.prompt.showModal).toBe(true));
- // Verify correct call with pathname, search, and state preserved
- expect(pushSpy).toHaveBeenCalledWith({ pathname, search }, locationState);
+ // Dismiss the modal without confirming
+ await act(async () => {
+ result.current.prompt.setShowModal(false);
+ });
- pushSpy.mockRestore();
+ expect(result.current.prompt.showModal).toBe(false);
+ expect(result.current.router.state.location.pathname).toBe('/dashboard');
});
diff --git a/superset-frontend/src/pages/AlertReportList/AlertReportList.test.tsx b/superset-frontend/src/pages/AlertReportList/AlertReportList.test.tsx
index 8ac726eb4d0..eb781a7675a 100644
--- a/superset-frontend/src/pages/AlertReportList/AlertReportList.test.tsx
+++ b/superset-frontend/src/pages/AlertReportList/AlertReportList.test.tsx
@@ -26,9 +26,9 @@ import {
createStore,
} from 'spec/helpers/testing-library';
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import AlertListComponent from 'src/pages/AlertReportList';
jest.setTimeout(30000);
@@ -153,11 +153,11 @@ const renderAlertList = (props: Record<string, any> = {}) => {
const store = createStore();
return render(
<Provider store={store}>
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<AlertList user={mockUser} {...props} />
</QueryParamProvider>
- </MemoryRouter>
+ </StandaloneRouter>
</Provider>,
);
};
@@ -451,11 +451,11 @@ test('read-only users do not see delete and bulk select controls', async () => {
render(
<Provider store={store}>
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<AlertList user={readOnlyUser} />
</QueryParamProvider>
- </MemoryRouter>
+ </StandaloneRouter>
</Provider>,
);
diff --git a/superset-frontend/src/pages/AlertReportList/index.tsx b/superset-frontend/src/pages/AlertReportList/index.tsx
index e6dfe4ccb7b..e3a05455ac1 100644
--- a/superset-frontend/src/pages/AlertReportList/index.tsx
+++ b/superset-frontend/src/pages/AlertReportList/index.tsx
@@ -18,7 +18,7 @@
*/
import { useState, useMemo, useEffect, useCallback } from 'react';
-import { useHistory } from 'react-router-dom';
+import { useNavigate } from '@tanstack/react-router';
import { t } from '@apache-superset/core/translation';
import {
SupersetClient,
@@ -376,11 +376,13 @@ function AlertList({
},
{
Cell: ({ row: { original } }: any) => {
- const history = useHistory();
+ const navigate = useNavigate();
const handleEdit = () => handleAlertEdit(original);
const handleDelete = () => setCurrentAlertDeleting(original);
const handleGotoExecutionLog = () =>
- history.push(`/${original.type.toLowerCase()}/${original.id}/log`);
+ navigate({
+ to: `/${original.type.toLowerCase()}/${original.id}/log`,
+ });
const allowEdit =
original.owners.map((o: Owner) => o.id).includes(user.userId) ||
diff --git a/superset-frontend/src/pages/AnnotationLayerList/AnnotationLayerList.test.tsx b/superset-frontend/src/pages/AnnotationLayerList/AnnotationLayerList.test.tsx
index ecc32e2c614..2c8d79e9419 100644
--- a/superset-frontend/src/pages/AnnotationLayerList/AnnotationLayerList.test.tsx
+++ b/superset-frontend/src/pages/AnnotationLayerList/AnnotationLayerList.test.tsx
@@ -25,9 +25,9 @@ import {
fireEvent,
waitFor,
} from 'spec/helpers/testing-library';
-import { MemoryRouter } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import React from 'react';
import AnnotationLayersListComponent from 'src/pages/AnnotationLayerList';
@@ -81,11 +81,11 @@ fetchMock.get(layersRelatedEndpoint, {
const renderAnnotationLayersList = (props = {}) =>
render(
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<AnnotationLayersList user={mockUser} {...props} />
</QueryParamProvider>
- </MemoryRouter>,
+ </StandaloneRouter>,
{
useRedux: true,
store,
diff --git a/superset-frontend/src/pages/AnnotationLayerList/index.tsx b/superset-frontend/src/pages/AnnotationLayerList/index.tsx
index 02d94cea471..ed6b1bd01a5 100644
--- a/superset-frontend/src/pages/AnnotationLayerList/index.tsx
+++ b/superset-frontend/src/pages/AnnotationLayerList/index.tsx
@@ -21,7 +21,7 @@ import { useMemo, useState } from 'react';
import rison from 'rison';
import { t } from '@apache-superset/core/translation';
import { SupersetClient } from '@superset-ui/core';
-import { Link, useHistory } from 'react-router-dom';
+import { Link, useRouter } from '@tanstack/react-router';
import { useListViewResource } from 'src/views/CRUD/hooks';
import { createFetchRelated, createErrorHandler } from 'src/views/CRUD/utils';
import withToasts from 'src/components/MessageToasts/withToasts';
@@ -140,16 +140,10 @@ function AnnotationLayersList({
original: { id, name },
},
}: any) => {
- let hasHistory = true;
+ // If no router context exists, we know not to use <Link> in render
+ const hasRouter = Boolean(useRouter({ warn: false }));
- try {
- useHistory();
- } catch (err) {
- // If error is thrown, we know not to use <Link> in render
- hasHistory = false;
- }
-
- if (hasHistory) {
+ if (hasRouter) {
return <Link to={`/annotationlayer/${id}/annotation`}>{name}</Link>;
}
diff --git a/superset-frontend/src/pages/AnnotationList/index.tsx b/superset-frontend/src/pages/AnnotationList/index.tsx
index 68011f38772..2d4292733ed 100644
--- a/superset-frontend/src/pages/AnnotationList/index.tsx
+++ b/superset-frontend/src/pages/AnnotationList/index.tsx
@@ -18,7 +18,7 @@
*/
import { useMemo, useState, useEffect, useCallback } from 'react';
-import { useParams, Link, useHistory } from 'react-router-dom';
+import { useParams, Link, useRouter } from '@tanstack/react-router';
import { t } from '@apache-superset/core/translation';
import { SupersetClient, getClientErrorObject } from '@superset-ui/core';
import { css, styled } from '@apache-superset/core/theme';
@@ -68,7 +68,7 @@ function AnnotationList({
addDangerToast,
addSuccessToast,
}: AnnotationListProps) {
- const { annotationLayerId }: any = useParams();
+ const { annotationLayerId }: any = useParams({ strict: false });
const {
state: {
loading,
@@ -247,14 +247,8 @@ function AnnotationList({
},
});
- let hasHistory = true;
-
- try {
- useHistory();
- } catch (err) {
- // If error is thrown, we know not to use <Link> in render
- hasHistory = false;
- }
+ // If no router context exists, we know not to use <Link> in render
+ const hasRouter = Boolean(useRouter({ warn: false }));
const emptyState = {
title: t('No annotation yet'),
@@ -277,7 +271,7 @@ function AnnotationList({
<StyledHeader>
<span>{t('Annotation Layer %s', annotationLayerName)}</span>
<span>
- {hasHistory ? (
+ {hasRouter ? (
<Link to="/annotationlayer/list/">{t('Back to all')}</Link>
) : (
<Typography.Link href="/annotationlayer/list/">
diff --git a/superset-frontend/src/pages/Chart/Chart.test.tsx b/superset-frontend/src/pages/Chart/Chart.test.tsx
index 6f15faceb99..0df00542fbe 100644
--- a/superset-frontend/src/pages/Chart/Chart.test.tsx
+++ b/superset-frontend/src/pages/Chart/Chart.test.tsx
@@ -17,7 +17,7 @@
* under the License.
*/
import fetchMock from 'fetch-mock';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
import {
render,
waitFor,
@@ -261,11 +261,9 @@ describe('ChartPage', () => {
const { getByTestId } = render(
<>
<Link
- to={{
- pathname: '/',
- search: `?${URL_PARAMS.dashboardPageId.name}=${dashboardPageId}`,
- state: { saveAction: 'overwrite' },
- }}
+ to="/"
+ search={{ [URL_PARAMS.dashboardPageId.name]: dashboardPageId }}
+ state={{ saveAction: 'overwrite' }}
>
Change route
</Link>
@@ -319,7 +317,9 @@ describe('ChartPage', () => {
});
render(
<>
- <Link to="/?slice_id=99">Navigate away</Link>
+ <Link to="/" search={{ slice_id: '99' }}>
+ Navigate away
+ </Link>
<ChartPage />
</>,
{
@@ -410,7 +410,9 @@ describe('ChartPage', () => {
render(
<>
- <Link to="/?slice_id=99">Navigate</Link>
+ <Link to="/" search={{ slice_id: '99' }}>
+ Navigate
+ </Link>
<ChartPage />
</>,
{
diff --git a/superset-frontend/src/pages/Chart/index.tsx b/superset-frontend/src/pages/Chart/index.tsx
index d1e3f7b8f75..ce14600d1e7 100644
--- a/superset-frontend/src/pages/Chart/index.tsx
+++ b/superset-frontend/src/pages/Chart/index.tsx
@@ -18,8 +18,7 @@
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
-import { useHistory } from 'react-router-dom';
-import type { Location, Action } from 'history';
+import { useRouter, type HistoryLocation } from '@tanstack/react-router';
import { t } from '@apache-superset/core/translation';
import {
getLabelsColorMap,
@@ -136,7 +135,7 @@ export default function ExplorePage() {
const fetchGeneration = useRef(0);
const abortControllerRef = useRef<AbortController | null>(null);
const dispatch = useDispatch();
- const history = useHistory();
+ const router = useRouter();
const loadExploreData = useCallback(
(
@@ -291,29 +290,36 @@ export default function ExplorePage() {
// Initial fetch on mount
useEffect(() => {
- loadExploreData(history.location);
+ loadExploreData(router.history.location);
getLabelsColorMap().source = LabelsColorMapSource.Explore;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Re-fetch on navigation or post-save.
- // PUSH/POP: full reload (unmount + re-fetch).
+ // PUSH/BACK/FORWARD/GO: full reload (unmount + re-fetch).
// REPLACE with saveAction state: re-fetch without unmount (keeps chart visible).
// Other REPLACE: ignored (URL sync from updateHistory).
useEffect(() => {
- const unlisten = history.listen((loc: Location, action: Action) => {
- const saveAction = (loc.state as Record<string, unknown>)?.saveAction as
- | SaveActionType
- | undefined;
- if (action === 'PUSH' || action === 'POP') {
- setIsLoaded(false);
- loadExploreData(loc, saveAction);
- } else if (saveAction) {
- loadExploreData(loc, saveAction);
- }
- });
- return unlisten;
- }, [history, loadExploreData]);
+ const unsubscribe = router.history.subscribe(
+ ({
+ location: loc,
+ action,
+ }: {
+ location: HistoryLocation;
+ action: { type: string };
+ }) => {
+ const saveAction = (loc.state as Record<string, unknown>)
+ ?.saveAction as SaveActionType | undefined;
+ if (action.type !== 'REPLACE') {
+ setIsLoaded(false);
+ loadExploreData(loc, saveAction);
+ } else if (saveAction) {
+ loadExploreData(loc, saveAction);
+ }
+ },
+ );
+ return unsubscribe;
+ }, [router, loadExploreData]);
if (!isLoaded) {
return <Loading />;
diff --git a/superset-frontend/src/pages/ChartCreation/index.tsx b/superset-frontend/src/pages/ChartCreation/index.tsx
index 83e18a08e18..d68f46ce356 100644
--- a/superset-frontend/src/pages/ChartCreation/index.tsx
+++ b/superset-frontend/src/pages/ChartCreation/index.tsx
@@ -24,7 +24,7 @@ import { styled } from '@apache-superset/core/theme';
import { withTheme, Theme } from '@emotion/react';
import { getUrlParam } from 'src/utils/urlUtils';
import { FilterPlugins, URL_PARAMS } from 'src/constants';
-import { Link, withRouter, RouteComponentProps } from 'react-router-dom';
+import { Link, useRouter } from '@tanstack/react-router';
import {
AsyncSelect,
Button,
@@ -49,10 +49,11 @@ import {
datasetLabelLower,
} from 'src/features/semanticLayers/label';
-export interface ChartCreationProps extends RouteComponentProps {
+export interface ChartCreationProps {
user: UserWithPermissionsAndRoles;
addSuccessToast: (arg: string) => void;
theme: Theme;
+ history: { push: (path: string) => void };
}
export type ChartCreationState = {
@@ -397,4 +398,11 @@ export class ChartCreation extends PureComponent<
}
}
-export default withRouter(withToasts(withTheme(ChartCreation)));
+const ChartCreationWithToastsAndTheme = withToasts(withTheme(ChartCreation));
+
+export default function ChartCreationPage(props: {
+ user: UserWithPermissionsAndRoles;
+}) {
+ const { history } = useRouter();
+ return <ChartCreationWithToastsAndTheme {...props} history={history} />;
+}
diff --git a/superset-frontend/src/pages/ChartList/ChartList.permissions.test.tsx b/superset-frontend/src/pages/ChartList/ChartList.permissions.test.tsx
index 38db8180d20..198981dcb56 100644
--- a/superset-frontend/src/pages/ChartList/ChartList.permissions.test.tsx
+++ b/superset-frontend/src/pages/ChartList/ChartList.permissions.test.tsx
@@ -19,10 +19,10 @@
import fetchMock from 'fetch-mock';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { configureStore } from '@reduxjs/toolkit';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import { isFeatureEnabled } from '@superset-ui/core';
import ChartList from 'src/pages/ChartList';
import { API_ENDPOINTS, mockCharts, setupMocks } from './ChartList.testHelpers';
@@ -116,11 +116,11 @@ const renderChartList = (
return render(
<Provider store={store}>
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter initialEntries={['/']}>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<ChartList user={user} {...props} />
</QueryParamProvider>
- </MemoryRouter>
+ </StandaloneRouter>
</Provider>,
);
};
diff --git a/superset-frontend/src/pages/ChartList/ChartList.testHelpers.tsx b/superset-frontend/src/pages/ChartList/ChartList.testHelpers.tsx
index 1a27d5affeb..9fc9a7bd303 100644
--- a/superset-frontend/src/pages/ChartList/ChartList.testHelpers.tsx
+++ b/superset-frontend/src/pages/ChartList/ChartList.testHelpers.tsx
@@ -20,10 +20,10 @@
import fetchMock from 'fetch-mock';
import { render } from 'spec/helpers/testing-library';
import { Provider } from 'react-redux';
-import { BrowserRouter } from 'react-router-dom';
import { configureStore } from '@reduxjs/toolkit';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import ChartList from 'src/pages/ChartList';
import handleResourceExport from 'src/utils/export';
@@ -267,13 +267,15 @@ export const renderChartList = (user: any, props = {}, storeState = {}) => {
const store = createMockStore(storeStateWithUser);
+ // Browser (jsdom) history, not memory history: tests assert on
+ // window.location after navigation, matching the old BrowserRouter.
return render(
<Provider store={store}>
- <BrowserRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<ChartList user={user} {...props} />
</QueryParamProvider>
- </BrowserRouter>
+ </StandaloneRouter>
</Provider>,
);
};
diff --git a/superset-frontend/src/pages/ChartList/index.tsx b/superset-frontend/src/pages/ChartList/index.tsx
index 3c5ae28caf1..067ab8090c2 100644
--- a/superset-frontend/src/pages/ChartList/index.tsx
+++ b/superset-frontend/src/pages/ChartList/index.tsx
@@ -68,7 +68,8 @@ import {
type ListViewFilter,
} from 'src/components';
import SubMenu, { SubMenuProps } from 'src/features/home/SubMenu';
-import { Link, useHistory } from 'react-router-dom';
+import { Link, useNavigate } from '@tanstack/react-router';
+import { parseSearch } from 'src/router/searchParams';
import { dangerouslyGetItemDoNotUse } from 'src/utils/localStorageHelpers';
import withToasts from 'src/components/MessageToasts/withToasts';
import PropertiesModal from 'src/explore/components/PropertiesModal';
@@ -175,7 +176,7 @@ function ChartList(props: ChartListProps) {
user: { userId },
} = props;
- const history = useHistory();
+ const navigate = useNavigate();
const {
state: {
@@ -365,22 +366,31 @@ function ChartList(props: ChartListProps) {
description,
},
},
- }: any) => (
- <FlexRowContainer>
- <Link to={url} data-test={`${sliceName}-list-chart-title`}>
- {certifiedBy && (
- <>
- <CertifiedBadge
- certifiedBy={certifiedBy}
- details={certificationDetails}
- />{' '}
- </>
- )}
- {sliceName}
- </Link>
- {description && <InfoTooltip tooltip={description} />}
- </FlexRowContainer>
- ),
+ }: any) => {
+ // url comes from the backend and may contain a query string
+ // (cast: search prop types collapse to never for dynamic 'to' strings)
+ const [pathname, queryString] = url.split('?');
+ return (
+ <FlexRowContainer>
+ <Link
+ to={pathname}
+ search={parseSearch(queryString ?? '') as never}
+ data-test={`${sliceName}-list-chart-title`}
+ >
+ {certifiedBy && (
+ <>
+ <CertifiedBadge
+ certifiedBy={certifiedBy}
+ details={certificationDetails}
+ />{' '}
+ </>
+ )}
+ {sliceName}
+ </Link>
+ {description && <InfoTooltip tooltip={description} />}
+ </FlexRowContainer>
+ );
+ },
Header: t('Name'),
accessor: 'slice_name',
id: 'slice_name',
@@ -857,7 +867,7 @@ function ChartList(props: ChartListProps) {
name: t('Chart'),
buttonStyle: 'primary',
onClick: () => {
- history.push('/chart/add');
+ navigate({ to: '/chart/add' });
},
});
}
diff --git a/superset-frontend/src/pages/CssTemplateList/CssTemplateList.test.tsx b/superset-frontend/src/pages/CssTemplateList/CssTemplateList.test.tsx
index f47434443f3..f45deac6fc1 100644
--- a/superset-frontend/src/pages/CssTemplateList/CssTemplateList.test.tsx
+++ b/superset-frontend/src/pages/CssTemplateList/CssTemplateList.test.tsx
@@ -25,9 +25,9 @@ import {
fireEvent,
waitFor,
} from 'spec/helpers/testing-library';
-import { MemoryRouter } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import React from 'react';
import CssTemplatesListComponent from 'src/pages/CssTemplateList';
@@ -81,11 +81,11 @@ fetchMock.get(templatesRelatedEndpoint, {
const renderCssTemplatesList = (props = {}) =>
render(
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<CssTemplatesList user={mockUser} {...props} />
</QueryParamProvider>
- </MemoryRouter>,
+ </StandaloneRouter>,
{
useRedux: true,
store,
diff --git a/superset-frontend/src/pages/Dashboard/index.tsx b/superset-frontend/src/pages/Dashboard/index.tsx
index 3f0e49cdba5..f1d57a40ee0 100644
--- a/superset-frontend/src/pages/Dashboard/index.tsx
+++ b/superset-frontend/src/pages/Dashboard/index.tsx
@@ -17,11 +17,11 @@
* under the License.
*/
import { FC } from 'react';
-import { useParams } from 'react-router-dom';
+import { useParams } from '@tanstack/react-router';
import { DashboardPage } from 'src/dashboard/containers/DashboardPage';
const DashboardRoute: FC = () => {
- const { idOrSlug } = useParams<{ idOrSlug: string }>();
+ const { idOrSlug } = useParams({ strict: false }) as { idOrSlug: string };
return <DashboardPage idOrSlug={idOrSlug} />;
};
diff --git a/superset-frontend/src/pages/DashboardList/DashboardList.permissions.test.tsx b/superset-frontend/src/pages/DashboardList/DashboardList.permissions.test.tsx
index 68d1229d97b..65f747dd84b 100644
--- a/superset-frontend/src/pages/DashboardList/DashboardList.permissions.test.tsx
+++ b/superset-frontend/src/pages/DashboardList/DashboardList.permissions.test.tsx
@@ -19,10 +19,10 @@
import fetchMock from 'fetch-mock';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { configureStore } from '@reduxjs/toolkit';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import { isFeatureEnabled } from '@superset-ui/core';
import DashboardListComponent from 'src/pages/DashboardList';
import {
@@ -123,11 +123,11 @@ const renderDashboardListWithPermissions = (
return render(
<Provider store={store}>
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter initialEntries={['/']}>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<DashboardList user={user} {...props} />
</QueryParamProvider>
- </MemoryRouter>
+ </StandaloneRouter>
</Provider>,
);
};
diff --git a/superset-frontend/src/pages/DashboardList/DashboardList.testHelpers.tsx b/superset-frontend/src/pages/DashboardList/DashboardList.testHelpers.tsx
index b5cc1e4ea20..31fefe91e21 100644
--- a/superset-frontend/src/pages/DashboardList/DashboardList.testHelpers.tsx
+++ b/superset-frontend/src/pages/DashboardList/DashboardList.testHelpers.tsx
@@ -21,10 +21,10 @@ import fetchMock from 'fetch-mock';
import rison from 'rison';
import { render, screen } from 'spec/helpers/testing-library';
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { configureStore } from '@reduxjs/toolkit';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import DashboardListComponent from 'src/pages/DashboardList';
import handleResourceExport from 'src/utils/export';
@@ -260,11 +260,11 @@ export const renderDashboardList = (
return render(
<Provider store={store}>
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter initialEntries={['/']}>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<DashboardList user={user} {...props} />
</QueryParamProvider>
- </MemoryRouter>
+ </StandaloneRouter>
</Provider>,
);
};
diff --git a/superset-frontend/src/pages/DashboardList/index.tsx b/superset-frontend/src/pages/DashboardList/index.tsx
index a12fc03bcd5..1b84fe1518c 100644
--- a/superset-frontend/src/pages/DashboardList/index.tsx
+++ b/superset-frontend/src/pages/DashboardList/index.tsx
@@ -25,7 +25,8 @@ import {
import { styled } from '@apache-superset/core/theme';
import { useSelector } from 'react-redux';
import { useState, useMemo, useCallback } from 'react';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
+import { parseSearch } from 'src/router/searchParams';
import rison from 'rison';
import {
createFetchRelated,
@@ -343,19 +344,28 @@ function DashboardList(props: DashboardListProps) {
certification_details: certificationDetails,
},
},
- }: any) => (
- <Link to={url} title={dashboardTitle}>
- {certifiedBy && (
- <>
- <CertifiedBadge
- certifiedBy={certifiedBy}
- details={certificationDetails}
- />{' '}
- </>
- )}
- {dashboardTitle}
- </Link>
- ),
+ }: any) => {
+ // url comes from the backend and may contain a query string
+ // (cast: search prop types collapse to never for dynamic 'to' strings)
+ const [pathname, queryString] = url.split('?');
+ return (
+ <Link
+ to={pathname}
+ search={parseSearch(queryString ?? '') as never}
+ title={dashboardTitle}
+ >
+ {certifiedBy && (
+ <>
+ <CertifiedBadge
+ certifiedBy={certifiedBy}
+ details={certificationDetails}
+ />{' '}
+ </>
+ )}
+ {dashboardTitle}
+ </Link>
+ );
+ },
Header: t('Name'),
accessor: 'dashboard_title',
id: 'dashboard_title',
diff --git a/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx b/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx
index 4d845a830cd..7713fa346e8 100644
--- a/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx
+++ b/superset-frontend/src/pages/DatasetCreation/DatasetCreation.test.tsx
@@ -19,12 +19,10 @@
import { render, screen } from 'spec/helpers/testing-library';
import AddDataset from 'src/pages/DatasetCreation';
-const mockHistoryPush = jest.fn();
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: () => ({
- push: mockHistoryPush,
- }),
+const mockNavigate = jest.fn();
+jest.mock('@tanstack/react-router', () => ({
+ ...jest.requireActual('@tanstack/react-router'),
+ useNavigate: () => mockNavigate,
useParams: () => ({ datasetId: undefined }),
}));
diff --git a/superset-frontend/src/pages/DatasetCreation/index.tsx b/superset-frontend/src/pages/DatasetCreation/index.tsx
index fb77e7eeb4b..e1c2502bb16 100644
--- a/superset-frontend/src/pages/DatasetCreation/index.tsx
+++ b/superset-frontend/src/pages/DatasetCreation/index.tsx
@@ -17,7 +17,7 @@
* under the License.
*/
import { useReducer, Reducer, useEffect, useState } from 'react';
-import { useParams } from 'react-router-dom';
+import { useParams } from '@tanstack/react-router';
import useDatasetsList from 'src/features/datasets/hooks/useDatasetLists';
import Header from 'src/features/datasets/AddDataset/Header';
import EditPage from 'src/features/datasets/AddDataset/EditDataset';
@@ -95,7 +95,9 @@ export default function AddDataset() {
dataset?.schema,
);
- const { datasetId: id } = useParams<{ datasetId: string }>();
+ const { datasetId: id } = useParams({ strict: false }) as {
+ datasetId: string;
+ };
useEffect(() => {
if (!Number.isNaN(parseInt(id, 10))) {
setEditPageIsVisible(true);
diff --git a/superset-frontend/src/pages/DatasetList/DatasetList.testHelpers.tsx b/superset-frontend/src/pages/DatasetList/DatasetList.testHelpers.tsx
index 30b51bbe6ed..2eb3f1d096e 100644
--- a/superset-frontend/src/pages/DatasetList/DatasetList.testHelpers.tsx
+++ b/superset-frontend/src/pages/DatasetList/DatasetList.testHelpers.tsx
@@ -20,10 +20,10 @@
import fetchMock from 'fetch-mock';
import { render, screen } from 'spec/helpers/testing-library';
import { Provider } from 'react-redux';
-import { MemoryRouter } from 'react-router-dom';
import { configureStore } from '@reduxjs/toolkit';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import DatasetList from 'src/pages/DatasetList';
import handleResourceExport from 'src/utils/export';
@@ -386,11 +386,11 @@ export const renderDatasetList = (
return render(
<Provider store={store}>
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter initialEntries={['/']}>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<DatasetList user={user} {...props} />
</QueryParamProvider>
- </MemoryRouter>
+ </StandaloneRouter>
</Provider>,
);
};
diff --git a/superset-frontend/src/pages/DatasetList/index.tsx b/superset-frontend/src/pages/DatasetList/index.tsx
index b74181953ef..2c98fcc3bda 100644
--- a/superset-frontend/src/pages/DatasetList/index.tsx
+++ b/superset-frontend/src/pages/DatasetList/index.tsx
@@ -33,7 +33,8 @@ import {
Key,
} from 'react';
import type { CellProps } from 'react-table';
-import { Link, useHistory } from 'react-router-dom';
+import { Link, useNavigate } from '@tanstack/react-router';
+import { parseSearch } from 'src/router/searchParams';
import rison from 'rison';
import {
createFetchRelated,
@@ -200,7 +201,7 @@ const DatasetList: FunctionComponent<DatasetListProps> = ({
addSuccessToast,
user,
}) => {
- const history = useHistory();
+ const navigate = useNavigate();
const theme = useTheme();
const {
state: { bulkSelectEnabled },
@@ -674,8 +675,14 @@ const DatasetList: FunctionComponent<DatasetListProps> = ({
}: CellProps<Dataset>) => {
let titleLink: JSX.Element;
if (PREVENT_UNSAFE_DEFAULT_URLS_ON_DATASET) {
+ // explore_url comes from the backend and may contain a query string
+ const [explorePath, exploreQuery] = exploreURL.split('?');
titleLink = (
- <Link data-test="internal-link" to={exploreURL}>
+ <Link
+ data-test="internal-link"
+ to={explorePath}
+ search={parseSearch(exploreQuery ?? '')}
+ >
{datasetTitle}
</Link>
);
@@ -1181,7 +1188,7 @@ const DatasetList: FunctionComponent<DatasetListProps> = ({
{
key: 'dataset',
label: t('Dataset'),
- onClick: () => history.push('/dataset/add/'),
+ onClick: () => navigate({ to: '/dataset/add/' }),
},
{
key: 'semantic-view',
@@ -1214,7 +1221,7 @@ const DatasetList: FunctionComponent<DatasetListProps> = ({
icon: <Icons.PlusOutlined iconSize="m" />,
name: datasetLabel(),
onClick: () => {
- history.push('/dataset/add/');
+ navigate({ to: '/dataset/add/' });
},
buttonStyle: 'primary',
});
diff --git a/superset-frontend/src/pages/ExecutionLogList/ExecutionLogList.test.tsx b/superset-frontend/src/pages/ExecutionLogList/ExecutionLogList.test.tsx
index 01bf922f331..385dd72c93f 100644
--- a/superset-frontend/src/pages/ExecutionLogList/ExecutionLogList.test.tsx
+++ b/superset-frontend/src/pages/ExecutionLogList/ExecutionLogList.test.tsx
@@ -47,8 +47,8 @@ fetchMock.get(reportEndpoint, {
result: { name: 'Test 0' },
});
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'), // use actual for all non-hook parts
+jest.mock('@tanstack/react-router', () => ({
+ ...jest.requireActual('@tanstack/react-router'), // use actual for all non-hook parts
useParams: () => ({ alertId: '1' }),
}));
diff --git a/superset-frontend/src/pages/ExecutionLogList/index.tsx b/superset-frontend/src/pages/ExecutionLogList/index.tsx
index 997eae32fb0..9c77aad3e55 100644
--- a/superset-frontend/src/pages/ExecutionLogList/index.tsx
+++ b/superset-frontend/src/pages/ExecutionLogList/index.tsx
@@ -24,7 +24,7 @@ import {
fDuration,
} from '@superset-ui/core/utils/dates';
import { useEffect, useMemo } from 'react';
-import { Link, useParams } from 'react-router-dom';
+import { Link, useParams } from '@tanstack/react-router';
import { Label, Tooltip } from '@superset-ui/core/components';
import { ListView } from 'src/components';
import SubMenu from 'src/features/home/SubMenu';
@@ -65,7 +65,7 @@ function ExecutionLog({
addSuccessToast,
isReportEnabled,
}: ExecutionLogProps) {
- const { alertId }: any = useParams();
+ const { alertId }: any = useParams({ strict: false });
const {
state: { loading, resourceCount: logCount, resourceCollection: logs },
fetchData,
diff --git a/superset-frontend/src/pages/FileHandler/index.test.tsx b/superset-frontend/src/pages/FileHandler/index.test.tsx
index a4496625fa7..5f2a5b35e25 100644
--- a/superset-frontend/src/pages/FileHandler/index.test.tsx
+++ b/superset-frontend/src/pages/FileHandler/index.test.tsx
@@ -23,12 +23,12 @@ import {
userEvent,
waitFor,
} from 'spec/helpers/testing-library';
-import { MemoryRouter, Route } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import FileHandler from './index';
const mockAddDangerToast = jest.fn();
const mockAddSuccessToast = jest.fn();
-const mockHistoryPush = jest.fn();
+const mockNavigate = jest.fn();
jest.setTimeout(60000);
@@ -82,12 +82,10 @@ jest.mock('src/features/databases/UploadDataModel', () => ({
),
}));
-// Mock react-router-dom's useHistory
-jest.mock('react-router-dom', () => ({
- ...jest.requireActual('react-router-dom'),
- useHistory: () => ({
- push: mockHistoryPush,
- }),
+// Mock @tanstack/react-router's useNavigate
+jest.mock('@tanstack/react-router', () => ({
+ ...jest.requireActual('@tanstack/react-router'),
+ useNavigate: () => mockNavigate,
}));
// Mock the File API
@@ -189,11 +187,9 @@ afterEach(async () => {
test('shows error when launchQueue is not supported', async () => {
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
@@ -201,7 +197,7 @@ test('shows error when launchQueue is not supported', async () => {
expect(mockAddDangerToast).toHaveBeenCalledWith(
'File handling is not supported in this browser. Please use a modern browser like Chrome or Edge.',
);
- expect(mockHistoryPush).toHaveBeenCalledWith('/superset/welcome/');
+ expect(mockNavigate).toHaveBeenCalledWith({ to: '/superset/welcome/' });
});
});
@@ -209,11 +205,9 @@ test('redirects when no files are provided', async () => {
const { triggerConsumer } = setupLaunchQueue();
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
@@ -221,7 +215,7 @@ test('redirects when no files are provided', async () => {
await triggerConsumer({ files: [] });
await waitFor(() => {
- expect(mockHistoryPush).toHaveBeenCalledWith('/superset/welcome/');
+ expect(mockNavigate).toHaveBeenCalledWith({ to: '/superset/welcome/' });
});
});
@@ -231,11 +225,9 @@ test.skip('handles CSV file correctly', async () => {
setupLaunchQueue(fileHandle);
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
@@ -252,11 +244,9 @@ test('handles Excel (.xls) file correctly', async () => {
setupLaunchQueue(fileHandle);
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
@@ -271,11 +261,9 @@ test('handles Excel (.xlsx) file correctly', async () => {
const { triggerConsumer } = setupLaunchQueue();
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
@@ -292,11 +280,9 @@ test('handles Parquet file correctly', async () => {
setupLaunchQueue(fileHandle);
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
@@ -310,11 +296,9 @@ test('shows error for unsupported file type', async () => {
const { triggerConsumer } = setupLaunchQueue();
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
@@ -326,7 +310,7 @@ test('shows error for unsupported file type', async () => {
expect(mockAddDangerToast).toHaveBeenCalledWith(
'Unsupported file type. Please use CSV, Excel, or Columnar files.',
);
- expect(mockHistoryPush).toHaveBeenCalledWith('/superset/welcome/');
+ expect(mockNavigate).toHaveBeenCalledWith({ to: '/superset/welcome/' });
});
});
@@ -335,11 +319,9 @@ test('handles file with uppercase extension', async () => {
setupLaunchQueue(fileHandle);
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
@@ -352,11 +334,9 @@ test('handles errors during file processing', async () => {
const { triggerConsumer } = setupLaunchQueue();
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
@@ -378,7 +358,7 @@ test('handles errors during file processing', async () => {
expect(mockAddDangerToast).toHaveBeenCalledWith(
'Failed to open file. Please try again.',
);
- expect(mockHistoryPush).toHaveBeenCalledWith('/superset/welcome/');
+ expect(mockNavigate).toHaveBeenCalledWith({ to: '/superset/welcome/' });
});
});
@@ -387,11 +367,9 @@ test('modal close redirects to welcome page', async () => {
setupLaunchQueue(fileHandle);
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
@@ -402,7 +380,7 @@ test('modal close redirects to welcome page', async () => {
await userEvent.click(screen.getByRole('button', { name: 'Close' }));
await waitFor(() => {
- expect(mockHistoryPush).toHaveBeenCalledWith('/superset/welcome/');
+ expect(mockNavigate).toHaveBeenCalledWith({ to: '/superset/welcome/' });
});
});
@@ -410,11 +388,9 @@ test('shows loading state while waiting for file', () => {
setupLaunchQueue();
render(
- <MemoryRouter initialEntries={['/superset/file-handler']}>
- <Route path="/superset/file-handler">
- <FileHandler />
- </Route>
- </MemoryRouter>,
+ <StandaloneRouter initialEntries={['/superset/file-handler']}>
+ <FileHandler />
+ </StandaloneRouter>,
{ useRedux: true },
);
diff --git a/superset-frontend/src/pages/FileHandler/index.tsx b/superset-frontend/src/pages/FileHandler/index.tsx
index 589db966f74..02471f13d5b 100644
--- a/superset-frontend/src/pages/FileHandler/index.tsx
+++ b/superset-frontend/src/pages/FileHandler/index.tsx
@@ -17,7 +17,7 @@
* under the License.
*/
import { useEffect, useState } from 'react';
-import { useHistory } from 'react-router-dom';
+import { useNavigate } from '@tanstack/react-router';
import { t } from '@apache-superset/core/translation';
import { Loading } from '@superset-ui/core/components';
import UploadDataModal from 'src/features/databases/UploadDataModel';
@@ -41,7 +41,7 @@ interface FileHandlerProps {
}
const FileHandler = ({ addDangerToast, addSuccessToast }: FileHandlerProps) => {
- const history = useHistory();
+ const navigate = useNavigate();
const [uploadFile, setUploadFile] = useState<File | null>(null);
const [uploadType, setUploadType] = useState<
'csv' | 'excel' | 'columnar' | null
@@ -59,13 +59,13 @@ const FileHandler = ({ addDangerToast, addSuccessToast }: FileHandlerProps) => {
'File handling is not supported in this browser. Please use a modern browser like Chrome or Edge.',
),
);
- history.push('/superset/welcome/');
+ navigate({ to: '/superset/welcome/' });
return;
}
launchQueue.setConsumer(async (launchParams: FileLaunchParams) => {
if (!launchParams.files || launchParams.files.length === 0) {
- history.push('/superset/welcome/');
+ navigate({ to: '/superset/welcome/' });
return;
}
@@ -92,7 +92,7 @@ const FileHandler = ({ addDangerToast, addSuccessToast }: FileHandlerProps) => {
'Unsupported file type. Please use CSV, Excel, or Columnar files.',
),
);
- history.push('/superset/welcome/');
+ navigate({ to: '/superset/welcome/' });
return;
}
@@ -103,19 +103,19 @@ const FileHandler = ({ addDangerToast, addSuccessToast }: FileHandlerProps) => {
} catch (error) {
console.error('Error handling file launch:', error);
addDangerToast(t('Failed to open file. Please try again.'));
- history.push('/superset/welcome/');
+ navigate({ to: '/superset/welcome/' });
}
});
};
handleFileLaunch();
- }, [history, addDangerToast]);
+ }, [navigate, addDangerToast]);
const handleModalClose = () => {
setShowModal(false);
setUploadFile(null);
setUploadType(null);
- history.push('/superset/welcome/');
+ navigate({ to: '/superset/welcome/' });
};
if (!uploadFile || !uploadType) {
diff --git a/superset-frontend/src/pages/GroupsList/GroupsList.test.tsx b/superset-frontend/src/pages/GroupsList/GroupsList.test.tsx
index 81bd86f8078..4753a650453 100644
--- a/superset-frontend/src/pages/GroupsList/GroupsList.test.tsx
+++ b/superset-frontend/src/pages/GroupsList/GroupsList.test.tsx
@@ -28,9 +28,6 @@ import {
act,
within,
} from 'spec/helpers/testing-library';
-import { MemoryRouter } from 'react-router-dom';
-import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
import GroupsList from './index';
const mockStore = configureStore([thunk]);
@@ -78,14 +75,11 @@ jest.mock('src/dashboard/util/permissionUtils', () => ({
describe('GroupsList', () => {
const renderComponent = async () => {
await act(async () => {
- render(
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
- <GroupsList user={mockUser} />
- </QueryParamProvider>
- </MemoryRouter>,
- { useRedux: true, store },
- );
+ render(<GroupsList user={mockUser} />, {
+ useRedux: true,
+ store,
+ useQueryParams: true,
+ });
});
};
diff --git a/superset-frontend/src/pages/QueryHistoryList/index.tsx b/superset-frontend/src/pages/QueryHistoryList/index.tsx
index b11ae6631e6..85585d6d7fb 100644
--- a/superset-frontend/src/pages/QueryHistoryList/index.tsx
+++ b/superset-frontend/src/pages/QueryHistoryList/index.tsx
@@ -17,7 +17,8 @@
* under the License.
*/
import { useMemo, useState, useCallback, ReactElement, useEffect } from 'react';
-import { Link, useHistory } from 'react-router-dom';
+import { Link, useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import { t } from '@apache-superset/core/translation';
import { QueryState, SupersetClient } from '@superset-ui/core';
import { css, styled, useTheme } from '@apache-superset/core/theme';
@@ -116,7 +117,7 @@ function QueryList({ addDangerToast }: QueryListProps) {
useState<QueryObject>();
const theme = useTheme();
- const history = useHistory();
+ const router = useRouter();
// Preload SQL language since this component will definitely display SQL
useEffect(() => {
@@ -400,7 +401,7 @@ function QueryList({ addDangerToast }: QueryListProps) {
},
}: any) => (
<Tooltip title={t('Open query in SQL Lab')} placement="bottom">
- <Link to={`/sqllab?queryId=${id}`}>
+ <Link to="/sqllab" search={{ queryId: String(id) }}>
<Icons.Full iconSize="l" />
</Link>
</Tooltip>
@@ -493,7 +494,9 @@ function QueryList({ addDangerToast }: QueryListProps) {
query={queryCurrentlyPreviewing}
queries={queries}
fetchData={handleQueryPreview}
- openInSqlLab={(id: number) => history.push(`/sqllab?queryId=${id}`)}
+ openInSqlLab={(id: number) =>
+ pushAppHref(router, `/sqllab?queryId=${id}`)
+ }
show
/>
)}
diff --git a/superset-frontend/src/pages/Register/Register.test.tsx b/superset-frontend/src/pages/Register/Register.test.tsx
index d870bc527ce..6e50a6ce0b6 100644
--- a/superset-frontend/src/pages/Register/Register.test.tsx
+++ b/superset-frontend/src/pages/Register/Register.test.tsx
@@ -17,7 +17,7 @@
* under the License.
*/
import { render, screen } from 'spec/helpers/testing-library';
-import { MemoryRouter } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import Register from './index';
jest.mock('src/utils/getBootstrapData', () => ({
@@ -38,9 +38,9 @@ jest.mock('react-google-recaptcha', () => ({
const renderRegister = () =>
render(
- <MemoryRouter>
+ <StandaloneRouter>
<Register />
- </MemoryRouter>,
+ </StandaloneRouter>,
);
test('should render register form elements', () => {
diff --git a/superset-frontend/src/pages/Register/index.tsx b/superset-frontend/src/pages/Register/index.tsx
index cb962687de1..66de00ef47b 100644
--- a/superset-frontend/src/pages/Register/index.tsx
+++ b/superset-frontend/src/pages/Register/index.tsx
@@ -31,7 +31,7 @@ import {
import { useState } from 'react';
import getBootstrapData from 'src/utils/getBootstrapData';
import ReactCAPTCHA from 'react-google-recaptcha';
-import { useParams } from 'react-router-dom';
+import { useParams } from '@tanstack/react-router';
interface RegisterForm {
username: string;
@@ -68,7 +68,9 @@ export default function Login() {
const [form] = Form.useForm<RegisterForm>();
const [loading, setLoading] = useState(false);
const [captchaResponse, setCaptchaResponse] = useState<string | null>(null);
- const { activationHash } = useParams<{ activationHash?: string }>();
+ const { activationHash } = useParams({ strict: false }) as {
+ activationHash?: string;
+ };
const bootstrapData = getBootstrapData();
diff --git a/superset-frontend/src/pages/RolesList/RolesList.test.tsx b/superset-frontend/src/pages/RolesList/RolesList.test.tsx
index 6a179238d4e..d0c912a8d5c 100644
--- a/superset-frontend/src/pages/RolesList/RolesList.test.tsx
+++ b/superset-frontend/src/pages/RolesList/RolesList.test.tsx
@@ -27,9 +27,6 @@ import {
act,
within,
} from 'spec/helpers/testing-library';
-import { MemoryRouter } from 'react-router-dom';
-import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
import RolesList from './index';
const mockStore = configureStore([thunk]);
@@ -106,17 +103,13 @@ describe('RolesList', () => {
const mounted = act(async () => {
const mockedProps = {};
render(
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
- <RolesList
- user={mockUser}
- addDangerToast={() => {}}
- addSuccessToast={() => {}}
- {...mockedProps}
- />
- </QueryParamProvider>
- </MemoryRouter>,
- { useRedux: true, store },
+ <RolesList
+ user={mockUser}
+ addDangerToast={() => {}}
+ addSuccessToast={() => {}}
+ {...mockedProps}
+ />,
+ { useRedux: true, store, useQueryParams: true },
);
});
return mounted;
diff --git a/superset-frontend/src/pages/RowLevelSecurityList/RowLevelSecurityList.test.tsx b/superset-frontend/src/pages/RowLevelSecurityList/RowLevelSecurityList.test.tsx
index 538e7ae41b1..1f7202dffe8 100644
--- a/superset-frontend/src/pages/RowLevelSecurityList/RowLevelSecurityList.test.tsx
+++ b/superset-frontend/src/pages/RowLevelSecurityList/RowLevelSecurityList.test.tsx
@@ -18,9 +18,9 @@
*/
import fetchMock from 'fetch-mock';
import { act, render, screen, within } from 'spec/helpers/testing-library';
-import { MemoryRouter } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import userEvent from '@testing-library/user-event';
import RowLevelSecurityList from '.';
@@ -109,11 +109,11 @@ describe('RuleList RTL', () => {
const mounted = act(async () => {
const mockedProps = {};
render(
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<RowLevelSecurityList {...mockedProps} user={mockUser} />
</QueryParamProvider>
- </MemoryRouter>,
+ </StandaloneRouter>,
{ useRedux: true },
);
});
diff --git a/superset-frontend/src/pages/SavedQueryList/SavedQueryList.test.tsx b/superset-frontend/src/pages/SavedQueryList/SavedQueryList.test.tsx
index 9fcb399e7e2..95ffbf00110 100644
--- a/superset-frontend/src/pages/SavedQueryList/SavedQueryList.test.tsx
+++ b/superset-frontend/src/pages/SavedQueryList/SavedQueryList.test.tsx
@@ -25,17 +25,22 @@ import {
fireEvent,
waitFor,
} from 'spec/helpers/testing-library';
-import { MemoryRouter, useLocation } from 'react-router-dom';
+import { useLocation } from '@tanstack/react-router';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import * as getBootstrapData from 'src/utils/getBootstrapData';
import SavedQueryList from '.';
// Renders the current router pathname+search so tests can assert navigation.
function LocationDisplay() {
const location = useLocation();
+ // searchStr already includes the leading '?' (it is the stringifySearch
+ // output), matching react-router's location.search semantics.
return (
- <div data-test="location-display">{`${location.pathname}${location.search}`}</div>
+ <div data-test="location-display">
+ {`${location.pathname}${location.searchStr}`}
+ </div>
);
}
@@ -94,12 +99,12 @@ fetchMock.delete(queryEndpoint, {}, { name: queryEndpoint });
const renderList = (props = {}, storeOverrides = {}) =>
render(
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter initialEntries={['/']}>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<SavedQueryList user={mockUser} {...props} />
<LocationDisplay />
</QueryParamProvider>
- </MemoryRouter>,
+ </StandaloneRouter>,
{
useRedux: true,
store: configureStore([thunk])({
@@ -256,11 +261,11 @@ describe('SavedQueryList', () => {
test('"+ Query" button pushes a router-relative path (subdirectory deployment)', async () => {
// Simulate SUPERSET_APP_ROOT=/superset. ensureAppRoot/makeUrl read
// applicationRoot() dynamically, so mocking it here makes the buggy code
- // path (makeUrl() around history.push) produce '/superset/sqllab?new=true'
- // instead of being a no-op. React Router's <Router basename> prefixes the
- // app root on its own, so history.push MUST receive a path without the
- // app-root prefix — otherwise navigation lands at /superset/superset/sqllab
- // and shows a blank page (sc-103661).
+ // path (makeUrl() around the history push) produce
+ // '/superset/sqllab?new=true' instead of being a no-op. The router's
+ // basepath prefixes the app root on its own, so the push MUST receive a
+ // path without the app-root prefix — otherwise navigation lands at
+ // /superset/superset/sqllab and shows a blank page (sc-103661).
const applicationRootSpy = jest
.spyOn(getBootstrapData, 'applicationRoot')
.mockReturnValue('/superset');
@@ -276,10 +281,11 @@ describe('SavedQueryList', () => {
fireEvent.click(queryButton);
await waitFor(() => {
- // The MemoryRouter in renderList uses the default ('/') basename, so
- // useLocation reflects exactly what history.push received. A correct
- // router-relative push produces '/sqllab?new=true'; a buggy push that
- // re-applied the app root would produce '/superset/sqllab?new=true'.
+ // The StandaloneRouter in renderList uses the default ('/') basepath,
+ // so useLocation reflects exactly what the history push received. A
+ // correct router-relative push produces '/sqllab?new=true'; a buggy
+ // push that re-applied the app root would produce
+ // '/superset/sqllab?new=true'.
const location = screen.getByTestId('location-display').textContent;
expect(location).toBe('/sqllab?new=true');
});
diff --git a/superset-frontend/src/pages/SavedQueryList/index.tsx b/superset-frontend/src/pages/SavedQueryList/index.tsx
index 1010585eb37..6a7d8b26748 100644
--- a/superset-frontend/src/pages/SavedQueryList/index.tsx
+++ b/superset-frontend/src/pages/SavedQueryList/index.tsx
@@ -25,7 +25,8 @@ import {
} from '@superset-ui/core';
import { styled } from '@apache-superset/core/theme';
import { useCallback, useMemo, useState, MouseEvent } from 'react';
-import { Link, useHistory } from 'react-router-dom';
+import { Link, useRouter } from '@tanstack/react-router';
+import { pushAppHref } from 'src/router/navigation';
import rison from 'rison';
import {
createErrorHandler,
@@ -146,7 +147,7 @@ function SavedQueryList({
sshTunnelPrivateKeyPasswordFields,
setSSHTunnelPrivateKeyPasswordFields,
] = useState<string[]>([]);
- const history = useHistory();
+ const router = useRouter();
const openSavedQueryImportModal = () => {
showImportModal(true);
@@ -223,9 +224,9 @@ function SavedQueryList({
name: t('Query'),
buttonStyle: 'primary',
onClick: () => {
- // React Router's basename already includes the application root; passing
+ // The router's basepath already includes the application root; passing
// a relative path ensures correct navigation under subdirectory deployments.
- history.push('/sqllab?new=true');
+ pushAppHref(router, '/sqllab?new=true');
},
});
@@ -247,9 +248,9 @@ function SavedQueryList({
if (openInNewWindow) {
window.open(makeUrl(`/sqllab?savedQueryId=${id}`));
} else {
- // React Router's basename already includes the application root; passing
+ // The router's basepath already includes the application root; passing
// a relative path ensures correct navigation under subdirectory deployments.
- history.push(`/sqllab?savedQueryId=${id}`);
+ pushAppHref(router, `/sqllab?savedQueryId=${id}`);
}
};
@@ -342,7 +343,11 @@ function SavedQueryList({
row: {
original: { id, label },
},
- }: any) => <Link to={`/sqllab?savedQueryId=${id}`}>{label}</Link>,
+ }: any) => (
+ <Link to="/sqllab" search={{ savedQueryId: String(id) }}>
+ {label}
+ </Link>
+ ),
id: 'label',
},
{
diff --git a/superset-frontend/src/pages/SqlLab/LocationContext.tsx b/superset-frontend/src/pages/SqlLab/LocationContext.tsx
index ae16704c91d..57fe446c98b 100644
--- a/superset-frontend/src/pages/SqlLab/LocationContext.tsx
+++ b/superset-frontend/src/pages/SqlLab/LocationContext.tsx
@@ -19,7 +19,7 @@
import { createContext, useContext, FC, ReactNode } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useLocation } from '@tanstack/react-router';
export type LocationState = {
requestedQuery?: Record<string, any>;
@@ -34,11 +34,14 @@ const EMPTY_STATE: LocationState = {};
export const LocationProvider: FC<{ children?: ReactNode }> = ({
children,
}) => {
- const location = useLocation<LocationState>();
- if (location.state) {
- return <Provider value={location.state}>{children}</Provider>;
+ const location = useLocation();
+ // TanStack's location.state is always an object (it carries internal
+ // router keys), so check for the keys this context actually consumes.
+ const state = location.state as LocationState;
+ if ('requestedQuery' in state || 'isDataset' in state) {
+ return <Provider value={state}>{children}</Provider>;
}
- const queryParams = new URLSearchParams(location.search);
+ const queryParams = new URLSearchParams(location.searchStr);
const permalink = location.pathname.match(/\/p\/\w+/)?.[0].slice(3);
if (queryParams.size > 0 || permalink) {
const autorun = queryParams.get('autorun') === 'true';
diff --git a/superset-frontend/src/pages/Tags/index.tsx b/superset-frontend/src/pages/Tags/index.tsx
index bb45bf1cab3..5d0b87b97e0 100644
--- a/superset-frontend/src/pages/Tags/index.tsx
+++ b/superset-frontend/src/pages/Tags/index.tsx
@@ -42,7 +42,7 @@ import SubMenu, { SubMenuProps } from 'src/features/home/SubMenu';
import { dangerouslyGetItemDoNotUse } from 'src/utils/localStorageHelpers';
import withToasts from 'src/components/MessageToasts/withToasts';
import { Icons } from '@superset-ui/core/components/Icons';
-import { Link } from 'react-router-dom';
+import { Link } from '@tanstack/react-router';
import { deleteTags } from 'src/features/tags/tags';
import { QueryObjectColumns, Tag } from 'src/views/CRUD/types';
import TagModal from 'src/features/tags/TagModal';
@@ -168,7 +168,9 @@ function TagList(props: TagListProps) {
},
}: any) => (
<AntdTag>
- <Link to={`/superset/all_entities/?id=${id}`}>{tagName}</Link>
+ <Link to="/superset/all_entities/" search={{ id: String(id) }}>
+ {tagName}
+ </Link>
</AntdTag>
),
Header: t('Name'),
diff --git a/superset-frontend/src/pages/TaskList/TaskList.test.tsx b/superset-frontend/src/pages/TaskList/TaskList.test.tsx
index f7b85c42e74..05120d83740 100644
--- a/superset-frontend/src/pages/TaskList/TaskList.test.tsx
+++ b/superset-frontend/src/pages/TaskList/TaskList.test.tsx
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { MemoryRouter } from 'react-router-dom';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
import fetchMock from 'fetch-mock';
import {
render,
@@ -25,7 +25,7 @@ import {
fireEvent,
} from 'spec/helpers/testing-library';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import { TaskStatus, TaskScope } from 'src/features/tasks/types';
import TaskList from 'src/pages/TaskList';
@@ -189,11 +189,11 @@ fetchMock.post(
const renderTaskList = (props = {}, userProp = mockUser) =>
render(
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
+ <StandaloneRouter>
+ <QueryParamProvider adapter={TanstackRouterAdapter}>
<TaskList {...props} user={userProp} />
</QueryParamProvider>
- </MemoryRouter>,
+ </StandaloneRouter>,
{ useRedux: true },
);
diff --git a/superset-frontend/src/pages/UserInfo/UserInfo.test.tsx b/superset-frontend/src/pages/UserInfo/UserInfo.test.tsx
index d15b7090e23..91e60dbbd83 100644
--- a/superset-frontend/src/pages/UserInfo/UserInfo.test.tsx
+++ b/superset-frontend/src/pages/UserInfo/UserInfo.test.tsx
@@ -26,9 +26,6 @@ import {
} from 'spec/helpers/testing-library';
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
-import { MemoryRouter } from 'react-router-dom';
-import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
import UserInfo from 'src/pages/UserInfo';
import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes';
@@ -64,14 +61,11 @@ const mockUser: UserWithPermissionsAndRoles = {
describe('UserInfo', () => {
const renderPage = async (user: UserWithPermissionsAndRoles = mockUser) =>
act(async () => {
- render(
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
- <UserInfo user={user} />
- </QueryParamProvider>
- </MemoryRouter>,
- { useRedux: true, store },
- );
+ render(<UserInfo user={user} />, {
+ useRedux: true,
+ store,
+ useQueryParams: true,
+ });
});
beforeEach(() => {
diff --git a/superset-frontend/src/pages/UsersList/UsersList.test.tsx b/superset-frontend/src/pages/UsersList/UsersList.test.tsx
index 63539113eed..909e4ac3aaa 100644
--- a/superset-frontend/src/pages/UsersList/UsersList.test.tsx
+++ b/superset-frontend/src/pages/UsersList/UsersList.test.tsx
@@ -27,9 +27,6 @@ import {
act,
within,
} from 'spec/helpers/testing-library';
-import { MemoryRouter } from 'react-router-dom';
-import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
import UsersList from './index';
const mockStore = configureStore([thunk]);
@@ -99,14 +96,11 @@ describe('UsersList', () => {
async function renderAndWait() {
const mounted = act(async () => {
const mockedProps = {};
- render(
- <MemoryRouter>
- <QueryParamProvider adapter={ReactRouter5Adapter}>
- <UsersList user={mockUser} {...mockedProps} />
- </QueryParamProvider>
- </MemoryRouter>,
- { useRedux: true, store },
- );
+ render(<UsersList user={mockUser} {...mockedProps} />, {
+ useRedux: true,
+ store,
+ useQueryParams: true,
+ });
});
return mounted;
}
diff --git a/superset-frontend/src/router/StandaloneRouter.tsx b/superset-frontend/src/router/StandaloneRouter.tsx
new file mode 100644
index 00000000000..b37a977e645
--- /dev/null
+++ b/superset-frontend/src/router/StandaloneRouter.tsx
@@ -0,0 +1,88 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { ReactNode, useEffect, useState } from 'react';
+import {
+ createMemoryHistory,
+ createRootRoute,
+ createRouter,
+ RouterContextProvider,
+ type RouterHistory,
+} from '@tanstack/react-router';
+import { parseSearch, stringifySearch } from './searchParams';
+
+/**
+ * A minimal router host for trees that need router context (Link,
+ * useNavigate, useLocation, useBlocker) without the SPA route table:
+ * the menu entry rendered on Flask-served pages, and component tests.
+ *
+ * Children are rendered directly inside RouterContextProvider (rather
+ * than through RouterProvider's async match rendering) so the tree
+ * mounts synchronously — required by tests that query right after
+ * render().
+ */
+
+export interface StandaloneRouterProps {
+ children?: ReactNode;
+ basepath?: string;
+ /** When provided, an in-memory history is used (tests). */
+ initialEntries?: string[];
+ initialIndex?: number;
+ /** Explicit history instance (tests that assert on navigation). */
+ history?: RouterHistory;
+}
+
+export function createStandaloneRouter({
+ basepath,
+ initialEntries,
+ initialIndex,
+ history,
+}: Omit<StandaloneRouterProps, 'children'> = {}) {
+ return createRouter({
+ routeTree: createRootRoute(),
+ basepath,
+ history:
+ history ??
+ (initialEntries
+ ? createMemoryHistory({ initialEntries, initialIndex })
+ : undefined),
+ parseSearch,
+ stringifySearch,
+ trailingSlash: 'preserve',
+ defaultPreload: false,
+ });
+}
+
+export function StandaloneRouter({
+ children,
+ ...routerOptions
+}: StandaloneRouterProps) {
+ const [router] = useState(() => createStandaloneRouter(routerOptions));
+
+ // RouterProvider's internal Transitioner normally wires history changes
+ // to router state; replicate that minimal wiring since we render
+ // children directly instead of through RouterProvider. No initial
+ // load(): location state is already populated by createRouter, and the
+ // extra state flush would re-render consumers (which breaks tests that
+ // mock selectors with mockReturnValueOnce sequences).
+ useEffect(() => router.history.subscribe(router.load), [router]);
+
+ return (
+ <RouterContextProvider router={router}>{children}</RouterContextProvider>
+ );
+}
diff --git a/superset-frontend/src/router/index.tsx b/superset-frontend/src/router/index.tsx
new file mode 100644
index 00000000000..246c1c3413b
--- /dev/null
+++ b/superset-frontend/src/router/index.tsx
@@ -0,0 +1,164 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { Suspense, useEffect } from 'react';
+import {
+ createRootRoute,
+ createRoute,
+ createRouter,
+ Outlet,
+ useLocation,
+} from '@tanstack/react-router';
+import { bindActionCreators } from 'redux';
+import { css } from '@apache-superset/core/theme';
+import { Layout, Loading } from '@superset-ui/core/components';
+import { ErrorBoundary } from 'src/components';
+import Menu from 'src/features/home/Menu';
+import getBootstrapData, { applicationRoot } from 'src/utils/getBootstrapData';
+import ToastContainer from 'src/components/MessageToasts/ToastContainer';
+import { routes, isFrontendRoute } from 'src/views/routes';
+import { Logger, LOG_ACTIONS_SPA_NAVIGATION } from 'src/logger/LogUtils';
+import { logEvent } from 'src/logger/actions';
+import { store } from 'src/views/store';
+import ExtensionsStartup from 'src/extensions/ExtensionsStartup';
+import { RootContextProviders } from 'src/views/RootContextProviders';
+import { ScrollToTop } from 'src/views/ScrollToTop';
+import { parseSearch, stringifySearch } from './searchParams';
+
+const bootstrapData = getBootstrapData();
+
+let lastLocationPathname: string;
+
+const boundActions = bindActionCreators({ logEvent }, store.dispatch);
+
+const LocationPathnameLogger = () => {
+ const pathname = useLocation({ select: location => location.pathname });
+ useEffect(() => {
+ // This will log client side route changes for single page app user navigation
+ boundActions.logEvent(LOG_ACTIONS_SPA_NAVIGATION, { path: pathname });
+ // reset performance logger timer start point to avoid soft navigation
+ // cause dashboard perf measurement problem
+ if (lastLocationPathname && lastLocationPathname !== pathname) {
+ Logger.markTimeOrigin();
+ }
+ lastLocationPathname = pathname;
+ }, [pathname]);
+ return <></>;
+};
+
+const RootComponent = () => (
+ <>
+ <ScrollToTop />
+ <LocationPathnameLogger />
+ <RootContextProviders>
+ <Menu
+ data={bootstrapData.common.menu_data}
+ isFrontendRoute={isFrontendRoute}
+ />
+ <ExtensionsStartup>
+ <Outlet />
+ </ExtensionsStartup>
+ <ToastContainer />
+ </RootContextProviders>
+ </>
+);
+
+const rootRoute = createRootRoute({ component: RootComponent });
+
+/**
+ * Convert a react-router v5 path pattern to TanStack syntax:
+ * ':param' segments become '$param' and trailing slashes are dropped
+ * (matching is trailing-slash insensitive via `trailingSlash: 'preserve'`).
+ */
+export const toTanstackPath = (path: string): string => {
+ const converted = path.replace(/:([A-Za-z0-9_]+)/g, '$$$1');
+ const trimmed = converted.replace(/\/+$/, '');
+ return trimmed === '' ? '/' : trimmed;
+};
+
+const seenPaths = new Set<string>();
+const routeChildren = routes
+ .filter(({ path }) => {
+ const tanstackPath = toTanstackPath(path);
+ if (seenPaths.has(tanstackPath)) return false;
+ seenPaths.add(tanstackPath);
+ return true;
+ })
+ .map(({ path, Component, load, props = {}, Fallback = Loading }) =>
+ createRoute({
+ getParentRoute: () => rootRoute,
+ path: toTanstackPath(path),
+ // Preloading a route (hover/focus intent) runs its loader, which
+ // warms the page's webpack chunk before the user commits to the
+ // navigation. The promise is deliberately NOT returned: loaders
+ // are awaited before render, and blocking would keep the shell
+ // (menu) from painting until the chunk lands. Fire-and-forget
+ // starts the fetch; the lazy() component suspends until it lands.
+ loader: load
+ ? () => {
+ load();
+ }
+ : undefined,
+ component: () => (
+ <Suspense fallback={<Fallback />}>
+ <Layout>
+ <Layout.Content
+ css={css`
+ display: flex;
+ flex-direction: column;
+ `}
+ >
+ <ErrorBoundary
+ css={css`
+ margin: 16px;
+ `}
+ >
+ <Component user={bootstrapData.user} {...props} />
+ </ErrorBoundary>
+ </Layout.Content>
+ </Layout>
+ </Suspense>
+ ),
+ }),
+ );
+
+const routeTree = rootRoute.addChildren(routeChildren);
+
+export const router = createRouter({
+ routeTree,
+ basepath: applicationRoot() || undefined,
+ // Preload route chunks when the user shows intent (link hover/focus).
+ defaultPreload: 'intent',
+ defaultPreloadDelay: 50,
+ // Search params hold rison and pre-encoded payloads managed outside the
+ // router (use-query-params, direct history pushes); treat them as opaque
+ // strings that round-trip unchanged.
+ parseSearch,
+ stringifySearch,
+ trailingSlash: 'preserve',
+ // Unmatched paths rendered nothing under react-router's <Switch>; those
+ // URLs are owned by the Flask backend.
+ defaultNotFoundComponent: () => null,
+ scrollRestoration: false,
+});
+
+// NOTE: the router type is deliberately NOT registered via
+// `declare module '@tanstack/react-router' { interface Register ... }`.
+// Registration would enforce strict route typing on every Link/navigate
+// call, but Superset builds many URLs from backend-provided strings
+// (e.g. dashboard.url); loose typing keeps those call sites valid.
diff --git a/superset-frontend/src/router/navigation.ts b/superset-frontend/src/router/navigation.ts
new file mode 100644
index 00000000000..d830765a6a8
--- /dev/null
+++ b/superset-frontend/src/router/navigation.ts
@@ -0,0 +1,61 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import type { AnyRouter } from '@tanstack/react-router';
+
+/**
+ * Prefix an app-relative href with the router's basepath.
+ *
+ * react-router's history.push prepended the basename automatically;
+ * TanStack's router.history is the raw browser history, so call sites
+ * that push raw hrefs (kept raw to preserve pre-encoded query strings,
+ * e.g. rison) must add the prefix themselves. No-ops when the href is
+ * already prefixed, so backend-built URLs that include the application
+ * root pass through unchanged.
+ */
+export function appHref(router: AnyRouter, href: string): string {
+ const base = (router.basepath ?? '').replace(/\/+$/, '');
+ if (!base || base === '/') return href;
+ return href === base || href.startsWith(`${base}/`) ? href : `${base}${href}`;
+}
+
+/** Push a raw app-relative href through the router's history. */
+export function pushAppHref(
+ router: AnyRouter,
+ href: string,
+ state?: unknown,
+): void {
+ if (state === undefined) {
+ router.history.push(appHref(router, href));
+ } else {
+ router.history.push(appHref(router, href), state as never);
+ }
+}
+
+/** Replace the current location with a raw app-relative href. */
+export function replaceAppHref(
+ router: AnyRouter,
+ href: string,
+ state?: unknown,
+): void {
+ if (state === undefined) {
+ router.history.replace(appHref(router, href));
+ } else {
+ router.history.replace(appHref(router, href), state as never);
+ }
+}
diff --git a/superset-frontend/src/router/queryParamAdapter.tsx b/superset-frontend/src/router/queryParamAdapter.tsx
new file mode 100644
index 00000000000..d01b31061bf
--- /dev/null
+++ b/superset-frontend/src/router/queryParamAdapter.tsx
@@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useRouter, useRouterState } from '@tanstack/react-router';
+import type {
+ PartialLocation,
+ QueryParamAdapter,
+ QueryParamAdapterComponent,
+} from 'use-query-params';
+
+const normalizeSearch = (search: string | undefined): string => {
+ if (!search) return '';
+ return search.startsWith('?') ? search : `?${search}`;
+};
+
+/**
+ * use-query-params adapter backed by the TanStack router, replacing
+ * ReactRouter5Adapter. Pushes go through the router's history with the
+ * raw search string so rison payloads round-trip untouched.
+ */
+export const TanstackRouterAdapter: QueryParamAdapterComponent = ({
+ children,
+}) => {
+ const router = useRouter();
+ const location = useRouterState({ select: state => state.location });
+
+ const navigate = (to: PartialLocation, replace: boolean) => {
+ const { pathname } = router.state.location;
+ const href = `${pathname}${normalizeSearch(to.search)}`;
+ if (replace) {
+ router.history.replace(href, to.state as never);
+ } else {
+ router.history.push(href, to.state as never);
+ }
+ };
+
+ const adapter: QueryParamAdapter = {
+ location: {
+ search: normalizeSearch(location.searchStr),
+ state: location.state,
+ },
+ push: to => navigate(to, false),
+ replace: to => navigate(to, true),
+ };
+
+ return children(adapter);
+};
diff --git a/superset-frontend/src/router/searchParams.ts b/superset-frontend/src/router/searchParams.ts
new file mode 100644
index 00000000000..b92036b6474
--- /dev/null
+++ b/superset-frontend/src/router/searchParams.ts
@@ -0,0 +1,95 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * Search param codec for the TanStack router instance.
+ *
+ * Superset URLs carry rison payloads (e.g. ?q=(filters:!(...))) and
+ * pre-encoded form_data, managed outside the router by use-query-params
+ * and direct history pushes. The router must therefore treat search
+ * params as opaque strings and round-trip them byte-for-byte: no JSON
+ * coercion, no re-encoding surprises.
+ */
+
+export type RawSearch = Record<string, string | string[]>;
+
+export function parseSearch(searchStr: string): RawSearch {
+ const result: RawSearch = {};
+ const raw = searchStr.startsWith('?') ? searchStr.slice(1) : searchStr;
+ if (!raw) return result;
+ raw.split('&').forEach(pair => {
+ if (!pair) return;
+ const eq = pair.indexOf('=');
+ const rawKey = eq === -1 ? pair : pair.slice(0, eq);
+ const rawValue = eq === -1 ? '' : pair.slice(eq + 1);
+ let key: string;
+ let value: string;
+ try {
+ key = decodeURIComponent(rawKey.replace(/\+/g, ' '));
+ value = decodeURIComponent(rawValue.replace(/\+/g, ' '));
+ } catch {
+ key = rawKey;
+ value = rawValue;
+ }
+ const existing = result[key];
+ if (existing === undefined) {
+ result[key] = value;
+ } else if (Array.isArray(existing)) {
+ existing.push(value);
+ } else {
+ result[key] = [existing, value];
+ }
+ });
+ return result;
+}
+
+// Encode only characters that are unsafe in a query string, leaving
+// rison syntax characters ((),:!') readable, matching the app's existing
+// `querystring.stringify(..., { encode: false })` style closely enough
+// to round-trip.
+function encodeQueryComponent(value: string): string {
+ return value.replace(
+ /[^A-Za-z0-9\-_.!~*'(),:;@$/[\]{}|^`\\]/g,
+ char => {
+ if (char === ' ') return '%20';
+ return encodeURIComponent(char);
+ },
+ );
+}
+
+export function stringifySearch(search: RawSearch): string {
+ const pairs: string[] = [];
+ Object.entries(search).forEach(([key, value]) => {
+ if (value === undefined || value === null) return;
+ const values = Array.isArray(value) ? value : [value];
+ values.forEach(v => {
+ if (v === undefined || v === null) return;
+ pairs.push(
+ `${encodeQueryComponent(String(key))}=${encodeQueryComponent(
+ String(v),
+ )}`,
+ );
+ });
+ });
+ return pairs.length ? `?${pairs.join('&')}` : '';
+}
+
+// Named aliases used by router construction sites.
+export const preserveRawSearchParser = parseSearch;
+export const preserveRawSearchSerializer = stringifySearch;
diff --git a/superset-frontend/src/views/ScrollToTop.tsx b/superset-frontend/src/types/tanstack-history.d.ts
similarity index 72%
copy from superset-frontend/src/views/ScrollToTop.tsx
copy to superset-frontend/src/types/tanstack-history.d.ts
index 283f1b4208f..2cb098c4614 100644
--- a/superset-frontend/src/views/ScrollToTop.tsx
+++ b/superset-frontend/src/types/tanstack-history.d.ts
@@ -17,15 +17,11 @@
* under the License.
*/
-import { useEffect } from 'react';
-import { useLocation } from 'react-router-dom';
-
-export const ScrollToTop = () => {
- const { pathname } = useLocation();
-
- useEffect(() => {
- window.scrollTo(0, 0);
- }, [pathname]);
-
- return null;
-};
+// Superset passes app-level objects through navigation state (e.g.
+// SQL Lab's `requestedQuery`, explore's `saveAction`). TanStack types
+// history state as a closed interface; open it up for arbitrary keys.
+declare module '@tanstack/history' {
+ interface HistoryState {
+ [key: string]: unknown;
+ }
+}
diff --git a/superset-frontend/src/views/App.tsx b/superset-frontend/src/views/App.tsx
index 4f30a552e94..d66b7564320 100644
--- a/superset-frontend/src/views/App.tsx
+++ b/superset-frontend/src/views/App.tsx
@@ -16,31 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
-import { Suspense, useEffect } from 'react';
-import {
- BrowserRouter as Router,
- Switch,
- Route,
- useLocation,
-} from 'react-router-dom';
-import { bindActionCreators } from 'redux';
-import { css } from '@apache-superset/core/theme';
-import { Layout, Loading } from '@superset-ui/core/components';
+import { RouterProvider } from '@tanstack/react-router';
import { setupAGGridModules } from '@superset-ui/core/components/ThemedAgGridReact';
-import { ErrorBoundary } from 'src/components';
-import Menu from 'src/features/home/Menu';
-import getBootstrapData, { applicationRoot } from 'src/utils/getBootstrapData';
-import ToastContainer from 'src/components/MessageToasts/ToastContainer';
+import getBootstrapData from 'src/utils/getBootstrapData';
import setupApp from 'src/setup/setupApp';
import setupPlugins from 'src/setup/setupPlugins';
-import { routes, isFrontendRoute } from 'src/views/routes';
-import { Logger, LOG_ACTIONS_SPA_NAVIGATION } from 'src/logger/LogUtils';
import setupCodeOverrides from 'src/setup/setupCodeOverrides';
-import { logEvent } from 'src/logger/actions';
-import { store } from 'src/views/store';
-import ExtensionsStartup from 'src/extensions/ExtensionsStartup';
-import { RootContextProviders } from './RootContextProviders';
-import { ScrollToTop } from './ScrollToTop';
+import { router } from 'src/router';
setupApp();
setupPlugins();
@@ -57,65 +39,6 @@ const locale =
bootstrapData.common?.locale || window.navigator.language || 'en';
document.documentElement.lang = String(locale).replace(/_/g, '-');
-let lastLocationPathname: string;
-
-const boundActions = bindActionCreators({ logEvent }, store.dispatch);
-
-const LocationPathnameLogger = () => {
- const location = useLocation();
- useEffect(() => {
- // This will log client side route changes for single page app user navigation
- boundActions.logEvent(LOG_ACTIONS_SPA_NAVIGATION, {
- path: location.pathname,
- });
- // reset performance logger timer start point to avoid soft navigation
- // cause dashboard perf measurement problem
- if (lastLocationPathname && lastLocationPathname !== location.pathname) {
- Logger.markTimeOrigin();
- }
- lastLocationPathname = location.pathname;
- }, [location.pathname]);
- return <></>;
-};
-
-const App = () => (
- <Router basename={applicationRoot()}>
- <ScrollToTop />
- <LocationPathnameLogger />
- <RootContextProviders>
- <Menu
- data={bootstrapData.common.menu_data}
- isFrontendRoute={isFrontendRoute}
- />
- <ExtensionsStartup>
- <Switch>
- {routes.map(({ path, Component, props = {}, Fallback = Loading }) => (
- <Route path={path} key={path}>
- <Suspense fallback={<Fallback />}>
- <Layout>
- <Layout.Content
- css={css`
- display: flex;
- flex-direction: column;
- `}
- >
- <ErrorBoundary
- css={css`
- margin: 16px;
- `}
- >
- <Component user={bootstrapData.user} {...props} />
- </ErrorBoundary>
- </Layout.Content>
- </Layout>
- </Suspense>
- </Route>
- ))}
- </Switch>
- </ExtensionsStartup>
- <ToastContainer />
- </RootContextProviders>
- </Router>
-);
+const App = () => <RouterProvider router={router} />;
export default App;
diff --git a/superset-frontend/src/views/RootContextProviders.tsx b/superset-frontend/src/views/RootContextProviders.tsx
index 38a6dab16e4..9772d5e2759 100644
--- a/superset-frontend/src/views/RootContextProviders.tsx
+++ b/superset-frontend/src/views/RootContextProviders.tsx
@@ -20,7 +20,7 @@
import { getExtensionsRegistry } from '@superset-ui/core';
import { Provider as ReduxProvider } from 'react-redux';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DynamicPluginProvider } from 'src/components';
@@ -49,7 +49,7 @@ export const RootContextProviders: React.FC<{ children?: React.ReactNode }> = ({
<EmbeddedUiConfigProvider>
<DynamicPluginProvider>
<QueryParamProvider
- adapter={ReactRouter5Adapter}
+ adapter={TanstackRouterAdapter}
options={{
searchStringToObject: querystring.parse,
objectToSearchString: (object: Record<string, any>) =>
diff --git a/superset-frontend/src/views/ScrollToTop.tsx b/superset-frontend/src/views/ScrollToTop.tsx
index 283f1b4208f..7b38ec44de6 100644
--- a/superset-frontend/src/views/ScrollToTop.tsx
+++ b/superset-frontend/src/views/ScrollToTop.tsx
@@ -18,10 +18,10 @@
*/
import { useEffect } from 'react';
-import { useLocation } from 'react-router-dom';
+import { useLocation } from '@tanstack/react-router';
export const ScrollToTop = () => {
- const { pathname } = useLocation();
+ const pathname = useLocation({ select: location => location.pathname });
useEffect(() => {
window.scrollTo(0, 0);
diff --git a/superset-frontend/src/views/menu.tsx b/superset-frontend/src/views/menu.tsx
index dda01a8e27e..e7584292275 100644
--- a/superset-frontend/src/views/menu.tsx
+++ b/superset-frontend/src/views/menu.tsx
@@ -22,10 +22,10 @@ import 'src/public-path';
// eg, backend rendered views
import { Provider } from 'react-redux';
import { createRoot } from 'react-dom/client';
-import { BrowserRouter } from 'react-router-dom';
import { CacheProvider } from '@emotion/react';
import { QueryParamProvider } from 'use-query-params';
-import { ReactRouter5Adapter } from 'use-query-params/adapters/react-router-5';
+import { StandaloneRouter } from 'src/router/StandaloneRouter';
+import { TanstackRouterAdapter } from 'src/router/queryParamAdapter';
import createCache from '@emotion/cache';
import { ThemeProvider } from '@apache-superset/core/theme';
import { theme } from '@apache-superset/core/theme';
@@ -48,9 +48,9 @@ const app = (
<CacheProvider value={emotionCache}>
<ThemeProvider theme={theme}>
<Provider store={store}>
- <BrowserRouter>
+ <StandaloneRouter>
<QueryParamProvider
- adapter={ReactRouter5Adapter}
+ adapter={TanstackRouterAdapter}
options={{
searchStringToObject: querystring.parse,
objectToSearchString: (object: Record<string, any>) =>
@@ -59,7 +59,7 @@ const app = (
>
<Menu data={menu} />
</QueryParamProvider>
- </BrowserRouter>
+ </StandaloneRouter>
</Provider>
</ThemeProvider>
</CacheProvider>
diff --git a/superset-frontend/src/views/routes.tsx b/superset-frontend/src/views/routes.tsx
index 4f066e3ec2c..5e9dd92ac6d 100644
--- a/superset-frontend/src/views/routes.tsx
+++ b/superset-frontend/src/views/routes.tsx
@@ -30,166 +30,124 @@ import getBootstrapData from 'src/utils/getBootstrapData';
// not lazy loaded since this is the home page.
import Home from 'src/pages/Home';
-const ChartCreation = lazy(
- () =>
- import(/* webpackChunkName: "ChartCreation" */ 'src/pages/ChartCreation'),
-);
-
-const AnnotationLayerList = lazy(
- () =>
- import(
- /* webpackChunkName: "AnnotationLayerList" */ 'src/pages/AnnotationLayerList'
- ),
-);
-
-const AlertReportList = lazy(
- () =>
- import(
- /* webpackChunkName: "AlertReportList" */ 'src/pages/AlertReportList'
- ),
-);
-
-const AnnotationList = lazy(
- () =>
- import(/* webpackChunkName: "AnnotationList" */ 'src/pages/AnnotationList'),
-);
-
-const ChartList = lazy(
- () => import(/* webpackChunkName: "ChartList" */ 'src/pages/ChartList'),
-);
-
-const CssTemplateList = lazy(
- () =>
- import(
- /* webpackChunkName: "CssTemplateList" */ 'src/pages/CssTemplateList'
- ),
-);
-
-const ThemeList = lazy(
- () => import(/* webpackChunkName: "ThemeList" */ 'src/pages/ThemeList'),
-);
-
-const DashboardList = lazy(
- () =>
- import(/* webpackChunkName: "DashboardList" */ 'src/pages/DashboardList'),
-);
-
-const Dashboard = lazy(
- () => import(/* webpackChunkName: "Dashboard" */ 'src/pages/Dashboard'),
-);
-
-const DatabaseList = lazy(
- () => import(/* webpackChunkName: "DatabaseList" */ 'src/pages/DatabaseList'),
-);
-
-const DatasetList = lazy(
- () => import(/* webpackChunkName: "DatasetList" */ 'src/pages/DatasetList'),
-);
-
-const DatasetCreation = lazy(
- () =>
- import(
- /* webpackChunkName: "DatasetCreation" */ 'src/pages/DatasetCreation'
- ),
-);
-
-const ExecutionLogList = lazy(
- () =>
- import(
- /* webpackChunkName: "ExecutionLogList" */ 'src/pages/ExecutionLogList'
- ),
-);
-
-const Chart = lazy(
- () => import(/* webpackChunkName: "Chart" */ 'src/pages/Chart'),
-);
-
-const QueryHistoryList = lazy(
- () =>
- import(
- /* webpackChunkName: "QueryHistoryList" */ 'src/pages/QueryHistoryList'
- ),
-);
-
-const SavedQueryList = lazy(
- () =>
- import(/* webpackChunkName: "SavedQueryList" */ 'src/pages/SavedQueryList'),
-);
-
-const SqlLab = lazy(
- () => import(/* webpackChunkName: "SqlLab" */ 'src/pages/SqlLab'),
-);
-
-const AllEntities = lazy(
- () => import(/* webpackChunkName: "AllEntities" */ 'src/pages/AllEntities'),
-);
-
-const Tags = lazy(
- () => import(/* webpackChunkName: "Tags" */ 'src/pages/Tags'),
-);
-
-const Extensions = lazy(
- () => import(/* webpackChunkName: "Tags" */ 'src/extensions/ExtensionsList'),
-);
-
-const RowLevelSecurityList = lazy(
- () =>
- import(
- /* webpackChunkName: "RowLevelSecurityList" */ 'src/pages/RowLevelSecurityList'
- ),
-);
-
-const TaskList = lazy(
- () => import(/* webpackChunkName: "TaskList" */ 'src/pages/TaskList'),
-);
-
-const RolesList = lazy(
- () => import(/* webpackChunkName: "RolesList" */ 'src/pages/RolesList'),
-);
-
-const UsersList: LazyExoticComponent<any> = lazy(
- () => import(/* webpackChunkName: "UsersList" */ 'src/pages/UsersList'),
-);
-
-const UserInfo = lazy(
- () => import(/* webpackChunkName: "UserInfo" */ 'src/pages/UserInfo'),
-);
-const ActionLogList: LazyExoticComponent<any> = lazy(
- () => import(/* webpackChunkName: "ActionLogList" */ 'src/pages/ActionLog'),
-);
-
-const Login = lazy(
- () => import(/* webpackChunkName: "Login" */ 'src/pages/Login'),
-);
-
-const Register = lazy(
- () => import(/* webpackChunkName: "Register" */ 'src/pages/Register'),
-);
-
-const GroupsList: LazyExoticComponent<any> = lazy(
- () => import(/* webpackChunkName: "GroupsList" */ 'src/pages/GroupsList'),
-);
-const UserRegistrations = lazy(
- () =>
- import(
- /* webpackChunkName: "UserRegistrations" */ 'src/pages/UserRegistrations'
- ),
-);
-
-const FileHandler = lazy(
- () => import(/* webpackChunkName: "FileHandler" */ 'src/pages/FileHandler'),
-);
-
-const RedirectWarning = lazy(
- () =>
- import(
- /* webpackChunkName: "RedirectWarning" */ 'src/pages/RedirectWarning'
- ),
-);
+type RouteModule = { default: ComponentType<any> };
+export type RouteLoader = () => Promise<RouteModule>;
+
+// Import thunks are declared separately from the lazy() wrappers so the
+// router can preload a route's chunk on intent (link hover/focus)
+// without rendering it.
+const loadChartCreation: RouteLoader = () =>
+ import(/* webpackChunkName: "ChartCreation" */ 'src/pages/ChartCreation');
+const loadAnnotationLayerList: RouteLoader = () =>
+ import(
+ /* webpackChunkName: "AnnotationLayerList" */ 'src/pages/AnnotationLayerList'
+ );
+const loadAlertReportList: RouteLoader = () =>
+ import(/* webpackChunkName: "AlertReportList" */ 'src/pages/AlertReportList');
+const loadAnnotationList: RouteLoader = () =>
+ import(/* webpackChunkName: "AnnotationList" */ 'src/pages/AnnotationList');
+const loadChartList: RouteLoader = () =>
+ import(/* webpackChunkName: "ChartList" */ 'src/pages/ChartList');
+const loadCssTemplateList: RouteLoader = () =>
+ import(/* webpackChunkName: "CssTemplateList" */ 'src/pages/CssTemplateList');
+const loadThemeList: RouteLoader = () =>
+ import(/* webpackChunkName: "ThemeList" */ 'src/pages/ThemeList');
+const loadDashboardList: RouteLoader = () =>
+ import(/* webpackChunkName: "DashboardList" */ 'src/pages/DashboardList');
+const loadDashboard: RouteLoader = () =>
+ import(/* webpackChunkName: "Dashboard" */ 'src/pages/Dashboard');
+const loadDatabaseList: RouteLoader = () =>
+ import(/* webpackChunkName: "DatabaseList" */ 'src/pages/DatabaseList');
+const loadDatasetList: RouteLoader = () =>
+ import(/* webpackChunkName: "DatasetList" */ 'src/pages/DatasetList');
+const loadDatasetCreation: RouteLoader = () =>
+ import(/* webpackChunkName: "DatasetCreation" */ 'src/pages/DatasetCreation');
+const loadExecutionLogList: RouteLoader = () =>
+ import(
+ /* webpackChunkName: "ExecutionLogList" */ 'src/pages/ExecutionLogList'
+ );
+const loadChart: RouteLoader = () =>
+ import(/* webpackChunkName: "Chart" */ 'src/pages/Chart');
+const loadQueryHistoryList: RouteLoader = () =>
+ import(
+ /* webpackChunkName: "QueryHistoryList" */ 'src/pages/QueryHistoryList'
+ );
+const loadSavedQueryList: RouteLoader = () =>
+ import(/* webpackChunkName: "SavedQueryList" */ 'src/pages/SavedQueryList');
+const loadSqlLab: RouteLoader = () =>
+ import(/* webpackChunkName: "SqlLab" */ 'src/pages/SqlLab');
+const loadAllEntities: RouteLoader = () =>
+ import(/* webpackChunkName: "AllEntities" */ 'src/pages/AllEntities');
+const loadTags: RouteLoader = () =>
+ import(/* webpackChunkName: "Tags" */ 'src/pages/Tags');
+const loadExtensions: RouteLoader = () =>
+ import(/* webpackChunkName: "Tags" */ 'src/extensions/ExtensionsList');
+const loadRowLevelSecurityList: RouteLoader = () =>
+ import(
+ /* webpackChunkName: "RowLevelSecurityList" */ 'src/pages/RowLevelSecurityList'
+ );
+const loadTaskList: RouteLoader = () =>
+ import(/* webpackChunkName: "TaskList" */ 'src/pages/TaskList');
+const loadRolesList: RouteLoader = () =>
+ import(/* webpackChunkName: "RolesList" */ 'src/pages/RolesList');
+const loadUsersList: RouteLoader = () =>
+ import(/* webpackChunkName: "UsersList" */ 'src/pages/UsersList');
+const loadUserInfo: RouteLoader = () =>
+ import(/* webpackChunkName: "UserInfo" */ 'src/pages/UserInfo');
+const loadActionLogList: RouteLoader = () =>
+ import(/* webpackChunkName: "ActionLogList" */ 'src/pages/ActionLog');
+const loadLogin: RouteLoader = () =>
+ import(/* webpackChunkName: "Login" */ 'src/pages/Login');
+const loadRegister: RouteLoader = () =>
+ import(/* webpackChunkName: "Register" */ 'src/pages/Register');
+const loadGroupsList: RouteLoader = () =>
+ import(/* webpackChunkName: "GroupsList" */ 'src/pages/GroupsList');
+const loadUserRegistrations: RouteLoader = () =>
+ import(
+ /* webpackChunkName: "UserRegistrations" */ 'src/pages/UserRegistrations'
+ );
+const loadFileHandler: RouteLoader = () =>
+ import(/* webpackChunkName: "FileHandler" */ 'src/pages/FileHandler');
+const loadRedirectWarning: RouteLoader = () =>
+ import(/* webpackChunkName: "RedirectWarning" */ 'src/pages/RedirectWarning');
+
+const ChartCreation = lazy(loadChartCreation);
+const AnnotationLayerList = lazy(loadAnnotationLayerList);
+const AlertReportList = lazy(loadAlertReportList);
+const AnnotationList = lazy(loadAnnotationList);
+const ChartList = lazy(loadChartList);
+const CssTemplateList = lazy(loadCssTemplateList);
+const ThemeList = lazy(loadThemeList);
+const DashboardList = lazy(loadDashboardList);
+const Dashboard = lazy(loadDashboard);
+const DatabaseList = lazy(loadDatabaseList);
+const DatasetList = lazy(loadDatasetList);
+const DatasetCreation = lazy(loadDatasetCreation);
+const ExecutionLogList = lazy(loadExecutionLogList);
+const Chart = lazy(loadChart);
+const QueryHistoryList = lazy(loadQueryHistoryList);
+const SavedQueryList = lazy(loadSavedQueryList);
+const SqlLab = lazy(loadSqlLab);
+const AllEntities = lazy(loadAllEntities);
+const Tags = lazy(loadTags);
+const Extensions = lazy(loadExtensions);
+const RowLevelSecurityList = lazy(loadRowLevelSecurityList);
+const TaskList = lazy(loadTaskList);
+const RolesList = lazy(loadRolesList);
+const UsersList: LazyExoticComponent<any> = lazy(loadUsersList);
+const UserInfo = lazy(loadUserInfo);
+const ActionLogList: LazyExoticComponent<any> = lazy(loadActionLogList);
+const Login = lazy(loadLogin);
+const Register = lazy(loadRegister);
+const GroupsList: LazyExoticComponent<any> = lazy(loadGroupsList);
+const UserRegistrations = lazy(loadUserRegistrations);
+const FileHandler = lazy(loadFileHandler);
+const RedirectWarning = lazy(loadRedirectWarning);
type Routes = {
path: string;
Component: ComponentType;
+ load?: RouteLoader;
Fallback?: ComponentType;
props?: ComponentProps<any>;
}[];
@@ -198,22 +156,27 @@ export const routes: Routes = [
{
path: '/redirect/',
Component: RedirectWarning,
+ load: loadRedirectWarning,
},
{
path: '/login/',
Component: Login,
+ load: loadLogin,
},
{
path: '/register/activation/:activationHash',
Component: Register,
+ load: loadRegister,
},
{
path: '/register/',
Component: Register,
+ load: loadRegister,
},
{
path: '/logout/',
Component: Login,
+ load: loadLogin,
},
{
path: '/superset/welcome/',
@@ -222,62 +185,77 @@ export const routes: Routes = [
{
path: '/superset/file-handler',
Component: FileHandler,
+ load: loadFileHandler,
},
{
path: '/dashboard/list/',
Component: DashboardList,
+ load: loadDashboardList,
},
{
path: '/superset/dashboard/:idOrSlug/',
Component: Dashboard,
+ load: loadDashboard,
},
{
path: '/chart/add',
Component: ChartCreation,
+ load: loadChartCreation,
},
{
path: '/chart/list/',
Component: ChartList,
+ load: loadChartList,
},
{
path: '/tablemodelview/list/',
Component: DatasetList,
+ load: loadDatasetList,
},
{
path: '/databaseview/list/',
Component: DatabaseList,
+ load: loadDatabaseList,
},
{
path: '/savedqueryview/list/',
Component: SavedQueryList,
+ load: loadSavedQueryList,
},
{
path: '/csstemplatemodelview/list/',
Component: CssTemplateList,
+ load: loadCssTemplateList,
},
{
path: '/theme/list/',
Component: ThemeList,
+ load: loadThemeList,
},
{
path: '/annotationlayer/list/',
Component: AnnotationLayerList,
+ load: loadAnnotationLayerList,
},
{
path: '/annotationlayer/:annotationLayerId/annotation/',
Component: AnnotationList,
+ load: loadAnnotationList,
},
{
path: '/sqllab/history/',
Component: QueryHistoryList,
+ load: loadQueryHistoryList,
},
{
path: '/alert/list/',
Component: AlertReportList,
+ load: loadAlertReportList,
},
{
path: '/report/list/',
Component: AlertReportList,
+ load: loadAlertReportList,
props: {
isReportEnabled: true,
},
@@ -285,10 +263,12 @@ export const routes: Routes = [
{
path: '/alert/:alertId/log/',
Component: ExecutionLogList,
+ load: loadExecutionLogList,
},
{
path: '/report/:alertId/log/',
Component: ExecutionLogList,
+ load: loadExecutionLogList,
props: {
isReportEnabled: true,
},
@@ -296,39 +276,48 @@ export const routes: Routes = [
{
path: '/explore/',
Component: Chart,
+ load: loadChart,
},
{
path: '/superset/explore/p',
Component: Chart,
+ load: loadChart,
},
{
path: '/dataset/add/',
Component: DatasetCreation,
+ load: loadDatasetCreation,
},
{
path: '/dataset/:datasetId',
Component: DatasetCreation,
+ load: loadDatasetCreation,
},
{
path: '/rowlevelsecurity/list',
Component: RowLevelSecurityList,
+ load: loadRowLevelSecurityList,
},
{
path: '/tasks/list/',
Component: TaskList,
+ load: loadTaskList,
},
{
path: '/sqllab/',
Component: SqlLab,
+ load: loadSqlLab,
},
- { path: '/user_info/', Component: UserInfo },
+ { path: '/user_info/', Component: UserInfo, load: loadUserInfo },
{
path: '/actionlog/list',
Component: ActionLogList,
+ load: loadActionLogList,
},
{
path: '/registrations/',
Component: UserRegistrations,
+ load: loadUserRegistrations,
},
];
@@ -336,10 +325,12 @@ if (isFeatureEnabled(FeatureFlag.TaggingSystem)) {
routes.push({
path: '/superset/all_entities/',
Component: AllEntities,
+ load: loadAllEntities,
});
routes.push({
path: '/superset/tags/',
Component: Tags,
+ load: loadTags,
});
}
@@ -353,14 +344,17 @@ if (isAdmin) {
{
path: '/roles/',
Component: RolesList,
+ load: loadRolesList,
},
{
path: '/users/',
Component: UsersList,
+ load: loadUsersList,
},
{
path: '/list_groups/',
Component: GroupsList,
+ load: loadGroupsList,
},
);
@@ -368,6 +362,7 @@ if (isAdmin) {
routes.push({
path: '/extensions/list/',
Component: Extensions,
+ load: loadExtensions,
});
}
}
@@ -376,6 +371,7 @@ if (authRegistrationEnabled) {
routes.push({
path: '/registrations/',
Component: UserRegistrations,
+ load: loadUserRegistrations,
});
}