navigation.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import type {Location, Query} from 'history';
  2. import {openModal} from 'sentry/actionCreators/modal';
  3. import ContextPickerModal from 'sentry/components/contextPickerModal';
  4. import ProjectsStore from 'sentry/stores/projectsStore';
  5. import type {InjectedRouter} from 'sentry/types/legacyReactRouter';
  6. import replaceRouterParams from 'sentry/utils/replaceRouterParams';
  7. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  8. // TODO(ts): figure out better typing for react-router here
  9. export function navigateTo(
  10. to: string | {pathname: string; query?: Query},
  11. router: InjectedRouter & {location?: Location},
  12. configUrl?: string
  13. ) {
  14. let pathname: string;
  15. if (typeof to === 'string') {
  16. pathname = to;
  17. } else {
  18. pathname = to.pathname;
  19. }
  20. // Check for placeholder params
  21. const needOrg = pathname.includes(':orgId');
  22. const needProject = pathname.includes(':projectId') || pathname.includes(':project');
  23. const comingFromProjectId = router?.location?.query?.project;
  24. const needProjectId = !comingFromProjectId || Array.isArray(comingFromProjectId);
  25. const projectById = ProjectsStore.getById(comingFromProjectId);
  26. if (needOrg || (needProject && (needProjectId || !projectById)) || configUrl) {
  27. openModal(
  28. modalProps => (
  29. <ContextPickerModal
  30. {...modalProps}
  31. nextPath={to}
  32. needOrg={needOrg}
  33. needProject={needProject}
  34. configUrl={configUrl}
  35. onFinish={path => {
  36. modalProps.closeModal();
  37. return window.setTimeout(() => router.push(normalizeUrl(path)), 0);
  38. }}
  39. />
  40. ),
  41. {}
  42. );
  43. } else {
  44. if (projectById) {
  45. pathname = replaceRouterParams(pathname, {
  46. projectId: projectById.slug,
  47. project: projectById.id,
  48. });
  49. }
  50. // Preserve query string
  51. router.push(normalizeUrl(typeof to === 'string' ? pathname : {...to, pathname}));
  52. }
  53. }