recreateRoute.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import {Location} from 'history';
  2. import findLastIndex from 'lodash/findLastIndex';
  3. import replaceRouterParams from 'sentry/utils/replaceRouterParams';
  4. import {RouteWithName} from 'sentry/views/settings/components/settingsBreadcrumb/types';
  5. type Options = {
  6. // parameters to replace any route string parameters (e.g. if route is `:orgId`,
  7. // params should have `{orgId: slug}`
  8. params: {[key: string]: string | undefined};
  9. routes: RouteWithName[];
  10. location?: Location;
  11. /**
  12. * The number of routes to to pop off of `routes
  13. * Must be < 0
  14. *
  15. * There's no ts type for negative numbers so we are arbitrarily specifying -1-9
  16. */
  17. stepBack?: -1 | -2 | -3 | -4 | -5 | -6 | -7 | -8 | -9;
  18. };
  19. /**
  20. * Given a route object or a string and a list of routes + params from router, this will attempt to recreate a location string while replacing url params.
  21. * Can additionally specify the number of routes to move back
  22. *
  23. * See tests for examples
  24. */
  25. export default function recreateRoute(
  26. to: string | RouteWithName,
  27. options: Options
  28. ): string {
  29. const {routes, params, location, stepBack} = options;
  30. const paths = routes.map(({path}) => path || '');
  31. let lastRootIndex: number;
  32. let routeIndex: number | undefined;
  33. // TODO(ts): typescript things
  34. if (typeof to !== 'string') {
  35. routeIndex = routes.indexOf(to) + 1;
  36. lastRootIndex = findLastIndex(paths.slice(0, routeIndex), path => path[0] === '/');
  37. } else {
  38. lastRootIndex = findLastIndex(paths, path => path[0] === '/');
  39. }
  40. let baseRoute = paths.slice(lastRootIndex, routeIndex);
  41. if (typeof stepBack !== 'undefined') {
  42. baseRoute = baseRoute.slice(0, stepBack);
  43. }
  44. const search = location?.search ?? '';
  45. const hash = location?.hash ?? '';
  46. const fullRoute = `${baseRoute.join('')}${
  47. typeof to !== 'string' ? '' : to
  48. }${search}${hash}`;
  49. return replaceRouterParams(fullRoute, params);
  50. }